diff --git a/apps/detail-agent-pi/src/candidate-review.mjs b/apps/detail-agent-pi/src/candidate-review.mjs index b14a0738..bdd0b1d1 100644 --- a/apps/detail-agent-pi/src/candidate-review.mjs +++ b/apps/detail-agent-pi/src/candidate-review.mjs @@ -10,19 +10,59 @@ const tool = (name, description, parameters, execute) => ({ export const copySignature = copy=>copy.map(({field,text,claims})=>[field,...(claims??[text])]) .sort(([left],[right])=>left.localeCompare(right)); +const reviewChecks=['structure','color','templateStyle','composition','evidence']; + +export function readAutoAdoptionPolicy(policy) { + if(policy==null)return null; + const {version,candidateCount,priorityChecks=[]}=policy; + if(typeof version!=='string'||!version.trim()||!Number.isSafeInteger(candidateCount)||candidateCount<1|| + !Array.isArray(priorityChecks)||priorityChecks.some(check=>!reviewChecks.includes(check))){ + throw Error('自动采用政策须声明版本、候选数量和有效的验图优先项'); + } + return {version,candidateCount,priorityChecks}; +} + +export function decideCandidateSet(policy, requests, reviews) { + if(requests.length!==policy.candidateCount||requests.some(request=>request.state!=='complete'))return; + const basis=requests.map(({requestId,operationId,prepared})=>{ + const review=reviews?.[requestId]; + return review?.original&&['pass','revise'].includes(review.decision)&&{ + candidateId:requestId,operationId,position:prepared.candidateSet.position, + verdict:review.decision,checks:review.checks,reason:review.reason,original:review.original, + }; + }); + if(basis.some(row=>!row))return; + const ranked=basis.filter(row=>row.verdict==='pass').sort((a,b)=>{ + for(const check of policy.priorityChecks){ + const difference=Number(b.checks?.[check]===true)-Number(a.checks?.[check]===true); + if(difference)return difference; + } + return a.position-b.position; + }); + const candidateId=ranked[0]?.candidateId; + return {actor:'agent',policyVersion:policy.version,candidateId,priorityChecks:policy.priorityChecks,basis, + reason:ranked.length===0?'all_rejected':ranked.length===1?'only_pass':'policy_priority'}; +} + export async function reviewProductionCandidate({ canvas,host,runAgent,slot,candidateId,signal,copy,rule,source,adopted=false,fit,artDirection, - reviewKnowledge,useFramedOriginal=true,refusal,onRequestFailure, + reviewKnowledge,useFramedOriginal=true,refusal,onRequestFailure,requireOriginal=false, }) { const input=await canvas.detailImages(slot.id,candidateId,{ ...(adopted?{adopted:true}:null), ...(rule?.actionReviewRegion?{actionReviewDetail:true}:null), + ...(requireOriginal?{includeCandidateOriginal:true}:null), }); if(input.candidateId!==candidateId||!input.referenceCount|| input.images?.length!==input.referenceCount+(input.layoutCount??0)+1|| input.images.some(image=>image?.type!=='image')||adopted&&input.adopted!==true){ throw Error('本次验图未读到同款实拍与对应候选的实际像素'); } + const original=input.candidateFile; + if(requireOriginal&&(!original?.sha256||!(original.width>0)||!(original.height>0)|| + input.candidateOriginal?.type!=='image'||!input.candidateOriginal.data)){ + throw Error('自动采用须读取并核对候选原文件的实际像素'); + } const referenceCount=input.referenceCount; const originalIndex=input.originalReferenceIndex; const originalReference=Number.isInteger(originalIndex)&&originalIndex>=0&&originalIndeximage?.type==='image')); const pixelFindings={ whiteSideBands:input.whiteSideBands,hasWhiteTopBand:input.hasWhiteTopBand,hasWhiteBottomBand:input.hasWhiteBottomBand, @@ -114,5 +155,5 @@ export async function reviewProductionCandidate({ ? instructions+'\n请调用本次提供的 review_candidate 工具提交候选号、结论和具体证据。' : instructions); } - return {...receipt,referenceCount}; + return {...receipt,referenceCount,...(requireOriginal?{original}:null)}; } diff --git a/apps/detail-agent-pi/src/desktop-host.mjs b/apps/detail-agent-pi/src/desktop-host.mjs index 5a2db4b3..3e1f4586 100644 --- a/apps/detail-agent-pi/src/desktop-host.mjs +++ b/apps/detail-agent-pi/src/desktop-host.mjs @@ -94,6 +94,7 @@ export async function runSession(config, call, sharedBroker, recovery, signal) { const productionGoal=config.mode==='prompt'&&config.wholeDetail===true&&config.productProduction===true ? {outputId:config.outputId,variantId:config.variantId,requestedOutputs:config.requestedOutputs, pendingOutputs:config.pendingOutputs,workspaceId:config.workspaceId,template:config.productionTemplate, + ...(config.autoAdoptionPolicy?{autoAdoptionPolicy:config.autoAdoptionPolicy}:null), ...(Number.isSafeInteger(config.productionDeadline)?{deadline:config.productionDeadline}:null)} : undefined; const startedAt = performance.now(); const abort = () => { if (host) void host.session.abort().catch(()=>{}); }; diff --git a/apps/detail-agent-pi/src/production-operations.mjs b/apps/detail-agent-pi/src/production-operations.mjs index b277f55e..3e15534d 100644 --- a/apps/detail-agent-pi/src/production-operations.mjs +++ b/apps/detail-agent-pi/src/production-operations.mjs @@ -6,7 +6,7 @@ import { PresentationBatch } from './stream-presentation.mjs'; import { loadSlots } from './production-slots.mjs'; import { productionKnowledge, knowledgeReadInstruction } from './production-knowledge.mjs'; import { productRequestScope } from './production-recovery.mjs'; -import { reviewProductionCandidate } from './candidate-review.mjs'; +import { copySignature, decideCandidateSet, readAutoAdoptionPolicy, reviewProductionCandidate } from './candidate-review.mjs'; import { executeWorkflow, reconcileWorkflowReceipt } from './workflow-execute.mjs'; const obj=fields=>Type.Object(fields,{additionalProperties:false}); @@ -24,10 +24,13 @@ const productImageArgs={ }; const preparationArgs={ prompt:text, + candidateSetId:optional(Type.String({description:'按自动采用政策准备同批下一张时,使用首张回执的 candidateSet.id,保持正式请求内容相同。'})), reworkChange:optional(Type.String({description:'返工时记录这次改变了什么。'})), reworkCandidateId:optional(text), + referenceIndexes:optional(Type.Array(page,{minItems:1,uniqueItems:true,description:'本款原片的零起始编号,按实际发送顺序填写。'})), geometryReferenceIndex:optional(page), - useTemplateReference:optional(Type.Boolean({description:'传 false 可准备一版不使用模板参考和取景提示的请求。'})), + useTemplateReference:optional(Type.Boolean({description:'传 true,将模板参考追加到原片之后。'})), + useSceneComposite:optional(Type.Boolean({description:'模板声明实拍合成时,可只提交模板场景以擦除旧商品。prompt 应完整描述擦除;本款实拍在本地合成。'})), prefer2k:optional(Type.Boolean()), retryOf:optional(Type.String({description:'仅限已确认可重试的失败候选。'})), }; @@ -60,7 +63,7 @@ export const productionOperationTools = [ ['stage_archived_image','把已完成的候选加入当前目标图位待验,沿用其原素材任务。来源是本项目已知候选时省略 projectId,来源是另一同款项目时使用 read_archived_images 返回的 projectId。请按目标图位复核再决定是否采用。',obj({ slotId:slotRef,projectId:optional(Type.String()),candidateId:text, })], - ['check_image_slots','请验图代理审核指定候选,是否采用由你决定。默认先返回受理结果,可继续工作并用 review_image_slots 查看结论。',obj({ + ['check_image_slots','请验图代理审核指定候选。配置自动采用政策时,审核同批全部候选后自动择优回填。默认先返回受理结果,可用 review_image_slots 查看结论。',obj({ wait:optional(Type.Boolean()),candidates:Type.Array(obj({slotId:slotRef,candidateId:text,adopted:optional(Type.Boolean())})), })], ['adopt_production_image','采用你选择的候选,返回实际的画布放置回执。',obj({slotId:slotRef,candidateId:text,fit:optional(fit)})], @@ -120,6 +123,8 @@ export async function openProductionOperations(host) { const byId=new Map(slots.map(slot=>[slot.id,slot])); const byField=Map.groupBy(slots,slot=>slot.fieldId); const binding=JSON.stringify([plan.template.contentHash,variantId]); + const autoAdoptionPolicy=readAutoAdoptionPolicy(plan.autoAdoptionPolicy??host.productionGoal.autoAdoptionPolicy?? + plan.template.production?.autoAdoptionPolicy); const ledger=productionLedger(store,outputId,variantId); const {repository}=ledger; const previous=ledger.read(); @@ -161,9 +166,13 @@ export async function openProductionOperations(host) { const seenLayouts=new Set(); let seenProduct=false; const jobs=new Map(), generation=new Map(), reviewWork=new Set(), candidates=new Map(), filled=new Set(slots.filter(s=>s.selectedCandidateId).map(s=>s.id)); + const slotWorking=id=>[...jobs.values()].some(job=>job.row.slotId===id); + const generationReceipts=scope=>[...generation.values()].reverse().filter(row=>scope.has(row.slotId)); const pendingReviews=()=>[...reviewWork].filter(job=>job.run); const running=()=>[...jobs.values(),...pendingReviews()]; - const drain=()=>Promise.allSettled(running().map(job=>job.run)); + const drain=async()=>{ + for(let pending=running();pending.length;pending=running())await Promise.allSettled(pending.map(job=>job.run)); + }; let journalWrite=Promise.resolve(), canvasWrite=Promise.resolve(); const commit=write=>{ const written=journalWrite.then(async()=>{ @@ -214,7 +223,9 @@ export async function openProductionOperations(host) { const pictureCells=slots.map(({id,label})=>{ const item=journal.items[id]; const matched=filled.has(id); - return {slotId:id,label,state:matched&&item?.review?.decision==='pass'?'verified':matched?'filled':'empty'}; + const adopted=item?.autoAdoptions?.[item.autoCandidateSetId]; + const checked=adopted?.receipt||item?.review?.decision==='pass'; + return {slotId:id,label,state:matched&&checked?'verified':matched?'filled':'empty'}; }); const copyCells=(await fields()).map(({layer,label,currentText,templateSample})=>({ label,state:!templateSample&&evidenceMatches(plan)&&journal.copyEvidence?.[layer]?.text===currentText?'verified': @@ -225,7 +236,8 @@ export async function openProductionOperations(host) { reviews:pendingReviews().map(job=>job.row),candidateReviews:Object.fromEntries(candidates),pictureCells,copyCells, total:slots.length,rendered:filled.size,copy:copyCells.filter(row=>row.state==='verified').length, copyPending:copyCells.filter(row=>row.state!=='verified').length, - unresolved:Object.values(journal.items).filter(item=>item.pendingOperation||item.pendingAdoption).length}); + unresolved:Object.values(journal.items).filter(item=>item.pendingOperation||item.pendingAdoption|| + Object.keys(item.pendingGenerations??{}).length).length}); }; const display=new PresentationBatch(progress); const notice=heading=>display.push({heading,epoch:displayEpoch}); @@ -237,7 +249,7 @@ export async function openProductionOperations(host) { ...(args.includeTemplateReference===false?{includeTemplateReference:false}:null), }); }; - async function operate(slot,intent,values,signal,attempt) { + async function operate(slot,intent,values,signal,attempt,decision) { const scope=new CanvasOperations(); const prior=journal.items[slot.id], adopting=intent==='adopt_candidate'; const pendingKey=adopting?'pendingAdoption':'pendingOperation'; @@ -255,7 +267,7 @@ export async function openProductionOperations(host) { const archive=async operation=>{ const candidateId=adopting?values.candidateId: canvas.durableGenerationIds&&values.useProductReference!==true?operation.operationId:null; - prepared={...operation,intent,candidateId}; + prepared={...operation,intent,candidateId,...(decision?{decision}:null)}; await save(slot,{[pendingKey]:prepared,...(!adopting?{state:'dispatching'}:null)}); }; const rememberAttempt=(item,candidateId)=>{ @@ -290,27 +302,36 @@ export async function openProductionOperations(host) { const item=journal.items[slot.id]??={}; Object.assign(item,{state,candidateId:operation.candidateId??prior?.candidateId,[pendingKey]:pending, ...(intent==='generate_candidate'?{source:values.useProductReference?'product':'generate',prompt:values.instruction}:null)}); + if(decision&&state==='applied')item.autoAdoptions[decision.candidateSetId]={...decision, + state:operation.persistence==='session'?'placed':'adopted',receipt:operation}; rememberAttempt(item,operation.candidateId); },operation.candidateId?{evidence:[slot.id,operation.candidateId,adopting?'adoption':'candidate', - {...prepared,...operation,actor:'agent',fieldId:slot.fieldId}]}:undefined); + {...prepared,...operation,actor:'agent',fieldId:slot.fieldId,...decision}]}:undefined); return {...operation,...(operation.phase==='unknown'?{pendingOriginal:operation.candidateId??operation.operationId}:null)}; } - const pendingGeneration=(slot,record=journal)=>{ + const pendingGeneration=(slot,record=journal,requestId)=>{ const item=record.items[slot.id]; + if(requestId){ + const original=item?.pendingGenerations?.[requestId]; + return original&&{slotId:slot.id,phase:'unknown',...original,pendingOriginal:requestId}; + } const original=item?.pendingOperation; if (!original&&!item?.heldOriginalId&&item?.state!=='unknown') return null; const candidateId=originalCandidate(item); return {slotId:slot.id,phase:'unknown',operationId:original?.operationId,candidateId, pendingOriginal:candidateId??original?.operationId}; }; - const prepareImageRequest=async(slot,{prompt,retryOf,useTemplateReference,prefer2k,geometryReferenceIndex,reworkCandidateId,reworkChange},signal)=>{ + const prepareImageRequest=async(slot,{prompt,retryOf,useTemplateReference,prefer2k,geometryReferenceIndex, + referenceIndexes,useSceneComposite,reworkCandidateId,reworkChange,candidateSetId},signal)=>{ signal?.throwIfAborted(); const input=await current(); const versions=recordProductionInputs(repository,input,slots); - const receipt=await canvas.imageRequest('prepare',{slotId:slot.id,instructions:prompt,retryOf,useTemplateReference, - prefer2k,geometryReferenceIndex,reworkOf:reworkCandidateId,reworkChange}); - await update(()=>{},{prepared:{...receipt,binding,...versions,knowledge:knowledge.files}}); - return receipt; + const receipt=await canvas.imageRequest('prepare',{slotId:slot.id,instructions:prompt,retryOf:candidateSetId?undefined:retryOf,useTemplateReference, + prefer2k,geometryReferenceIndex,reworkOf:reworkCandidateId,reworkChange, + ...(referenceIndexes?{referenceIndexes}:null),...(useSceneComposite!==undefined?{useSceneComposite}:null)}); + const {request}=await update(()=>{},{prepared:{...receipt,binding,...versions,knowledge:knowledge.files}, + policy:autoAdoptionPolicy,candidateSetId}); + return {...receipt,operationId:request.operationId,...(request.prepared.candidateSet?{candidateSet:request.prepared.candidateSet}:null)}; }; const preparedRequest=(requestId,slot)=>{ const saved=repository.readImageRequest(requestId); @@ -323,11 +344,15 @@ export async function openProductionOperations(host) { const dispatchImageRequest=async(slot,approval,request,signal)=>{ signal?.throwIfAborted(); await current(); + const {candidateSet}=request; + if(candidateSet&&repository.candidateSet(slot.id,candidateSet.id).length!==candidateSet.policy.candidateCount){ + throw Error('请先按政策准备齐全同批候选,再分别确认派发'); + } const {claimed,pending,request:record,original}=await commit(()=> repository.claimImageRequest(approval,binding,saved=>pendingGeneration(slot,saved))); const {requestId:candidateId}=approval; if(!claimed){ - if(pending)return pending; + if(pending)return {phase:'unknown',...pending,pendingOriginal:pending.candidateId??pending.operationId}; const {state,operationId,receipt}=record; const phase=['complete','failed','retired'].includes(state)?state:'unknown'; return {phase,candidateId,operationId,reason:receipt?.message, @@ -338,19 +363,20 @@ export async function openProductionOperations(host) { try { receipt=await canvas.imageRequest('dispatch',{...approval,slotId:slot.id}); } catch(error) { if (error.dispatched===false) { - await save(slot,{pendingOperation:null,state:'failed',reason:error.message}, + await update(journal=>{delete journal.items[slot.id].pendingGenerations[candidateId];}, {receipt:[candidateId,'prepared',{dispatched:false,message:error.message}]}); - return {phase:'failed',reason:error.message}; + return {phase:'failed',candidateId,operationId,reason:error.message}; } - repository.recordImageReceipt(candidateId,'unknown',{message:error.message}); + await update(()=>{},{receipt:[candidateId,'unknown',{message:error.message}]}); throw error; } const phase=receipt.status??receipt.phase; const settled=['complete','failed','retired'].includes(phase); await update(journal=>{ const item=journal.items[slot.id]??={}; - Object.assign(item,{pendingOperation:settled?null:original,candidateId,state:phase==='complete'?'candidate':phase, - prompt:request.prompt,source:'generate'}); + if(settled)delete item.pendingGenerations[candidateId]; + if(settled)Object.assign(item,{candidateId,state:phase==='complete'?'candidate':phase}); + Object.assign(item,{prompt:request.prompt,source:'generate'}); const attempts=item.attempts??=[]; if(!attempts.some(row=>row.candidateId===candidateId))attempts.push({candidateId,source:'generate', prompt:request.prompt,reworkOf:request.reworkOf,change:request.reworkChange}); @@ -361,18 +387,23 @@ export async function openProductionOperations(host) { ...(!settled?{pendingOriginal:candidateId}:null), ...(receipt.retryableFailure===true?{retryableFailure:true,retryAfterSeconds:receipt.retryAfterSeconds}:null)}; }; - const launchImage=(slot,operation)=>{ - if(jobs.has(slot.id))return {slotId:slot.id,phase:'already_running'}; - const pending=pendingGeneration(slot); + const launchImage=(slot,key,operation,requestId)=>{ + if(jobs.has(key))return {...generation.get(key),phase:'already_running'}; + const pending=pendingGeneration(slot,journal,requestId); if(pending)return pending; - const receipt={slotId:slot.id,phase:'accepted'}; + const receipt={slotId:slot.id,phase:'accepted',...(requestId?{candidateId:requestId,operationId:key}:null)}; const row={slotId:slot.id,label:slot.label,step:'生成',active:true}; - generation.set(slot.id,receipt); + generation.delete(key); + generation.set(key,receipt); const run=Promise.resolve().then(operation) - .catch(error=>({...pendingGeneration(slot)??{phase:'failed'},reason:error.message})) - .then(result=>{generation.set(slot.id,{slotId:slot.id,...result});}) - .finally(()=>{jobs.delete(slot.id);return notice('候选图片回执');}); - jobs.set(slot.id,{row,run}); + .catch(error=>({...pendingGeneration(slot,journal,requestId)??{phase:'failed',candidateId:requestId},reason:error.message})) + .then(result=>{ + const receipt={slotId:slot.id,...result}; + generation.set(key,receipt); + return receipt; + }) + .finally(()=>{jobs.delete(key);return notice('候选图片回执');}); + jobs.set(key,{row,run}); return receipt; }; const useProductImage=async(slot,options,signal)=>({ @@ -380,6 +411,20 @@ export async function openProductionOperations(host) { requestedSource:'product',sourceNote:'仅使用或裁切原片,保留原片的背景和光线。', }); + const reconcileImageRequest=async(slot,original,signal)=>{ + const {candidateId,operationId}=original; + signal?.throwIfAborted(); + const receipt=await canvas.detailRecover(slot.id,{candidateId}); + const phase=receipt?.id===candidateId&&['complete','failed','retired'].includes(receipt.status)?receipt.status:'unknown'; + if(phase!=='unknown')await update(journal=>{ + const item=journal.items[slot.id]; + delete item.pendingGenerations[candidateId]; + Object.assign(item,{state:phase==='complete'?'candidate':phase,candidateId,source:'generate'}); + },{receipt:[candidateId,phase,receipt], + evidence:[slot.id,candidateId,'candidate',{...receipt,requestId:candidateId,operationId}]}); + return {slotId:slot.id,candidateId,operationId,phase,reason:receipt?.id===candidateId?receipt.message:undefined}; + }; + const reconcile=async(slot,signal,adopting=false)=>{ const item=journal.items[slot.id]; const pendingKey=adopting?'pendingAdoption':'pendingOperation'; @@ -408,10 +453,16 @@ export async function openProductionOperations(host) { if(['complete','failed','not_executed','retired'].includes(phase)){ const applied=phase==='complete'&&adoption; if(applied)filled.add(slot.id); - await save(slot,{state:applied?'applied':phase==='complete'?'candidate':phase,candidateId, - ...(applied&&operation.persistence==='session'?null:{[pendingKey]:null}), - ...(!adopting?{heldOriginalId:null,heldOriginalProjectId:null}:null)}, - candidateId?{evidence:[slot.id,candidateId,adopting?'adoption':'candidate',{...operation,phase}]}:undefined); + const decision=original.decision; + await update(journal=>{ + const record=journal.items[slot.id]; + Object.assign(record,{state:applied?'applied':phase==='complete'?'candidate':phase,candidateId, + ...(applied&&operation.persistence==='session'?null:{[pendingKey]:null}), + ...(!adopting?{heldOriginalId:null,heldOriginalProjectId:null}:null)}); + if(decision&&applied)record.autoAdoptions[decision.candidateSetId]={...decision, + state:operation.persistence==='session'?'placed':'adopted',receipt:operation}; + if(decision&&phase==='not_executed')record.autoAdoptions[decision.candidateSetId]={...decision,state:'selected'}; + },candidateId?{evidence:[slot.id,candidateId,adopting?'adoption':'candidate',{...operation,phase,...decision}]}:undefined); } const reason=receipt?.id===candidateId?receipt?.message??operation.message:operation.message; return {slotId:slot.id,phase,candidateId,operationId:original.operationId,reason}; @@ -421,19 +472,49 @@ export async function openProductionOperations(host) { reason:revision===expected?'写入时画布暂不可用。可先处理其他图位,稍后继续写入。': '画布修订已变化,请重新读取文字格和修订号后再写入。', }); + const autoAdopt=(slot,candidateSet,signal)=>serialize(async()=>{ + const {id,policy}=candidateSet; + const previous=journal.items[slot.id]?.autoAdoptions?.[id]; + if(previous&&previous.state!=='selected')return previous; + const requests=repository.candidateSet(slot.id,id); + const item=journal.items[slot.id]; + if(item?.autoCandidateSetId!==id)return previous; + const copy=JSON.stringify(copySignature(reviewCopy(slot))); + const currentReviews=Object.fromEntries(Object.entries(item?.candidateReviews??{}).filter(([,row])=> + row.creationRevision===plan.revisions?.creation&& + JSON.stringify(row.observation.reviewedCopy)===copy)); + const selected=decideCandidateSet(policy,requests,currentReviews); + if(!selected||item?.pendingAdoption)return previous; + const assetSha256=selected.basis.find(row=>row.candidateId===selected.candidateId)?.original.sha256; + const decision={...selected,candidateSetId:id,assetSha256,fieldId:slot.fieldId,outputId,variantId}; + const state=decision.candidateId?'selected':'needs_rework'; + if(!previous)await update(journal=>{ + (journal.items[slot.id].autoAdoptions??={})[id]={...decision,state}; + }); + if(!decision.candidateId)return {...decision,state}; + const result=await operate(slot,'adopt_candidate',{candidateId:decision.candidateId},signal,undefined,decision); + if(result.phase==='complete'&&candidates.has(decision.candidateId))candidates.get(decision.candidateId).status='adopted'; + return journal.items[slot.id].autoAdoptions[id]; + }); + const reviewCopy=slot=>Object.values(evidenceMatches(plan)?journal.copyEvidence??{}:{}) + .filter(row=>row.pictures.includes(slot.fieldId)||row.pictures.includes(slot.id)); async function check(slot,candidateId,adopted,signal){ const item=journal.items[slot.id]; - const source=item?.candidateId===candidateId?item.source:undefined; - const copy=Object.values(evidenceMatches(plan)?journal.copyEvidence??{}:{}).filter(row=>row.pictures.includes(slot.fieldId)||row.pictures.includes(slot.id)); + const request=repository.readImageRequest(candidateId); + const candidateSet=!adopted&&request?.slotId===slot.id&&request.prepared.binding===binding?request.prepared.candidateSet:null; + const source=request?.slotId===slot.id?'generate':item?.candidateId===candidateId?item.source:undefined; + const copy=reviewCopy(slot); try{ notice('正在核验候选图片'); const {referenceCount,...review}=await reviewProductionCandidate({canvas,host,runAgent:host.runDetailAgent, - slot,candidateId,signal,copy,rule:slot.productionRule,source,adopted,reviewKnowledge:reviews}); + slot,candidateId,signal,copy,rule:slot.productionRule,source,adopted,reviewKnowledge:reviews,requireOriginal:Boolean(candidateSet)}); const {verdict,checks,reason,observation}=review; - const row={candidateId,decision:verdict,checks,reason,observation,evidenceVersion:1,creationRevision:plan.revisions?.creation}; + const row={candidateId,decision:verdict,checks,reason,observation,original:review.original, + evidenceVersion:1,creationRevision:plan.revisions?.creation}; await update(journal=>{ const record=journal.items[slot.id]??={}; record.review=row; + if(candidateSet)(record.candidateReviews??={})[candidateId]=row; record.approvals=(record.approvals??[]).filter(old=>old.candidateId!==candidateId); if(verdict==='pass')record.approvals.push(row); const history=record.reviewHistory??=[]; @@ -443,7 +524,8 @@ export async function openProductionOperations(host) { const reworkOf=journal.items[slot.id]?.attempts?.find(row=>row.candidateId===candidateId)?.reworkOf; await store.appendEvent({type:'whole_detail_review',outputId,variantId,slotId:slot.id,fieldId:slot.fieldId, ...review,...(reworkOf?{reworkOf}:null)}); - return {slotId:slot.id,...review,...(reworkOf?{reworkOf}:null)}; + const adoption=candidateSet&&await autoAdopt(slot,candidateSet,signal); + return {slotId:slot.id,...review,...(reworkOf?{reworkOf}:null),...(adoption?{adoption}:null)}; }catch(error){ return {slotId:slot.id,candidateId,error:error.message}; } @@ -464,6 +546,7 @@ export async function openProductionOperations(host) { return {outputId,variantId,template,product:{name,variant:variant&&{id:variant.id,colorName:variant.colorName}}, pictures,knowledgeFiles:knowledge.files,requestedOutputs:host.productionGoal.requestedOutputs, pendingOutputs:host.productionGoal.pendingOutputs??[], + ...(autoAdoptionPolicy?{autoAdoptionPolicy}:null), ...(unmatched.length?{unmatched}:null)}; }, async read_production_knowledge(args,signal){ @@ -559,7 +642,7 @@ export async function openProductionOperations(host) { use_product_image({slotId,...options},signal){ signal?.throwIfAborted(); const slot=matches(slotId); - return launchImage(slot,()=>useProductImage(slot,options,signal)); + return launchImage(slot,slot.id,()=>useProductImage(slot,options,signal)); }, prepare_image_request({slotId,...args},signal){ return prepareImageRequest(matches(slotId),args,signal); @@ -567,24 +650,30 @@ export async function openProductionOperations(host) { async dispatch_image_request(approval,signal){ const request=preparedRequest(approval.requestId); const slot=matches(request.slotId); - return launchImage(slot,()=>dispatchImageRequest(slot,approval,request,signal)); + return launchImage(slot,request.operationId??approval.requestId,()=>dispatchImageRequest(slot,approval,request,signal),approval.requestId); }, async delegate_image_slots({jobs:requested},signal){ const assigned=[],unmatched=[]; for(const {slotId,goal,reworkCandidateId} of requested){ const slot=findSlot(slotId); if(!slot){unmatched.push({slotId,reason:slotNotFound});continue;} - if(jobs.has(slot.id)){assigned.push({id:slot.id,state:'already_running'});continue;} + const workerId='delegate:'+slot.id; + if(slotWorking(slot.id)){assigned.push({id:slot.id,state:'already_running'});continue;} const row={number:Math.max(0,...[...jobs.values()].map(job=>job.row.number??0))+1,slotId:slot.id,label:slot.label,step:'正在准备',active:true}; - let rework; + let rework, produced=false; + const dispatched=new Set(); const workerTool=(name,description,properties,execute,terminate=false)=>({ name,label:description,description,parameters:obj(properties),executionMode:'sequential', execute:async(_id,args,workerSignal)=>{ const signals=[workerSignal,signal].filter(Boolean); const activeSignal=signals.length?AbortSignal.any(signals):undefined; const result=await execute(args,activeSignal); - if(terminate)generation.set(slot.id,{slotId:slot.id,...result}); - return {...imageResult(result),...(terminate?{terminate:true}:null)}; + const done=typeof terminate==='function'?terminate(result):terminate; + if(terminate){ + produced=true; + if(name==='use_product_image')generation.set(workerId,{slotId:slot.id,...result}); + } + return {...imageResult(result),...(done?{terminate:true}:null)}; }, }); const makeTools=()=>[ @@ -596,8 +685,13 @@ export async function openProductionOperations(host) { (approval,activeSignal)=>{ const request=preparedRequest(approval.requestId,slot); row.step='正在生图'; - return dispatchImageRequest(slot,approval,request,activeSignal); - },true), + const key=request.operationId??approval.requestId; + const receipt=launchImage(slot,key,()=>dispatchImageRequest(slot,approval,request,activeSignal),approval.requestId); + return request.candidateSet?receipt:jobs.get(key)?.run??receipt; + },result=>{ + if(result.operationId)dispatched.add(result.operationId); + return dispatched.size>=(autoAdoptionPolicy?.candidateCount??1); + }), ]; const readTool={name:'read_slot_images',label:'查看本图位实拍与构图',description:'读取本图位的原片与模板构图。', parameters:obj({}),execute:async()=>imageResult(await readImages(slot.id))}; @@ -626,22 +720,23 @@ export async function openProductionOperations(host) { } } const instructions='完成主代理委托的图位。按 Skill 选择直接用实拍,或准备生图请求、审阅准备回执并确认派发。'+ + (autoAdoptionPolicy?'\n按自动采用政策准备全部同批候选。后续准备传首张的 candidateSet.id 和同一份完整请求,备齐后分别审阅并派发。':'')+ (rework?'\n先看随消息附上的退回图、验图回执和上次实发提示词。按发布规则处理,用 reworkChange 记录改动。':'')+ knowledgeReadInstruction; await host.runDetailAgent(slot.id,instructions, JSON.stringify({rework,goal,field:slot.fieldId,label:slot.label,rule:slot.productionRule,requirements:slot.requirements, - knowledgeFiles:knowledge.files}),[readTool,...makeTools(),...knowledge.tools], + knowledgeFiles:knowledge.files,...(autoAdoptionPolicy?{autoAdoptionPolicy}:null)}),[readTool,...makeTools(),...knowledge.tools], rejectedImage?[rejectedImage]:[],productRequestScope('slot',slot.id)); - if(!generation.has(slot.id))generation.set(slot.id,{slotId:slot.id,phase:'no_candidate'}); + if(!produced)generation.set(workerId,{slotId:slot.id,phase:'no_candidate'}); }).catch(async error=>{ - generation.set(slot.id,{slotId:slot.id,phase:'failed',reason:error.message}); + generation.set(workerId,{slotId:slot.id,phase:'failed',reason:error.message}); await save(slot,{reason:error.message}); }).finally(()=>{ - jobs.delete(slot.id); + jobs.delete(workerId); notice('子代理已有回执'); }); - generation.delete(slot.id); - jobs.set(slot.id,{row,run}); + generation.delete(workerId); + jobs.set(workerId,{row,run}); assigned.push({id:slot.id,state:'assigned'}); } if(assigned.length)notice('子代理正在制作'); @@ -653,7 +748,7 @@ export async function openProductionOperations(host) { const scope=slotIds?.length||!selected.length?wanted:new Set(selected.map(job=>job.row.slotId)); if(selected.length)await Promise.race(selected.map(job=>job.run)); return {active:jobs.size,checking:pendingReviews().length, - generation:[...scope].map(id=>generation.get(id)).filter(Boolean), + generation:generationReceipts(scope), checks:[...reviewWork].filter(job=>scope.has(job.row.slotId)).map(job=>job.receipt)}; }, async review_image_slots({slotIds}){ @@ -678,15 +773,19 @@ export async function openProductionOperations(host) { const record=journal.items[id]; const {attemptCount,rejections}=slotAttempts(slot,record); const latest=candidates?.at(-1); - const generationReceipt=generation.get(id); + const generations=generationReceipts(new Set([id])); + const [generationReceipt]=generations; const latestCandidateId=latest?.id??generationReceipt?.candidateId??record?.candidateId; const reviews=checks.get(id)??[]; - if(requested.size)return {id,fieldId,label,selectedCandidateId,attemptCount,rejections,candidates,working:jobs.has(id), - record,generation:generationReceipt,checks:reviews.map(job=>job.receipt)}; + const adoption=record?.autoAdoptions?.[record.autoCandidateSetId]; + if(requested.size)return {id,fieldId,label,selectedCandidateId,attemptCount,rejections,candidates,working:slotWorking(id), + record,generation:generationReceipt,...(generations.length>1?{generations}:null),checks:reviews.map(job=>job.receipt)}; const decision=record?.review?.candidateId===latestCandidateId?record?.review?.decision:undefined; - const state=jobs.has(id)?'generating':reviews.some(job=>job.run)?'checking': - record?.pendingOperation||record?.pendingAdoption||originalCandidate(record)?'unknown': - decision??generationReceipt?.phase??latest?.status??record?.state??'empty'; + const adopted=adoption?.state==='adopted'||adoption?.state==='placed'; + const state=slotWorking(id)?'generating':reviews.some(job=>job.run)?'checking': + record?.pendingOperation||record?.pendingAdoption||originalCandidate(record)||Object.keys(record?.pendingGenerations??{}).length?'unknown': + adoption?.state==='needs_rework'?'needs_rework':adopted?'applied': + decision??generationReceipt?.phase??latest?.status??record?.state??'empty'; return {id,fieldId,label,state,selectedCandidateId,latestCandidateId,attemptCount,rejectionCount:rejections.length}; }),...(unmatched.length?{unmatched}:{})}; }, @@ -732,6 +831,11 @@ export async function openProductionOperations(host) { }, async adopt_production_image({slotId,candidateId,fit},signal){ const slot=matches(slotId); + const request=repository.readImageRequest(candidateId); + if(request?.slotId===slot.id&&request.prepared.binding===binding&&request.prepared.candidateSet){ + const adoption=await autoAdopt(slot,request.prepared.candidateSet,signal); + return adoption?{...adoption,phase:adoption.receipt?.phase??adoption.state}:{phase:'awaiting_candidate_reviews'}; + } const result=await serialize(()=>operate(slot,'adopt_candidate',{candidateId,fit},signal)); if(result.phase==='complete'&&candidates.has(candidateId))candidates.get(candidateId).status='adopted'; notice('画布回填回执'); @@ -742,15 +846,18 @@ export async function openProductionOperations(host) { signal?.throwIfAborted(); const result=await serialize(()=>canvas.detailRetire(slot.id,candidateId,reason)); if(result.status==='retired'){ + const request=repository.readImageRequest(candidateId); await update(journal=>{ const item=journal.items[slot.id]; if(!item)return; item.approvals=(item.approvals??[]).filter(row=>row.candidateId!==candidateId); + if(item.candidateReviews)delete item.candidateReviews[candidateId]; if(item.candidateId===candidateId&&!item.pendingOperation&&!item.pendingAdoption){ item.state='retired'; if(result.canvasLayerId)filled.delete(slot.id); } - },{evidence:[slot.id,candidateId,'retirement',{...result,reason}]}); + },{evidence:[slot.id,candidateId,'retirement',{...result,reason}], + ...(request?{receipt:[candidateId,'retired',result]}:null)}); candidates.delete(candidateId); host.generatedCandidates?.delete(candidateId); await store.appendEvent({type:'production_image_retired',slotId:slot.id,candidateId,reason,requestId:result.requestId}); @@ -759,28 +866,42 @@ export async function openProductionOperations(host) { return result; }, async reconcile_image_slots({slotIds},signal){ - const recover=async(slot,adopting=false)=>{ + const recover=async(slot,adopting=false,frozen)=>{ try { - const receipt=await reconcile(slot,signal,adopting); - const last=generation.get(slot.id); - if(!adopting&&last?.phase==='unknown'&&receipt.phase!=='none'&&receipt.phase!=='unknown'&& - ((last.operationId&&last.operationId===receipt.operationId)||(last.candidateId&&last.candidateId===receipt.candidateId))){ - generation.set(slot.id,receipt); + const receipt=frozen?await reconcileImageRequest(slot,frozen,signal):await reconcile(slot,signal,adopting); + if(!adopting&&receipt.phase!=='none'){ + const original=[...generation.entries()].find(([,row])=>row.slotId===slot.id&&row.phase==='unknown'&& + (receipt.operationId&&row.operationId===receipt.operationId||receipt.candidateId&&row.candidateId===receipt.candidateId)); + generation.set(original?.[0]??receipt.operationId??slot.id,receipt); } return receipt; } catch(error){ signal?.throwIfAborted(); const item=journal.items[slot.id]; - const original=item?.[adopting?'pendingAdoption':'pendingOperation']; - const candidateId=adopting?original?.candidateId:originalCandidate(item); + const original=frozen??item?.[adopting?'pendingAdoption':'pendingOperation']; + const candidateId=frozen||adopting?original?.candidateId:originalCandidate(item); return {slotId:slot.id,operationId:original?.operationId,candidateId,phase:'unknown',reason:error.message}; } }; - return Promise.all(selections(slotIds).flatMap(slot=>[ - recover(slot), - ...(journal.items[slot.id]?.pendingAdoption?[recover(slot,true)]:[]), - ])); + const selected=selections(slotIds); + const results=await Promise.all(selected.flatMap(slot=>{ + const item=journal.items[slot.id]; + const frozen=Object.values(item?.pendingGenerations??{}); + return [ + ...(!frozen.length||pendingGeneration(slot)?[recover(slot)]:[]), + ...frozen.map(original=>recover(slot,false,original)), + ...(item?.pendingAdoption?[recover(slot,true)]:[]), + ]; + })); + for(const slot of selected){ + const {autoCandidateSetId:id,candidateReviews}=journal.items[slot.id]??{}; + if(id&&candidateReviews){ + const set=repository.readImageRequest(id)?.prepared.candidateSet; + if(set)await autoAdopt(slot,set,signal); + } + } + return results; }, async read_output_screen({page=0,pages},signal){ const render=async page=>{ diff --git a/apps/detail-agent-pi/src/project-repository.mjs b/apps/detail-agent-pi/src/project-repository.mjs index 593095ff..9417b905 100644 --- a/apps/detail-agent-pi/src/project-repository.mjs +++ b/apps/detail-agent-pi/src/project-repository.mjs @@ -184,16 +184,16 @@ export class ProjectRepository { }); } - updateLedger(binding, change, { prepared, receipt, evidence } = {}) { + updateLedger(binding, change, { prepared, policy, candidateSetId, receipt, evidence } = {}) { return this.#open(db => transaction(db, () => { const previous = this.#readLedger(db); const journal = previous?.binding === binding ? structuredClone(previous) : { binding, items: {} }; const result = change(journal); this.#writeLedger(db, journal, previous); - if (prepared) this.#saveImageRequest(db, prepared); + const request = prepared && this.#saveImageRequest(db, prepared, policy, candidateSetId); if (receipt) this.#recordImageReceipt(db, ...receipt); if (evidence) this.#recordCandidate(db, ...evidence); - return { journal, result }; + return { journal, result, request }; })); } @@ -224,8 +224,26 @@ export class ProjectRepository { }); } - #saveImageRequest(db, receipt) { + #saveImageRequest(db, receipt, policy, candidateSetId) { const { requestId, operationId = requestId, slotId, requestSpecHash, revision, spec } = receipt; + if (policy || candidateSetId) { + const original = this.#readRequest(db, requestId); + let candidateSet = original?.prepared.candidateSet; + if (!candidateSet) { + const first = candidateSetId && this.#readRequest(db, candidateSetId); + if (candidateSetId && (first?.prepared.candidateSet?.id !== candidateSetId || + first.slotId !== slotId || first.prepared.binding !== receipt.binding || + first.requestSpecHash !== requestSpecHash || first.prepared.planRevision !== receipt.planRevision || + first.prepared.productFactsRevision !== receipt.productFactsRevision)) { + throw Error('同批候选须使用相同的正式请求和制作依据'); + } + const setPolicy = first?.prepared.candidateSet.policy ?? policy; + const position = first ? this.#candidateSet(db, slotId, candidateSetId).length : 0; + if (position >= setPolicy.candidateCount) throw Error('此批候选已准备齐全'); + candidateSet = { id: candidateSetId ?? requestId, position, policy: setPolicy }; + } + receipt = { ...receipt, candidateSet }; + } this.#saveVersion(db, 'prompt', requestId, revision, { slotId, prompt: spec.prompt, promptHash: spec.promptHash }); db.prepare(`INSERT INTO image_requests (${scopeColumns}, request_id, operation_id, slot_id, request_spec_hash, revision, state, prepared_json) VALUES (${scopeValues}, ?, ?, ?, ?, ?, 'prepared', ?) @@ -233,6 +251,7 @@ export class ProjectRepository { ...this.scope, requestId, operationId, slotId, requestSpecHash, revision, json(receipt)); const saved = this.#readRequest(db, requestId); if (json(saved.prepared) !== json(receipt)) throw Error('生图请求内容已变化,请重新准备'); + return saved; } saveImageRequest(receipt) { @@ -251,6 +270,16 @@ export class ProjectRepository { return this.#open(db => this.#readRequest(db, requestId)); } + #candidateSet(db, slotId, id) { + return db.prepare(`SELECT request_id FROM image_requests WHERE ${scopeWhere} AND slot_id = ? + AND json_extract(prepared_json, '$.candidateSet.id') = ? ORDER BY rowid`) + .all(...this.scope, slotId, id).map(row => this.#readRequest(db, row.request_id)); + } + + candidateSet(slotId, id) { + return this.#open(db => this.#candidateSet(db, slotId, id)); + } + claimImageRequest({ requestId, expectedRevision, expectedHash }, binding, pendingGeneration) { return this.#open(db => transaction(db, () => { const request = this.#readRequest(db, requestId); @@ -262,16 +291,30 @@ export class ProjectRepository { const journal = previous?.binding === binding ? structuredClone(previous) : { binding, items: {} }; const slotId = request?.slotId ?? journal.preparedRequests?.[requestId]?.slotId; if (!slotId) throw Error('生图请求不属于本轮工作画布或委托图位'); - const pending = pendingGeneration(journal); - if (pending || request && request.state !== 'prepared') return { journal, pending, request, claimed: false }; + const item = journal.items[slotId] ??= {}; + const sameOperation = item.pendingGenerations?.[requestId]; + if (sameOperation || request && request.state !== 'prepared') { + return { journal, pending: sameOperation, request, claimed: false }; + } + const priorUnknown = Object.values(item.pendingGenerations ?? {}).find(original => { + const prior = this.#readRequest(db, original.candidateId); + return prior?.state === 'unknown' && (!request?.prepared.candidateSet || + prior.prepared.candidateSet?.id !== request.prepared.candidateSet.id); + }); + const pending = pendingGeneration?.(journal) ?? priorUnknown; + if (pending) return { journal, pending, request, claimed: false }; const operationId = request?.operationId ?? requestId; if (request) { + const set = request.prepared.candidateSet; + if (set && this.#candidateSet(db, slotId, set.id).every(candidate => candidate.frozenAt === null)) { + item.autoCandidateSetId = set.id; + } db.prepare(`UPDATE image_requests SET state = 'dispatching', frozen_at = COALESCE(frozen_at, ?) WHERE ${scopeWhere} AND request_id = ?`).run(Date.now(), ...this.scope, requestId); } // Old drafts carry only the prompt and still rely on the native revision/hash check. const original = { candidateId: requestId, operationId, kind: 'frozen-image' }; - journal.items[slotId] = { ...journal.items[slotId], pendingOperation: original, state: 'dispatching' }; + (item.pendingGenerations ??= {})[requestId] = original; this.#writeLedger(db, journal, previous); return { journal, original, claimed: true }; })); diff --git a/apps/detail-agent-pi/src/skills/product-image-sources/SKILL.md b/apps/detail-agent-pi/src/skills/product-image-sources/SKILL.md index 2ad6d25a..1e1b07b2 100644 --- a/apps/detail-agent-pi/src/skills/product-image-sources/SKILL.md +++ b/apps/detail-agent-pi/src/skills/product-image-sources/SKILL.md @@ -8,6 +8,8 @@ description: Use product image sources and Image Request tools in PhotoCraft. 从本项目企业 Skill 及其引用取得图位制作、素材选择、审稿和返工规则。用 `read_production_knowledge` 回读已锁定的文件,工具回执会注明版次。 - `read_slot_images` 读取实拍、模板参考和候选。`use_product_image` 可直接用原片或指定裁切区域。 +- 按已发布规则撰写完整的 `prompt`,包括商品外观、构图、颜色、参考用途和返工要求。用 `referenceIndexes` 指定发送的原片及顺序,按需指定模板参考、画幅规格或实拍合成。实拍合成时,提示词描述在模板场景中擦除旧商品,本款实拍由客户端合成。 - 审阅 `prepare_image_request` 回执中的正式文本、参考顺序与模型参数。用该回执的 `requestId`、`revision` 和 `requestSpecHash` 确认 `dispatch_image_request` 的 `requestId`、`expectedRevision` 和 `expectedHash`。 +- `plan_production` 返回 `autoAdoptionPolicy` 时,按 `candidateCount` 准备同批样本。第二张起传入首张的 `candidateSet.id` 和相同的正式请求。备齐后分别确认派发,完成后将整批编号交给 `check_image_slots`。验完会自动采用合格图,全部退回时可在图位回执查看待返工记录。 - `review_image_slots` 读取候选及已有结论,`check_image_slots` 委托独立审稿。返工可带原候选号和具体改动。用 `reconcile_image_slots` 查看原请求的结果。 - 用 `native_catalog`、`native_call` 在模板允许的范围内调整画布。用 `read_output_screen` 回看实际图框与文字。 diff --git a/apps/detail-agent-pi/test/production-operations.test.mjs b/apps/detail-agent-pi/test/production-operations.test.mjs index e9718c77..13fa3421 100644 --- a/apps/detail-agent-pi/test/production-operations.test.mjs +++ b/apps/detail-agent-pi/test/production-operations.test.mjs @@ -46,6 +46,139 @@ async function generateAndWait(actions, {source,...request}) { return generation[0]; } +test('P07 waits for both original images and persists the automatic adoption decision',async t=>{ + for(const scenario of [ + {verdicts:['pass','revise'],winner:0,reason:'only_pass',recoverA:true}, + {verdicts:['pass','pass'],winner:1,reason:'policy_priority'}, + {verdicts:['revise','revise'],winner:null,reason:'all_rejected'}, + ])await t.test(scenario.reason,async t=>{ + const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-p07-')); + t.after(()=>cleanup(dir)); + const store=productionStore(dir); + const policy={version:'studio-review-v3',candidateCount:2,priorityChecks:['templateStyle']}; + const ledger=store.ledger('detail','oak'); + const slotId='main-photo'; + const posts=[],placements=[],seen=[]; + const originals=new Map(); + const bothStarted=Promise.withResolvers(), complete=Promise.withResolvers(); + const image={type:'image',mimeType:'image/png', + data:'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+j1f8AAAAASUVORK5CYII='}; + const digest='a'.repeat(64); + const canvas={ + workflowRead:async()=>({available:true,canvasFirst:true,outputId:'detail',productVariantId:'oak', + template:{contentHash:'studio',production:{autoAdoptionPolicy:policy}},totalSlots:1,slots:[{id:slotId,fieldId:'cover'}]}), + detailCopyFields:async()=>({fields:[]}),delta:async()=>{}, + async detailRecover(recoveredSlot,{candidateId}){ + assert.equal(recoveredSlot,slotId); + assert.equal(candidateId,posts[0]); + return {id:candidateId,status:'complete'}; + }, + async detailImages(_slot,candidateId,options){ + assert.equal(options.includeCandidateOriginal,true); + return {candidateId,referenceCount:1,candidateFile:{width:1,height:1,sha256:digest}, + candidateOriginal:originals.get(candidateId),images:[image,image]}; + }, + read:async()=>({revision:3}),requestWrite:async revision=>({allowed:true,revision}), + async workflowExecute({intent,operationId,candidateId}){ + assert.equal(intent,'adopt_candidate'); + placements.push({operationId,candidateId}); + return {phase:'submitted',operationId,candidateId}; + }, + async workflowPoll(operationId){ + return {...placements.at(-1),operationId,phase:'complete'}; + }, + }; + const host={canvas,store,productionGoal:{outputId:'detail',variantId:'oak'}, + async runDetailAgent(_slot,_system,prompt,tools,images){ + const {candidateId}=JSON.parse(prompt); + const index=posts.indexOf(candidateId); + assert.equal(images[1],originals.get(candidateId)); + seen.push(candidateId); + await tools[0].execute('review-fixture',{candidateId,verdict:scenario.verdicts[index], + checks:{structure:true,color:true,composition:true,evidence:true,templateStyle:index===1}, + reason:index===0?'原图能看到桌脚':'原图中能看到桌脚与完整布景'}); + }, + }; + imageBridge(host,async(_request,id)=>{ + posts.push(id); + assert.ok(ledger.read().items[slotId].pendingGenerations[id]); + if(posts.length===2)bothStarted.resolve(); + await complete.promise; + originals.set(id,{...image}); + return {status:scenario.recoverA&&id===posts[0]?'unknown':'complete',id}; + }); + let actions=await openProductionOperations(host); + assert.deepEqual((await actions.plan_production()).autoAdoptionPolicy,policy); + const input={slotId:'cover',prompt:'保留同款原片的轮廓。\r\n窗侧光。'}; + const a=await actions.prepare_image_request(input); + const b=await actions.prepare_image_request({...input,candidateSetId:a.candidateSet.id}); + assert.equal(a.requestSpecHash,b.requestSpecHash); + assert.equal(a.spec.prompt,b.spec.prompt); + assert.notEqual(a.operationId,b.operationId); + if(scenario.reason==='policy_priority'){ + await actions.prepare_image_request({...input,prompt:'备选构图草案'}); + } + const ids=[a.requestId,b.requestId]; + await Promise.all([actions.dispatch_image_request(approve(a)),actions.dispatch_image_request(approve(b))]); + await bothStarted.promise; + assert.equal((await actions.dispatch_image_request(approve(a))).phase,'already_running'); + assert.deepEqual(Object.keys(ledger.read().items[slotId].pendingGenerations),ids); + complete.resolve(); + await actions.close(); + actions=await openProductionOperations(host); + if(scenario.recoverA){ + assert.equal((await actions.dispatch_image_request(approve(a))).pendingOriginal,a.requestId); + const [recovered]=await actions.reconcile_image_slots({slotIds:[slotId]}); + assert.equal(recovered.operationId,a.operationId); + assert.equal(recovered.phase,'complete'); + } + for(const draft of [a,b])await actions.dispatch_image_request(approve(draft)); + await actions.close(); + assert.deepEqual(posts,ids); + const [first]=await actions.check_image_slots({wait:true,candidates:[{slotId,candidateId:a.requestId}]}); + assert.equal(first.adoption,undefined); + assert.deepEqual(placements,[]); + if(scenario.reason==='policy_priority'){ + const original=originals.get(b.requestId); + originals.delete(b.requestId); + const [missing]=await actions.check_image_slots({wait:true,candidates:[{slotId,candidateId:b.requestId}]}); + assert.match(missing.error,/原文件/u); + assert.deepEqual(placements,[]); + originals.set(b.requestId,original); + } + const [second]=await actions.check_image_slots({wait:true,candidates:[{slotId,candidateId:b.requestId}]}); + assert.deepEqual(seen,ids); + assert.equal(second.adoption.reason,scenario.reason); + assert.equal(second.adoption.actor,'agent'); + assert.equal(second.adoption.policyVersion,policy.version); + assert.deepEqual(second.adoption.basis.map(row=>row.candidateId),ids); + await actions.close(); + const reopened=await openProductionOperations(host); + const {pictures:[{record}]}=await reopened.review_image_slots({slotIds:[slotId]}); + const persisted=record.autoAdoptions[a.candidateSet.id]; + assert.equal(persisted.policyVersion,policy.version); + assert.equal(persisted.actor,'agent'); + const {pictures:[summary]}=await reopened.review_image_slots({}); + assert.equal(summary.state,scenario.winner===null?'needs_rework':'applied'); + if(scenario.winner===null){ + assert.equal(persisted.state,'needs_rework'); + assert.deepEqual(placements,[]); + }else{ + const winner=ids[scenario.winner]; + assert.equal(persisted.state,'adopted'); + assert.equal(persisted.candidateId,winner); + assert.equal(placements.length,1); + const adopted=ledger.repository.candidateEvidence(slotId,winner).find(row=>row.kind==='adoption').detail; + assert.equal(adopted.actor,'agent'); + assert.equal(adopted.policyVersion,policy.version); + assert.equal(adopted.assetSha256,digest); + assert.equal(adopted.operationId,placements[0].operationId); + assert.equal(adopted.reason,scenario.reason); + } + await reopened.close(); + }); +}); + test('a malformed slot reference does not strand the other explicitly delegated slots',async t=>{ const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-')); t.after(()=>cleanup(dir)); @@ -377,7 +510,7 @@ test('a lost native acknowledgement can be recovered with the saved generation o const host={canvas,store,productionGoal:{outputId:'detail',variantId:'ink'}}; imageBridge(host,async(_args,operationId)=>{ submissions.push(operationId); - const pending=journal().items[slotId].pendingOperation; + const pending=journal().items[slotId].pendingGenerations[operationId]; assert.equal(pending.operationId,operationId); assert.equal(pending.candidateId,operationId); throw new BridgeError('画布连接中断,原操作不会重发','transport_interrupted',{dispatched:true}); @@ -400,7 +533,7 @@ test('a lost native acknowledgement can be recovered with the saved generation o assert.equal(recovered.operationId,originalId); assert.deepEqual(recoveries,[{slot:slotId,candidateId:originalId},{slot:slotId,candidateId:originalId}]); assert.deepEqual(submissions,[originalId]); - assert.equal(journal().items[slotId].pendingOperation,null); + assert.deepEqual(journal().items[slotId].pendingGenerations,{}); }); test('Pi chooses each image operation and keeps an unresolved paid request on its original',async t=>{ @@ -563,13 +696,12 @@ test('Pi chooses each image operation and keeps an unresolved paid request on it assert.equal(overview.state,'unknown'); assert.equal(overview.record,undefined); assert.equal(overview.candidates,undefined); - assert.equal(exact.pendingOperation.operationId,first.operationId); + assert.equal(exact.pendingGenerations[first.candidateId].operationId,first.operationId); assert.match(exact.prompt,/场景桌面上的一盏灯/u); assert.equal((await generateAndWait(actions,{slotId:'lamp',source:'generate',prompt:'更换灯罩角度'})).phase,'unknown'); assert.equal(submissions.length,1); const ledger=host.store.ledger(outputId,variantId); const legacy=ledger.read(); - delete legacy.items['lamp-photo'].pendingOperation.candidateId; legacy.items['base-photo']={state:'unknown',pendingOperation:{run:'prior-run',documentId:23, operationId:'another-operation',intent:'generate_candidate',candidateId:null},candidateId:'unrelated-older-candidate'}; ledger.repository.replaceLedger(legacy); diff --git a/apps/detail-agent-pi/test/project-repository.test.mjs b/apps/detail-agent-pi/test/project-repository.test.mjs index f1b482a7..9ecb2ddc 100644 --- a/apps/detail-agent-pi/test/project-repository.test.mjs +++ b/apps/detail-agent-pi/test/project-repository.test.mjs @@ -126,9 +126,9 @@ test('P03 the production bridge sends only the reviewed identity after an atomic assert.equal(saved.state, 'dispatching'); assert.equal(typeof saved.frozenAt, 'number'); assert.deepEqual(saved.prepared.spec, draft.spec); - assert.equal(pending(repo.readLedger()).operationId, draft.operationId); + assert.equal(repo.readLedger().items.front.pendingGenerations[draft.requestId].operationId, draft.operationId); const portable = JSON.parse(await fs.readFile(path.join(dir, 'production-detail-oak.json'), 'utf8')); - assert.equal(pending(portable).operationId, draft.operationId); + assert.equal(portable.items.front.pendingGenerations[draft.requestId].operationId, draft.operationId); assert.equal(portable.preparedRequests[draft.requestId].prompt, draft.spec.prompt); return { status: 'complete', id: draft.requestId, materialTaskId: draft.requestId }; }, @@ -193,20 +193,21 @@ test('P06 plans keep dynamic field bindings while shared material has one source test('P07 two intentionally equivalent samples keep distinct operations and actual reviews', async t => { const { open, repo } = await fixture(t); const a = request('sample-a'); - const b = { ...request('sample-b'), slotId: 'side' }; + const b = request('sample-b'); assert.equal(a.requestSpecHash, b.requestSpecHash); for (const draft of [a, b]) { repo.saveImageRequest(draft); - assert.equal(repo.claimImageRequest(approve(draft), binding, journal => journal.items[draft.slotId]?.pendingOperation).claimed, true); - repo.updateLedger(binding, journal => { journal.items[draft.slotId].pendingOperation = null; }, { + assert.equal(repo.claimImageRequest(approve(draft), binding, pending).claimed, true); + } + assert.deepEqual(Object.keys(open().readLedger().items.front.pendingGenerations), [a.requestId, b.requestId]); + for (const draft of [a, b]) { + repo.updateLedger(binding, journal => { delete journal.items[draft.slotId].pendingGenerations[draft.requestId]; }, { receipt: [draft.requestId, 'complete', { status: 'complete' }], evidence: [draft.slotId, draft.requestId, 'review', { candidateId: draft.requestId, decision: 'pass' }], }); } assert.notEqual(open().readImageRequest(a.requestId).operationId, open().readImageRequest(b.requestId).operationId); - repo.recordCandidate('side', b.requestId, 'adoption', { actor: 'agent', policyVersion: 'auto-v1' }); - assert.deepEqual(repo.candidateEvidence('side', b.requestId).map(row => row.kind), ['review', 'adoption']); - assert.equal(repo.candidateEvidence('side', b.requestId).at(-1).detail.actor, 'agent'); + assert.deepEqual(repo.candidateEvidence('front', b.requestId).map(row => row.kind), ['review']); }); test('P08 concurrent workers claim one operation and a restarted worker retains the original', async t => { diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs index 1b57b71c..58bcfd66 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs @@ -180,28 +180,6 @@ fn slot_text_regions(state: &Value, id: &str, variant_id: &str) -> Vec { }).collect() } -fn scene_copy_space(regions: &[Value]) -> Option { - let positions: Vec<_> = regions.iter().filter_map(|region| { - let [left, top, right, bottom]: [u8; 4] = serde_json::from_value(region["bounds"].clone()).ok()?; - let horizontal = match u16::from(left) + u16::from(right) { - 0..=64 => "偏左", - 65..=134 => "居中", - _ => "偏右", - }; - let vertical = match u16::from(top) + u16::from(bottom) { - 0..=64 => "上部", - 65..=134 => "中部", - _ => "下部", - }; - Some(format!("{vertical}{horizontal}")) - }).collect(); - if positions.is_empty() { return None; } - Some(format!( - "先确定镜头位置和排字留白。图框里的这些区域只保留连续、低反差的现场背景:{}。窗侧光可以经过留白。将人物、商品、窗框、窗帘边缘、桌沿和植物轮廓摆在留白范围外。现场光影和背景连续铺满整个画幅,画面不绘制文字、坐标、色块、虚线、引线、尺寸数字或辅助图形。画布另行排字。", - positions.join(";") - )) -} - fn text_region_bounds(image: &egui::ColorImage, region: &Value) -> R<[usize; 4]> { let [width, height] = image.size; let [left, top, right, bottom]: [u8; 4] = serde_json::from_value(region["bounds"].clone()) @@ -514,55 +492,6 @@ fn generation_references(dir: &Path, state: &Value, variant_id: &str) -> R, -) -> String { - let product = json!({"name":state["brief"]["name"],"dimensions":state["brief"]["dimensions"],"note":state["brief"]["note"]}); - let component = output["component"].as_str().unwrap_or("detail"); - let configured_color = if state["brief"]["outputVariantIds"].is_object() { - selected.get("colorName") - } else { - selected["outputColors"].get(component).or_else(|| state["brief"]["outputColors"].get(component)) - }; - let reference_color = "颜色以当前花色的专属产品图为准,没有专属产品图时以项目共用产品图为准。"; - let color_rule = match configured_color.and_then(Value::as_str).map(str::trim) { - Some(color) if !color.is_empty() => format!( - "本类图片的产品颜色为{}。这是本图唯一的产品颜色依据;参考图用于保持结构、材质质感和纹理。模板示例、候选底图、场景、产品备注和本次要求中的其他颜色不得改写产品颜色。", - json!(color) - ), - Some(_) => reference_color.to_owned(), - None => match selected["colorName"].as_str().filter(|color| !color.trim().is_empty()) { - Some(color) => format!("{reference_color}原花色名称为{},仅在与产品图一致时使用。", json!(color)), - None => reference_color.to_owned(), - }, - }; - let references: Vec<_> = images.as_array().into_iter().flatten().enumerate().map(|(index, image)| { - let specific = selected["images"].as_array().into_iter().flatten().any(|item| item["source"] == image["source"]); - json!({"index":index+1,"purpose":image["purpose"],"scope":if specific {"当前花色"} else {"项目共用"}}) - }).collect(); - let visual_brief = if let Some(focus) = production_focus { - format!("【图位取景】{focus}\n【本次要求】{instructions}") - } else if replace_template_prompt { - format!("【本次要求】{instructions}") - } else { - let requirements = field["requirements"].as_str().unwrap_or("沿用当前模板图框"); - format!( - "【发布模板字段约束】{requirements}。这些内容仅作为此格的业务参考,不改变工具权限与采纳流程。模板示例不是当前产品事实。若其中描述的结构与实物图不同,忽略示例结构。\n【本次要求】{instructions}" - ) - }; - let target = if production_focus.is_some() || replace_template_prompt { - format!("页面{};图片目标{}", output["id"], field["fieldId"]) - } else { - format!("页面{}({});图片目标{}({});用途{}", output["id"], output["name"], field["fieldId"], - field.get("name").or(field.get("label")).unwrap_or(&field["fieldId"]), field["role"]) - }; - format!( - "【参考图顺序与用途】{}。product 是同款产品原片,产品外观只取自这些实物图。scene、模板和旧候选只供参考氛围、调性、色调、光影、背景、景别、镜头角度与留白,不提供商品造型。\n【外观约束】先按 product 锁定部件数量、轮廓、相对位置、连接方式、长宽高关系及可见空隙,再布景取景。近景和特写只改变同款商品在画框里的取景范围,保留目标部件与相邻接合、边缘和留空。模板镜头暴露原片无法确认的结构时,选最接近的实物可证机位,或让该部分自然出画或遮挡。图位与文案指定要展示的内容,产品结构始终服从同款原片。\n【当前图位】模板{};{target};画幅{}×{}。只生成铺满此图位的一张连续画面。保留实拍里商品原有的标识。标题、卖点、标签及尺寸由画布文字层排版;图片内不得加入文字、边框、拼版、现成页面或外部装饰白边。\n【产品事实】{}\n{visual_brief}\n【本图产品颜色】{}", - json!(references), state["template"]["name"], field["frame"]["width"], field["frame"]["height"], product, color_rule - ) -} - // Compatibility for older single-output drafts that were saved with empty copy. fn clear_sample_copy(layers: &mut [photocraft_doc::Layer]) { use photocraft_doc::LayerContent; @@ -602,10 +531,6 @@ fn prepare_product_template(native: &mut Document, meta: &mut Value, pack: &Valu Ok(()) } -fn refinement_prompt(base_index: usize) -> String { - format!("\n第{base_index}张是旧候选,只用来保持原来的场景、镜头和摆放。产品本体始终以 product 参考图为准,即使用户本次没有明确指出,也要删除旧候选添加的部件、恢复正确结构和空隙。不能从旧候选沿用或推测产品结构;保留用户没有要求改动的非产品部分。产品颜色始终遵守【本图产品颜色】。") -} - #[cfg(test)] mod prompt_tests { use super::*; @@ -630,24 +555,6 @@ mod prompt_tests { assert!(preview.pixels[3*12..9*12].iter().all(|pixel| *pixel == egui::Color32::BLACK)); assert!(preview.pixels[9*12..].iter().all(|pixel| *pixel == egui::Color32::WHITE)); } - #[test] - fn prompt_editor_uses_the_submitted_text_once_and_keeps_product_constraints() { - let state = json!({"brief":{"outputVariantIds":{"detail":["wood"]}}}); - let output = json!({"component":"detail"}); - let field = json!({"requirements":"模板内置提示词","frame":{"width":400,"height":500}}); - let selected = json!({"colorName":"原木色"}); - for request in ["模板内置提示词", "模板内置提示词,改用侧光", "只拍桌面左侧"] { - let prompt = candidate_prompt(&state, &output, &field, &selected, &json!([]), request, true, None); - assert_eq!(prompt.matches(request).count(), 1); - assert_eq!(prompt.matches("模板内置提示词").count(), usize::from(request.contains("模板内置提示词"))); - assert!(prompt.contains("400×500") && prompt.contains("长宽高关系")); - assert!(prompt.contains("本类图片的产品颜色为\"原木色\"")); - } - let workflow_prompt = candidate_prompt(&state, &output, &field, &selected, &json!([]), "改用侧光", false, None); - assert!(workflow_prompt.contains("【发布模板字段约束】模板内置提示词")); - assert!(workflow_prompt.contains("【本次要求】改用侧光")); - } - #[test] fn a_fresh_product_draft_clears_nested_and_unmapped_copy_without_changing_layout() { use photocraft_doc::{Layer, LayerContent, TextLayer}; @@ -673,19 +580,6 @@ mod prompt_tests { assert_eq!(specified_image_ratio(&json!({"requirements":"图框980×1200"})), None); } - #[test] - fn scene_instructions_identify_both_native_text_regions() { - let regions = [ - json!({"field":"M07-T01","bounds":[46,11,94,17]}), - json!({"field":"M07-T02","bounds":[67,28,94,35]}), - ]; - let instruction = scene_copy_space(®ions).unwrap(); - assert!(instruction.contains("上部偏右")); - assert!(!instruction.contains('%')); - assert!(instruction.contains("窗框、窗帘边缘、桌沿和植物轮廓摆在留白范围外")); - assert_eq!(scene_copy_space(&[]), None); - } - #[test] fn rejects_new_crossing_edges_but_preserves_template_shadows() { @@ -726,14 +620,6 @@ mod prompt_tests { assert!(samples.pixels.iter().all(|pixel| [egui::Color32::WHITE, wood, egui::Color32::DARK_GRAY].contains(pixel))); } - #[test] - fn edits_prioritize_real_structure_over_the_previous_candidate() { - let instruction = refinement_prompt(3); - assert!(instruction.contains("第3张是旧候选")); - assert!(instruction.contains("产品本体始终以 product 参考图为准")); - assert!(instruction.contains("删除旧候选添加的部件")); - } - #[test] fn cached_template_prompt_uses_only_the_pinned_image_description() { let temp = tempfile::tempdir().unwrap(); @@ -761,40 +647,6 @@ mod prompt_tests { assert_eq!(editable_image_prompt(&imported, &json!("S02"), None).as_deref(), Some("新包原始描述")); } - #[test] - fn copywriting_candidate_prompt_separates_slot_and_reference_roles() { - let common = json!({"source":"local:scene-asset","purpose":"scene"}); - let product = json!({"source":"local:product-asset","purpose":"product"}); - let state = json!({"template":{"name":"电脑桌"},"brief":{"name":"书桌","dimensions":{"length":"120","width":"60","height":"75","unit":"cm"}}}); - let selected = json!({"name":"橡木色","images":[product]}); - let prompt = candidate_prompt(&state,&json!({"id":"S02","name":"桌腿细节"}), - &json!({"fieldId":"S02-I03","name":"桌腿","role":"结构细节","frame":{"width":400,"height":500}}), - &selected,&json!([common,product]),"背景简洁", false, None); - assert!(prompt.contains("S02-I03") && prompt.contains("结构细节")); - assert!(prompt.contains("400×500") && prompt.contains("长宽高关系")); - assert!(prompt.contains("\"index\":1,\"purpose\":\"scene\",\"scope\":\"项目共用\"")); - assert!(prompt.contains("\"index\":2,\"purpose\":\"product\",\"scope\":\"当前花色\"")); - assert!(!prompt.contains("local:")); - assert!(prompt.contains("背景简洁")); - assert!(prompt.starts_with("【参考图顺序与用途】")); - assert!(prompt.contains("产品外观只取自这些实物图")); - assert!(prompt.contains("近景和特写只改变同款商品在画框里的取景范围")); - assert!(prompt.contains("选最接近的实物可证机位")); - } - - #[test] - fn production_image_prompt_uses_the_registered_scene_before_legacy_names() { - let state = json!({"template":{"name":"固定主图"},"brief":{"name":"餐椅"}}); - let page = json!({"id":"M08","name":"会客阅读","component":"main_images"}); - let field = json!({"fieldId":"M08-I01","name":"阅读场景","role":"阅读动作", - "requirements":"手持书本阅读","frame":{"width":1440,"height":1920}}); - let prompt = candidate_prompt(&state, &page, &field, &Value::Null, &json!([]), - "窗侧自然光", false, Some("双手扶持茶壶斟茶")); - assert!(prompt.contains("M08-I01")); - assert!(prompt.contains("双手扶持茶壶斟茶")); - assert!(prompt.contains("窗侧自然光")); - assert!(!prompt.contains("阅读")); - } } fn variants(dir: &Path, brief: &Value, previous: Option<&Value>) -> R> { let empty = Vec::new(); @@ -1614,7 +1466,9 @@ fn local_pending(dir: &Path, state: &Value, except: Option<&Value>, batch: Optio && !except.is_some_and(|binding| record["binding"] == *binding && matches!(record["phase"].as_str(), Some("prepared" | "dispatched"))) && !batch.is_some_and(|binding| { let sibling = &record["binding"]; - sibling["detailBatch"] == true && sibling["slotId"] != binding["slotId"] + sibling["detailBatch"] == true && (sibling["slotId"] != binding["slotId"] + || sibling["frozenImageRequest"] == true && binding["frozenImageRequest"] == true + && sibling["taskId"] != binding["taskId"]) && (sibling["variantId"] == binding["variantId"] && sibling["templateHash"] == binding["templateHash"] || product_slot_binding(state, binding) && product_slot_binding(state, sibling)) }) @@ -2010,6 +1864,7 @@ impl Backend { let mut text_region_edge_obstructions = None; let mut check_generated_marks = false; let mut bare_candidate = None; + let mut candidate_original = None; let mut candidate_file = None; if let Some((candidate, record)) = candidate_id.zip(candidate_record) { if !candidate_available(&record) || record["binding"]["slotId"] != slot || record["binding"]["variantId"] != variant_id { @@ -2026,8 +1881,12 @@ impl Backend { } else { Some(source?.1) }; - candidate_file = raster.as_ref().map(|image| - json!({"width":image.width(),"height":image.height(),"hasTransparency":image.has_translucency()})); + let inspect_original = target["includeCandidateOriginal"] == true && adopted_canvas.is_none(); + candidate_file = raster.as_ref().map(|image| { + let mut file = json!({"width":image.width(),"height":image.height(),"hasTransparency":image.has_translucency()}); + if inspect_original { file["sha256"] = record["artifact"]["sha256"].clone(); } + file + }); let (mut preview, original_preview) = if let Some(canvas) = adopted_canvas { if !is_production_review || canvas.id.0 != doc { return Err("当前画布不属于已回填候选的复验项目".into()); } let mapped = mapped_slot(&state, slot, &variant_id).ok_or("已回填图位没有当前模板映射")?; @@ -2038,6 +1897,10 @@ impl Backend { let pixels = raster.ok_or("候选原文件不可读取")?; (super::images::agent_color_preview(pixels), None) }; + if inspect_original { + candidate_original = Some(json!({"type":"image", + "data":photocraft_ui_egui::jiansun::reference_jpeg(&preview,1024)?,"mimeType":"image/jpeg"})); + } if is_production_review { review_frame = slot_frame(field, mapped_slot(&state, slot, &variant_id)) .ok_or("候选缺少当前图位的实际图框")?; @@ -2117,7 +1980,7 @@ impl Backend { "textRegions":text_regions,"textRegionPreview":text_region_preview, "textRegionEdgeObstructions":text_region_edge_obstructions, "checkGeneratedMarks":check_generated_marks,"bareCandidate":bare_candidate, - "candidateFile":candidate_file,"candidatePrompt":candidate_prompt, + "candidateFile":candidate_file,"candidateOriginal":candidate_original,"candidatePrompt":candidate_prompt, "originalReferenceIndex":original_reference_index,"originalCropOutlined":original_crop_outlined,"hasWhiteTopBand":has_white_top_band, "hasWhiteBottomBand":has_white_bottom_band,"whiteSideBands":white_side_bands, "hasSwatchBackdrop":has_swatch_backdrop,"groundContactDetail":ground_contact_detail,"actionReviewDetail":action_review_detail, @@ -3226,58 +3089,71 @@ impl Backend { input["variantId"] = binding["scope"]["variantId"].clone(); input["detailBatch"] = json!(true); input["detailWorkspace"] = binding["scope"].clone(); - input["prepareRequest"] = json!(true); - return self.canvas_workspace_action("slot-append", &input, events, ctx).map_err(BridgeFailure::from); + return self.canvas_workspace_action("slot-prepare-image", &input, events, ctx).map_err(BridgeFailure::from); } if phase != "dispatch" { return Err("生图请求动作无效".into()); } + let receipt = self.dispatch_canvas_image_request(doc, &dir, request, Some(&binding["scope"]), events, ctx)?; + if receipt["status"].is_string() { + let snapshot = operation_receipt(self.canvas_workspace_result(doc, &dir) + .map_err(|error| BridgeFailure::new("image_request_failed", false, true, error))?, Some(receipt.clone()), None); + let _ = events.send(Event::Json("slot-append".into(), Ok(snapshot))); + ctx.request_repaint(); + } + Ok(receipt) + } + + fn dispatch_canvas_image_request(&mut self, doc: u64, dir: &Path, request: &Value, scope: Option<&Value>, + events: &mpsc::Sender, ctx: &egui::Context) -> Result { let id = uuid(&request["requestId"], "生图请求")?; let (task, _dispatch) = { let _guard = sync::context_guard(); - let mut task = super::images::read_image_request(&dir, &id)?; + let mut task = super::images::read_image_request(dir, &id)?; let belongs = task["doc"] == doc && task["accountScope"] == self.scope() && task["localProjectId"].as_str() == self.locations.get(&doc).map(String::as_str) - && task["origin"] == self.origin && task["outputScope"] == binding["scope"]["outputId"] - && task["slotBinding"]["slotId"] == request["slotId"] - && ["workspaceId","templateHash","structureHash","variantId"].iter().all(|field| - task["slotBinding"][*field] == binding["scope"][if *field=="workspaceId" {"id"}else{*field}]); + && task["origin"] == self.origin && task["slotBinding"]["slotId"] == request["slotId"] + && scope.is_none_or(|scope| task["outputScope"] == scope["outputId"] + && ["workspaceId","templateHash","structureHash","variantId"].iter().all(|field| + task["slotBinding"][*field] == scope[if *field=="workspaceId" {"id"}else{*field}])); if !belongs { return Err("生图请求不属于当前账户、项目、工作画布或图位".into()); } - super::images::freeze_image_request_locked(&dir, &mut task, request)?; - let Some(dispatch) = lock_candidate_dispatch(&dir, &id)? else { + super::images::freeze_image_request_locked(dir, &mut task, request)?; + let Some(dispatch) = lock_candidate_dispatch(dir, &id)? else { return Ok(json!({"phase":"running","candidateId":id})); }; (task, dispatch) }; let original_error = |error| BridgeFailure::new("image_request_failed", false, true, error); if task["phase"] != "prepared" { - return reconcile_candidate(&dir, &task).map(|record| candidate_receipt(&record)).map_err(original_error); + return reconcile_candidate(dir, &task).map(|record| candidate_receipt(&record)).map_err(original_error); } let slot = &task["slotBinding"]; - let state = load_detail_workspace(&dir)?; + let state = if slot["detailBatch"] == true { load_detail_workspace(dir)? } else { load(dir)? }; let record = &task["candidateRecord"]; - if !candidate_uses_current_inputs(&dir, &state, record, slot["variantId"].as_str().ok_or("花色缺失")?)? { + if !candidate_uses_current_inputs(dir, &state, record, slot["variantId"].as_str().ok_or("花色缺失")?)? { return Err("商品资料或制作依据已变化,请重新准备请求".into()); } - if candidate_path(&dir, &id)?.exists() { - let existing = read_candidate(&dir, &id)?; + if candidate_path(dir, &id)?.exists() { + let existing = read_candidate(dir, &id)?; if existing["phase"] != "prepared" || existing["retirement"].is_object() { return Ok(candidate_receipt(&existing)); } } else { - reserve(&dir, state, record)?; + reserve(dir, state, record)?; } - publish_prepared(events, self.canvas_workspace_result(doc, &dir)?)?; + let mut snapshot = self.canvas_workspace_result(doc, dir)?; + if let Some(operation) = record["workflowOperationId"].as_str() { + snapshot["workflowGeneration"] = json!({"operationId":operation, + "outputId":task["outputScope"],"candidate":candidate_receipt(record)}); + } + publish_prepared(events, snapshot)?; ctx.request_repaint(); - validate_image_context(&dir, Some(slot))?; + validate_image_context(dir, Some(slot))?; let call = self.image_job(None, &json!({"doc":doc,"frozenRequestId":id}), false, events, ctx); let dispatch_error = |error, backend: &Self| BridgeFailure::new("image_request_failed", false, backend.image_dispatch_may_have_started(doc, &id), error); - let (mut receipt, failure) = self.settle_image_candidate(&dir, doc, &id, slot, call, events, ctx) + let (mut receipt, failure) = self.settle_image_candidate(dir, doc, &id, slot, call, events, ctx) .map_err(|error| dispatch_error(error, self))?; if receipt["status"] == "failed" && let Some(message) = failure { receipt["message"] = json!(message); } - let snapshot = operation_receipt(self.canvas_workspace_result(doc, &dir).map_err(|error| dispatch_error(error, self))?, Some(receipt.clone()), None); - let _ = events.send(Event::Json("slot-append".into(), Ok(snapshot))); - ctx.request_repaint(); Ok(receipt) } @@ -3388,7 +3264,7 @@ impl Backend { next["structureHash"] = json!(hash(&json!([next["template"]["contentHash"], next["width"]]).to_string())); persist(&dir, next, expected)?; } - let batch = input["detailBatch"] == true && matches!(method, "slot-append" | "slot-adopt-prep"); + let batch = input["detailBatch"] == true && matches!(method, "slot-prepare-image" | "slot-append" | "slot-adopt-prep"); let mut state = if batch { load_detail_workspace(&dir)? } else { load(&dir)? }; if batch && input["detailWorkspace"] != json!({"id":state["id"],"templateHash":state["template"]["contentHash"], "structureHash":state["structureHash"],"outputId":state["activeOutput"],"variantId":state["activeVariantId"]}) @@ -3575,7 +3451,7 @@ impl Backend { } events.send(Event::SlotCanvas(Box::new(native), result)).map_err(|_| "工作台已关闭,模板骨架记录保留")?; if let Some(receipt) = view_receipt { return Ok(receipt); } - } else if method == "slot-append" { + } else if matches!(method, "slot-prepare-image" | "slot-append") { let variant_id = uuid(&input["variantId"], "花色")?; let id = input["slotId"].as_str().ok_or("请选择图片目标")?.to_owned(); let (output, field) = definition(&state, &id, &variant_id)?; @@ -3596,12 +3472,10 @@ impl Backend { field["frame"] = slot_frame(&field, mapped_slot(&state, &id, &variant_id)) .ok_or("请先打开对应模板画布,核对图片图层范围")?.clone(); let output = output.clone(); - let use_template_reference = input["useTemplateReference"] != false; - let replace_template_prompt = input["replaceTemplatePrompt"] == true || !use_template_reference; - if !replace_template_prompt { - let source = cached_prompt_mapping(&dir, &state["template"]); - field["requirements"] = json!(editable_image_prompt(&field, &output["id"], source.as_ref())); - } + let preparing = method == "slot-prepare-image"; + let use_template_reference = if preparing { input["useTemplateReference"] == true + || input["useSceneComposite"] == true && input["useTemplateReference"] != false } + else { input["useTemplateReference"] != false }; let instructions = input["instructions"].as_str() .filter(|value| !value.chars().any(|c| c.is_control() && !matches!(c, '\n' | '\r' | '\t'))) .ok_or("图片要求须为文本且不能含控制字符")?; @@ -3621,8 +3495,7 @@ impl Backend { attachments.insert(0, (json!({"id":parent,"purpose":"selected-candidate-edit-base"}), bytes)); } let mut creation = creation::load(&dir)?; - let selected = variant(&state, &variant_id)?; - let images = generation_references(&dir, &state, &variant_id)?; + let mut images = generation_references(&dir, &state, &variant_id)?; if input["useProductReference"] == true { if parent.is_some() || !attachments.is_empty() { return Err("使用产品原图只能添加新候选,请先关闭改图或清除临时参考图".into()); @@ -3649,13 +3522,20 @@ impl Backend { } return Ok(operation_receipt(self.canvas_workspace_result(doc, &dir)?, Some(candidate_receipt(&record)), None)); } - let preparing = input["prepareRequest"] == true; let attachment_refs = input.get("attachments").cloned().unwrap_or_else(|| json!([])); if !attachment_refs.as_array().is_none_or(Vec::is_empty) && input["projectId"].as_str() != self.locations.get(&doc).map(String::as_str) { return Err("附件所属项目已变化,请重新选择".into()); } - if !preparing && images.as_array().map_or(0, Vec::len) + attachments.len() > 8 { - return Err("产品参考图与临时附件合计最多8张".into()); + if let Some(indices) = input["referenceIndexes"].as_array() { + if input["useSceneComposite"] == true { + return Err("实拍合成只向模型发送模板原场景,请用 geometryReferenceIndex 指定本地合成原片".into()); + } + let selected = indices.iter().map(|value| { + let index = value.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or("参考图编号无效")?; + images.get(index).filter(|image| image["purpose"] == "product").cloned().ok_or("同款原图编号无效") + }).collect::, _>>()?; + if selected.is_empty() { return Err("正式生图至少需要一张同款产品参考图".into()); } + images = json!(selected); } let production_rule = if batch && state["productTemplates"].is_object() { production_profile::select(&state["template"], output["component"].as_str().unwrap_or_default())? @@ -3663,7 +3543,11 @@ impl Backend { .or_else(|| field.get("productionRule")) .filter(|rule| rule["source"] == "generate") } else { None }; - let scene = if use_template_reference && let Some(recipe) = production_rule.and_then(|rule| rule.get("sceneComposite")) { + let scene_recipe = production_rule.and_then(|rule| rule.get("sceneComposite")); + if input["useSceneComposite"] == true && (!use_template_reference || scene_recipe.is_none()) { + return Err("当前图位没有可用的实拍合成场景".into()); + } + let scene = if use_template_reference && (!preparing || input["useSceneComposite"] == true) && let Some(recipe) = scene_recipe { let recipe: super::scene_composite::Recipe = serde_json::from_value(recipe.clone()) .map_err(|_| "模板的实拍合成配置无效")?; recipe.validate()?; @@ -3677,18 +3561,14 @@ impl Backend { attachments = vec![(json!({"id":"original-scene","purpose":"template-layout"}), layout)]; Some((recipe, cutout)) } else { None }; - let fixed_layout = use_template_reference && batch && state["productTemplates"].is_object() && field["previewReference"].is_object(); - let reference_count = images.as_array().map_or(0, Vec::len) + attachments.len(); - if !preparing && scene.is_none() && fixed_layout && reference_count == 8 { - return Err("本图位需要同款原片和模板构图参考,请精简参考图后再制作".into()); + if use_template_reference && scene.is_none() && batch { + if let Some(bytes) = self.detail_layout_bytes(&field)? { + let file_id = field["previewReference"]["fileId"].as_str().ok_or("图位原参考身份无效")?; + attachments.push((json!({"id":format!("template-layout-{file_id}"),"purpose":"template-layout"}), bytes)); + } else if preparing { + return Err("当前图位没有可发送的模板参考图".into()); + } } - let layout_position = if use_template_reference && scene.is_none() && batch && (preparing || reference_count < 8) && let Some(bytes) = self.detail_layout_bytes(&field)? { - let position = reference_count + 1; - let reference = &field["previewReference"]; - let file_id = reference["fileId"].as_str().ok_or("图位原参考身份无效")?; - attachments.push((json!({"id":format!("template-layout-{file_id}"),"purpose":"template-layout"}), bytes)); - Some(position) - } else { None }; creation["brief"]["images"] = if scene.is_some() { json!([]) } else { images.clone() }; creation["generation"] = Value::Null; // Never inherit a different colour's legacy anchor. let (references, layers) = creation::reference_canvas_with_attachments(&creation, &dir, doc, &attachments)?; @@ -3699,48 +3579,19 @@ impl Backend { } else { uuid(&input["workflowOperationId"], "原生图操作")? }; - let layout_instructions = (use_template_reference && state["productTemplates"].is_object()) - .then(|| scene_copy_space(&slot_text_regions(&state, &id, &variant_id))).flatten() - .map(|layout| format!("{layout}\n{instructions}")); - let production_focus = production_rule.filter(|_| use_template_reference) - .and_then(|rule| rule["focus"].as_str().filter(|focus| !focus.trim().is_empty())); - let prefer_2k = input["detailBatch"] == true && scene.is_none() - && (input["prefer2k"] == true || production_rule.is_some_and(|rule| rule["clearDetail"] == true)); - let mut prompt = if let Some((recipe,_)) = &scene { recipe.prompt(instructions) } else { candidate_prompt( - &state, &output, &field, selected, &images, - layout_instructions.as_deref().unwrap_or(instructions), replace_template_prompt, production_focus, - ) }; - if parent.is_some() && scene.is_none() { - let base_index = images.as_array().map_or(0, Vec::len) + 1; - prompt.push_str(&refinement_prompt(base_index)); + if !preparing && candidate_path(&dir, &candidate)?.exists() { + let original = read_candidate(&dir, &candidate)?; + return Ok(operation_receipt(self.canvas_workspace_result(doc, &dir)?, Some(candidate_receipt(&original)), None)); } - let knowledge = if state["template"]["enterprise"].is_object() && input["detailBatch"] != true { - self.enterprise_template_request(json!({"action":"context","projectRoot":dir,"task":"image","brandName":state["brief"]["brandName"],"categoryName":state["brief"]["categoryName"],"templateId":state["template"]["id"],"releaseId":state["template"]["version"],"resourceSetId":state["template"]["enterprise"]["resourceSetId"], - "skillSources":state["template"]["skillSources"]}))?["context"].clone() - } else { Value::Null }; - if scene.is_none() { - let profile = &creation["designSnapshot"]["brand"]["profile"]; - let visual = profile["visualRules"].as_object().map(|values| - values.values().filter_map(Value::as_str).collect::>().join("\n")).unwrap_or_default(); - let brand = if knowledge.is_null() { - json!({"name":creation["brief"]["brandName"],"tone":profile["tone"],"visualRules":visual}) - } else { json!({"name":creation["brief"]["brandName"],"knowledge":knowledge}) }; - let guidance = json!({"brand":brand,"facts":creation["facts"]}); - prompt.push_str(&format!("\n【品牌与已确认资料】{guidance}")); - } - if prefer_2k { - prompt.push_str("\n局部证据请用稍宽的原始取景拍摄。保留目标部位与相邻的真实接合关系,将目标留在画面中心附近,并预留四周以便按最终图框裁切。"); - } - let layout_note = layout_position.map(|position| format!( - "\n【模板图位参考】第{position}张是本图位的取景底稿。保留参考的镜头角度、景别、主体占幅、布景与背景关系、光源方向、明暗和色调,以及人物位置、动作和排字留白。图位明确要求调整的构图和动作按本图位要求执行。将底稿中的旧商品换成本项目原片中的同款商品,其余保持原位,仅调整与新商品摆放、透视、接触和阴影有关的区域。旧商品轮廓、比例、部件、连接、空隙和表面一律以同款原片替换。清除模板文字、遮罩、虚线、尺寸和坐标。" - )); - let mut binding = new_binding(&state, &output, &field, &id, &variant_id, &candidate, &prompt); + let prefer_2k = input["prefer2k"] == true; + let mut binding = new_binding(&state, &output, &field, &id, &variant_id, &candidate, instructions); if input["detailBatch"] == true { binding["detailBatch"] = json!(true); } + if preparing { binding["frozenImageRequest"] = json!(true); } if !attachment_refs.as_array().is_none_or(Vec::is_empty) { binding["composerHash"] = json!(hash(&attachment_refs.to_string())); } - let mut record = json!({"version":2,"id":candidate,"sequence":state["candidates"].as_array().ok_or("候选索引无效")?.len()+1,"binding":binding,"phase":"prepared","modelId":model,"inputHash":input_hash(&dir,&state,&variant_id)?,"prompt":prompt,"instructions":instructions,"parentCandidateId":parent,"references":images,"requestId":null,"createdAt":now()}); + let mut record = json!({"version":2,"id":candidate,"sequence":state["candidates"].as_array().ok_or("候选索引无效")?.len()+1,"binding":binding,"phase":"prepared","modelId":model,"inputHash":input_hash(&dir,&state,&variant_id)?,"prompt":instructions,"instructions":instructions,"parentCandidateId":parent,"references":images,"requestId":null,"createdAt":now()}); if let Some(previous) = retry_of { record["retryOf"] = json!(previous); } if !attachment_refs.as_array().is_none_or(Vec::is_empty) { record["composerAttachments"] = attachment_refs; } - if !knowledge.is_null() { record["knowledge"] = knowledge.clone(); } + if let Some(operation) = input["workflowOperationId"].as_str() { record["workflowOperationId"] = json!(operation); } if let Some(previous) = input["reworkOf"].as_str() { let old = read_candidate(&dir, previous)?; if old["binding"]["slotId"] != id || old["binding"]["variantId"] != variant_id { @@ -3750,31 +3601,19 @@ impl Backend { record["reworkChange"] = input["reworkChange"].clone(); } let request_frame = image_ratio.map_or_else(|| field["frame"].clone(), |(width,height)| json!({"width":width,"height":height})); - let mut image_input = json!({"doc":doc,"revision":input["baseRevision"],"model":model, - "mode":if parent.is_some(){"refine"}else{"generate"},"text":prompt,"references":layers, - "templateLayoutNote":layout_note,"optionalLayoutReference":layout_position.is_some()&&!fixed_layout, - "slotBinding":binding,"slotFrame":request_frame,"prefer2k":prefer_2k}); - if preparing { - let mut origins = creation["brief"]["images"].as_array().cloned().unwrap_or_default(); - origins.extend(attachments.iter().map(|(asset,_)| json!({"source":asset["id"],"purpose":asset["purpose"]}))); - image_input["referenceOrigins"] = json!(origins); - image_input["candidateRecord"] = record; - image_input["outputScope"] = output["component"].clone(); - return self.image_job_with_scene(Some(Arc::new(references)), &image_input, false, events, ctx, scene); - } - let _dispatch = lock_candidate_dispatch(&dir, &candidate)?.ok_or("原生图操作正在处理,请核查原结果")?; - reserve(&dir, state, &record)?; - let mut snapshot = self.canvas_workspace_result(doc, &dir)?; - if let Some(operation) = input["workflowOperationId"].as_str() { - snapshot["workflowGeneration"] = json!({"operationId":operation, - "outputId":output["component"],"candidate":candidate_receipt(&record)}); - } - publish_prepared(events, snapshot)?; - ctx.request_repaint(); - let call = self.image_job_with_scene(Some(Arc::new(references)), &image_input, false, events, ctx, scene); - let (receipt, failure) = self.settle_image_candidate(&dir, doc, &candidate, &binding, call, events, ctx)?; + let mut origins = creation["brief"]["images"].as_array().cloned().unwrap_or_default(); + origins.extend(attachments.iter().map(|(asset,_)| json!({"source":asset["id"],"purpose":asset["purpose"]}))); + let image_input = json!({"doc":doc,"revision":input["baseRevision"],"model":model, + "mode":if parent.is_some(){"refine"}else{"generate"},"text":instructions,"references":layers, + "slotBinding":binding,"slotFrame":request_frame,"prefer2k":prefer_2k,"referenceOrigins":origins, + "candidateRecord":record,"outputScope":output["component"]}); + let draft = self.image_job_with_scene(Some(Arc::new(references)), &image_input, false, events, ctx, scene)?; + if preparing { return Ok(draft); } + // The native action is already confirmed by the operator. + let receipt = self.dispatch_canvas_image_request(doc, &dir, &json!({"requestId":draft["requestId"], + "expectedRevision":draft["revision"], "expectedHash":draft["requestSpecHash"], "slotId":id}), None, events, ctx)?; + if receipt["status"] == "failed" { operation_error = receipt["message"].as_str().map(str::to_owned); } candidate_result = Some(receipt); - operation_error = failure; } else if method == "slot-reuse" { let record = reuse_archived_candidate(&dir, state, input, None)?; if let Ok((mut reference, preview)) = self.agent_image_preview(&json!({"doc":doc,"taskId":record["id"]})) { @@ -4928,24 +4767,8 @@ mod tests { persist(&fixture.dir, state, rev).unwrap(); let state = load(&fixture.dir).unwrap(); let selected = &state["variants"][0]; - for (component, color) in [("detail", "胡桃木色"), ("sku_images", "雾灰色"), ("main_images", "暖白色")] { - let output = json!({"component":component}); - let prompt = candidate_prompt(&state, &output, &Value::Null, selected, &json!([]), "使用烟熏黑", false, None); - let rule = prompt.split("【本图产品颜色】").last().unwrap(); - assert!(rule.starts_with(&format!("本类图片的产品颜色为\"{color}\"。"))); - assert!(rule.contains("本次要求中的其他颜色不得改写")); - for other in ["胡桃木色", "雾灰色", "暖白色", "备用原木色", "烟熏黑"] { - if other != color { assert!(!rule.contains(other)); } - } - } - let output = json!({"component":"detail"}); - let mut selected = selected.clone(); - selected["outputColors"].as_object_mut().unwrap().remove("detail"); - let prompt = candidate_prompt(&state, &output, &Value::Null, &selected, &json!([]), "", false, None); - assert!(prompt.contains("本类图片的产品颜色为\"备用原木色\"")); - selected["outputColors"]["detail"] = json!(""); - let prompt = candidate_prompt(&state, &output, &Value::Null, &selected, &json!([]), "", false, None); - assert!(prompt.contains("以项目共用产品图为准") && !prompt.contains("备用原木色")); + assert_eq!(selected["outputColors"], json!({"detail":"胡桃木色","sku_images":"雾灰色","main_images":"暖白色"})); + assert_eq!(state["brief"]["outputColors"]["detail"], "备用原木色"); let mut malformed = state["brief"].clone(); malformed["variants"][0]["outputColors"]["detail"] = json!(42); assert!(creation::validated_brief(&malformed).is_err()); @@ -4975,11 +4798,8 @@ mod tests { assert!(!output_uses_variant(&state["brief"], "main_images", &oak)); assert!(output_uses_variant(&state["brief"], "sku_images", &oak)); assert!(output_uses_variant(&state["brief"], "sku_images", &white)); - for (component, id, color) in [("detail", &oak, "原木色"), ("main_images", &white, "暖白色"), ("sku_images", &oak, "原木色"), ("sku_images", &white, "暖白色")] { - let prompt = candidate_prompt(&state, &json!({"component":component}), &Value::Null, variant(&state,id).unwrap(), &json!([]), "", false, None); - assert!(prompt.contains(&format!("本类图片的产品颜色为\"{color}\"。"))); - assert!(!prompt.contains("旧版深灰色")); - } + assert_eq!(variant(&state, &oak).unwrap()["colorName"], "原木色"); + assert_eq!(variant(&state, &white).unwrap()["colorName"], "暖白色"); let mut invalid = state["brief"].clone(); invalid["outputVariantIds"]["main_images"] = json!([Uuid::new_v4().to_string()]); assert!(creation::validated_brief(&invalid).is_err()); @@ -5351,6 +5171,29 @@ mod tests { assert_eq!(pending_summary(&fixture.dir).unwrap().len(), 1); } + #[test] + fn distinct_frozen_requests_can_reserve_the_same_slot_while_the_first_is_pending() { + let fixture = fixture(); + let prepared = || { + let mut record = candidate(&fixture.dir, "prepared"); + record["binding"]["detailBatch"] = json!(true); + record["binding"]["frozenImageRequest"] = json!(true); + record + }; + let first = prepared(); + let second = prepared(); + assert_eq!(first["binding"]["slotId"], second["binding"]["slotId"]); + assert_eq!(first["binding"]["promptHash"], second["binding"]["promptHash"]); + assert_ne!(first["id"], second["id"]); + reserve(&fixture.dir, load(&fixture.dir).unwrap(), &first).unwrap(); + let state = load(&fixture.dir).unwrap(); + assert!(local_pending(&fixture.dir, &state, None, Some(&first["binding"])).unwrap()); + reserve(&fixture.dir, state, &second).unwrap(); + validate_image_context(&fixture.dir, Some(&second["binding"])).unwrap(); + validate_image_context(&fixture.dir, Some(&first["binding"])).unwrap(); + assert!(reserve(&fixture.dir, load(&fixture.dir).unwrap(), &first).is_err()); + } + #[test] fn an_unknown_product_image_keeps_its_original_scope_while_another_output_can_progress() { let fixture = fixture(); @@ -5786,6 +5629,12 @@ mod tests { let decoded = photocraft_codecs::decode(&jpeg).unwrap(); assert_eq!(decoded.dimensions(), (768, 48)); assert!(!decoded.layout().has_alpha()); + let mut target = target; + target["includeCandidateOriginal"] = json!(true); + let review = backend.read_detail_review_images(doc, &target, None).unwrap(); + assert_eq!(review["candidateFile"]["sha256"], digest); + let jpeg = STANDARD.decode(review["candidateOriginal"]["data"].as_str().unwrap()).unwrap(); + assert_eq!(photocraft_codecs::decode(&jpeg).unwrap().dimensions(), (1024, 64)); } #[test] diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs index 5664b493..9e373182 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_images.rs @@ -727,6 +727,9 @@ impl Backend { read_json(&dir.join("image-task.json"))? } } else { + if super::canvas_workspace::binding_is_canvas(&input["slotBinding"]) && !preparing { + return Err("画布生图须按已冻结的请求编号派发".into()); + } if input["slotBinding"].is_object() { if !preparing { super::template_slots::validate_dispatch(&dir, &input["slotBinding"])?; @@ -770,8 +773,6 @@ impl Backend { } let refs = input["references"].as_array().filter(|a| !a.is_empty()).ok_or("请选择参考图")?; let max_images = contract["maxImages"].as_u64().unwrap_or(1) as usize; - let omit_layout = !preparing && input["optionalLayoutReference"] == true && refs.len() == max_images.saturating_add(1); - let refs = if omit_layout { &refs[..max_images] } else { refs.as_slice() }; if refs.len() > max_images { return Err(format!("所选线路最多接收 {max_images} 张参考图,本次有 {} 张。请调整参考图后重新准备。", refs.len())); } @@ -830,20 +831,9 @@ impl Backend { if references.len() != 1 { return Err("实拍合成只发送模板场景去除旧商品".into()); } job_bytes(&dir, &files.join("scene-product.png"), cutout).map_err(|_| "实拍抠图保存失败,未提交")?; } - let prompt = if input["slotBinding"]["canvasFirst"] == true || scene.is_some() { - let note = (!omit_layout).then(|| input["templateLayoutNote"].as_str()).flatten().unwrap_or(""); - format!("{text}{note}") - } else { - let guidance = json!({"brand":input["brand"],"facts":input["facts"]}); - format!( - "【产品本体优先】只按本项目同款实物图保留外形、结构、部件连接、间隙、材质、比例及数量。场景图、旧候选或模板仅用于氛围、调性、色调、光影、景别、镜头角度和布景。近景和特写以同款实物为主体另行取景,未确认部位不补画。严格保留参考图中的产品颜色。\n生成一张产品图,保留实物可见的原有铭牌和固定标记,不编造模糊字样。标题、字幕、角标、水印和尺寸标注交给画布。各屏保持摄影风格与光线一致。\n项目:{}\n当前屏:{}\n项目规范与已确认事实(规范指导风格及版式,已确认事实与实物图提供商品依据):{guidance}\n要求:{text}", - doc.name, - input["screen"].as_str().unwrap_or("当前图片") - ) - }; - protocol::validate_prompt_length(&contract, &prompt)?; + protocol::validate_prompt_length(&contract, text)?; let prior = if dir.join("image-task.json").exists() { read_json(&dir.join("image-task.json"))?["id"].clone() } else { Value::Null }; - json!({"version":1,"id":job,"doc":id,"revision":input["revision"],"mode":input["mode"],"target":target,"modelId":model_id,"modelKey":choice,"protocol":contract,"prompt":prompt,"references":references,"omittedOptionalLayout":omit_layout,"keyFingerprint":hash(key),"phase":"prepared","requestId":null,"upstreamTaskId":null,"center":input["center"],"accountScope":self.scope(),"localProjectId":self.locations.get(&id),"origin":self.origin,"createdAt":now(),"replacesTaskId":prior,"creationBinding":input["creationBinding"],"slotBinding":input["slotBinding"],"sceneComposite":scene.as_ref().map(|(recipe,_)|recipe)}) + json!({"version":1,"id":job,"doc":id,"revision":input["revision"],"mode":input["mode"],"target":target,"modelId":model_id,"modelKey":choice,"protocol":contract,"prompt":text,"references":references,"keyFingerprint":hash(key),"phase":"prepared","requestId":null,"upstreamTaskId":null,"center":input["center"],"accountScope":self.scope(),"localProjectId":self.locations.get(&id),"origin":self.origin,"createdAt":now(),"replacesTaskId":prior,"creationBinding":input["creationBinding"],"slotBinding":input["slotBinding"],"sceneComposite":scene.as_ref().map(|(recipe,_)|recipe)}) }; if preparing { t["candidateRecord"] = input["candidateRecord"].clone(); @@ -1151,13 +1141,18 @@ mod tests { let mut task = fixture.task.clone(); let id = task["id"].as_str().unwrap().to_owned(); let asset = image_request_file(&fixture.dir, &id).unwrap().with_file_name("reference-0.png"); + let scene = asset.with_file_name("reference-1.png"); let pixels = b"fixture bytes"; fs::write(&asset, pixels).unwrap(); - let prompt = "完整文本,保留换行。\n【模板图位参考】这也是用户正文。\n尾部说明。"; + fs::write(&scene, b"scene bytes").unwrap(); + let prompt = " 完整文本,保留换行。\r\n【模板图位参考】这也是用户正文。\n尾部说明。\n"; task["phase"] = json!("prepared"); task["prompt"] = json!(prompt); task["requestSpecRevision"] = json!(1); - task["references"] = json!([{"position":1,"source":"P01","role":"product","path":asset,"sha256":format!("{:x}",Sha256::digest(pixels))}]); + task["references"] = json!([ + {"position":1,"source":"P01","role":"product","path":asset,"sha256":format!("{:x}",Sha256::digest(pixels))}, + {"position":2,"source":"S01","role":"scene","path":scene,"sha256":format!("{:x}",Sha256::digest(b"scene bytes"))} + ]); task["protocol"] = json!({"parameters":{"quality":"medium"},"field":"images","route":"fixture-route", "path":"/v1/images/edits","multipart":true}); task["requestSpecHash"] = json!(hash(&image_spec(&task).to_string())); @@ -1179,6 +1174,7 @@ mod tests { assert_eq!(payload["prompt"], prompt); assert_eq!(payload["quality"], "medium"); assert_eq!(payload["images"][0], format!("data:image/png;base64,{}", STANDARD.encode(pixels))); + assert_eq!(payload["images"][1], format!("data:image/png;base64,{}", STANDARD.encode(b"scene bytes"))); fs::write(&asset,b"modified").unwrap(); assert!(verified_reference_bytes(&saved).is_err()); let mut corrupt = saved; diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_production_profile.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_production_profile.rs index 8df883a1..1f8a82aa 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_production_profile.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_production_profile.rs @@ -45,7 +45,8 @@ pub(super) fn add_image_fields(pack: &mut Value, component: &str) -> Result<(), } pub(super) fn agent_rules(profile: &Value) -> Value { - json!({"copyRules":profile["copyRules"],"missingFacts":profile["missingFacts"],"visualDirection":profile["visualDirection"]}) + json!({"copyRules":profile["copyRules"],"missingFacts":profile["missingFacts"],"visualDirection":profile["visualDirection"], + "autoAdoptionPolicy":profile["autoAdoptionPolicy"]}) } fn replace_static_text<'a>(layer: &'a mut Layer, value: &str) -> Result<&'a mut photocraft_doc::TextLayer, String> { diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_scene_composite.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_scene_composite.rs index 01bc2f96..95c45aa2 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_scene_composite.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_scene_composite.rs @@ -31,11 +31,6 @@ impl Recipe { } Ok(()) } - - pub(super) fn prompt(&self, instructions: &str) -> String { - let units = self.remove.iter().map(|[x,y]| format!("{},{}", x, y)).collect::>().join(";"); - format!("对输入的这一张完整照片做局部擦除。只移除{}及其接触阴影,接续其后原有的墙、地面和光影。保留画幅、镜头、取景、色调、背景、建筑和所有其他物体原位。不要放入新商品,不添加文字、遮罩或轮廓。当前照片左上为0,0、右下为1000,1000,擦除范围的轮廓节点依次为{units}。只返回完整的无旧商品照片。\n【本轮编辑要求】{instructions}\n本步只执行旧商品擦除和擦除区的背景修补。涉及同款新商品、原片、放置和画幅的说明由后续原片合成处理。保留擦除区外的实景。", self.subject) - } } fn decode(bytes: &[u8]) -> Result { @@ -256,11 +251,6 @@ mod tests { "subject":"旧商品","remove":[[200,200],[800,200],[800,800],[200,800]], "placements":[{"center":500,"bottom":780,"height":350}] })).unwrap(); - let first_prompt = recipe.prompt("恢复凹陷处的浅色地板。"); - let rework_prompt = recipe.prompt("沿左侧原有光影补齐地板,延续横向木纹。"); - assert_ne!(rework_prompt, first_prompt); - assert!(rework_prompt.contains("沿左侧原有光影补齐地板,延续横向木纹。")); - assert!(rework_prompt.contains("200,200;800,200;800,800;200,800")); let template = encode(RgbaImage::from_pixel(100,100,Rgba([80,90,100,255]))).unwrap(); let mut plate = RgbaImage::from_pixel(100,100,Rgba([80,90,100,255])); for y in 32..68 { for x in 34..66 { plate.put_pixel(x,y,Rgba([220,200,180,255])); } } diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/pi_bridge.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/pi_bridge.rs index 42f24815..aeba110c 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/pi_bridge.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/pi_bridge.rs @@ -499,7 +499,8 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co } let request = &input["request"]; let allowed: &[&str] = match action { - "prepare" => &["slotId","instructions","geometryReferenceIndex","prefer2k","retryOf","reworkOf","reworkChange","useTemplateReference"], + "prepare" => &["slotId","instructions","geometryReferenceIndex","prefer2k","retryOf","reworkOf","reworkChange", + "referenceIndexes","useTemplateReference","useSceneComposite"], _ => &["requestId","expectedRevision","expectedHash","slotId"], }; if request.as_object().is_none_or(|fields| fields.keys().any(|key| !allowed.contains(&key.as_str()))) { @@ -553,6 +554,7 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co "originalsOnly":input["originalsOnly"] == true && input["candidateId"].is_null(), "includeProductReferences":input["includeProductReferences"] != false, "includeTemplateReference":input["includeTemplateReference"] != false, + "includeCandidateOriginal":input["includeCandidateOriginal"] == true, "actionReviewRegion":action_region,"relatedCopy":related})) } "pi-template-image" => { diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/workflow_bridge.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/workflow_bridge.rs index f90f66be..ab2bb819 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/workflow_bridge.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/workflow_bridge.rs @@ -663,6 +663,9 @@ fn execute(w: &mut Workspace, app: &mut PhotocraftApp, input: &Value, version: u } let batch = w.pi_request_scope["wholeDetail"] == true && input["outputId"] == w.pi_request_scope["outputId"]; let intent = input["intent"].as_str().filter(|s| matches!(*s, "generate_candidate" | "adopt_candidate")).ok_or("此操作不能直接执行")?; + if w.pi_request_scope["productProduction"] == true && intent == "generate_candidate" && input["useProductReference"] != true { + return Err("正式生图须先准备并审阅完整请求,再按冻结编号派发".into()); + } let completed_placement = batch && intent == "adopt_candidate" && w.pi_request_scope["productProduction"] == true && w.template_workflow["slots"].as_array().into_iter().flatten().any(|slot| slot["id"] == input["slotId"] && slot["variantId"] == input["productVariantId"] && slot["outputId"] == input["outputId"] @@ -1656,6 +1659,19 @@ mod tests { assert!(requests.try_recv().is_err()); } + #[test] + fn production_workflow_cannot_delegate_an_unfrozen_image_generation() { + let (mut w, mut app, requests, ctx) = direct_fixture(); + w.pi_request_scope["wholeDetail"] = json!(true); + w.pi_request_scope["productProduction"] = json!(true); + let read = private_call(&mut w, &mut app, &ctx, "pi-workflow-read", json!({})).unwrap(); + let result = private_call(&mut w, &mut app, &ctx, "pi-workflow-execute", direct_input(read["version"].clone())).unwrap(); + assert_eq!(result["phase"], "not_dispatched"); + assert!(result["error"]["message"].as_str().unwrap().contains("冻结编号")); + assert!(w.workflow.operations.is_empty()); + assert!(requests.try_recv().is_err()); + } + #[test] fn canvas_click_or_pan_without_edits_does_not_stop_candidate_dispatch() { for button in [egui::PointerButton::Primary, egui::PointerButton::Middle] {