合入小壹每图位双候选挑优、默认四张封顶与候选验收补项(R5-Z9)
# Conflicts: # apps/detail-agent-pi/src/production-operations.mjs # apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs
This commit is contained in:
commit
c04eccb68f
@ -12,6 +12,19 @@ const tool = (name, description, parameters, execute) => ({
|
||||
const copySignature = copy=>copy.map(({field,text,claims})=>[field,...(claims??[text])])
|
||||
.sort(([left],[right])=>(left??'').localeCompare(right??''));
|
||||
|
||||
export const visualReviewChecks = {
|
||||
viewpoint:'视角与景别符合图位任务',
|
||||
accessories:'饰品及其与主体的接触关系符合要求',
|
||||
ratioAndCrop:'比例与裁切符合图框要求且保留必要信息',
|
||||
originalComposition:'重新构思,未照搬模板原图',
|
||||
visibleScene:'要求的场景元素在画面中可见',
|
||||
purposeWithoutTitle:'遮住标题仍能辨认画面用途',
|
||||
productScale:'主体尺度与人物、物件及空间关系合理',
|
||||
forbiddenMarks:'无本款资料或审稿规则禁止的标识,包括供样铭牌和他牌标识',
|
||||
productIdentity:'与同款实拍身份一致',
|
||||
textAndFacts:'画面文字可读且符合已核实的商品事实',
|
||||
};
|
||||
|
||||
const actions=['adopt','canvas_adjust','regenerate'];
|
||||
const coordinate=Type.Integer({minimum:0,maximum:1000});
|
||||
export const canvasTransformArgs={
|
||||
@ -27,7 +40,7 @@ export const canvasTransformArgs={
|
||||
|
||||
export async function reviewProductionCandidate({
|
||||
canvas,runAgent,slot,candidateId,signal,copy,rule,source,adopted=false,fit,artDirection,
|
||||
liveScreenCopy,screen,
|
||||
liveScreenCopy,screen,generationEvidence,
|
||||
}) {
|
||||
const input=await canvas.detailImages(slot.id,candidateId,{
|
||||
...(adopted?{adopted:true}:null),
|
||||
@ -51,12 +64,16 @@ export async function reviewProductionCandidate({
|
||||
const guidePoint=Type.Tuple([Type.Integer({minimum:0,maximum:1000}),Type.Integer({minimum:0,maximum:1000})]);
|
||||
const guides=adopted?[]:Object.entries(rule?.structureGuides??{});
|
||||
const issue = {location:Type.String(),problem:Type.String(),suggestion:Type.String()};
|
||||
const visualChecks=Object.fromEntries(Object.entries(visualReviewChecks).map(([key,description])=>{
|
||||
const value=Type.Union([Type.Boolean(),Type.Null()],{description});
|
||||
return [key,generationEvidence?value:Type.Optional(value)];
|
||||
}));
|
||||
const assessment=params({
|
||||
candidateId:Type.String(),verdict:Type.Union(['pass','revise','missing'].map(value=>Type.Literal(value))),
|
||||
shownSubject:Type.Optional(Type.String({description:'画面实际突出呈现的部位、景别或场景。'})),
|
||||
recommendedAction:Type.Optional(Type.Union(actions.map(value=>Type.Literal(value)))),
|
||||
canvasTransform:Type.Optional(params(canvasTransformArgs)),
|
||||
checks:params({structure:Type.Boolean(),color:Type.Boolean(),
|
||||
checks:params({...visualChecks,structure:Type.Boolean(),color:Type.Boolean(),
|
||||
material:Type.Optional(Type.Boolean()),
|
||||
templateStyle:Type.Optional(Type.Boolean({description:'按本项目发布的规则判断模板风格'})),
|
||||
composition:Type.Boolean(),evidence:Type.Boolean(),
|
||||
@ -96,7 +113,7 @@ export async function reviewProductionCandidate({
|
||||
wholeScreen,...value.screenReview,
|
||||
};
|
||||
receipt={candidateId,verdict:value.verdict,recommendedAction:value.recommendedAction,canvasTransform:value.canvasTransform,
|
||||
checks:value.checks,reason:value.reason,shownSubject:value.shownSubject,observation:{
|
||||
checks:{...Object.fromEntries(Object.keys(visualReviewChecks).map(key=>[key,null])),...value.checks},reason:value.reason,shownSubject:value.shownSubject,observation:{
|
||||
source,shownSubject:value.shownSubject,reviewedCopy,visualEvidence:value.shownFields??[],
|
||||
screenReview,
|
||||
mustRedo:value.mustRedo??[],canvasFixes:value.canvasFixes??[],
|
||||
@ -113,7 +130,7 @@ export async function reviewProductionCandidate({
|
||||
screenCopy,
|
||||
productReferenceCount:originalImages.length,layoutReferenceCount:layoutImages.length,
|
||||
originalReference,frame:input.frame,ratio:input.frame?.width>0&&input.frame?.height>0?input.frame.width+':'+input.frame.height:input.aspectRatio,
|
||||
candidateFile:input.candidateFile,product:input.brief,outputSpec:input.outputSpec,layoutIssue:input.layoutIssue,
|
||||
candidateFile:input.candidateFile,generationEvidence,product:input.brief,outputSpec:input.outputSpec,layoutIssue:input.layoutIssue,
|
||||
fit:screen.details.fit??fit,artDirection,textRegions:input.textRegions,
|
||||
composite:{page:screen.details.page+1,name:screen.details.pageName,slots:screen.details.slots,
|
||||
screenCopy:screen.details.screenCopy,overlayLayers:screen.details.overlayLayers}});
|
||||
@ -127,6 +144,7 @@ export async function reviewProductionCandidate({
|
||||
'原件信息见 candidateFile,图框见 frame。requirements 是当前图位的要求,screenCopy 是实时文案。',
|
||||
'用 shownSubject 描述实际画面,用 shownFields 标明与文案对应的画面依据,其中 field 填 screenCopy 的字段号,label 用于识别文案。mustRedo 和 canvasFixes 分别记录建议重做和能用画布处理的问题。裁切坐标以未裁切原图为准。',
|
||||
...(guides.length?['模板要求的结构标注落点用图框内 [0,0] 到 [1000,1000] 的坐标。']:[]),
|
||||
'按 checks 逐项记录结论,比较同款实拍和模板参考。对不适用或缺乏证据的检查填 null,并在 reason 说明。检查 generationEvidence 中的实发模型、参数和像素。根据本款 product 资料和已发布的企业 Skill 判定禁止标识,查看主体和配饰上的铭牌、文字及 logo。未读到模板原图时记录依据缺失。暗中遮住标题,描述仍能看出的用途。任何实际问题要记录位置和依据。',
|
||||
'调用 review_candidate 提交结论。',
|
||||
].join('\n');
|
||||
const images=[input.images.at(-1),screen.image,...originalImages,...layoutImages];
|
||||
|
||||
@ -98,7 +98,7 @@ export const productionOperationTools = [
|
||||
['use_product_image','用本款原片或裁切区域创建候选。通过 adopt_production_image 回填时,放置回执会列出覆盖图位的模板叠层。',obj({...outputScope,slotId:slotRef,...productImageArgs})],
|
||||
['transform_slot_image','在本机裁切、镜像、旋转、缩放或位移本款实拍及任一成品的同花色候选,返回新候选和像素清晰度指标。',obj({...outputScope,slotId:slotRef,...transformImageArgs})],
|
||||
['prepare_image_request','保存完整生图请求,返回正式文本、参考顺序、模型参数与请求编号。'+imagePromptGuidance,obj({...outputScope,slotId:slotRef,...preparationArgs})],
|
||||
['dispatch_image_request','审阅准备回执后填写 requestId 确认派发。宿主从该编号绑定的请求读取版本和哈希。使用 await_image_slots 或 review_image_slots 查看实际结果。',obj({...outputScope,...dispatchArgs})],
|
||||
['dispatch_image_request','审阅准备回执后填写首个 requestId 确认派发生图批次。宿主从该编号绑定的请求读取版本和哈希。使用 await_image_slots 或 review_image_slots 查看实际结果。',obj({...outputScope,...dispatchArgs})],
|
||||
['delegate_image_slots','异步分派一批图位,空闲的制作助手立即开始,其余图位顺序排队。每个 goal 写明对应屏的核心卖点与画面要证明的细节。逐图位返回接收情况及待写文案字段。生图派发后宿主继续跟踪原请求,可用 await_image_slots 查看回执。',obj({
|
||||
...outputScope,jobs:Type.Array(obj({slotId:slotRef,goal:text,reworkCandidateId:optional(Type.String({description:'返工时,指定之前被退回的候选号。'}))})),
|
||||
})],
|
||||
@ -114,7 +114,7 @@ export const productionOperationTools = [
|
||||
['check_image_slots','请验图代理按企业 Skill 同看候选原图及候选放入后的整屏画面,检查商品还原和叠层对位,并对照当前图位关联文案核对图文一致性。可用 fit 指定预览放置方式。默认先返回受理结果,可用 review_image_slots 查看结论,用 adopt_production_image 采用你选定的候选。',obj({
|
||||
...outputScope,wait:optional(Type.Boolean()),candidates:Type.Array(obj({slotId:slotRef,candidateId:text,adopted:optional(Type.Boolean()),fit:optional(fit)})),
|
||||
})],
|
||||
['adopt_production_image','采用你选择的候选,返回画布修订和模板叠层。单图位屏与验图画面一致时沿用复核结论。screensReadyForReview 列出图位已齐、尚未复核当前画面的多图位屏。可用 read_output_screen 查看整屏合成画面。',obj({slotId:slotRef,candidateId:text,fit:optional(fit)})],
|
||||
['adopt_production_image','采用你选择的候选,用 reason 记录采用理由,返回画布修订和模板叠层。单图位屏与验图画面一致时沿用复核结论。screensReadyForReview 列出图位已齐、尚未复核当前画面的多图位屏。可用 read_output_screen 查看整屏合成画面。',obj({slotId:slotRef,candidateId:text,fit:optional(fit),reason:optional(text)})],
|
||||
['retire_production_image','清理你已判为失败的当前图位候选,保留原因、提示词和原请求记录。返工需要旧图时,先让子代理读取再清理。若该图已在画布上,回执会给出应替换的图层。',obj({slotId:slotRef,candidateId:text,reason:text})],
|
||||
['reconcile_image_slots','按已保存的原操作或原候选号核查结果。未绑定画布时核查本轮项目输出,可用完整图位 id 缩小范围。unknown 继续核查原号,结果有留存时按原号取回,不重新付费。expired 表示原结果已不可取回:网关确认结果过期(HTTP 410)、结果链接下载返回 404 或 410,或原请求在 180 秒恢复预算用完后仍是 unresolved。expired 可以为同图位另备新请求;已派发的原请求仍计入该图位的生图次数上限。',obj({...outputScope,slotIds:optional(ids)})],
|
||||
['read_output_screen',`读取整屏合成画面的实际像素、overlayLayers 和 slotGeometry。subjectBounds 是画布坐标 [x,y,w,h],由放置后的像素与边缘背景的色差估测,并裁到图位可见框内。测不出时由 subjectBoundsReason 说明原因。对位有误时可对照两组 bounds,用 native_call 的 edit.transform 移动或缩放叠层,或用 transform_slot_image 调整候选并采纳,再复核本屏。page 指定单屏,pages 可按需查看 2–4 屏,屏号从 0 开始。只保留最新一次查看图片。${COPY_IMAGE_SCREEN_GUIDANCE}需要修正时通过 native_catalog 查命令,再用 native_call 编辑叠层,或用 write_copy_fields、transform_slot_image 更新映射内容。`,obj({
|
||||
@ -244,7 +244,7 @@ async function readNativeOriginal(canvas,original,scope) {
|
||||
const receipt=await canvas.detailRecover(slotId,{candidateId},scope);
|
||||
if(receipt.id!==candidateId)throw Error('原生回执与请求号不一致');
|
||||
const phase=settledImagePhases.includes(receipt.status)?receipt.status:'unknown';
|
||||
return {slotId,candidateId,operationId,phase,reason:receipt.message,...expiryFields(receipt)};
|
||||
return {slotId,candidateId,operationId,phase,reason:receipt.message,...(receipt.generationEvidence?{generationEvidence:receipt.generationEvidence}:null),...expiryFields(receipt)};
|
||||
}
|
||||
|
||||
function createImageReconciler(canvas,{outputId,variantId},readJournal,update,{projectScope,onAdopted,onError}={}) {
|
||||
@ -417,7 +417,9 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
const byField=Map.groupBy(slots,slot=>slot.fieldId);
|
||||
const binding=JSON.stringify([plan.template.contentHash,variantId]);
|
||||
const imageScope={...output,templateHash:plan.template.contentHash};
|
||||
const configuredLimit=plan.template.production?.maxGenerationAttempts;
|
||||
const {candidatesPerSlot:configuredBatch,maxCandidatesPerSlot,maxGenerationAttempts:legacyLimit}=plan.template.production??{};
|
||||
const candidatesPerSlot=Number.isSafeInteger(configuredBatch)&&configuredBatch>0?configuredBatch:2;
|
||||
const configuredLimit=maxCandidatesPerSlot??legacyLimit;
|
||||
const hasTemplateLimit=Number.isSafeInteger(configuredLimit)&&configuredLimit>0;
|
||||
const maxGenerationAttempts=hasTemplateLimit?configuredLimit:defaultGenerationLimit;
|
||||
const generationLimitSource=hasTemplateLimit?'模板制作配置':'客户端默认';
|
||||
@ -559,7 +561,8 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
const drawStatuses=selected=>new Map(selected.map(slot=>[slot.id,slotDrawStatus(slot)]));
|
||||
const drawLimit=(slot,status)=>({slotId:slot.id,phase:'draw_limit_reached',limitReached:true,...status,
|
||||
candidates:slot.candidates??[],
|
||||
reason:`该图位已用完 ${maxGenerationAttempts} 次生图额度。来源:${generationLimitSource}。`,
|
||||
reviews:journal.items[slot.id]?.reviewHistory??[],
|
||||
reason:`本图位已达上限,已用完 ${maxGenerationAttempts} 次生图额度。来源:${generationLimitSource}。`,
|
||||
});
|
||||
const readPlan=()=>canvasReady?scopedPlan():trackCanvas(canvas.workflowRead({section:'overview',outputId}));
|
||||
const current=async({refresh=false}={})=>{
|
||||
@ -832,9 +835,11 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
{operationId:candidateId,requestId:candidateId,onEnqueued},imageScope);
|
||||
if(host.productionSignal?.aborted)return {candidateId,operationId:candidateId,phase:'cancelled'};
|
||||
const phase=receipt.status??receipt.phase;
|
||||
return {candidateId,operationId:candidateId,phase:phase==='running'?'unknown':phase,reason:receipt.message,
|
||||
return {candidateId:receipt.id??candidateId,operationId:candidateId,phase:phase==='running'?'unknown':phase,reason:receipt.message,
|
||||
...(receipt.candidates?{candidates:receipt.candidates}:null),
|
||||
...(receipt.generationEvidence?{generationEvidence:receipt.generationEvidence}:null),
|
||||
requestedSource:'generate',...expiryFields(receipt),...(request.reworkOf?{reworkOf:request.reworkOf}:null),
|
||||
...(!settledImagePhases.includes(phase)?{pendingOriginal:candidateId}:null),
|
||||
...(!settledImagePhases.includes(phase)&&phase!=='draw_limit_reached'?{pendingOriginal:receipt.id??candidateId}:null),
|
||||
...(receipt.retryableFailure===true?{retryableFailure:true,retryAfterSeconds:receipt.retryAfterSeconds}:null)};
|
||||
};
|
||||
const queueDispatch=async(slot,approval,request,signal,workerNumber)=>{
|
||||
@ -862,7 +867,19 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
const run=Promise.resolve().then(()=>dispatchImageRequest(slot,approval,request,row.number,submission.resolve))
|
||||
.catch(error=>({candidateId:id,operationId:id,reason:error.message,
|
||||
...(error.dispatched===false?{phase:'failed'}:{phase:'unknown',pendingOriginal:id})}))
|
||||
.then(result=>({slotId:slot.id,...result}))
|
||||
.then(async result=>{
|
||||
if(result.candidates){
|
||||
for(const member of result.candidates){
|
||||
generation.set(member.id,{slotId:slot.id,candidateId:member.id,operationId:member.id,
|
||||
phase:member.status,reason:member.message,generationEvidence:member.generationEvidence});
|
||||
}
|
||||
const completed=result.candidates.filter(member=>member.status==='complete');
|
||||
if(completed.length)await operations.check_image_slots({
|
||||
candidates:completed.map(member=>({slotId:slot.id,candidateId:member.id})),
|
||||
},signal);
|
||||
}
|
||||
return {slotId:slot.id,...result};
|
||||
})
|
||||
.finally(()=>{
|
||||
submission.resolve();
|
||||
dispatchingImages.delete(id);
|
||||
@ -990,6 +1007,7 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
async function check(slot,candidateId,adopted,fit,signal,row){
|
||||
const item=journal.items[slot.id];
|
||||
const live=await liveSlot(slot);
|
||||
const generationEvidence=live.candidates?.find(row=>row.id===candidateId)?.generationEvidence;
|
||||
const source=nativeGenerations(live).includes(candidateId)?'generate':item?.candidateId===candidateId?item.source:undefined;
|
||||
try{
|
||||
const copyInputs=productionInputs(await current(),variantId);
|
||||
@ -1001,7 +1019,7 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
...options,...(canvasReady?{targetOutput:output}:null),
|
||||
})};
|
||||
const {referenceCount,...review}=await reviewProductionCandidate({canvas:readCanvas,runAgent:runDetailAgent,
|
||||
slot,candidateId,signal,liveScreenCopy,rule:slot.productionRule,source,adopted,fit,screen});
|
||||
slot,candidateId,signal,liveScreenCopy,rule:slot.productionRule,source,adopted,fit,screen,generationEvidence});
|
||||
const {verdict,checks,reason,observation,recommendedAction,canvasTransform}=review;
|
||||
const entry={screenReview:observation.screenReview,copyInputs};
|
||||
const approval={candidateId,decision:verdict,checks,reason,observation,original:review.original,recommendedAction,canvasTransform,
|
||||
@ -1013,7 +1031,7 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
if(verdict==='pass')record.approvals.push(approval);
|
||||
const history=record.reviewHistory??=[];
|
||||
history.push({candidateId,verdict,reason,recommendedAction,canvasTransform,mustRedo:observation.mustRedo,
|
||||
generationFixes:observation.generationFixes,...entry});
|
||||
generationFixes:observation.generationFixes,checks,original:review.original,generationEvidence,...entry});
|
||||
},{evidence:[slot.id,candidateId,'review',approval]});
|
||||
if(entry.screenReview.wholeScreen&&!canvasReady){
|
||||
await serialize(async()=>{
|
||||
@ -1118,7 +1136,7 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
return {outputId,variantId,workingOutput:workingOutputId?{outputId:workingOutputId,variantId:workingVariantId}:null,
|
||||
fieldConflicts:await fieldConflicts(await copySnapshot(),plan),fieldRequirements:fieldRequirements(plan),
|
||||
template,product:{name,dimensions,note,variant:variant&&{id:variant.id,colorName:variant.colorName}},
|
||||
maxGenerationAttempts,generationLimitSource,pictures,dispatchReady:dispatchReady(selected,pendingCopy),
|
||||
candidatesPerSlot,maxCandidatesPerSlot:maxGenerationAttempts,maxGenerationAttempts,generationLimitSource,pictures,dispatchReady:dispatchReady(selected,pendingCopy),
|
||||
inFlightImages:(await pendingNative()).map(row=>row.candidateId),
|
||||
...(includeKnowledge?{knowledgeFiles:host.productionSkills?.files??[]}:null),
|
||||
...(host.productionSkills?.versionNotice?{knowledgeVersionNotice:host.productionSkills.versionNotice}:null),
|
||||
@ -1443,9 +1461,13 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
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,...status,rejections,candidates,working:slotWorking(id),
|
||||
...(waitingCanvas.has(id)?{state:'waiting_canvas'}:null),
|
||||
record,generation:generationReceipt,...(generations.length>1?{generations}:null),checks:reviews.map(job=>job.receipt)};
|
||||
if(requested.size){
|
||||
const comparison=[...new Map((record?.reviewHistory??[]).map(row=>[row.candidateId,row])).values()];
|
||||
return {id,fieldId,label,selectedCandidateId,attemptCount,...status,rejections,candidates,working:slotWorking(id),
|
||||
...(waitingCanvas.has(id)?{state:'waiting_canvas'}:null),
|
||||
record,comparison,generation:generationReceipt,...(generations.length>1?{generations}:null),
|
||||
checks:reviews.map(job=>job.receipt)};
|
||||
}
|
||||
const decision=record?.review?.candidateId===latestCandidateId?record?.review?.decision:undefined;
|
||||
const adopted=selectedCandidateId&&selectedCandidateId===latestCandidateId;
|
||||
const state=waitingCanvas.has(id)?'waiting_canvas':slotWorking(id)?'generating':reviews.some(job=>job.run)?'checking':
|
||||
@ -1506,11 +1528,12 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
});
|
||||
return wait?Promise.all(batch.map(job=>job.run??job.receipt)):batch.map(job=>job.receipt);
|
||||
},
|
||||
async adopt_production_image({slotId,candidateId,fit},signal){
|
||||
async adopt_production_image({slotId,candidateId,fit,reason},signal){
|
||||
const slot=matches(slotId);
|
||||
const result=await onCanvas(signal,()=>serialize(async()=>{
|
||||
const adopted=await operate(slot,'adopt_candidate',{candidateId,fit},signal);
|
||||
if(adopted.phase!=='complete')return adopted;
|
||||
if(reason)await save(slot,{adoptionReason:{candidateId,reason}});
|
||||
const entry=journal.items[slot.id]?.reviewHistory?.findLast(row=>row.candidateId===candidateId&&row.screenReview);
|
||||
try {
|
||||
const screenReview=await reuseCandidateScreen(entry,signal);
|
||||
@ -1563,6 +1586,8 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
const originals=await Promise.all(pending.filter(row=>ids.has(row.slotId))
|
||||
.map(row=>readNativeOriginal(canvas,row,canvasReady?output:undefined)));
|
||||
signal?.throwIfAborted();
|
||||
const recovered=originals.filter(row=>row.phase==='complete'&&row.generationEvidence);
|
||||
if(recovered.length)await operations.check_image_slots({candidates:recovered},signal);
|
||||
const pendingSlots=new Set(originals.map(row=>row.slotId));
|
||||
return [...originals,...results.filter(row=>row.phase!=='none'||!pendingSlots.has(row.slotId))];
|
||||
},
|
||||
@ -1733,8 +1758,20 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
[...new Map([...mapped.filter(Boolean),...overlays].map(row=>[row.layer,row])).values()]));
|
||||
}
|
||||
if((await canvas.read()).revision!==revision)throw Error('画布已更新,请读取当前画面再提交导出');
|
||||
const knownIssues=[...issues];
|
||||
for(const slot of await liveSlots()){
|
||||
if(!slotDrawStatus(slot).drawLimitReached||!slot.selectedCandidateId)continue;
|
||||
const history=journal.items[slot.id]?.reviewHistory??[];
|
||||
const selected=history.findLast(row=>row.candidateId===slot.selectedCandidateId);
|
||||
if(selected?.verdict!=='revise'||!selected.screenReview?.page)continue;
|
||||
const page=selected.screenReview.page;
|
||||
const reason=`本图位已达上限。图位 ${slot.fieldId},采用 ${selected.candidateId},待解决问题:${selected.reason}`;
|
||||
const index=knownIssues.findIndex(row=>row.outputId===outputId&&row.variantId===variantId&&row.page===page);
|
||||
if(index===-1)knownIssues.push({outputId,variantId,page,reason});
|
||||
else knownIssues[index]={...knownIssues[index],reason:knownIssues[index].reason+'\n'+reason};
|
||||
}
|
||||
return {text:'已提交当前画布,正在保存和导出。',production:{
|
||||
outputId,variantId,complete:true,canvasRevision:revision,issues,...screenEvidence,
|
||||
outputId,variantId,complete:true,canvasRevision:revision,issues:knownIssues,...screenEvidence,
|
||||
fieldRequirements:fieldRequirements(inputPlan),visibleConflicts,visibleConflictCount:visibleConflicts.length,
|
||||
}};
|
||||
},
|
||||
|
||||
@ -12,7 +12,9 @@ maxGenerationAttempts: 4
|
||||
- transform_slot_image 可在本地裁切、旋转、镜像、缩放或位移同图位或跨图位候选及本款实拍,并返回像素清晰度指标。仅有构图问题时可复用现有图片。近景和特写可裁切现有或用 prefer2k: true 请求的 2K 中景,担心模板参考影响商品结构时可用 useTemplateReference: false。
|
||||
- 按已发布规则撰写完整的 `prompt`,包括商品外观、构图、颜色、参考用途和返工要求。用 `referenceIndexes` 指定发送的原片及顺序,按需指定模板参考、画幅规格或实拍合成。实拍合成时,提示词描述在模板场景中擦除旧商品,本款实拍由客户端合成。
|
||||
- 审阅 `prepare_image_request` 回执中的正式文本、参考顺序与模型参数。调用 `dispatch_image_request` 时填写该回执的 `requestId`,宿主从该编号绑定的请求读取版本和哈希。
|
||||
- 需要比较多张候选时,分别准备并确认各自的请求,完成后可把候选号一起交给 `check_image_slots`。根据验图依据选择候选,再用 `adopt_production_image` 放入画布。
|
||||
- 生图准备回执列出同批候选的各自请求号。确认首个 `requestId` 即派发本批。对照 `review_image_slots` 的 `comparison`、实际像素、画幅、五段提示词及哈希回执,选择采用的候选,再用 `adopt_production_image` 的 `reason` 记录选择理由。
|
||||
- 同批有未知原请求时,按原号核查到终态后才能补出。每次补出按剩余额度派发。全部候选未通过且本图位已达上限时,挑最合适的可用候选并写明采用理由。交付时会将该候选尚未解决的审稿问题记入已知问题。
|
||||
- 模板制作配置示例 `{"schemaVersion":1,"candidatesPerSlot":2,"maxCandidatesPerSlot":4}`。默认每批 2 张,每个图位累计 4 张。已提交后失败或结果未知均计入额度。
|
||||
- `review_image_slots` 读取候选及已有结论,`check_image_slots` 委托独立审稿。返工可带原候选号和具体改动。用 `reconcile_image_slots` 查看原请求的结果。
|
||||
- 验图可提供画布调整建议,按当前画面决定是否调整、重新生成或采用。
|
||||
- 用 `native_catalog`、`native_call` 在模板允许的范围内调整画布。用 `read_output_screen` 回看实际图框与文字。叠层的 `group` 标明直属组,`overlayGroups` 按组列出本屏成员 ID。同组的尺寸线、端点和数字作为一套核对和处理。留意 `belowSlot` 中可能露出的旧字和底条。该字段按 `fieldId` 列出上方图位、它对屏内图层边界的覆盖比例 `coverage`、内容不透明度 `opacity` 和混合模式 `blendMode`。
|
||||
|
||||
@ -84,6 +84,10 @@ test('candidate review records the observed subject and alignment while acceptin
|
||||
assert.equal(result.shownSubject,shownSubject);
|
||||
assert.equal(result.observation.shownSubject,shownSubject);
|
||||
assert.equal(result.checks.copyAlignment,copyAlignment);
|
||||
for(const key of ['viewpoint','accessories','ratioAndCrop','originalComposition','visibleScene',
|
||||
'purposeWithoutTitle','productScale','forbiddenMarks','productIdentity','textAndFacts']){
|
||||
assert.ok(Object.hasOwn(result.checks,key),key);
|
||||
}
|
||||
assert.deepEqual(result.observation.reviewedCopy,[['tag','实木横梁'],['title','加厚桌腿']]);
|
||||
}
|
||||
});
|
||||
|
||||
@ -2144,6 +2144,76 @@ test('copy writes forward revisions and optional expected text for the canvas to
|
||||
await ops.close();
|
||||
});
|
||||
|
||||
test('a host batch returns both original requests and blocks only its slot until recovery',async t=>{
|
||||
const {host}=await tailFixture(t,['hero','side']);
|
||||
const dispatched=[];
|
||||
host.canvas.detailRecover=async(_slot,{candidateId})=>({id:candidateId,status:'failed'});
|
||||
const pixels={width:2048,height:1024};
|
||||
const image={type:'image',mimeType:'image/png',data:'fixture'};
|
||||
host.canvas.detailImages=async(_slot,candidateId)=>({candidateId,referenceCount:1,images:[image,image],candidateFile:pixels});
|
||||
const reviewed=[];
|
||||
host.runDetailAgent=async(_slot,_system,prompt,[tool])=>{
|
||||
const {candidateId,generationEvidence}=JSON.parse(prompt);
|
||||
assert.deepEqual(generationEvidence.actualPixels,pixels);
|
||||
const checks=Object.fromEntries(Object.keys(tool.parameters.properties.checks.properties).map(key=>[key,true]));
|
||||
await tool.execute('review',{candidateId,checks,verdict:'pass',reason:'结构与实拍一致',screenReview:passedScreen});
|
||||
reviewed.push(candidateId);
|
||||
};
|
||||
imageBridge(host,async({slotId},id)=>{
|
||||
dispatched.push(id);
|
||||
const complete=slotId==='side';
|
||||
return {id,status:complete?'complete':dispatched.length===1?'unknown':'failed',
|
||||
generationEvidence:{actualPixels:complete?pixels:null,actualRatio:complete?'2:1':null,
|
||||
allPromptSectionsPresent:true,savedPromptHash:'fixture',submittedPromptHash:'fixture',promptHashMatches:true}};
|
||||
});
|
||||
const request=host.canvas.imageRequest;
|
||||
const batches=new Map();
|
||||
host.canvas.imageRequest=async(action,args,execution,scope)=>{
|
||||
if(action==='prepare'){
|
||||
const candidates=await Promise.all([request(action,args,execution,scope),request(action,args,execution,scope)]);
|
||||
batches.set(candidates[0].requestId,candidates);
|
||||
return {...candidates[0],candidates};
|
||||
}
|
||||
if(action==='dispatch'){
|
||||
const candidates=[];
|
||||
for(const member of batches.get(args.requestId)){
|
||||
const result=await request(action,{...args,...approve(member)},execution,scope);
|
||||
candidates.push(result);
|
||||
}
|
||||
return {...candidates[0],candidates};
|
||||
}
|
||||
return request(action,args,execution,scope);
|
||||
};
|
||||
const ops=await openProductionOperations(host);
|
||||
t.after(()=>ops.close());
|
||||
const prepare=slotId=>ops.prepare_image_request({slotId,prompt:'同款结构'});
|
||||
const send=async(draft,slotId)=>{
|
||||
assert.equal((await ops.dispatch_image_request(approve(draft))).phase,'accepted');
|
||||
return ops.await_image_slots({slotIds:[slotId]});
|
||||
};
|
||||
const a=await prepare('hero');
|
||||
const first=await send(a,'hero');
|
||||
assert.equal(dispatched.length,2);
|
||||
assert.equal(first.generation.find(row=>row.candidateId===a.candidates[1].requestId).generationEvidence.promptHashMatches,true);
|
||||
const b=await prepare('hero');
|
||||
assert.equal((await ops.dispatch_image_request(approve(b))).pendingOriginal,a.requestId);
|
||||
const side=await prepare('side');
|
||||
await send(side,'side');
|
||||
while((await ops.await_image_slots({slotIds:['side']})).checking){}
|
||||
assert.equal(dispatched.length,4);
|
||||
assert.deepEqual(reviewed.sort(),side.candidates.map(row=>row.requestId).sort());
|
||||
const [sideStatus]=(await ops.review_image_slots({slotIds:['side']})).pictures;
|
||||
assert.equal(sideStatus.comparison.length,2);
|
||||
assert.deepEqual(sideStatus.comparison[0].generationEvidence.actualPixels,pixels);
|
||||
await ops.reconcile_image_slots({slotIds:['hero']});
|
||||
await send(b,'hero');
|
||||
const stopped=await ops.prepare_image_request({slotId:'hero',prompt:'补图'});
|
||||
assert.equal(stopped.generationAttempts,4);
|
||||
assert.match(stopped.reason,/本图位已达上限/u);
|
||||
assert.equal(dispatched.length,6);
|
||||
await ops.close();
|
||||
});
|
||||
|
||||
test('draw limit receipts identify the template value or the bundled default regardless of enterprise Skill headers',async t=>{
|
||||
const {host}=await tailFixture(t,['hero']);
|
||||
host.productionSkills=await openEnterpriseSkills(host.store,host.productionGoal,async()=>({
|
||||
|
||||
@ -777,7 +777,16 @@ fn candidate_available(record: &Value) -> bool {
|
||||
}
|
||||
|
||||
fn lock_candidate_dispatch(dir: &Path, id: &str) -> R<Option<fs::File>> {
|
||||
let path = candidate_path(dir, id)?.with_file_name("dispatch.lock");
|
||||
lock_image_dispatch(&candidate_path(dir, id)?.with_file_name("dispatch.lock"))
|
||||
}
|
||||
|
||||
fn lock_slot_dispatch(dir: &Path, slot: &Value) -> R<Option<fs::File>> {
|
||||
let id = slot["slotId"].as_str().filter(|id| id.len() == 64 && id.bytes().all(|byte| byte.is_ascii_hexdigit()))
|
||||
.ok_or("图片图位身份无效")?;
|
||||
lock_image_dispatch(&dir.join("image-jobs").join("slot-dispatch").join(id))
|
||||
}
|
||||
|
||||
fn lock_image_dispatch(path: &Path) -> R<Option<fs::File>> {
|
||||
fs::create_dir_all(path.parent().ok_or("原候选路径无效")?).map_err(|error| error.to_string())?;
|
||||
let file = fs::OpenOptions::new().read(true).write(true).create(true).truncate(false)
|
||||
.open(path).map_err(|error| error.to_string())?;
|
||||
@ -897,11 +906,6 @@ fn reserve_candidate(dir: &Path, mut state: Value, record: &Value, project_scope
|
||||
}
|
||||
state = original;
|
||||
}
|
||||
if let Some(previous) = record["retryOf"].as_str() {
|
||||
if records(dir, &state)?.iter().any(|candidate| candidate["retryOf"] == previous) {
|
||||
return Err("原候选已有重试记录,未重复发起".into());
|
||||
}
|
||||
}
|
||||
let expected = revision(&state);
|
||||
let file = candidate_path(dir, record["id"].as_str().ok_or("候选身份缺失")?)?;
|
||||
if file.exists() {
|
||||
@ -1094,6 +1098,12 @@ fn production_image_presentation(doc: u64, binding: &Value, account: &Value, ori
|
||||
"workerNumber":binding["request"]["workerNumber"]})
|
||||
}
|
||||
|
||||
fn emit_production_image_receipt(events: &mpsc::Sender<Event>, mut presentation: Value, receipt: &Value, cancelled: bool) {
|
||||
presentation["phase"] = if cancelled { json!("cancelled") } else { receipt["status"].clone() };
|
||||
presentation["isSlotCandidate"] = json!(true);
|
||||
let _ = events.send(Event::Json("image".into(), Ok(presentation)));
|
||||
}
|
||||
|
||||
fn production_image_target(state: Value, scope: &Value) -> R<Value> {
|
||||
let output = scope["outputId"].as_str().ok_or("成品编号缺失")?;
|
||||
let variant = scope["variantId"].as_str().ok_or("花色编号缺失")?;
|
||||
@ -1112,6 +1122,7 @@ fn candidate_receipt(record: &Value) -> Value {
|
||||
receipt["message"] = record["retirement"]["reason"].clone();
|
||||
}
|
||||
if record["phase"] == "complete" { receipt["materialTaskId"] = material_task_id(record).clone(); }
|
||||
if record["generationEvidence"].is_object() { receipt["generationEvidence"] = record["generationEvidence"].clone(); }
|
||||
if record["phase"] == "expired" {
|
||||
receipt["requestId"] = record["requestId"].clone();
|
||||
receipt["retryable"] = json!(false);
|
||||
@ -1235,6 +1246,32 @@ fn candidate_needs_recovery(dir: &Path, record: &Value) -> R<bool> {
|
||||
matches!(task["phase"].as_str(), Some("complete" | "applied" | "failed" | "expired"))))
|
||||
}
|
||||
|
||||
fn candidate_limits(state: &Value, output: &str) -> R<(u64, u64)> {
|
||||
let profile = production_profile::select(&state["template"], output)?.unwrap_or(&Value::Null);
|
||||
let positive = |key: &str| profile[key].as_u64().filter(|&value| value > 0);
|
||||
Ok((positive("candidatesPerSlot").unwrap_or(2),
|
||||
positive("maxCandidatesPerSlot").or_else(|| positive("maxGenerationAttempts")).unwrap_or(4)))
|
||||
}
|
||||
|
||||
fn slot_dispatch_usage(dir: &Path, state: &Value, slot: &Value, batch: &[String], current: Option<&str>) -> R<(u64, Option<Value>)> {
|
||||
let mut used = 0;
|
||||
let mut pending = None;
|
||||
for record in records(dir, state)? {
|
||||
if record["binding"]["slotId"] != slot["slotId"] || record["binding"]["variantId"] != slot["variantId"] {
|
||||
continue;
|
||||
}
|
||||
let task = candidate_projection_task(dir, &record)?;
|
||||
if generation_was_dispatched(&record, task.as_ref()) {
|
||||
used += 1;
|
||||
}
|
||||
if record["id"].as_str() != current && !batch.iter().any(|id| record["id"] == id.as_str())
|
||||
&& candidate_needs_recovery(dir, &record)? {
|
||||
pending = Some(record["id"].clone());
|
||||
}
|
||||
}
|
||||
Ok((used, pending))
|
||||
}
|
||||
|
||||
fn generation_was_dispatched(record: &Value, task: Option<&Value>) -> bool {
|
||||
record["sourceType"].is_null() && record["reusedFrom"].is_null()
|
||||
&& task.map_or_else(|| matches!(record["phase"].as_str(), Some("complete" | "expired")),
|
||||
@ -1694,6 +1731,39 @@ fn project_candidate(dir: &Path, record: &Value, journal: &Value) -> R<Value> {
|
||||
let artifact = template_slots::artifact(dir, record["id"].as_str().ok_or("原候选身份缺失")?, journal)?;
|
||||
record["artifact"] = artifact;
|
||||
}
|
||||
if let Some(submitted) = journal["submittedPromptHash"].as_str() {
|
||||
let prompt = journal["prompt"].as_str().ok_or("生图请求文本缺失")?;
|
||||
let saved = hash(record["prompt"].as_str().ok_or("候选提示词缺失")?);
|
||||
let headings = ["主体", "主体配饰", "镜头与构图", "场景", "风格"];
|
||||
let mut sections = Vec::new();
|
||||
for line in prompt.lines().map(str::trim) {
|
||||
if let Some(heading) = line.strip_suffix([':', ':']).filter(|heading| headings.contains(heading)) {
|
||||
sections.push(heading);
|
||||
}
|
||||
}
|
||||
use std::io::Read as _;
|
||||
let requested = &journal["slotFrame"];
|
||||
let actual = if phase == "complete" {
|
||||
let path = record["artifact"]["path"].as_str().ok_or("候选图片路径缺失")?;
|
||||
let mut header = [0; 24];
|
||||
fs::File::open(dir.join(path)).and_then(|mut file| file.read_exact(&mut header))
|
||||
.map_err(|_| "候选图片像素信息不可读取")?;
|
||||
Some(creation::png_size(&header)?)
|
||||
} else { None };
|
||||
let expected = requested["width"].as_f64().zip(requested["height"].as_f64());
|
||||
record["generationEvidence"] = json!({
|
||||
"modelId":journal["modelId"],"parameters":journal["protocol"]["parameters"],"requested2k":journal["prefer2k"],
|
||||
"actualPixels":actual.map(|(width,height)| json!({"width":width,"height":height})),
|
||||
"requestedImagePixels":journal["requestedImagePixels"],
|
||||
"matchesRequestedImagePixels":actual.filter(|_| journal["requestedImagePixels"].is_array())
|
||||
.map(|(width,height)| journal["requestedImagePixels"] == json!([width,height])),
|
||||
"actualRatio":actual.map(|(width,height)| format!("{width}:{height}")),
|
||||
"requestedRatio":expected.map(|(width,height)| format!("{width}:{height}")),
|
||||
"ratioMatches":actual.zip(expected).map(|((w,h),(ew,eh))| (w as f64 * eh - h as f64 * ew).abs() < ew.max(eh)),
|
||||
"promptSections":sections,"allPromptSectionsPresent":sections == headings,
|
||||
"savedPromptHash":saved,"submittedPromptHash":submitted,"promptHashMatches":saved == submitted
|
||||
});
|
||||
}
|
||||
record["phase"] = json!(phase);
|
||||
if phase == "expired" { record["resultExpiry"] = journal["resultExpiry"].clone(); }
|
||||
let preflight_retry = journal["phase"] == "prepared" && journal["notDispatched"] == true
|
||||
@ -3515,7 +3585,7 @@ fn snapshot_for_view(dir: &Path, view: Option<Value>, read_only: bool) -> R<Valu
|
||||
let review = &reviews[candidate_id];
|
||||
let decision = (review["slotId"] == id).then(|| &review["decision"]);
|
||||
let mut row = json!({"id":record["id"],"taskId":record["id"],"variant":record["id"],"sequence":record["sequence"],"status":record["phase"],"requestId":record["requestId"],
|
||||
"materialTaskId":material_task_id(record),"sourceRequestId":record["sourceRequestId"],"instructions":record["instructions"],"parentCandidateId":record["parentCandidateId"],"reworkOf":record["reworkOf"],"sourceType":record["sourceType"],"reusedFrom":record["reusedFrom"],"previewUri":format!("bytes://template-candidate-{candidate_id}"),"error":record["message"],"reviewDecision":decision,"retryableFailure":record["retryableFailure"],"retryAfterSeconds":record["retryAfterSeconds"]});
|
||||
"materialTaskId":material_task_id(record),"sourceRequestId":record["sourceRequestId"],"instructions":record["instructions"],"parentCandidateId":record["parentCandidateId"],"reworkOf":record["reworkOf"],"sourceType":record["sourceType"],"reusedFrom":record["reusedFrom"],"previewUri":format!("bytes://template-candidate-{candidate_id}"),"error":record["message"],"generationEvidence":record["generationEvidence"],"reviewDecision":decision,"retryableFailure":record["retryableFailure"],"retryAfterSeconds":record["retryAfterSeconds"]});
|
||||
if record["phase"] == "expired" {
|
||||
row["retryable"] = json!(false);
|
||||
row["resultExpiry"] = record["resultExpiry"].clone();
|
||||
@ -3675,18 +3745,93 @@ impl Backend {
|
||||
}
|
||||
_ => "slot-prepare-image",
|
||||
};
|
||||
return self.canvas_workspace_action(action, &input, events, ctx).map_err(BridgeFailure::from);
|
||||
// Only paid generation is batched and counted against the per-slot candidate limit.
|
||||
if action != "slot-prepare-image" {
|
||||
return self.canvas_workspace_action(action, &input, events, ctx).map_err(BridgeFailure::from);
|
||||
}
|
||||
let component = binding["scope"]["outputId"].as_str().ok_or("输出类型缺失")?;
|
||||
let variant = input["variantId"].as_str().ok_or("花色缺失")?;
|
||||
let source = production_output_state(load_detail_workspace(&dir)?, component, variant)?;
|
||||
let source_slot = json!({"slotId":request["slotId"],"variantId":variant});
|
||||
let (per_batch, max) = candidate_limits(&source, component)?;
|
||||
let (used, _) = {
|
||||
let _guard = sync::context_guard();
|
||||
slot_dispatch_usage(&dir, &load(&dir)?, &source_slot, &[], None)?
|
||||
};
|
||||
if used >= max { return Err("本图位已达上限".into()); }
|
||||
let mut drafts = Vec::new();
|
||||
for _ in 0..per_batch.min(max - used) {
|
||||
drafts.push(self.canvas_workspace_action(action, &input, events, ctx)?);
|
||||
}
|
||||
let mut receipt = drafts[0].clone();
|
||||
let primary = uuid(&receipt["requestId"], "生图请求")?;
|
||||
let mut task = super::images::read_image_request(&dir, &primary)?;
|
||||
task["candidateBatch"] = json!(drafts.iter().skip(1).map(|draft| json!({
|
||||
"requestId":draft["requestId"],"expectedRevision":draft["revision"],"expectedHash":draft["requestSpecHash"]
|
||||
})).collect::<Vec<_>>());
|
||||
super::images::job_save(&dir, &task)?;
|
||||
receipt["candidates"] = json!(drafts);
|
||||
return Ok(receipt);
|
||||
}
|
||||
if phase != "dispatch" { return Err("生图请求动作无效".into()); }
|
||||
let presentation = production_image_presentation(doc, binding, &self.auth["account"]["id"], &self.origin);
|
||||
let receipt = self.dispatch_canvas_image_request(doc, &dir, request,
|
||||
Some((&binding["scope"], &presentation)), events, ctx, cancellation)?;
|
||||
let primary = uuid(&request["requestId"], "生图请求")?;
|
||||
let mut draft = super::images::read_image_request(&dir, &primary)?;
|
||||
let _slot_dispatch = if draft["slotBinding"]["detailBatch"] == true {
|
||||
let Some(lock) = lock_slot_dispatch(&dir, request)? else {
|
||||
return Err(BridgeFailure::new("slot_image_running", true, false, "本图位已有生图批次正在处理"));
|
||||
};
|
||||
draft = super::images::read_image_request(&dir, &primary)?;
|
||||
Some(lock)
|
||||
} else { None };
|
||||
let siblings = draft["candidateBatch"].as_array().filter(|rows| draft["phase"] == "prepared" && !rows.is_empty());
|
||||
let mut batch = Vec::new();
|
||||
let receipt = match self.dispatch_canvas_image_request(doc, &dir, request,
|
||||
Some((&binding["scope"], &presentation)), events, ctx, cancellation, &batch) {
|
||||
Ok(receipt) => receipt,
|
||||
Err(error) if error.dispatched && siblings.is_some() =>
|
||||
json!({"id":primary,"status":"unknown","message":error.message}),
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let mut receipt = receipt;
|
||||
if receipt["id"] == request["requestId"] && receipt["status"] != "retired" && draft["candidateBatch"].is_array() {
|
||||
// Only members dispatched by this invocation can bypass its pending-original gate.
|
||||
// A replay of an already submitted primary request must recover by original ID.
|
||||
let mut receipts = vec![receipt.clone()];
|
||||
if let Some(siblings) = siblings {
|
||||
batch.push(uuid(&request["requestId"], "生图请求")?);
|
||||
for sibling in siblings {
|
||||
let id = uuid(&sibling["requestId"], "生图请求")?;
|
||||
let mut member = sibling.clone();
|
||||
member["slotId"] = request["slotId"].clone();
|
||||
let mut member_presentation = presentation.clone();
|
||||
member_presentation["taskId"] = json!(id);
|
||||
let result = self.dispatch_canvas_image_request(doc, &dir, &member,
|
||||
Some((&binding["scope"], &member_presentation)), events, ctx, cancellation, &batch);
|
||||
let member_receipt = match result {
|
||||
Ok(mut value) => {
|
||||
if value["id"].is_null() { value["id"] = json!(id); }
|
||||
value
|
||||
}
|
||||
Err(error) => json!({"id":id,"status":if error.dispatched {"unknown"} else {"failed"},"message":error.message}),
|
||||
};
|
||||
emit_production_image_receipt(events, member_presentation, &member_receipt,
|
||||
check_image_dispatch_cancelled(cancellation).is_err());
|
||||
receipts.push(member_receipt);
|
||||
batch.push(id);
|
||||
}
|
||||
}
|
||||
receipt["candidates"] = json!(receipts);
|
||||
}
|
||||
self.publish_production_image_receipt(doc, &dir, binding, presentation, receipt, events, ctx, cancellation)
|
||||
}
|
||||
|
||||
fn publish_production_image_receipt(&self, doc: u64, dir: &Path, binding: &Value, presentation: Value,
|
||||
receipt: Value, events: &mpsc::Sender<Event>, ctx: &egui::Context,
|
||||
cancellation: Option<&std::sync::atomic::AtomicBool>) -> Result<Value, BridgeFailure> {
|
||||
let cancelled = check_image_dispatch_cancelled(cancellation).is_err();
|
||||
if receipt["status"].is_string() {
|
||||
let mut image = presentation;
|
||||
image["phase"] = if cancelled { json!("cancelled") } else { receipt["status"].clone() };
|
||||
image["isSlotCandidate"] = json!(true);
|
||||
let _ = events.send(Event::Json("image".into(), Ok(image)));
|
||||
emit_production_image_receipt(events, presentation, &receipt, cancelled);
|
||||
if !cancelled {
|
||||
match self.canvas_workspace_result(doc, &dir) {
|
||||
Ok(workspace) if binding["projectScope"] == true => {
|
||||
@ -3707,7 +3852,7 @@ impl Backend {
|
||||
}
|
||||
|
||||
fn dispatch_canvas_image_request(&mut self, doc: u64, dir: &Path, request: &Value, production: Option<(&Value, &Value)>,
|
||||
events: &mpsc::Sender<Event>, ctx: &egui::Context, cancellation: Option<&std::sync::atomic::AtomicBool>) -> Result<Value, BridgeFailure> {
|
||||
events: &mpsc::Sender<Event>, ctx: &egui::Context, cancellation: Option<&std::sync::atomic::AtomicBool>, batch: &[String]) -> Result<Value, BridgeFailure> {
|
||||
let id = uuid(&request["requestId"], "生图请求")?;
|
||||
let scope = production.map(|(scope, _)| scope);
|
||||
let (task, _dispatch) = {
|
||||
@ -3733,8 +3878,22 @@ impl Backend {
|
||||
let slot = &task["slotBinding"];
|
||||
let state = if slot["detailBatch"] == true { load_detail_workspace(dir)? } else { load(dir)? };
|
||||
let record = &task["candidateRecord"];
|
||||
let _slot_dispatch = if production.is_none() && slot["detailBatch"] == true {
|
||||
Some(lock_slot_dispatch(dir, slot)?.ok_or("本图位已有生图批次正在处理")?)
|
||||
} else { None };
|
||||
let admitted = production.is_some() && slot["detailBatch"] == true;
|
||||
let source = if admitted { image_output_state(state.clone(), slot)? } else { state.clone() };
|
||||
if slot["detailBatch"] == true {
|
||||
let (_, max) = candidate_limits(&source, task["outputScope"].as_str().ok_or("输出类型缺失")?)?;
|
||||
let (used, pending) = {
|
||||
let _guard = sync::context_guard();
|
||||
slot_dispatch_usage(dir, &load(dir)?, slot, batch, Some(&id))?
|
||||
};
|
||||
if used >= max { return Ok(json!({"status":"draw_limit_reached","message":"本图位已达上限"})); }
|
||||
if let Some(original) = pending {
|
||||
return Ok(json!({"status":"unknown","id":original,"message":"本图位有未知原请求,请先按原号核查"}));
|
||||
}
|
||||
}
|
||||
if !candidate_uses_current_inputs(dir, &source, record, slot["variantId"].as_str().ok_or("花色缺失")?)? {
|
||||
return Err("商品资料或制作依据已变化,请重新准备请求".into());
|
||||
}
|
||||
@ -4310,7 +4469,7 @@ impl Backend {
|
||||
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, None)?;
|
||||
"expectedRevision":draft["revision"], "expectedHash":draft["requestSpecHash"], "slotId":id}), None, events, ctx, None, &[])?;
|
||||
if receipt["status"] == "failed" { operation_error = receipt["message"].as_str().map(str::to_owned); }
|
||||
candidate_result = Some(receipt);
|
||||
} else if method == "slot-reuse" {
|
||||
@ -6406,6 +6565,67 @@ mod tests {
|
||||
assert!(!transient_image_preflight("服务连接中断"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generation_receipt_reports_pixels_ratio_sections_and_submitted_prompt() {
|
||||
let fixture = fixture();
|
||||
let dir = &fixture.dir;
|
||||
let mut record = candidate(dir, "prepared");
|
||||
let id = record["id"].as_str().unwrap().to_owned();
|
||||
let prompt = "主体:\n参考 P01\n\n主体配饰:\n\n镜头与构图:\n正面\n\n场景:\n室内\n\n风格:\n自然光";
|
||||
record["prompt"] = json!(prompt);
|
||||
let job = dir.join("image-jobs").join(&id);
|
||||
fs::create_dir_all(&job).unwrap();
|
||||
let image = photocraft_codecs::Image::from_u8(2, 1, photocraft_codecs::ChannelLayout::Rgba, vec![80; 8]).unwrap();
|
||||
let png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap();
|
||||
fs::write(job.join("generated.png"), &png).unwrap();
|
||||
let task = json!({"id":id,"phase":"complete","modelId":"fixture","prompt":prompt,
|
||||
"submittedPromptHash":hash(prompt),"slotFrame":{"width":100,"height":50},
|
||||
"sha256":format!("{:x}",Sha256::digest(&png))});
|
||||
let projected = project_candidate(dir, &record, &task).unwrap();
|
||||
let receipt = candidate_receipt(&projected);
|
||||
let evidence = &receipt["generationEvidence"];
|
||||
assert_eq!(evidence["actualPixels"], json!({"width":2,"height":1}));
|
||||
assert_eq!(evidence["actualRatio"], "2:1");
|
||||
assert_eq!(evidence["requestedRatio"], "100:50");
|
||||
assert_eq!(evidence["ratioMatches"], true);
|
||||
assert_eq!(evidence["allPromptSectionsPresent"], true);
|
||||
assert_eq!(evidence["promptHashMatches"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_members_share_admission_but_later_batches_wait_for_originals() {
|
||||
let fixture = fixture();
|
||||
let dir = &fixture.dir;
|
||||
let mut batch = Vec::new();
|
||||
let (batch_size, cap) = candidate_limits(&load(dir).unwrap(), "detail").unwrap();
|
||||
assert_eq!((batch_size, cap), (2, 4));
|
||||
for number in 0..cap {
|
||||
let phase = if number == 0 { "unknown" } else { "failed" };
|
||||
let record = candidate(dir, "prepared");
|
||||
let mut state = load(dir).unwrap();
|
||||
let id = record["id"].as_str().unwrap().to_owned();
|
||||
state["candidates"].as_array_mut().unwrap().push(json!(id));
|
||||
write_json(&candidate_path(dir, &id).unwrap(), &record).unwrap();
|
||||
write_json(&dir.join("image-jobs").join(&id).join("task.json"), &json!({"phase":phase})).unwrap();
|
||||
let (used, pending) = slot_dispatch_usage(dir, &state, &record["binding"], &batch, None).unwrap();
|
||||
assert_eq!(used, number + 1);
|
||||
assert_eq!(pending.is_some(), number == 0);
|
||||
let mut other = record["binding"].clone();
|
||||
other["slotId"] = json!("other-slot");
|
||||
assert_eq!(slot_dispatch_usage(dir, &state, &other, &[], None).unwrap(), (0, None));
|
||||
if number == 0 { batch.push(id.clone()); }
|
||||
if number == 1 {
|
||||
assert_eq!(slot_dispatch_usage(dir, &state, &record["binding"], &[], None).unwrap(),
|
||||
(2, Some(json!(batch[0]))));
|
||||
let path = dir.join("image-jobs").join(&batch[0]).join("task.json");
|
||||
write_json(&path, &json!({"phase":"failed"})).unwrap();
|
||||
batch.clear();
|
||||
}
|
||||
let rev = revision(&state);
|
||||
persist(dir, state, rev).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_reservation_blocks_new_candidates_and_existing_task_never_redispatches() {
|
||||
let fixture = fixture();
|
||||
|
||||
@ -1067,6 +1067,9 @@ impl Backend {
|
||||
t["slotBinding"]["promptHash"] = json!(hash(t["prompt"].as_str().ok_or("生图请求文本缺失")?));
|
||||
t["candidateRecord"]["binding"] = t["slotBinding"].clone();
|
||||
t["outputScope"] = input["outputScope"].clone();
|
||||
t["slotFrame"] = input["slotFrame"].clone();
|
||||
t["prefer2k"] = input["prefer2k"].clone();
|
||||
t["requestedImagePixels"] = json!(protocol::requested_dimensions(&t["protocol"]));
|
||||
if let Some((_,cutout)) = &scene {
|
||||
t["localProductSha256"] = json!(format!("{:x}", Sha256::digest(cutout)));
|
||||
}
|
||||
@ -1216,6 +1219,7 @@ impl Backend {
|
||||
let request = request.map_err(|_| "生图请求准备失败,未提交")?;
|
||||
self.image_validate(deadline)?; // Live permission immediately before a paid dispatch.
|
||||
if self.exiting() { return Err("客户端正在退出,未提交生图请求".into()); }
|
||||
t["submittedPromptHash"] = json!(hash(payload["prompt"].as_str().ok_or("生图请求文本缺失")?));
|
||||
t["phase"] = json!("dispatched");
|
||||
job_save(&dir, &t)?;
|
||||
if t["creationBinding"].is_object() {
|
||||
|
||||
@ -48,7 +48,7 @@ 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"],
|
||||
"autoAdoptionPolicy":profile["autoAdoptionPolicy"],"maxGenerationAttempts":profile["maxGenerationAttempts"]})
|
||||
"autoAdoptionPolicy":profile["autoAdoptionPolicy"],"maxGenerationAttempts":profile["maxGenerationAttempts"],"candidatesPerSlot":profile["candidatesPerSlot"],"maxCandidatesPerSlot":profile["maxCandidatesPerSlot"]})
|
||||
}
|
||||
|
||||
fn replace_static_text<'a>(layer: &'a mut Layer, value: &str) -> Result<&'a mut photocraft_doc::TextLayer, String> {
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user