From bdf220a2a00c61e732f4d2bb177d36b2ad00d5fc Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Fri, 27 Nov 2026 23:54:33 +0800 Subject: [PATCH] =?UTF-8?q?=E6=94=B6=E5=8F=A3=E5=B0=8F=E5=A3=B9=E7=94=9F?= =?UTF-8?q?=E5=9B=BE=E5=8E=9F=E8=AF=B7=E6=B1=82=E7=8A=B6=E6=80=81=E5=88=B0?= =?UTF-8?q?=E5=AE=BF=E4=B8=BB=E6=A1=A3=E6=A1=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/production-operations.mjs | 351 ++++++++---------- .../src/production-repository.mjs | 6 +- .../src/project-repository.mjs | 135 +------ .../test/copy-image-alignment.test.mjs | 2 + .../detail-agent-pi/test/native-wire.test.mjs | 1 + .../test/production-operations.test.mjs | 313 ++++++++-------- .../test/project-repository.test.mjs | 142 +++---- .../src/jiansun_canvas_workspace.rs | 94 ++++- .../crates/ui-egui/src/jiansun/pi_bridge.rs | 11 +- .../ui-egui/src/jiansun/workflow_bridge.rs | 4 + 10 files changed, 472 insertions(+), 587 deletions(-) diff --git a/apps/detail-agent-pi/src/production-operations.mjs b/apps/detail-agent-pi/src/production-operations.mjs index f20b3817..3b6a393f 100644 --- a/apps/detail-agent-pi/src/production-operations.mjs +++ b/apps/detail-agent-pi/src/production-operations.mjs @@ -44,7 +44,7 @@ const recoveryNotices={ }; const MAX_SLOT_GENERATIONS=4; const expiryFields=receipt=>receipt?.resultExpiry? - {requestId:receipt.requestId,retryable:false,resultExpiry:receipt.resultExpiry}:{}; + {requestId:receipt.resultExpiry.requestId??receipt.requestId,retryable:false,resultExpiry:receipt.resultExpiry}:{}; function rememberImageExpiry(item,candidateId,receipt){ const expiry=expiryFields(receipt); if(!expiry.resultExpiry)return; @@ -94,7 +94,7 @@ export const productionOperationTools = [ jobs:Type.Array(obj({slotId:slotRef,goal:text,reworkCandidateId:optional(Type.String({description:'返工时,指定之前被退回的候选号。'}))})), })], ['await_image_slots','等待任一在途制作、验图或生图请求返回,并读取已有回执。省略 slotIds 时也关注按屏复核,结论见 screenChecks。已经返回结果未知的原请求用 reconcile_image_slots 核查。',obj({slotIds:optional(ids)})], - ['review_image_slots','只读查看当前制作输出的候选、验图、原请求、覆盖统计与整屏复核进度。默认逐图位返回状态和尝试次数。指定 slotIds 获取候选、退回原因、原请求、验图详细结论与提示词。',obj({slotIds:optional(Type.Array(Type.String()))})], + ['review_image_slots','只读查看当前制作输出的候选、验图、原请求、覆盖统计与整屏复核进度。默认逐图位返回状态和尝试次数。指定 slotIds 获取候选、退回原因、原请求和验图详细结论。',obj({slotIds:optional(Type.Array(Type.String()))})], ['read_archived_images','只读查找其他本机项目同款的历史候选。可选 slotIds 查看有对应图位的结果。不同模板或花色的已完成候选也可放入当前图位复核。',obj({ slotIds:optional(Type.Array(Type.String())), })], @@ -183,15 +183,18 @@ function slotAttempts(slot, record) { function originalCandidate(item) { if(item?.heldOriginalId)return item.heldOriginalId; const operation=item?.pendingOperation; + if(operation?.kind==='frozen-image')return undefined; + if(!operation&&item?.pendingGenerations)return undefined; if(operation&&Object.hasOwn(operation,'candidateId'))return operation.candidateId; return item?.state==='unknown'&&(!operation||!item.reason)?item.candidateId:undefined; } function slotOriginals(item) { - const originals=Object.values(item?.pendingGenerations??{}).map(frozen=>({frozen,request:frozen})); + const originals=[]; const candidateId=originalCandidate(item); - if(item?.pendingOperation||candidateId){ - originals.push({request:{...item.pendingOperation,candidateId,projectId:item.heldOriginalProjectId}}); + const operation=item?.pendingOperation?.kind==='frozen-image'?undefined:item?.pendingOperation; + if(operation||candidateId){ + originals.push({request:{...operation,candidateId,projectId:item.heldOriginalProjectId}}); } if(item?.pendingAdoption)originals.push({adopting:true,request:item.pendingAdoption}); return originals; @@ -201,34 +204,21 @@ function imageOriginals({items}) { return Object.entries(items).flatMap(([slotId,item])=>{ const originals=slotOriginals(item).map(({request:{candidateId,operationId,projectId},adopting})=> ({slotId,candidateId,operationId,projectId,adoption:adopting})); - return !originals.length&&item.state==='unknown'?[{slotId,phase:'unknown'}]:originals; + return !originals.length&&item.state==='unknown'&&!item.pendingGenerations&&item.pendingOperation?.kind!=='frozen-image' + ?[{slotId,phase:'unknown'}]:originals; }); } +async function readNativeOriginal(canvas,original,scope) { + const {slotId,candidateId,operationId}=original; + 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)}; +} + function createImageReconciler(canvas,{outputId,variantId},readJournal,update,{projectScope,onAdopted,onError}={}) { const detailRecover=(slotId,original)=>canvas.detailRecover(slotId,original,projectScope); - const reconcileImageRequest=async(slot,original,signal)=>{ - const {candidateId,operationId}=original; - signal?.throwIfAborted(); - const receipt=await detailRecover(slot.id,{candidateId}); - signal?.throwIfAborted(); - const phase=receipt?.id===candidateId&&settledImagePhases.includes(receipt.status)?receipt.status:'unknown'; - if(phase!=='unknown')await update(journal=>{ - signal?.throwIfAborted(); - const item=journal.items[slot.id]; - const attempts=item.attempts??=[]; - if(!attempts.some(row=>row.candidateId===candidateId))attempts.push({candidateId,source:'generate'}); - rememberImageExpiry(item,candidateId,receipt); - if(item.pendingGenerations?.[candidateId]){ - delete item.pendingGenerations[candidateId]; - Object.assign(item,{state:phase==='complete'?'candidate':phase,candidateId,source:'generate'}); - } - },{receipt:[candidateId,phase,receipt], - evidence:[slot.id,candidateId,'candidate',{requestId:candidateId,...receipt,operationId}]}); - return {slotId:slot.id,candidateId,operationId,phase,reason:receipt?.id===candidateId?receipt.message:undefined, - ...(receipt?.id===candidateId?expiryFields(receipt):null)}; - }; - const reconcile=async(slot,signal,adopting=false)=>{ const item=readJournal().items[slot.id]; const pendingKey=adopting?'pendingAdoption':'pendingOperation'; @@ -248,7 +238,6 @@ function createImageReconciler(canvas,{outputId,variantId},readJournal,update,{p pendingOperation:null,heldGeneration:false,heldOriginalId:null,heldOriginalProjectId:null, }); },{ - ...(original?.kind==='frozen-image'?{receipt:[archivedCandidate,phase,receipt]}:null), evidence:[slot.id,archivedCandidate,'candidate',{...receipt,sourceProjectId:item.heldOriginalProjectId}], }); const reason=receipt?.id===archivedCandidate?receipt.message:undefined; @@ -286,15 +275,15 @@ function createImageReconciler(canvas,{outputId,variantId},readJournal,update,{p const reason=receipt?.id===candidateId?receipt?.message??operation.message:operation.message; return {slotId:slot.id,phase,candidateId,operationId:original.operationId,reason,...expiry}; }; - return async (slot,adopting,original,signal)=>{ + return async (slot,adopting,signal)=>{ try { - return original?await reconcileImageRequest(slot,original,signal):await reconcile(slot,signal,adopting); + return await reconcile(slot,signal,adopting); } catch(error) { signal?.throwIfAborted(); onError?.(error); const item=readJournal().items[slot.id]; - const request=original??item?.[adopting?'pendingAdoption':'pendingOperation']; - const candidateId=original||adopting?request?.candidateId:originalCandidate(item); + const request=item?.[adopting?'pendingAdoption':'pendingOperation']; + const candidateId=adopting?request?.candidateId:originalCandidate(item); return {slotId:slot.id,operationId:request?.operationId,candidateId,phase:'unknown',reason:error.message}; } }; @@ -303,8 +292,13 @@ function createImageReconciler(canvas,{outputId,variantId},readJournal,update,{p export async function reconcileProjectImageSlots(host,{slotIds},signal) { const {canvas,store,productionGoal:goal}=host; const requested=new Set(slotIds); - const results=[]; - for(const {outputId,variantId} of goal.pendingOutputs??goal.requestedOutputs){ + const outputs=goal.pendingOutputs??goal.requestedOutputs; + const pending=(await canvas.imageRequest('pending',{})).filter(row=> + outputs.some(scope=>scope.outputId===row.outputId&&scope.variantId===row.variantId) + &&(!requested.size||requested.has(row.slotId))); + const results=await Promise.all(pending.map(async row=>({outputId:row.outputId,variantId:row.variantId, + ...await readNativeOriginal(canvas,row,{outputId:row.outputId,variantId:row.variantId})}))); + for(const {outputId,variantId} of outputs){ signal?.throwIfAborted(); const ledger=productionLedger(store,outputId,variantId); let journal=ledger.read(); @@ -315,8 +309,8 @@ export async function reconcileProjectImageSlots(host,{slotIds},signal) { await ledger.publishAudit(journal); },{projectScope:{outputId,variantId}}); for(const [id,item] of slots){ - for(const {adopting,frozen} of slotOriginals(item)){ - results.push({outputId,variantId,...await recover({id},adopting,frozen,signal)}); + for(const {adopting} of slotOriginals(item)){ + results.push({outputId,variantId,...await recover({id},adopting,signal)}); } } } @@ -344,7 +338,6 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen const {repository}=ledger; const previous=ledger.read(); let journal=previous?.binding===binding?previous:{binding,items:{}}; - if(previous)await ledger.publishAudit(previous); const evidenceMatches=(value,record=journal)=>Object.hasOwn(record,'copyInputs') ?record.copyInputs===productionInputs(value,variantId) :record.creationRevision===value.revisions?.creation; @@ -459,8 +452,11 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen return live.slots; }; const liveSlot=async slot=>(await liveSlots()).find(row=>row.id===slot.id)??slot; - const nativeGenerations=slot=>(slot.candidates??[]).filter(row=> - !row.sourceType&&!row.reusedFrom&&row.status!=='prepared').map(row=>row.id); + const nativeGenerations=slot=>[ + ...(slot.generationRequestIds??(slot.candidates??[]).filter(row=> + !row.sourceType&&!row.reusedFrom&&row.status!=='prepared').map(row=>row.id)), + ...[...dispatchingImages].filter(([,job])=>job?.slotId===slot.id).map(([id])=>id), + ]; const drawStatus=generationAttempts=>({ generationAttempts,maxGenerationAttempts, remainingGenerationAttempts:Math.max(0,maxGenerationAttempts-generationAttempts), @@ -565,8 +561,7 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen const jobProgress={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|| - Object.keys(item.pendingGenerations??{}).length).length}; + unresolved:Object.values(journal.items).filter(item=>item.pendingOperation||item.pendingAdoption).length}; const category=jobs.size?'remote_image':pendingReviews().length||runningScreens().length?'inference':'canvas_read'; await store.appendEvent({type:'production_progress',category,phase:'progress',status:'running',outputId,variantId,jobProgress}); const workers=new Map(); @@ -657,18 +652,6 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen tailWatcher.refresh(); } } - 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 transformImage=async(slot,{sourceCandidateId,referenceIndex,...transform},signal)=>{ signal?.throwIfAborted(); await current(); @@ -677,7 +660,7 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen const result={...receipt,candidateId:receipt.id,phase:'complete'}; await update(journal=>{ const item=journal.items[slot.id]??={}; - if(item.state!=='applied'&&!item.pendingOperation&&!item.pendingAdoption&&!Object.keys(item.pendingGenerations??{}).length){ + if(item.state!=='applied'&&!item.pendingOperation&&!item.pendingAdoption){ Object.assign(item,{state:'candidate',candidateId:receipt.id,source:'transform'}); } },{evidence:[slot.id,receipt.id,'candidate',receipt]}); @@ -688,152 +671,106 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen const prepareImageRequest=async(slot,{prompt,retryOf,useTemplateReference,prefer2k,geometryReferenceIndex, referenceIndexes,useSceneComposite,reworkCandidateId,reworkChange},signal)=>{ signal?.throwIfAborted(); - const input=await current(); + await current(); const live=await liveSlot(slot); const status=slotDrawStatus(live); if(status.drawLimitReached)return drawLimit(live,status); - const versions=recordProductionInputs(repository,input,slots); const receipt=await canvas.imageRequest('prepare',{slotId:slot.id,instructions:prompt,retryOf:retryOf?.trim()||undefined,useTemplateReference, prefer2k,geometryReferenceIndex,reworkOf:reworkCandidateId,reworkChange, ...(referenceIndexes?{referenceIndexes}:null),...(useSceneComposite!==undefined?{useSceneComposite}:null)}); - const {request}=await update(()=>{},{prepared:{...receipt,binding,...versions,knowledge:knowledge.files}}); - return {...receipt,operationId:request.operationId}; + return {...receipt,operationId:receipt.requestId}; }; - const preparedRequest=(requestId,slot)=>{ - const saved=repository.readImageRequest(requestId); - const request=saved?.prepared.binding===binding - ? {...saved.prepared,prompt:saved.prepared.spec.prompt,operationId:saved.operationId} - : journal.preparedRequests?.[requestId]; - if (!request || slot && request.slotId!==slot.id) throw Error('生图请求不属于本轮工作画布或委托图位'); - return request; - }; - const claimDispatch=async(slot,approval,request,signal)=>{ - signal?.throwIfAborted(); - await current(); - const live=await liveSlot(slot); - approval={requestId:approval.requestId,expectedRevision:approval.expectedRevision??request.revision, - expectedHash:approval.expectedHash??request.requestSpecHash}; - let claimedOperationId, submission; - const {claimed,pending,request:record,original,generationAttempts}=await commit(()=>{ - signal?.throwIfAborted(); - const claim=repository.claimImageRequest(approval,binding,(saved,prior)=>pendingGeneration(slot,saved)??prior, - {maxGenerationAttempts,nativeIds:nativeGenerations(live)}); - if(claim.claimed){ - claimedOperationId=claim.original.operationId; - submission=Promise.withResolvers(); - dispatchingImages.set(claimedOperationId,submission.promise); - } - return claim; - }).catch(error=>{ - submission?.resolve(); - dispatchingImages.delete(claimedOperationId); - tailWatcher.refresh(); - throw error; - }); - const {requestId:candidateId}=approval; - if(generationAttempts!==undefined){ - const status=drawStatus(generationAttempts); - return {receipt:drawLimit(await liveSlot(slot),status)}; + const preparedRequest=async(requestId,slot)=>{ + const receipt=await canvas.imageRequest('read',{requestId}); + if(receipt.requestId!==requestId||receipt.templateHash!==plan.template.contentHash|| + receipt.outputId!==outputId||receipt.variantId!==variantId||slot&&receipt.slotId!==slot.id){ + throw Error('生图请求不属于本轮工作画布或委托图位'); } - if(!claimed){ - if(pending)return {receipt:{phase:'unknown',...pending,pendingOriginal:pending.candidateId??pending.operationId}}; - const {state,operationId,receipt}=record; - const phase=settledImagePhases.includes(state)?state:'unknown'; - return {receipt:{phase,candidateId,operationId,reason:receipt?.message,...expiryFields(receipt), - ...(phase==='unknown'?{pendingOriginal:candidateId}:null)}}; - } - return {approval,original,onEnqueued:submission.resolve}; - }; - const dispatchImageRequest=async(slot,approval,request,original,workerNumber,onEnqueued)=>{ - const {requestId:candidateId}=approval; - const {operationId}=original; - let receipt; - try { receipt=await canvas.imageRequest('dispatch',{...approval,slotId:slot.id,workerNumber},{operationId,requestId:candidateId,onEnqueued}); } - catch(error) { - if (error.dispatched===false) { - await update(journal=>{delete journal.items[slot.id].pendingGenerations[candidateId];}, - {receipt:[candidateId,'prepared',{dispatched:false,message:error.message}]}); - return {phase:'failed',candidateId,operationId,reason:error.message}; - } - await update(()=>{},{receipt:[candidateId,'unknown',{message:error.message}]}); - throw error; - } - const phase=receipt.status??receipt.phase; - const settled=settledImagePhases.includes(phase); - const late=host.productionSignal?.aborted; - const evidence={...receipt,requestId:candidateId,operationId,reworkOf:request.reworkOf, - ...(late?{consumption:'archived_after_cancel'}:null)}; - await update(journal=>{ - const item=journal.items[slot.id]??={}; - if(settled)delete item.pendingGenerations[candidateId]; - 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}); - if(late)return; - if(settled)Object.assign(item,{candidateId,state:phase==='complete'?'candidate':phase}); - Object.assign(item,{prompt:request.prompt,source:'generate'}); - rememberImageExpiry(item,candidateId,receipt); - },{receipt:[candidateId,settled?phase:'unknown',evidence], - evidence:[slot.id,candidateId,'candidate',evidence]}); - await store.appendEvent({type:'image_request_receipt',operationId,requestId:candidateId,outputId,variantId,slotId:slot.id, - category:'remote_image',phase:'archive',status:late?'cancelled':settled?phase:'unknown',consumption:evidence.consumption}) - .catch(error=>console.warn('小壹生图事件写入失败',error.code ?? error.name)); - if(late)return {candidateId,operationId,phase:'cancelled',consumption:evidence.consumption}; - return {candidateId,operationId,phase:settled?phase:'unknown',reason:receipt.message, - requestedSource:'generate',...expiryFields(receipt),...(request.reworkOf?{reworkOf:request.reworkOf}:null), - ...(!settled?{pendingOriginal:candidateId}:null), - ...(receipt.retryableFailure===true?{retryableFailure:true,retryAfterSeconds:receipt.retryAfterSeconds}:null)}; - }; - const launchImage=(slot,key,operation,requestId,workerNumber)=>{ - if(jobs.has(key))return {...generation.get(key),phase:'already_running'}; - const pending=!requestId&&pendingGeneration(slot); - if(pending)return pending; - const receipt={slotId:slot.id,phase:'accepted',...(requestId?{candidateId:requestId,operationId:key}:null)}; - const row={number:workerNumber??nextWorkerNumber(),slotId:slot.id,label:slot.label,step:requestId?'正在生图':'生成',active:true}; - generation.delete(key); - generation.set(key,receipt); - const run=Promise.resolve().then(()=>operation(row.number)) - .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}); - if(workerNumber===undefined)notice(requestId?'正在生图':'正在制作候选图片'); return receipt; }; + const dispatchImageRequest=async(slot,approval,request,workerNumber,onEnqueued)=>{ + const {requestId:candidateId}=approval; + const receipt=await canvas.imageRequest('dispatch',{requestId:candidateId,slotId:slot.id,workerNumber, + expectedRevision:approval.expectedRevision??request.revision,expectedHash:approval.expectedHash??request.requestSpecHash}, + {operationId:candidateId,requestId:candidateId,onEnqueued}); + 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, + requestedSource:'generate',...expiryFields(receipt),...(request.reworkOf?{reworkOf:request.reworkOf}:null), + ...(!settledImagePhases.includes(phase)?{pendingOriginal:candidateId}:null), + ...(receipt.retryableFailure===true?{retryableFailure:true,retryAfterSeconds:receipt.retryAfterSeconds}:null)}; + }; const queueDispatch=async(slot,approval,request,signal,workerNumber)=>{ - const key=request.operationId??approval.requestId; - if(jobs.has(key))return {...generation.get(key),phase:'already_running'}; - const claim=await claimDispatch(slot,approval,request,signal).catch(error=>({error})); - if(claim.receipt?.limitReached)return claim.receipt; - if(claim.receipt?.pendingOriginal&&!jobs.has(key)){ - return {slotId:slot.id,...claim.receipt}; + await current(); + const live=await liveSlot(slot); + signal.throwIfAborted(); + const id=approval.requestId; + if(jobs.has(id))return {slotId:slot.id,candidateId:id,operationId:id,phase:'already_running'}; + if(request.phase!=='prepared'){ + const phase=request.phase==='applied'?'complete':settledImagePhases.includes(request.phase)?request.phase:'unknown'; + return {slotId:slot.id,candidateId:id,operationId:id,phase, + reason:request.message,...(!settledImagePhases.includes(phase)?{pendingOriginal:id}:null),...expiryFields(request)}; } - return launchImage(slot,key,number=>{ - if(claim.error)throw claim.error; - return claim.receipt??dispatchImageRequest(slot,claim.approval,request,claim.original,number,claim.onEnqueued).finally(()=>{ - claim.onEnqueued(); - dispatchingImages.delete(claim.original.operationId); - tailWatcher.refresh(); + const status=slotDrawStatus(live); + if(status.drawLimitReached)return drawLimit(live,status); + const original=(live.candidates??[]).find(row=>!row.sourceType&&!row.reusedFrom&& + ['dispatched','running','unknown'].includes(row.status)); + if(original)return {slotId:slot.id,phase:'unknown',candidateId:original.id,pendingOriginal:original.id}; + const sending=[...dispatchingImages].find(([,job])=>job?.slotId===slot.id); + if(sending)return {slotId:slot.id,phase:'unknown',candidateId:sending[0],pendingOriginal:sending[0]}; + + const submission=Promise.withResolvers(); + dispatchingImages.set(id,{slotId:slot.id,enqueued:submission.promise}); + const row={number:workerNumber??nextWorkerNumber(),slotId:slot.id,label:slot.label,step:'正在生图',active:true}; + 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})) + .finally(()=>{ + submission.resolve(); + dispatchingImages.delete(id); + jobs.delete(id); + notice('候选图片回执'); }); - },approval.requestId,workerNumber); + jobs.set(id,{row,run,requestId:id}); + if(workerNumber===undefined)notice('正在生图'); + return {slotId:slot.id,phase:'accepted',candidateId:id,operationId:id}; }; const useProductImage=async(slot,options,signal)=>({ ...await operate(slot,'generate_candidate',{useProductReference:true,...options},signal,{source:'product'}), requestedSource:'product',sourceNote:'仅使用或裁切原片,保留原片的背景和光线。', }); + const launchProductImage=(slot,options,signal)=>{ + const key=slot.id; + if(jobs.has(key))return {...generation.get(key),phase:'already_running'}; + const receipt={slotId:key,phase:'accepted'}; + const row={number:nextWorkerNumber(),slotId:key,label:slot.label,step:'生成',active:true}; + generation.set(key,receipt); + const run=useProductImage(slot,options,signal) + .catch(error=>({phase:'failed',reason:error.message})) + .then(result=>{ + const receipt={slotId:key,...result}; + generation.set(key,receipt); + return receipt; + }) + .finally(()=>{jobs.delete(key);return notice('候选图片回执');}); + jobs.set(key,{row,run}); + notice('正在制作候选图片'); + return receipt; + }; const reportRecoveryError=error=>console.warn('原图片请求核查失败',error.code??error.name); const recoverImage=createImageReconciler(canvas,{outputId,variantId},()=>journal,update,{ onAdopted:(id,candidateId)=>filled.set(id,candidateId), onError:reportRecoveryError, }); + const pendingNative=async()=> (await canvas.imageRequest('pending',{})).filter(row=> + row.outputId===outputId&&row.variantId===variantId); + const dispatchedImages=()=>[...dispatchingImages].flatMap(([candidateId,job])=> + job?[{slotId:job.slotId,candidateId,operationId:candidateId}]:[]); const outstanding=async()=>{ await journalWrite; - const requests=imageOriginals(journal); + const requests=[...imageOriginals(journal),...await pendingNative(),...dispatchedImages()]; const images=[...new Set(requests.filter(row=>!row.projectId&&!row.adoption&&row.candidateId).map(row=>row.candidateId))]; return {requests,originals:{models:[],images}}; }; @@ -854,10 +791,10 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen async probe({slot,key},signal){ const tail=tailsFor(slot).find(tail=>tail.key===key); if(!tail)return {slotId:slot.id,phase:'none'}; - const {adopting,frozen,request:{candidateId,operationId}}=tail; + const {adopting,request:{candidateId,operationId}}=tail; if(dispatchingImages.has(operationId))return {slotId:slot.id,candidateId,operationId,phase:'unknown'}; const alreadyPlaced=adopting&&filled.get(slot.id)===candidateId; - const receipt=await recoverImage(slot,adopting,frozen,signal); + const receipt=await recoverImage(slot,adopting,signal); signal.throwIfAborted(); if(!adopting&&receipt.phase!=='none'){ const original=[...generation.entries()].find(([,row])=>row.slotId===slot.id&&row.phase==='unknown'&& @@ -882,8 +819,8 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen }); async function check(slot,candidateId,adopted,signal){ const item=journal.items[slot.id]; - const request=repository.readImageRequest(candidateId); - const source=request?.slotId===slot.id?'generate':item?.candidateId===candidateId?item.source:undefined; + const live=await liveSlot(slot); + const source=nativeGenerations(live).includes(candidateId)?'generate':item?.candidateId===candidateId?item.source:undefined; try{ const liveScreenCopy=await liveSlotCopy(slot); const {referenceCount,...review}=await reviewProductionCandidate({canvas,runAgent:host.runDetailAgent, @@ -900,7 +837,8 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen history.push({candidateId,verdict,reason,recommendedAction,canvasTransform,mustRedo:observation.mustRedo,generationFixes:observation.generationFixes}); },{evidence:[slot.id,candidateId,'review',row]}); candidates.set(candidateId,{slotId:slot.id,status:verdict==='pass'?'passed':'rejected',reason}); - const reworkOf=journal.items[slot.id]?.attempts?.find(row=>row.candidateId===candidateId)?.reworkOf; + const reworkOf=live.candidates?.find(row=>row.id===candidateId)?.reworkOf ?? + item?.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)}; @@ -917,15 +855,19 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen stageController.abort(); await canvasWrite; await journalWrite; + tailWatcher.close(); // Hand off only after admitted requests have entered the native transport. - await Promise.all(dispatchingImages.values()); - const inFlightImages=imageOriginals(journal) + const dispatches=dispatchedImages(); + await Promise.all([...dispatchingImages.values()].map(job=>job?.enqueued)); + const native=host.productionCompletion||host.productionSignal?.aborted?[]:await pendingNative(); + const originalImages=[...imageOriginals(journal),...native,...dispatches]; + const inFlightImages=[...new Map(originalImages.filter(row=>row.candidateId) + .map(row=>[row.candidateId,row])).values()] .filter(({candidateId,projectId,adoption})=>candidateId&&!projectId&&!adoption) .map(({slotId,candidateId,operationId})=>({slotId,requestId:candidateId,operationId})); const inFlightSlots=new Set(inFlightImages.map(image=>image.slotId)); const cancelledSlots=delegates.filter(([key,{row,dispatched}])=> !inFlightSlots.has(row.slotId)&&!dispatched.size&&!generation.get(key)?.candidateId).map(([,job])=>job.row.slotId); - tailWatcher.close(); return {outputId,variantId,cancelledSlots,inFlightImages}; }, screenReviewRevisions, @@ -1062,7 +1004,7 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen use_product_image({slotId,...options},signal){ signal?.throwIfAborted(); const slot=matches(slotId); - return launchImage(slot,slot.id,()=>useProductImage(slot,options,signal?AbortSignal.any([signal,stageSignal]):stageSignal)); + return launchProductImage(slot,options,signal?AbortSignal.any([signal,stageSignal]):stageSignal); }, transform_slot_image({slotId,...options},signal){ return serialize(()=>transformImage(matches(slotId),options,signal)); @@ -1071,7 +1013,7 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen return prepareImageRequest(matches(slotId),args,signal); }, async dispatch_image_request(approval,signal){ - const request=preparedRequest(approval.requestId); + const request=await preparedRequest(approval.requestId); const slot=matches(request.slotId); return queueDispatch(slot,approval,request,signal?AbortSignal.any([signal,stageSignal]):stageSignal); }, @@ -1115,12 +1057,12 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen (args,activeSignal)=>prepareImageRequest(slot,{...args,reworkCandidateId:rework?.candidateId},activeSignal)), workerTool('dispatch_image_request','审阅准备回执后填写 requestId 确认派发',dispatchArgs, async (approval,activeSignal)=>{ - const request=preparedRequest(approval.requestId,slot); + const request=await preparedRequest(approval.requestId,slot); row.step='正在生图'; notice('子代理正在生图'); const receipt=await queueDispatch(slot,approval,request,activeSignal,row.number); if(receipt.operationId)dispatched.add(receipt.operationId); - await dispatchingImages.get(receipt.operationId); + await dispatchingImages.get(receipt.operationId)?.enqueued; return receipt; },result=>!result.limitReached), ]; @@ -1194,9 +1136,14 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen const scope=slotIds?.length||!selected.length?wanted:new Set(selected.map(job=>job.row.slotId)); const screens=slotIds?.length?[]:[...screenChecks.values()]; const pending=[...selected,...screens.filter(job=>job.run)].map(job=>job.run); - if(pending.length)await Promise.race(pending); + const receipt=pending.length?await Promise.race(pending):undefined; + const native=(await liveSlots()).filter(slot=>scope.has(slot.id)).flatMap(slot=> + (slot.candidates??[]).filter(row=>!row.sourceType&&!row.reusedFrom).map(row=> + ({...row,slotId:slot.id,candidateId:row.id,operationId:row.id,phase:row.status,reason:row.message??row.error}))) + .sort((a,b)=>(b.sequence??0)-(a.sequence??0)); + const completed=receipt?.operationId&&scope.has(receipt.slotId)?[receipt]:[]; return {active:jobs.size,checking:pendingReviews().length, - generation:generationReceipts(scope), + generation:[...completed,...generationReceipts(scope),...native.filter(row=>row.candidateId!==completed[0]?.candidateId)], checks:[...reviewWork].filter(job=>scope.has(job.row.slotId)).map(job=>job.receipt), ...(screens.length?{screenChecks:screens.map(job=>job.receipt)}:null)}; }, @@ -1224,8 +1171,13 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen const record=journal.items[id]; const {attemptCount,rejections}=slotAttempts(slot,record); const status=statuses.get(id); - const latest=candidates?.at(-1); - const generations=generationReceipts(new Set([id])); + const ordered=(candidates??[]).toSorted((a,b)=>(b.sequence??0)-(a.sequence??0)); + const latest=ordered[0]; + const sending=[...jobs.values()].filter(job=>job.requestId&&job.row.slotId===id) + .map(({requestId})=>({slotId:id,candidateId:requestId,operationId:requestId,phase:'accepted'})); + const generations=[...sending,...ordered.filter(row=>!row.sourceType&&!row.reusedFrom&& + !sending.some(receipt=>receipt.candidateId===row.id)) + .map(row=>({...row,candidateId:row.id,phase:row.status})),...generationReceipts(new Set([id]))]; const [generationReceipt]=generations; const latestCandidateId=latest?.id??generationReceipt?.candidateId??record?.candidateId; const reviews=checks.get(id)??[]; @@ -1234,7 +1186,7 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen const decision=record?.review?.candidateId===latestCandidateId?record?.review?.decision:undefined; const adopted=selectedCandidateId&&selectedCandidateId===latestCandidateId; const state=slotWorking(id)?'generating':reviews.some(job=>job.run)?'checking': - record?.pendingOperation||record?.pendingAdoption||originalCandidate(record)||Object.keys(record?.pendingGenerations??{}).length?'unknown': + slotOriginals(record).length?'unknown': adopted?'applied': decision??generationReceipt?.phase??latest?.status??record?.state??'empty'; return {id,fieldId,label,state,selectedCandidateId,latestCandidateId,attemptCount,...status,rejectionCount:rejections.length}; @@ -1300,21 +1252,16 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen const generated=nativeGenerations(await liveSlot(slot)).includes(candidateId); const result=await serialize(()=>canvas.detailRetire(slot.id,candidateId,reason)); if(result.status==='retired'){ - const request=repository.readImageRequest(candidateId); await update(journal=>{ if(!journal.items[slot.id]&&!generated)return; const item=journal.items[slot.id]??={}; - if(generated&&!(item.attempts??[]).some(row=>row.candidateId===candidateId)){ - (item.attempts??=[]).push({candidateId,source:'generate'}); - } 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}], - ...(request?{receipt:[candidateId,'retired',result]}:null)}); + },{evidence:[slot.id,candidateId,'retirement',{...result,reason}]}); candidates.delete(candidateId); host.generatedCandidates?.delete(candidateId); markProgressDirty(); @@ -1332,8 +1279,14 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen if(tails.every(tail=>tail.adopting))receipts.unshift({slotId:slot.id,phase:'none'}); return receipts; })); + const pending=await pendingNative(); signal?.throwIfAborted(); - return results; + const ids=new Set(selected.map(slot=>slot.id)); + const originals=await Promise.all(pending.filter(row=>ids.has(row.slotId)) + .map(row=>readNativeOriginal(canvas,row))); + signal?.throwIfAborted(); + const pendingSlots=new Set(originals.map(row=>row.slotId)); + return [...originals,...results.filter(row=>row.phase!=='none'||!pendingSlots.has(row.slotId))]; }, async read_output_screen({page=0,pages},signal){ const render=async page=>{ diff --git a/apps/detail-agent-pi/src/production-repository.mjs b/apps/detail-agent-pi/src/production-repository.mjs index a3622bd4..2bda0d37 100644 --- a/apps/detail-agent-pi/src/production-repository.mjs +++ b/apps/detail-agent-pi/src/production-repository.mjs @@ -18,7 +18,11 @@ export function productionLedger(store, outputId, variantId) { // PhotoCraft consumes this view for adoption, archives and .xiaoyi saves. // On the original project, SQLite owns all changes after the first import. const publishAudit = async journal => { - const view = repository.exportLedger(journal); + const {preparedRequests, ...audit} = journal; + const view = {...audit, items:Object.fromEntries(Object.entries(journal.items).map(([id, item])=>{ + const {pendingGenerations, ...record} = item; + return [id, record]; + }))}; const encoded = JSON.stringify(view, null, 2); if (published === undefined) { try { published = await fs.readFile(legacyFile, 'utf8'); } diff --git a/apps/detail-agent-pi/src/project-repository.mjs b/apps/detail-agent-pi/src/project-repository.mjs index a720ab04..b591900b 100644 --- a/apps/detail-agent-pi/src/project-repository.mjs +++ b/apps/detail-agent-pi/src/project-repository.mjs @@ -38,6 +38,7 @@ const schema = ` value_json TEXT NOT NULL, PRIMARY KEY (${scopeColumns}, kind, record_id, revision) ) STRICT; + -- Historical R2/R3 request records. The host owns new image requests. CREATE TABLE image_requests ( ${scopeDefinition}, request_id TEXT NOT NULL, @@ -170,30 +171,14 @@ export class ProjectRepository { }); } - exportLedger(journal) { - return this.#open(db => { - const rows = db.prepare(`SELECT request_id, prepared_json FROM image_requests WHERE ${scopeWhere}`).all(...this.scope); - const requests = rows.map(row => [row.request_id, JSON.parse(row.prepared_json)]) - .filter(([, draft]) => draft.binding === journal.binding); - if (!requests.length) return journal; - const preparedRequests = { ...journal.preparedRequests, ...Object.fromEntries( - requests.map(([id, { slotId, spec, reworkOf, reworkChange }]) => - [id, { slotId, prompt: spec.prompt, reworkOf, reworkChange }]), - ) }; - return { ...journal, preparedRequests }; - }); - } - - updateLedger(binding, change, { prepared, policy, candidateSetId, receipt, evidence } = {}) { + updateLedger(binding, change, { 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); - const request = prepared && this.#saveImageRequest(db, prepared, policy, candidateSetId); - if (receipt) this.#recordImageReceipt(db, ...receipt); if (evidence) this.#recordCandidate(db, ...evidence); - return { journal, result, request }; + return { journal, result }; })); } @@ -231,39 +216,6 @@ export class ProjectRepository { }); } - #saveImageRequest(db, receipt, policy, candidateSetId) { - const { requestId, operationId = requestId, slotId, requestSpecHash, revision } = 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 }; - } - db.prepare(`INSERT INTO image_requests (${scopeColumns}, request_id, operation_id, slot_id, request_spec_hash, - revision, state, prepared_json) VALUES (${scopeValues}, ?, ?, ?, ?, ?, 'prepared', ?) - ON CONFLICT (${scopeColumns}, request_id) DO NOTHING`).run( - ...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) { - return this.#open(db => transaction(db, () => this.#saveImageRequest(db, receipt))); - } - #readRequest(db, requestId) { const row = db.prepare(`SELECT * FROM image_requests WHERE ${scopeWhere} AND request_id = ?`).get(...this.scope, requestId); if (!row) return null; @@ -277,21 +229,10 @@ 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)); - } - #countImageGenerations(requests, nativeIds, item) { const ids = new Set(nativeIds); - for (const {request_id, state, receipt_json} of requests) { + for (const {request_id, state} of requests) { if (state !== 'prepared') ids.add(request_id); - else if (receipt_json && JSON.parse(receipt_json).dispatched === false) ids.delete(request_id); } for (const row of item?.attempts ?? []) if (row.source === 'generate' && row.candidateId) ids.add(row.candidateId); for (const id of Object.keys(item?.pendingGenerations ?? {})) ids.add(id); @@ -303,7 +244,7 @@ export class ProjectRepository { } #generationRequests(db, binding, slotId) { - return db.prepare(`SELECT slot_id, request_id, state, receipt_json FROM image_requests + return db.prepare(`SELECT slot_id, request_id, state FROM image_requests WHERE ${scopeWhere} AND json_extract(prepared_json, '$.binding') = ?${slotId ? ' AND slot_id = ?' : ''}`) .all(...this.scope, binding, ...(slotId ? [slotId] : [])); } @@ -318,72 +259,6 @@ export class ProjectRepository { }); } - claimImageRequest({ requestId, expectedRevision, expectedHash }, binding, pendingGeneration, generationLimit) { - return this.#open(db => transaction(db, () => { - const request = this.#readRequest(db, requestId); - if (request && (request.prepared.binding !== binding || - request.revision !== expectedRevision || request.requestSpecHash !== expectedHash)) { - throw Error('生图请求版本已变化,请重新准备'); - } - const previous = this.#readLedger(db); - const journal = previous?.binding === binding ? structuredClone(previous) : { binding, items: {} }; - const slotId = request?.slotId ?? journal.preparedRequests?.[requestId]?.slotId; - if (!slotId) throw Error('生图请求不属于本轮工作画布或委托图位'); - const item = journal.items[slotId] ??= {}; - const sameOperation = item.pendingGenerations?.[requestId]; - const expired = !request && item.attempts?.find(attempt => attempt.candidateId === requestId && attempt.phase === 'expired'); - if (expired) return { journal, request: { state: 'expired', operationId: requestId, receipt: expired }, claimed: false }; - if (sameOperation || request && request.state !== 'prepared') { - return { journal, pending: sameOperation, request, claimed: false }; - } - if (generationLimit) { - const {maxGenerationAttempts, nativeIds} = generationLimit; - const requests = this.#generationRequests(db, binding, slotId); - const generationAttempts = this.#countImageGenerations(requests, nativeIds, item); - if (generationAttempts >= maxGenerationAttempts) return { journal, claimed: false, generationAttempts }; - const set = request?.prepared.candidateSet; - if (set && this.#candidateSet(db, slotId, set.id).length !== set.policy.candidateCount) { - throw Error('请先按政策准备齐全同批候选,再分别确认派发'); - } - } - const priorGeneration = Object.values(item.pendingGenerations ?? {}).find(original => { - const prior = this.#readRequest(db, original.candidateId); - return !request?.prepared.candidateSet || - prior?.prepared.candidateSet?.id !== request.prepared.candidateSet.id; - }); - const priorState = priorGeneration && this.#readRequest(db, priorGeneration.candidateId)?.state; - const pending = pendingGeneration?.(journal, priorGeneration) ?? - (priorState !== 'dispatching' ? priorGeneration : undefined); - 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' }; - (item.pendingGenerations ??= {})[requestId] = original; - this.#writeLedger(db, journal, previous); - return { journal, original, claimed: true }; - })); - } - - #recordImageReceipt(db, requestId, state, receipt) { - // Expiration is a terminal failure to retrieve the result. Its receipt carries - // the exact outcome, with the same durable schema as earlier projects. - db.prepare(`UPDATE image_requests SET state = ?, receipt_json = ? - WHERE ${scopeWhere} AND request_id = ? AND json_extract(receipt_json, '$.resultExpiry') IS NULL`) - .run(state === 'expired' ? 'failed' : state, json(receipt), ...this.scope, requestId); - } - - recordImageReceipt(requestId, state, receipt) { - this.#open(db => this.#recordImageReceipt(db, requestId, state, receipt)); - } - #recordCandidate(db, slotId, candidateId, kind, detail) { db.prepare(`INSERT INTO candidate_evidence (${scopeColumns}, slot_id, candidate_id, kind, detail_json) VALUES (${scopeValues}, ?, ?, ?, ?)`).run(...this.scope, slotId, candidateId, kind, json(detail)); diff --git a/apps/detail-agent-pi/test/copy-image-alignment.test.mjs b/apps/detail-agent-pi/test/copy-image-alignment.test.mjs index 7d8a15cd..fe13fae9 100644 --- a/apps/detail-agent-pi/test/copy-image-alignment.test.mjs +++ b/apps/detail-agent-pi/test/copy-image-alignment.test.mjs @@ -120,6 +120,7 @@ test('production delegation and screen rendering use live copy after a direct ca {nativeLayerId:42,mapped:true,text:null,bounds:[32,40,90,130],overlapsSlots:[slot.id]}, ]; const host={store:productionStore(dir),productionGoal:{outputId:'detail',variantId:'oak'},canvas:{ + imageRequest:async()=>[], workflowRead:async()=>({available:true,canvasFirst:true,outputId:'detail',productVariantId:'oak', template:{contentHash:'fixture'},totalSlots:1,slots:[slot]}), detailCopyFields:async options=>{ @@ -169,6 +170,7 @@ test('switching outputs discards the prior canvas copy reads and uses the new li outputId=binding.outputId; return binding; }, + imageRequest:async()=>[], workflowRead:async()=>({available:true,canvasFirst:true,outputId,productVariantId:variantId, template:{contentHash:'fixture'},totalSlots:1,slots:[slot]}), detailCopyFields:async()=>({revision,pages,fields:[{...fields[0],currentText:copyByOutput[outputId]}]}), diff --git a/apps/detail-agent-pi/test/native-wire.test.mjs b/apps/detail-agent-pi/test/native-wire.test.mjs index ec835342..08c741f9 100644 --- a/apps/detail-agent-pi/test/native-wire.test.mjs +++ b/apps/detail-agent-pi/test/native-wire.test.mjs @@ -371,6 +371,7 @@ test('Pi loads the Skill and opens a project-selected output with the same sessi } return sse({content:'已核对画册。'},'stop'); },undefined,{outputs,template,callBudget:8,canvas:{ + imageRequest:async()=>[], workflowRead:async()=>({available:true,canvasFirst:true,version:1,outputId:'gallery',productVariantId:outputs[1].variantId, template:{contentHash:'fixture'},totalSlots:0,slots:[]}), requestWrite(){assert.fail('selection should not ask for canvas write access');}, diff --git a/apps/detail-agent-pi/test/production-operations.test.mjs b/apps/detail-agent-pi/test/production-operations.test.mjs index dc9a3b4f..6679eda2 100644 --- a/apps/detail-agent-pi/test/production-operations.test.mjs +++ b/apps/detail-agent-pi/test/production-operations.test.mjs @@ -5,35 +5,80 @@ import assert from 'node:assert/strict'; import fs from 'node:fs/promises'; import os from 'node:os'; import path from 'node:path'; -import { openProductionOperations } from '../src/production-operations.mjs'; +import { openProductionOperations as openOperations } from '../src/production-operations.mjs'; import { callProductionTool, closeProductionTurn, mayContinueProductionGoal } from '../src/production-goal.mjs'; import { cleanup } from './cleanup.mjs'; import { bindRecovery } from '../src/desktop-host.mjs'; import { productionStore } from './production-store-fixture.mjs'; +const imageBridges=new WeakSet(); + +// The fixture models the host journal. Each Pi operations instance reads it anew. function imageBridge(host,dispatch,id=()=>randomUUID()) { const prepared=new Map(); - host.canvas.imageRequest=async(action,args,execution)=>{ + const canvas=host.canvas; + imageBridges.add(canvas); + const workflowRead=canvas.workflowRead.bind(canvas); + const originalRecovery=canvas.detailRecover?.bind(canvas); + canvas.workflowRead=async input=>{ + const view=await workflowRead(input); + const matching=[...prepared.values()].filter(({receipt})=> + receipt.outputId===view.outputId&&receipt.variantId===view.productVariantId&&receipt.phase!=='prepared'); + return {...view,slots:view.slots?.map(slot=>({...slot,candidates:[ + ...(slot.candidates??[]),...matching.filter(({receipt})=>receipt.slotId===slot.id&& + !slot.candidates?.some(row=>row.id===receipt.requestId)) + .map(({receipt,result},index)=>({...result,id:receipt.requestId,status:receipt.phase,sequence:(slot.candidates?.length??0)+index+1, + reworkOf:receipt.reworkOf,instructions:receipt.spec.prompt})), + ]}))}; + }; + const settle=(receipt,result)=>{ + Object.assign(receipt,{phase:result.status,resultExpiry:result.resultExpiry,message:result.message}); + prepared.get(receipt.requestId).result=result; + }; + canvas.detailRecover=async(slot,options,scope)=>{ + const result=await originalRecovery(slot,options,scope); + const {receipt}=prepared.get(options.candidateId)??{}; + if(receipt)settle(receipt,result); + return result; + }; + canvas.imageRequest=async(action,args,execution)=>{ + if(action==='pending')return [...prepared.values()].filter(({receipt})=> + ['dispatched','running','unknown'].includes(receipt.phase)).map(({receipt})=>({ + slotId:receipt.slotId,candidateId:receipt.requestId,operationId:receipt.requestId, + phase:receipt.phase,outputId:receipt.outputId,variantId:receipt.variantId, + })); if(action==='prepare'){ const requestId=id(); - const receipt={requestId,revision:1,requestSpecHash:'fixture-digest',frozen:false, + const receipt={requestId,revision:1,requestSpecHash:'fixture-digest',frozen:false,phase:'prepared', + templateHash:(await workflowRead({section:'overview',outputId:host.productionGoal.outputId})).template.contentHash, outputId:host.productionGoal.outputId,variantId:host.productionGoal.variantId,slotId:args.slotId, reworkOf:args.reworkOf,reworkChange:args.reworkChange,spec:{prompt:args.instructions}}; prepared.set(requestId,{receipt,args}); return structuredClone(receipt); } - assert.equal(action,'dispatch'); - assert.deepEqual(Object.keys(args),['requestId','expectedRevision','expectedHash','slotId','workerNumber']); const request=prepared.get(args.requestId); - assert.ok(request); + if(!request)throw Error('未找到原生生图请求'); + if(action==='read')return structuredClone(request.receipt); + assert.equal(action,'dispatch'); assert.equal(args.slotId,request.receipt.slotId); if(args.expectedHash!==request.receipt.requestSpecHash||args.expectedRevision!==request.receipt.revision){ - throw new BridgeError('生图请求版本已变化,请重新准备'); + throw Object.assign(new BridgeError('生图请求版本已变化,请重新准备'),{dispatched:false}); } if(dispatch.length<4)execution?.onEnqueued?.(); - return dispatch(request.args,args.requestId,args.workerNumber,execution?.onEnqueued); + request.receipt.phase='dispatched'; + const result=await dispatch(request.args,args.requestId,args.workerNumber,execution?.onEnqueued); + settle(request.receipt,result); + return result; }; + return {prepared,settle}; } +function openProductionOperations(host,options){ + const canvas=host.canvas; + const original=canvas.imageRequest?.bind(canvas); + canvas.imageRequest=async(action,...args)=> action==='pending'&&!imageBridges.has(canvas) ? [] : original(action,...args); + return openOperations(host,options); +} + function approve({requestId,revision,requestSpecHash}) { return {requestId,expectedRevision:revision,expectedHash:requestSpecHash}; } @@ -73,7 +118,7 @@ async function tailFixture(t,ids,items={}){ const host={store,productionGoal:{outputId:'detail',variantId:'oak'},canvas:{ workflowRead:async()=>({available:true,canvasFirst:true,outputId:'detail',productVariantId:'oak', template:{contentHash:'studio'},totalSlots:slots.length,slots}), - detailCopyFields:async()=>({fields:[]}), + imageRequest:async()=>[],detailCopyFields:async()=>({fields:[]}), async delta(_text,_thinking,{heading}){notices.get(heading)?.resolve();}, }}; if(Object.keys(items).length)ledger.repository.replaceLedger({binding:JSON.stringify(['studio','oak']),items}); @@ -84,50 +129,34 @@ async function tailFixture(t,ids,items={}){ }}; } -test('a newly uncertain dispatch and a restored frozen request are watched without posting again',{timeout:5000},async t=>{ - for(const reopen of [false,true])await t.test(reopen?'restored from the ledger':'reported during production',async t=>{ - const {dir,host,ledger,clock,notice}=await tailFixture(t,['hero']); - const posted=[],reads=[]; - const recovered=notice('原请求结果已取回'); - const result=Promise.withResolvers(); - imageBridge(host,async(_args,id)=>{ - posted.push(id); - return {id,status:'unknown'}; - }); - host.canvas.detailRecover=async(slotId,{candidateId})=>{ - reads.push({slotId,candidateId}); - return result.promise; - }; - let actions=await openProductionOperations(host,{tailWatchClock:clock}); - assert.equal(clock.nextDue,undefined); - const original=await generateAndWait(actions,{slotId:'hero',prompt:'保留同款结构'}); - assert.equal(original.phase,'unknown'); - if(reopen){ - await actions.close(); - assert.equal(clock.nextDue,undefined); - actions=await openProductionOperations(host,{tailWatchClock:clock}); - } - t.after(()=>actions.close()); - assert.equal(clock.nextDue,0); - await clock.advance(); - const manual=actions.reconcile_image_slots({slotIds:['hero']}); - assert.deepEqual(reads,[{slotId:'hero',candidateId:original.candidateId}]); - const localImage=path.join(dir,'recovered-image.png'); - await fs.writeFile(localImage,'native image fixture'); - result.resolve({id:original.candidateId,status:'complete',path:localImage}); - const [receipt]=await manual; - await recovered; - assert.equal(receipt.phase,'complete'); - assert.equal(receipt.operationId,original.operationId); - assert.deepEqual(reads,[{slotId:'hero',candidateId:original.candidateId}]); - assert.deepEqual(posted,[original.candidateId]); - assert.deepEqual((await actions.await_image_slots({slotIds:['hero']})).generation,[receipt]); - assert.equal(ledger.repository.readImageRequest(original.candidateId).receipt.path,localImage); - const saved=JSON.parse(await fs.readFile(path.join(dir,'production-detail-oak.json'),'utf8')); - assert.deepEqual(saved.items.hero.pendingGenerations,{}); - assert.equal(saved.items.hero.state,'candidate'); - assert.equal(clock.nextDue,undefined); +test('a host-owned original survives a Pi restart and is recovered without another POST',async t=>{ + const {dir,host,ledger,clock}=await tailFixture(t,['hero']); + const posted=[],reads=[]; + host.canvas.detailRecover=async(slotId,{candidateId})=>{ + reads.push({slotId,candidateId}); + return {id:candidateId,status:'complete'}; + }; + imageBridge(host,async(_args,id)=>{ + posted.push(id); + return {id,status:'unknown'}; }); + let actions=await openProductionOperations(host,{tailWatchClock:clock}); + const original=await generateAndWait(actions,{slotId:'hero',prompt:'保留同款结构'}); + assert.equal(original.phase,'unknown'); + const closed=await actions.close(); + assert.deepEqual(closed.inFlightImages,[{slotId:'hero',requestId:original.candidateId,operationId:original.operationId}]); + actions=await openProductionOperations(host,{tailWatchClock:clock}); + t.after(()=>actions.close()); + assert.equal(clock.nextDue,undefined); + assert.equal((await actions.dispatch_image_request({requestId:original.candidateId})).pendingOriginal,original.candidateId); + const [receipt]=await actions.reconcile_image_slots({slotIds:['hero']}); + assert.equal(receipt.phase,'complete'); + assert.equal(receipt.operationId,original.operationId); + assert.deepEqual(reads,[{slotId:'hero',candidateId:original.candidateId}]); + assert.deepEqual(posted,[original.candidateId]); + assert.equal(ledger.repository.readImageRequest(original.candidateId),null); + assert.equal(ledger.read(),null); + await assert.rejects(fs.stat(path.join(dir,'production-detail-oak.json')),{code:'ENOENT'}); }); test('six original lookups run while all six generation delegates are posting',{timeout:8000},async t=>{ @@ -437,7 +466,7 @@ test('a late image settles its original request after cancellation without selec detailCopyFields:async()=>({fields:[]}),delta:async()=>{}, workflowExecute:async()=>assert.fail('a cancelled candidate cannot be adopted'), }}; - imageBridge(host,async(_args,id)=>{started.resolve();await done.promise;return {id,status:'complete'};}); + const native=imageBridge(host,async(_args,id)=>{started.resolve();await done.promise;return {id,status:'complete'};}); const old=await openProductionOperations(host); const prepared=await old.prepare_image_request({slotId:'photo',prompt:'保留桌面轮廓'}); assert.equal((await old.dispatch_image_request(approve(prepared),abort.signal)).phase,'accepted'); @@ -446,17 +475,10 @@ test('a late image settles its original request after cancellation without selec done.resolve(); await old.await_image_slots({}); await old.close(); - const receipt=ledger.repository.readImageRequest(prepared.requestId); - assert.equal(receipt.state,'complete'); - assert.equal(receipt.operationId,prepared.operationId); - assert.equal(receipt.receipt.consumption,'archived_after_cancel'); - assert.equal(ledger.read().items.photo.candidateId,undefined); - assert.equal(ledger.read().items.photo.pendingAdoption,undefined); - assert.deepEqual(events.find(event=>event.type==='image_request_receipt'),{ - type:'image_request_receipt',operationId:prepared.operationId,requestId:prepared.requestId, - outputId:'detail',variantId:'oak',slotId:'photo',category:'remote_image',phase:'archive', - status:'cancelled',consumption:'archived_after_cancel', - }); + assert.equal(native.prepared.get(prepared.requestId).receipt.phase,'complete'); + assert.equal(ledger.repository.readImageRequest(prepared.requestId),null); + assert.equal(ledger.read(),null); + assert.equal(events.some(event=>event.type==='image_request_receipt'),false); const fresh=await openProductionOperations({...host,productionSignal:new AbortController().signal}); assert.equal((await fresh.plan_production()).outputId,'detail'); await fresh.close(); @@ -514,16 +536,16 @@ test('switch hands off original requests and cancels queued work without waiting assert.deepEqual(handoffs,[]); localTransport.resolve(); const receipt=await switched; - const {operationId}=ledger.repository.readImageRequest(requestId); + const operationId=requestId; assert.deepEqual(handoffs,[[requestId]]); assert.deepEqual(receipt.previousWork,{outputId:'detail',variantId:'oak', cancelledSlots:['queued'],inFlightImages:[{slotId:'active',requestId,operationId}]}); assert.deepEqual(workerStarts,['active']); - assert.equal(ledger.read().items.queued,undefined); + assert.equal(ledger.read()?.items.queued,undefined); remote.resolve(); - while(operations.active)await operations.await_image_slots({}); - assert.equal(ledger.read().items.active.state,'candidate'); - assert.equal(ledger.read().items.active.candidateId,requestId); + assert.equal((await operations.close()).outputId,'detail'); + assert.equal((await host.canvas.imageRequest('read',{requestId})).phase,'complete'); + assert.equal(ledger.repository.readImageRequest(requestId),null); await closeProductionTurn(host); }); @@ -535,10 +557,12 @@ test('deferral keeps active workers, unknown originals and ordinary rework in pr const worker=Promise.withResolvers(); const ledger=store.ledger(outputId,variantId); const binding=JSON.stringify(['template',variantId]); + let pending=[]; const host={ store,productionGoal:{outputId,variantId}, runDetailAgent:()=>worker.promise, canvas:{ + imageRequest:async()=>pending, workflowRead:async()=>({available:true,canvasFirst:true,outputId,productVariantId:variantId, template:{contentHash:'template'},totalSlots:1,slots:[{id:slotId,fieldId:'M01'}]}), detailCopyFields:async()=>({fields:[]}),delta:async()=>{},read:async()=>({revision:1}), @@ -556,8 +580,7 @@ test('deferral keeps active workers, unknown originals and ordinary rework in pr await (await host.productionOperations).close(); const original={candidateId:'original-image',operationId:'original-operation'}; - ledger.repository.replaceLedger({binding,items:{[slotId]:{state:'unknown', - pendingGenerations:{[original.candidateId]:original}}}}); + pending=[{...original,outputId,variantId,slotId,phase:'unknown'}]; host.productionOperations=null; const deferred=await call('defer_production_output',{blocker}); assert.equal(deferred.reason,'originals_pending'); @@ -570,6 +593,7 @@ test('deferral keeps active workers, unknown originals and ordinary rework in pr assert.deepEqual(receipt.originals,deferred.originals); assert.equal(host.productionCompletion,undefined); + pending=[]; ledger.repository.replaceLedger({binding,items:{[slotId]:{state:'candidate', review:{candidateId:'rejected-image',decision:'revise',reason:'主体构图需要调整'}}}}); host.productionOperations=null; @@ -621,12 +645,14 @@ test('an unbound production turn checks project originals without opening any wo const main={outputId:'main_images',variantId:'white'}; const ledger=store.ledger(main.outputId,main.variantId); const goal={requestedOutputs:[detail,main],pendingOutputs:[detail,main]}; - const calls=[]; + const calls=[],pending=[]; const host={store,productionGoal:goal,canvas:{ openProductionOutput(){assert.fail('project reconciliation must leave canvas selection unchanged');}, - workflowRead(){assert.fail('project reconciliation must use the saved ledger');}, + workflowRead(){assert.fail('project reconciliation must use the original host records');}, + imageRequest:async()=>pending, async detailRecover(slot,request,scope){ calls.push({slot,request,scope}); + pending.length=0; return {id:request.candidateId,status:'complete'}; }, }}; @@ -635,6 +661,7 @@ test('an unbound production turn checks project originals without opening any wo ledger.repository.replaceLedger({binding:JSON.stringify(['main-template','white']),items:{ 'original-slot':{state:'unknown',pendingGenerations:{original:{candidateId:'original',operationId:'operation'}}}, }}); + pending.push({...main,slotId:'original-slot',candidateId:'original',operationId:'operation'}); assert.equal((await callProductionTool(host,'plan_production',{})).workingOutput,null); assert.deepEqual(await reconcile({slotIds:['other-slot']}),{scope:'project',results:[]}); const result=await reconcile({}); @@ -643,7 +670,7 @@ test('an unbound production turn checks project originals without opening any wo {...main,slotId:'original-slot',candidateId:'original',operationId:'operation',phase:'complete'}, ]); assert.deepEqual(calls,[{slot:'original-slot',request:{candidateId:'original'},scope:main}]); - assert.deepEqual(ledger.read().items['original-slot'].pendingGenerations,{}); + assert.deepEqual(ledger.read().items['original-slot'].pendingGenerations,{original:{candidateId:'original',operationId:'operation'}}); assert.deepEqual(await reconcile({}),{scope:'project',results:[]}); assert.equal(goal.outputId,undefined); }); @@ -727,7 +754,7 @@ test('candidate review leaves placement to the main agent, even with an old temp }; imageBridge(host,async(_request,id)=>{ posts.push(id); - assert.ok(ledger.read().items[slotId].pendingGenerations[id]); + assert.equal(ledger.repository.readImageRequest(id),null); firstStarted.resolve(); await complete.promise; return {status:recoverA&&id===posts[0]?'unknown':'complete',id}; @@ -744,7 +771,7 @@ test('candidate review leaves placement to the main agent, even with an old temp await actions.dispatch_image_request(approve(a)); await firstStarted.promise; assert.equal((await actions.dispatch_image_request(approve(a))).phase,'already_running'); - assert.deepEqual(Object.keys(ledger.read().items[slotId].pendingGenerations),[a.requestId]); + assert.equal(ledger.repository.readImageRequest(a.requestId),null); complete.resolve(); while(actions.active)await actions.await_image_slots({}); await actions.close(); @@ -937,8 +964,9 @@ test('a rework delegate sees the rejected image, exact previous prompt and revie assert.equal(exact.attemptCount,3); assert.equal(overview.rejectionCount,2); assert.equal(overview.rejections,undefined); - assert.deepEqual(exact.record.attempts.at(-1),{candidateId:'replacement',source:'generate', - prompt:'以同款原片直杆为准,改为单张自然光近景',reworkOf:'old',change:'去掉模板构图并以原片确认支撑形状'}); + assert.equal(exact.generations?.find(row=>row.candidateId==='replacement')?.reworkOf ?? + exact.generation.reworkOf,'old'); + assert.equal(exact.record.attempts.at(-1).candidateId,'old'); await ops.delegate_image_slots({jobs:[{slotId:'front',goal:'核对指定候选',reworkCandidateId:'missing'}]}); await ops.await_image_slots({}); @@ -1090,9 +1118,9 @@ test('a sibling variant edit leaves the current plan usable, and a local edit ca variants[1].colorName='暖白色'; creation++; const prepare=canvas.imageRequest; - canvas.imageRequest=(action,args)=>{ + canvas.imageRequest=(action,args,execution)=>{ if(action==='prepare')assert.equal(args.retryOf,undefined); - return prepare(action,args); + return prepare(action,args,execution); }; const draft=await actions.prepare_image_request({...request,retryOf:''}); assert.equal(draft.spec.prompt,request.prompt); @@ -1169,9 +1197,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].pendingGenerations[operationId]; - assert.equal(pending.operationId,operationId); - assert.equal(pending.candidateId,operationId); + assert.equal(journal(),null); throw new BridgeError('画布连接中断,原操作不会重发','transport_interrupted',{dispatched:true}); }); let actions=await openProductionOperations(host,{tailWatchClock}); @@ -1193,91 +1219,44 @@ 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.deepEqual(journal().items[slotId].pendingGenerations,{}); + assert.equal(journal(),null); + await actions.close(); }); -test('410 settles only the original result and permits an explicitly prepared replacement',async t=>{ - for(const legacy of [false,true])await t.test(legacy?'imported R28 ledger':'frozen SQLite request',async t=>{ - const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-expiry-')); - t.after(()=>cleanup(dir)); - const store=productionStore(dir); - const ledger=store.ledger('main_images','ink'); - const {repository}=ledger; - const slotId='main-photo'; - const originalId=randomUUID(), remoteRequestId=randomUUID(); - const resultExpiry={httpStatus:410,source:'retained-result',requestId:remoteRequestId,observedAt:1795685081}; - const expiry={id:originalId,status:'expired',requestId:remoteRequestId,retryable:false,resultExpiry,message:'原生图结果已过期'}; - let response='timeout'; +test('the host can settle 410, failure and exhausted unresolved, then Pi can prepare another request',async t=>{ + for(const terminal of ['expired','failed','unresolved'])await t.test(terminal,async t=>{ + const {host,ledger}=await tailFixture(t,['hero']); + let status='unknown'; const posted=[], reads=[]; - const host={store,productionGoal:{outputId:'main_images',variantId:'ink'},canvas:{ - workflowRead:async()=>({available:true,canvasFirst:true,outputId:'main_images',productVariantId:'ink', - template:{contentHash:'fixture'},totalSlots:1,slots:[{id:slotId,fieldId:'M02-I01'}]}), - detailCopyFields:async()=>({fields:[]}),delta:async()=>{}, - async detailRecover(slot,{candidateId}){ - reads.push({slot,candidateId}); - if(response==='timeout'||response==='connection lost')throw Error(response); - return response==='410'?expiry:{id:originalId,status:'unknown',message:'HTTP '+response}; - }, - }}; - if(legacy){ - await fs.writeFile(path.join(dir,'production-main_images-ink.json'),JSON.stringify({ - binding:JSON.stringify(['fixture','ink']),preparedRequests:{[originalId]:{slotId,prompt:'旧提示词'}}, - items:{[slotId]:{state:'unknown',candidateId:originalId,source:'generate', - pendingOperation:{candidateId:originalId,operationId:originalId,kind:'frozen-image'}, - attempts:[{candidateId:originalId,prompt:'旧提示词',source:'generate'}]}}, - })); - } + const resultExpiry={httpStatus:410,requestId:'original-remote'}; + host.canvas.detailRecover=async(slotId,{candidateId})=>{ + reads.push([slotId,candidateId]); + return {id:candidateId,status,...(status==='expired'?{resultExpiry}:null)}; + }; imageBridge(host,async(_args,id)=>{ posted.push(id); - return {id,status:id===originalId?'unknown':'complete'}; - },()=>!legacy&&!posted.length?originalId:randomUUID()); - - let actions=await openProductionOperations(host); - const input={slotId:'M02-I01',source:'generate',prompt:'旧提示词'}; - if(!legacy)assert.equal((await generateAndWait(actions,input)).phase,'unknown'); - const before=legacy?[]:[originalId]; - await actions.close(); - actions=await openProductionOperations(host); - for(response of ['timeout','connection lost','429','503']){ - const [receipt]=await actions.reconcile_image_slots({slotIds:[slotId]}); - assert.equal(receipt.phase,'unknown'); - assert.equal(receipt.candidateId,originalId); - assert.equal((await generateAndWait(actions,{...input,prompt:'新提示词'})).pendingOriginal,originalId); - assert.deepEqual(posted,before); - if(!legacy)assert.equal(repository.readImageRequest(originalId).state,'unknown'); - } - - response='410'; - const [expired]=await actions.reconcile_image_slots({slotIds:[slotId]}); - assert.deepEqual(expired,{slotId,candidateId:originalId,operationId:originalId,phase:'expired', - reason:expiry.message,requestId:remoteRequestId,retryable:false,resultExpiry}); - assert.deepEqual(posted,before); - const replacements=reads.length; - assert.ok(reads.every(read=>read.slot===slotId&&read.candidateId===originalId)); - if(!legacy)assert.equal(repository.readImageRequest(originalId).state,'expired'); - await actions.close(); - - actions=await openProductionOperations(host); - assert.equal((await actions.reconcile_image_slots({slotIds:[slotId]}))[0].phase,'none'); - assert.equal(reads.length,replacements); - const same=await actions.dispatch_image_request({requestId:originalId,expectedRevision:1,expectedHash:'fixture-digest'}); - assert.equal(same.phase,'accepted'); - assert.equal((await actions.await_image_slots({slotIds:[slotId]})).generation[0].phase,'expired'); - assert.deepEqual(posted,before); - - const replacement=await generateAndWait(actions,{...input,prompt:'新提示词'}); - assert.equal(replacement.phase,'complete'); - assert.notEqual(replacement.candidateId,originalId); - assert.deepEqual(posted,[...before,replacement.candidateId]); - const {items}=JSON.parse(await fs.readFile(path.join(dir,'production-main_images-ink.json'),'utf8')); - assert.equal(items[slotId].candidateId,replacement.candidateId); - assert.equal(items[slotId].pendingOperation??null,null); - assert.deepEqual(items[slotId].pendingGenerations,{}); - assert.deepEqual(items[slotId].attempts.find(item=>item.candidateId===originalId),{ - candidateId:originalId,source:'generate',prompt:'旧提示词',phase:'expired', - requestId:remoteRequestId,retryable:false,resultExpiry, + return {id,status:posted.length===1?'unknown':'complete'}; }); - assert.deepEqual(repository.candidateEvidence(slotId,originalId).at(-1).detail.resultExpiry,resultExpiry); + const actions=await openProductionOperations(host); + const input={slotId:'hero',prompt:'原提示词'}; + const original=await generateAndWait(actions,input); + assert.equal(original.phase,'unknown'); + assert.equal((await actions.reconcile_image_slots({}))[0].candidateId,original.candidateId); + assert.equal((await generateAndWait(actions,{...input,prompt:'新提示词'})).pendingOriginal,original.candidateId); + assert.deepEqual(posted,[original.candidateId]); + // Exhaustion is a terminal receipt supplied by the Rust recovery owner. + status=terminal==='unresolved'?'failed':terminal; + const [settled]=await actions.reconcile_image_slots({}); + assert.equal(settled.phase,status); + if(terminal==='expired')assert.deepEqual(settled.resultExpiry,resultExpiry); + assert.equal((await actions.dispatch_image_request({requestId:original.candidateId})).phase,status); + const next=await generateAndWait(actions,{...input,prompt:'新提示词'}); + assert.equal(next.phase,'complete'); + assert.notEqual(next.candidateId,original.candidateId); + assert.deepEqual(reads,[['hero',original.candidateId],['hero',original.candidateId]]); + assert.deepEqual(posted,[original.candidateId,next.candidateId]); + assert.equal(ledger.repository.readImageRequest(original.candidateId),null); + assert.equal(ledger.repository.readImageRequest(next.candidateId),null); await actions.close(); }); }); @@ -1440,12 +1419,12 @@ test('Pi chooses each image operation and keeps an unresolved paid request on it assert.match(submissions[0].instructions,/场景桌面上的一盏灯$/u); assert.equal(submissions[0].prefer2k,true); const overview=(await actions.review_image_slots({slotIds:[]})).pictures.find(row=>row.id==='lamp-photo'); - const exact=(await actions.review_image_slots({slotIds:['lamp']})).pictures[0].record; + const exact=(await actions.review_image_slots({slotIds:['lamp']})).pictures[0]; assert.equal(overview.state,'unknown'); assert.equal(overview.record,undefined); assert.equal(overview.candidates,undefined); - assert.equal(exact.pendingGenerations[first.candidateId].operationId,first.operationId); - assert.match(exact.prompt,/场景桌面上的一盏灯/u); + assert.equal(exact.generation.candidateId,first.candidateId); + assert.match(exact.generation.instructions,/场景桌面上的一盏灯/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); @@ -1541,7 +1520,7 @@ test('worker progress shares a number with delegated image dispatch and reuses r detailImages:async()=>{await reviewRelease.promise; throw Error('测试候选不提供像素');}, async delta(_text,_thinking,progress){ if(progress.heading==='子代理正在制作'&&progress.workers.length===5)started.resolve(progress); - if(progress.heading==='子代理正在生图')generating.resolve(progress); + if(progress.workers.some(row=>row.slotId===first.id&&row.step==='正在生图'))generating.resolve(progress); if(progress.heading==='子代理正在验图')checking.resolve(progress); if(progress.heading==='验图已有回执')reviewed.resolve(progress); }, @@ -1866,6 +1845,7 @@ test('the fourth draw occupies the last slot while in flight and a rejected cand dispatches.push(id); if(dispatches.length===3){fourthStarted.resolve();await fourthDone.promise;} slot.candidates.push({id,status:'complete',sourceType:null}); + slot.generationRequestIds?.push(id); return {id,status:'complete'}; }); const ops=await openProductionOperations(host); @@ -1873,6 +1853,7 @@ test('the fourth draw occupies the last slot while in flight and a rejected cand for(const [key,value] of Object.entries(expected))assert.equal(row[key],value,key); }; const plan=()=>ops.plan_production({slotIds:['hero']}); + slot.generationRequestIds=['existing']; assertStatus((await plan()).pictures[0],drawStatus(1)); await ops.retire_production_image({slotId:'hero',candidateId:'existing',reason:'构图不合适'}); assertStatus((await plan()).pictures[0],drawStatus(1)); diff --git a/apps/detail-agent-pi/test/project-repository.test.mjs b/apps/detail-agent-pi/test/project-repository.test.mjs index 86fec589..48a5e4f0 100644 --- a/apps/detail-agent-pi/test/project-repository.test.mjs +++ b/apps/detail-agent-pi/test/project-repository.test.mjs @@ -5,7 +5,6 @@ import os from 'node:os'; import path from 'node:path'; import { DatabaseSync } from 'node:sqlite'; import test from 'node:test'; -import { Worker } from 'node:worker_threads'; import { openProductionOperations } from '../src/production-operations.mjs'; import { ProjectRepository } from '../src/project-repository.mjs'; import { recordProductionInputs } from '../src/production-repository.mjs'; @@ -22,7 +21,16 @@ const request = (requestId = 'image-a', spec = { prompt: '用同款实拍约束 const approve = draft => ({ requestId: draft.requestId, expectedHash: draft.requestSpecHash, expectedRevision: draft.revision, }); -const pending = journal => journal.items.front?.pendingOperation; +function seedLegacyRequest(repo, draft, state='prepared', receipt=null) { + repo.readLedger(); + const db=new DatabaseSync(repo.file); + try { + db.prepare(`INSERT INTO image_requests + (account_id,project_id,output_id,variant_id,request_id,operation_id,slot_id,request_spec_hash,revision,state,prepared_json,receipt_json) + VALUES (?,?,?,?,?,?,?,?,?,?,?,?)`).run(...repo.scope,draft.requestId,draft.operationId,draft.slotId,draft.requestSpecHash, + draft.revision,state,JSON.stringify(draft),receipt&&JSON.stringify(receipt)); + } finally { db.close(); } +} async function fixture(t) { const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-pi-project-repository-')); @@ -114,11 +122,11 @@ test('P01 local facts, document evidence and delivery reopen without a collabora assert.deepEqual(open().readDelivery(), delivery); }); -test('P02 stores the exact complete prompt and rejects changes at the same revision', async t => { +test('P02 reopens the exact complete prompt from a legacy request', async t => { const { file, open, repo } = await fixture(t); const draft = request('long', { prompt: '自然光与质感。\n'.repeat(300) + '末尾必需限制:只保留一件。\r\n' }); assert.ok(draft.spec.prompt.length > 2000); - repo.saveImageRequest(draft); + seedLegacyRequest(repo, draft); assert.equal(open().readVersion('prompt', 'long', 1).prompt, draft.spec.prompt); assert.equal(open().readImageRequest('long').prepared.spec.prompt, draft.spec.prompt); const db = new DatabaseSync(file, { readOnly:true }); @@ -127,46 +135,40 @@ test('P02 stores the exact complete prompt and rejects changes at the same revis } finally { db.close(); } - assert.throws(() => repo.saveImageRequest(request('long', { prompt: 'changed' })), /新版本/); }); -test('P03 the production bridge sends reviewed identity and the display number after an atomic local freeze', async t => { +test('P03 dispatches a host-confirmed request once without a Pi request row', async t => { const { dir } = await fixture(t); const store = productionStore(dir, { scope: scope.accountId, project: scope.projectId }); const repo = store.ledger('detail', 'oak').repository; - const draft = request('frozen', { prompt: '原始完整文字\n保留边缘', modelId: 'actual-model', - parameters: { size: '2048x2048' }, references: [{ position: 1, role: 'product', sha256: hash('reference') }] }); - const calls = []; - const host = { store, productionGoal: { outputId: 'detail', variantId: 'oak' }, canvas: { - workflowRead: async () => ({ available: true, canvasFirst: true, outputId: 'detail', productVariantId: 'oak', - template: { contentHash: 'template' }, totalSlots: 1, slots: [{ id: 'front', fieldId: 'cover' }] }), - detailCopyFields: async () => ({ fields: [] }), - delta: async () => {}, - async imageRequest(action, args) { - if (action === 'prepare') return draft; + const draft = {...request('frozen'),phase:'prepared',outputId:'detail',variantId:'oak',templateHash:'template'}; + const slot={id:'front',fieldId:'cover',candidates:[]}; + const calls=[]; + const host={store,productionGoal:{outputId:'detail',variantId:'oak'},canvas:{ + workflowRead:async()=>({available:true,canvasFirst:true,outputId:'detail',productVariantId:'oak', + template:{contentHash:'template'},totalSlots:1,slots:[slot]}), + detailCopyFields:async()=>({fields:[]}),delta:async()=>{}, + async imageRequest(action,args,execution){ + if(action==='pending')return []; + if(action==='read'||action==='prepare')return {...draft}; calls.push(args); - const saved = repo.readImageRequest(draft.requestId); - assert.equal(saved.state, 'dispatching'); - assert.equal(typeof saved.frozenAt, 'number'); - assert.deepEqual(saved.prepared.spec, draft.spec); - 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(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 }; + assert.equal(args.expectedRevision,draft.revision); + assert.equal(args.expectedHash,draft.requestSpecHash); + execution.onEnqueued(); + draft.phase='complete'; + slot.candidates.push({id:draft.requestId,status:'complete'}); + return {status:'complete',id:draft.requestId}; }, }}; - const tools = await openProductionOperations(host); - const prepared = await tools.prepare_image_request({ slotId: 'cover', prompt: draft.spec.prompt }); - await tools.dispatch_image_request({ ...approve(prepared), expectedRevision: 2 }); - assert.equal((await tools.await_image_slots({ slotIds: ['cover'] })).generation[0].phase, 'failed'); - assert.equal(calls.length, 0); - for (let attempt = 0; attempt < 2; attempt++) { - await tools.dispatch_image_request({ requestId: prepared.requestId }); - assert.equal((await tools.await_image_slots({ slotIds: ['cover'] })).generation[0].phase, 'complete'); - } - assert.deepEqual(calls, [{ ...approve(draft), slotId: 'front', workerNumber: 1 }]); - assert.equal(repo.readImageRequest(draft.requestId).receipt.status, 'complete'); + const tools=await openProductionOperations(host); + const prepared=await tools.prepare_image_request({slotId:'cover',prompt:draft.spec.prompt}); + assert.equal((await tools.dispatch_image_request(approve(prepared))).phase,'accepted'); + assert.equal((await tools.await_image_slots({})).generation[0].phase,'complete'); + assert.equal((await tools.dispatch_image_request({requestId:prepared.requestId})).phase,'complete'); + assert.deepEqual(calls,[{...approve(draft),slotId:'front',workerNumber:1}]); + assert.equal(repo.readImageRequest(draft.requestId),null); + assert.equal(repo.readLedger(),null); + await assert.rejects(fs.stat(path.join(dir,'production-detail-oak.json')),{code:'ENOENT'}); await tools.close(); }); @@ -180,7 +182,7 @@ test('P04 keeps original and normalized references, asset identities and send or position: index + 1, role: 'product', source: 'P1', originalAssetId: original.assetId, sourceSha256: original.sha256, assetId: input.assetId, sha256: input.sha256, })); - repo.saveImageRequest(request('p1', { prompt: '同款两视角。', references })); + seedLegacyRequest(repo, request('p1', { prompt: '同款两视角。', references })); assert.deepEqual(open().readImageRequest('p1').prepared.spec.references, references); assert.equal(open().readAsset(references[0].originalAssetId).path, original.path); assert.equal(open().readAsset(references[1].assetId).path, wide.path); @@ -190,8 +192,8 @@ test('P05 a prompt edit cannot relabel a candidate generated by the old request' const { repo } = await fixture(t); const first = request('old', { prompt: '第一版' }); const corrected = { ...request('rework', { prompt: '新取景' }), reworkOf: 'old', reworkChange: '修改机位' }; - repo.saveImageRequest(first); - repo.saveImageRequest(corrected); + seedLegacyRequest(repo, first); + seedLegacyRequest(repo, corrected); repo.recordCandidate('front', 'old', 'candidate', { requestId: 'old', requestSpecHash: first.requestSpecHash }); repo.recordCandidate('side', 'reuse', 'candidate', { reusedFrom: { projectId: 'project', candidateId: 'old' } }); assert.equal(repo.candidateEvidence('front', 'old')[0].detail.requestSpecHash, first.requestSpecHash); @@ -219,48 +221,22 @@ test('P07 two intentionally equivalent samples keep distinct operations and actu 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, pending).claimed, true); + seedLegacyRequest(repo, draft); } - 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' }], - }); + repo.recordCandidate(draft.slotId,draft.requestId,'review',{candidateId:draft.requestId,decision:'pass'}); } assert.notEqual(open().readImageRequest(a.requestId).operationId, open().readImageRequest(b.requestId).operationId); 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 => { - const { file, open, repo } = await fixture(t); - const draft = request('interrupted'); - repo.saveImageRequest(draft); - const start = new SharedArrayBuffer(4); - const run = () => new Promise((resolve, reject) => { - const worker = new Worker(` - const { parentPort, workerData } = require('node:worker_threads'); - (async () => { - const { ProjectRepository } = await import(workerData.module); - const repo = new ProjectRepository(workerData.file, workerData.scope); - const barrier = new Int32Array(workerData.start); - Atomics.add(barrier, 0, 1); - Atomics.notify(barrier, 0); - Atomics.wait(barrier, 0, 1, 5000); - parentPort.postMessage(repo.claimImageRequest(workerData.approval, workerData.binding, - journal => journal.items.front?.pendingOperation).claimed); - })().catch(error => { throw error; }); - `, { eval: true, workerData: { start, file, scope, binding, approval: approve(draft), - module: new URL('../src/project-repository.mjs', import.meta.url).href } }); - worker.once('message', resolve); - worker.once('error', reject); - }); - assert.deepEqual((await Promise.all([run(), run()])).sort(), [false, true]); - const resumed = open().claimImageRequest(approve(draft), binding, pending); - assert.equal(resumed.claimed, false); - assert.equal(resumed.pending.operationId, draft.operationId); - assert.equal(open().readImageRequest(draft.requestId).state, 'dispatching'); +test('P08 reads the original dispatching state from a historical database after reopening', async t => { + const {repo,open}=await fixture(t); + const draft=request(); + seedLegacyRequest(repo,draft,'dispatching'); + const saved=open().readImageRequest(draft.requestId); + assert.equal(saved.state,'dispatching'); + assert.equal(saved.operationId,draft.operationId); }); test('P09 output, variant, project and account are independent even when their IDs overlap', async t => { @@ -268,15 +244,13 @@ test('P09 output, variant, project and account are independent even when their I const neighbors = [open({ variantId: 'walnut' }), open({ outputId: 'main_images' }), open({ projectId: 'other' }), open({ accountId: 'other' })]; const draft = request(); - repo.saveImageRequest(draft); - repo.claimImageRequest(approve(draft), binding, pending); + seedLegacyRequest(repo, draft); for (const other of neighbors) { assert.equal(other.readImageRequest(draft.requestId), null); assert.equal(other.readLedger(), null); other.replaceLedger({ binding: 'independent', items: { front: { candidateId: 'other' } } }); } - repo.updateLedger(binding, journal => { journal.items.front.candidateId = draft.requestId; }, - { receipt: [draft.requestId, 'complete', { status: 'complete' }] }); + repo.updateLedger(binding, journal => { journal.items.front = {candidateId:draft.requestId}; }); for (const other of neighbors) assert.equal(other.readLedger().items.front.candidateId, 'other'); }); @@ -301,7 +275,7 @@ test('P11 records the actual background request separately from local compositin const { repo } = await fixture(t); const draft = request('background', { prompt: '移除模板中的旧商品。', sceneComposite: true, references: [{ position: 1, role: 'scene', sha256: hash('template scene') }] }); - repo.saveImageRequest(draft); + seedLegacyRequest(repo,draft,'complete',{status:'complete'}); repo.recordCandidate('front', 'composite', 'candidate', { requestId: 'background', processing: { kind: 'composite', productAssetId: 'actual-product-cutout', placement: [10, 20, 900, 1200] } }); assert.deepEqual(repo.readImageRequest('background').prepared.spec.references.map(row => row.role), ['scene']); @@ -329,7 +303,7 @@ test('P13 reloads full facts, plan, formal prompt and locked rule from stable ve }, [{ id: 'front', fieldId: 'cover', requirements: '展示圆角' }]); const draft = { ...request(), productFactsRevision, planRevision, knowledge: [{ fileId: 'image-prompt', revision: 'r7' }] }; - repo.saveImageRequest(draft); + seedLegacyRequest(repo, draft); const { prepared } = open().readImageRequest(draft.requestId); assert.equal(open().readVersion('product_facts', 'product', prepared.productFactsRevision).facts.items[0].source, 'P1'); assert.equal(open().readVersion('plan', 'production', prepared.planRevision).slots[0].requirements, '展示圆角'); @@ -359,15 +333,13 @@ test('P14 reads the locked rule on demand and surfaces an unavailable reference' test('P15 execution success and a failed pixel check remain independently traceable', async t => { const { open, repo } = await fixture(t); const draft = request('undersize', { prompt: '输出 4K,保留产品结构。' }); - repo.saveImageRequest(draft); - repo.claimImageRequest(approve(draft), binding, pending); - repo.recordImageReceipt(draft.requestId, 'complete', { status: 'complete' }); + seedLegacyRequest(repo,draft,'complete',{status:'complete'}); repo.recordCandidate('front', draft.requestId, 'review', { decision: 'revise', actualPixels: [1024, 1024], reason: '尺寸不足且接合结构错误', }); const next = { ...request('corrected'), reworkOf: draft.requestId }; - repo.saveImageRequest(next); - assert.equal(open().readImageRequest(draft.requestId).state, 'complete'); + seedLegacyRequest(repo, next); + assert.equal(open().readImageRequest(draft.requestId).prepared.spec.prompt,draft.spec.prompt); assert.equal(open().candidateEvidence('front', draft.requestId)[0].detail.decision, 'revise'); assert.equal(open().readImageRequest(next.requestId).prepared.reworkOf, draft.requestId); }); 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 f3dba68e..eda11832 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs @@ -786,6 +786,32 @@ fn records(dir: &Path, state: &Value) -> R> { } Ok(out) } + +fn pending_production_images(dir: &Path, state: &Value) -> R { + let mut pending = Vec::new(); + for record in records(dir, state)? { + let binding = &record["binding"]; + if binding["detailBatch"] != true || !record["sourceType"].is_null() + || !record["retirement"].is_null() + || matches!(record["phase"].as_str(), Some("complete" | "failed" | "expired")) { + continue; + } + let id = uuid(&record["id"], "原候选")?; + let file = dir.join("image-jobs").join(&id).join("task.json"); + if !file.try_exists().map_err(|error| error.to_string())? { continue; } + let task = read_json(&file)?; + if task["id"] != id || task["slotBinding"] != *binding { + return Err("原候选任务与图位记录不一致".into()); + } + if matches!(task["phase"].as_str(), Some("dispatched" | "running" | "unknown")) { + pending.push(json!({"candidateId":id,"operationId":record["workflowOperationId"].as_str().unwrap_or(&id), + "slotId":binding["slotId"],"variantId":binding["variantId"],"outputId":task["outputScope"], + "phase":task["phase"],"reason":task["message"]})); + } + } + Ok(json!(pending)) +} + fn reserve(dir: &Path, mut state: Value, record: &Value) -> R<()> { let _guard = sync::context_guard(); let original = load(dir)?; @@ -1492,6 +1518,7 @@ pub(super) fn reconcile_candidate(dir: &Path, journal: &Value) -> R { let artifact = template_slots::artifact(dir, record["id"].as_str().ok_or("原候选身份缺失")?, journal)?; record["artifact"] = artifact; } + let previous = record.clone(); record["phase"] = json!(phase); if phase == "expired" { record["resultExpiry"] = journal["resultExpiry"].clone(); } let preflight_retry = journal["phase"] == "prepared" && journal["notDispatched"] == true @@ -1504,11 +1531,13 @@ pub(super) fn reconcile_candidate(dir: &Path, journal: &Value) -> R { if journal["requestId"].is_string() || record["requestId"].is_null() { record["requestId"] = journal["requestId"].clone(); } - record["updatedAt"] = json!(now()); if journal["message"].is_string() { record["message"] = journal["message"].clone(); } - write_json(&candidate_path(dir, record["id"].as_str().ok_or("原候选身份缺失")?)?, &record)?; + if record != previous { + record["updatedAt"] = json!(now()); + write_json(&candidate_path(dir, record["id"].as_str().ok_or("原候选身份缺失")?)?, &record)?; + } Ok(record) } fn mapping_key(variant: &str, component: &str, document: Option<&str>) -> String { @@ -3067,12 +3096,15 @@ fn snapshot_for_view(dir: &Path, view: Option) -> R { let in_slot = || history.iter().filter(|record| record["binding"]["slotId"] == id); let retired: Vec<_> = in_slot().filter(|record| record["retirement"].is_object()) .map(|record| &record["id"]).collect(); + let generation_request_ids: Vec<_> = in_slot().filter(|record| + record["sourceType"].is_null() && record["reusedFrom"].is_null() && record["phase"] != "prepared") + .map(|record| &record["id"]).collect(); let candidates: Vec<_> = in_slot().filter(|record| record["retirement"].is_null()).map(|record| { let candidate_id = record["id"].as_str().unwrap_or(""); 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"],"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"],"reviewDecision":decision,"retryableFailure":record["retryableFailure"],"retryAfterSeconds":record["retryAfterSeconds"]}); if record["phase"] == "expired" { row["retryable"] = json!(false); row["resultExpiry"] = record["resultExpiry"].clone(); @@ -3084,7 +3116,7 @@ fn snapshot_for_view(dir: &Path, view: Option) -> R { .and_then(|profile| profile["imageRules"].get(field["fieldId"].as_str()?)) .or_else(|| field.get("productionRule")); slots.push(json!({"id":id,"fieldId":field["fieldId"],"documentId":output["id"],"outputId":output["component"],"variantId":active,"kind":"image","label":field.get("name").or(field.get("label")).unwrap_or(&field["fieldId"]),"width":frame["width"],"height":frame["height"],"frame":frame,"box":frame,"crop":field["crop"],"sourcePolicy":field["sourcePolicy"],"templatePrompt":editable_image_prompt(field, &output["id"], prompt_mapping.as_ref()),"nativeLayerId":mapped.map(|m|m["nativeLayerId"].clone()),"candidates":candidates,"retiredCandidateIds":retired,"selectedCandidateId":null,"appliedCandidateId":null,"fields":[],"required":false, - "role":field["role"],"requirements":field["requirements"],"relatedFields":field["relatedFields"], + "role":field["role"],"requirements":field["requirements"],"relatedFields":field["relatedFields"],"generationRequestIds":generation_request_ids, "layoutReference":field["previewReference"].is_object(),"checkGeneratedMarks":state["productTemplates"].is_object(),"productionRule":production_rule, "textRegions":state["productTemplates"].is_object().then(||slot_text_regions(&state,&id,active))})); } @@ -3165,7 +3197,6 @@ impl Backend { } pub(super) fn production_image_request(&mut self, doc: u64, binding: &Value, events: &mpsc::Sender, ctx: &egui::Context, cancellation: Option<&std::sync::atomic::AtomicBool>) -> Result { - check_image_dispatch_cancelled(cancellation)?; self.check_dispatch().map_err(|message| BridgeFailure::new("auth_revoked", false, false, message))?; self.ensure_owner(doc)?; let dir = self.project_dir(doc)?; @@ -3173,6 +3204,28 @@ impl Backend { let phase = binding["action"].as_str().ok_or("生图请求动作缺失")?; let request = &binding["request"]; transfer::no_credentials(request)?; + if phase == "read" { + let id = uuid(&request["requestId"], "生图请求")?; + let task = super::images::read_image_request(&dir, &id)?; + let scope = &binding["scope"]; + if task["accountScope"] != self.scope() || task["localProjectId"] == Value::Null + || task["localProjectId"].as_str() != self.locations.get(&doc).map(String::as_str) + || task["origin"] != self.origin || task["outputScope"] != scope["outputId"] + || task["slotBinding"]["variantId"] != scope["variantId"] + || task["slotBinding"]["workspaceId"] != scope["id"] + || task["slotBinding"]["templateHash"] != scope["templateHash"] { + return Err("生图请求不属于当前账户、项目或工作画布".into()); + } + let mut receipt = super::images::image_request_receipt(&task); + if task["message"].is_string() { receipt["message"] = task["message"].clone(); } + if task["resultExpiry"].is_object() { receipt["resultExpiry"] = task["resultExpiry"].clone(); } + return Ok(receipt); + } + if phase == "pending" { + let _guard = sync::context_guard(); + return pending_production_images(&dir, &load(&dir)?).map_err(BridgeFailure::from); + } + check_image_dispatch_cancelled(cancellation)?; if matches!(phase, "prepare" | "transform") { let mut input = request.clone(); input["doc"] = json!(doc); @@ -3925,6 +3978,28 @@ mod fidelity_tests; mod tests { use super::*; + #[test] + fn pending_production_reads_legacy_tasks_on_their_original_output() { + let fixture = fixture(); + let id = Uuid::new_v4().to_string(); + let binding = json!({"candidateId":id,"taskId":id,"slotId":"cover","detailBatch":true,"variantId":"oak"}); + write_json(&candidate_path(&fixture.dir, &id).unwrap(), + &json!({"version":2,"id":id,"binding":binding,"phase":"prepared"})).unwrap(); + let file = fixture.dir.join("image-jobs").join(&id).join("task.json"); + let mut task = json!({"id":id,"slotBinding":binding,"outputScope":"main_images","phase":"unknown"}); + write_json(&file, &task).unwrap(); + let view = json!({"activeOutput":"detail","candidates":[id]}); + let originals = pending_production_images(&fixture.dir, &view).unwrap(); + assert_eq!(originals[0]["candidateId"], id); + assert_eq!(originals[0]["outputId"], "main_images"); + assert_eq!(originals[0]["phase"], "unknown"); + assert_eq!(read_json(&file).unwrap(), task); + task["phase"] = json!("expired"); + write_json(&file, &task).unwrap(); + assert_eq!(pending_production_images(&fixture.dir, &view).unwrap(), json!([])); + assert_eq!(read_candidate(&fixture.dir, &id).unwrap()["phase"], "prepared"); + } + #[test] fn production_image_presentation_preserves_request_identity_and_slot_geometry() { let binding = json!({"run":"current-run","scope":{"outputId":"detail","variantId":"walnut"}, @@ -4642,6 +4717,15 @@ mod tests { write_json(&file, &task).unwrap(); let (events, _) = mpsc::channel(); let ctx = egui::Context::default(); + let mut read = json!({"action":"read","scope":scope,"request":{"requestId":id}}); + let receipt = backend.production_image_request(doc, &read, &events, &ctx, None).unwrap(); + assert_eq!(receipt["phase"], "prepared"); + assert_eq!(receipt["spec"]["prompt"], task["prompt"]); + read["scope"]["outputId"] = json!("main_images"); + assert!(backend.production_image_request(doc, &read, &events, &ctx, None).is_err()); + let pending = backend.production_image_request(doc, &json!({"action":"pending","request":{}}), &events, &ctx, None).unwrap(); + assert_eq!(pending, json!([])); + assert_eq!(read_json(&file).unwrap(), task); let mut approval = json!({"action":"dispatch","scope":scope,"request":{ "requestId":id,"slotId":"other-slot","expectedRevision":1,"expectedHash":task["requestSpecHash"]}}); for (field, value) in [("slotId",json!("other-slot")), ("expectedRevision",json!(2)), ("expectedHash",json!("other-hash"))] { 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 791732c9..d68b2009 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 @@ -533,8 +533,17 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co "templateHash":w.template_workflow["templateHash"],"canvasLayerId":canvas_layer})) } "pi-image-request" => { - let action = input["action"].as_str().filter(|action| matches!(*action,"prepare"|"dispatch"|"transform")) + let action = input["action"].as_str().filter(|action| matches!(*action,"prepare"|"dispatch"|"transform"|"read"|"pending")) .ok_or("生图请求动作无效")?; + if matches!(action, "read" | "pending") { + if w.pi_request_scope["productProduction"] != true { + return Err("本轮没有制作请求的读取授权".into()); + } + return Ok(json!({"action":action,"request":input["request"], + "scope":{"id":w.template_workflow["workspaceId"],"templateHash":w.template_workflow["templateHash"], + "outputId":w.pi_request_scope["outputId"], + "variantId":w.pi_request_scope["variantId"]}})); + } if w.pi_request_scope["productProduction"] != true || !w.canvas_scope_valid(app) || w.pi_request_scope["outputId"] != w.template_workflow["outputId"] || w.pi_request_scope["variantId"] != w.template_workflow["variantId"] { 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 85337b7f..30096d41 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 @@ -669,6 +669,9 @@ fn read(w: &Workspace, version: u64, section: &str, output: &str, offset: usize, result["slots"] = json!(slots.into_iter().skip(offset).take(12).map(|slot| { let candidates=slot["candidates"].as_array().into_iter().flatten().rev().map(|candidate| json!({"id":clip(&candidate["id"],100),"variant":clip(&candidate["variant"],100),"status":clip(&candidate["status"],24),"sourceType":candidate["sourceType"], "materialTaskId":candidate["materialTaskId"],"sourceRequestId":candidate["sourceRequestId"], + "sequence":candidate["sequence"],"requestId":candidate["requestId"],"error":candidate["error"],"resultExpiry":candidate["resultExpiry"], + "reworkOf":candidate["reworkOf"],"retryableFailure":candidate["retryableFailure"], + "retryAfterSeconds":candidate["retryAfterSeconds"], "reused":candidate["reusedFrom"].is_object()})).collect::>(); let rejection = if w.pi_request_scope["productProduction"] == true && w.pi_canvas_basis.is_some() { slot["nativeLayerId"].as_u64().zip(active_doc) @@ -678,6 +681,7 @@ fn read(w: &Workspace, version: u64, section: &str, output: &str, offset: usize, "label":clip(&slot["label"],160),"selectedCandidateId":if w.template_workflow["canvasFirst"]==true{adopted(&slot["id"])}else{slot["selectedCandidateId"].clone()}, "sourcePolicy":slot["sourcePolicy"],"manuallyEdited":rejection == Some(super::product_production::LayerRejection::UserEdit), "writeBlockReason":rejection.map(|reason| reason.code()),"candidates":candidates, + "generationRequestIds":slot["generationRequestIds"],"retiredCandidateIds":slot["retiredCandidateIds"], "role":slot["role"],"requirements":slot["requirements"], "templatePrompt":slot["templatePrompt"],"relatedFields":slot["relatedFields"], "layoutReference":slot["layoutReference"],"textRegions":slot["textRegions"],"productionRule":slot["productionRule"]})