合入小壹活跃制作生图尾巴监控
This commit is contained in:
commit
d56cd1415a
@ -41,6 +41,7 @@ export async function recordProductionExport(dir, goalId) {
|
||||
}
|
||||
|
||||
export async function runPiProductionGoal(host, text, continuation, images=[]) {
|
||||
watchBoundOutput(host);
|
||||
const current = piGoalState(host.manager);
|
||||
const objective = productionObjective(host.productionGoal.requestedOutputs);
|
||||
const continuing = current && current.status !== 'complete' && current.objective === objective;
|
||||
@ -135,18 +136,33 @@ async function bindProductionOutput(host, binding) {
|
||||
host.bindGoalRequestScope();
|
||||
}
|
||||
if (pendingOutputs) goal.pendingOutputs=pendingOutputs;
|
||||
watchBoundOutput(host);
|
||||
}
|
||||
|
||||
function watchBoundOutput(host) {
|
||||
if(!host.productionGoal.outputId||host.productionOperations||host.productionSignal?.aborted)return;
|
||||
const pending=host.productionOperations=openProductionOperations(host);
|
||||
pending.catch(()=>{
|
||||
if(host.productionOperations===pending)host.productionOperations=null;
|
||||
});
|
||||
}
|
||||
|
||||
async function submitProduction(host, input, signal) {
|
||||
const receipt = await host.canvas.finishProduction(input,signal);
|
||||
host.productionGoal.pendingOutputs=receipt.pendingOutputs;
|
||||
if (receipt.finalized) host.productionCompletion={receipt,
|
||||
text:receipt.completed?'本轮成品已完成保存和核验。':'本轮已结束,待处理项和编辑稿已保留。'};
|
||||
if (receipt.finalized) {
|
||||
host.productionCompletion={receipt,
|
||||
text:receipt.completed?'本轮成品已完成保存和核验。':'本轮已结束,待处理项和编辑稿已保留。'};
|
||||
await closeProductionTurn(host);
|
||||
}
|
||||
return receipt;
|
||||
}
|
||||
|
||||
export async function closeProductionTurn(host) {
|
||||
const operations=await host.productionOperations;
|
||||
host.productionOperations=null;
|
||||
await operations?.close();
|
||||
const pending=host.productionOperations;
|
||||
try {
|
||||
await (await pending)?.close();
|
||||
} finally {
|
||||
if(host.productionOperations===pending)host.productionOperations=null;
|
||||
}
|
||||
}
|
||||
|
||||
@ -15,6 +15,7 @@ import { executeWorkflow, LOCAL_OPERATION_WAIT_MS, reconcileWorkflowReceipt } fr
|
||||
import { createVideoToolExecutors, videoTools } from './video-tools.mjs';
|
||||
import { activityToolLabel, COPY_UPDATE_LIMIT, copyUpdateItem } from './activity-event.mjs';
|
||||
import { reviewOutputScreen, screenReviewScope } from './screen-review.mjs';
|
||||
import { createTailWatcher } from './tail-watcher.mjs';
|
||||
|
||||
const obj=fields=>Type.Object(fields,{additionalProperties:false});
|
||||
const text=Type.String({minLength:1});
|
||||
@ -36,6 +37,13 @@ const transformImageArgs={
|
||||
...canvasTransformArgs,
|
||||
};
|
||||
const settledImagePhases=['complete','failed','retired','expired'];
|
||||
const recoveryNotices={
|
||||
complete:'原请求结果已取回',
|
||||
failed:'原请求已确认失败',
|
||||
retired:'原请求候选已退回',
|
||||
expired:'原请求结果已过期',
|
||||
not_executed:'原操作已确认未执行',
|
||||
};
|
||||
const MAX_SLOT_GENERATIONS=4;
|
||||
const expiryFields=receipt=>receipt?.resultExpiry?
|
||||
{requestId:receipt.requestId,retryable:false,resultExpiry:receipt.resultExpiry}:{};
|
||||
@ -200,14 +208,16 @@ function imageOriginals({items}) {
|
||||
});
|
||||
}
|
||||
|
||||
function createImageReconciler(canvas,{outputId,variantId},readJournal,update,{projectScope,onAdopted}={}) {
|
||||
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'});
|
||||
@ -229,12 +239,11 @@ function createImageReconciler(canvas,{outputId,variantId},readJournal,update,{p
|
||||
const archivedCandidate=adopting?undefined:originalCandidate(item);
|
||||
signal?.throwIfAborted();
|
||||
if(archivedCandidate){
|
||||
if(original&&original.candidateId!==archivedCandidate){
|
||||
await update(journal=>{journal.items[slot.id].pendingOperation={...original,candidateId:archivedCandidate};});
|
||||
}
|
||||
const receipt=await detailRecover(slot.id,{projectId:item.heldOriginalProjectId,candidateId:archivedCandidate});
|
||||
signal?.throwIfAborted();
|
||||
const phase=receipt?.id===archivedCandidate&&settledImagePhases.includes(receipt.status)?receipt.status:'unknown';
|
||||
if(phase!=='unknown')await update(journal=>{
|
||||
signal?.throwIfAborted();
|
||||
const saved=journal.items[slot.id];
|
||||
rememberImageExpiry(saved,archivedCandidate,receipt);
|
||||
if(originalCandidate(saved)===archivedCandidate)Object.assign(saved,{
|
||||
@ -252,26 +261,30 @@ function createImageReconciler(canvas,{outputId,variantId},readJournal,update,{p
|
||||
if(!original)return {slotId:slot.id,phase:'none'};
|
||||
const adoption=adopting?{outputId,productVariantId:variantId,slotId:slot.id}:undefined;
|
||||
const operation=await reconcileWorkflowReceipt(canvas,{...original,adoption});
|
||||
signal?.throwIfAborted();
|
||||
const candidateId=operation.candidateId??original.candidateId;
|
||||
const receipt=!adoption&&candidateId&&operation.phase==='unknown'
|
||||
? await detailRecover(slot.id,{candidateId}) : null;
|
||||
signal?.throwIfAborted();
|
||||
const phase=receipt?.id===candidateId&&settledImagePhases.includes(receipt.status)?receipt.status:operation.phase;
|
||||
const expiry=expiryFields(receipt?.id===candidateId?receipt:operation);
|
||||
if(settledImagePhases.includes(phase)||phase==='not_executed'){
|
||||
const applied=phase==='complete'&&adoption;
|
||||
if(applied)onAdopted?.(slot.id,candidateId);
|
||||
const decision=original.decision;
|
||||
await update(journal=>{
|
||||
const sessionPlacement=applied&&operation.persistence==='session';
|
||||
if(!sessionPlacement||item.state!=='applied'||item.candidateId!==candidateId)await update(journal=>{
|
||||
signal?.throwIfAborted();
|
||||
const record=journal.items[slot.id];
|
||||
rememberImageExpiry(record,candidateId,expiry);
|
||||
Object.assign(record,{state:applied?'applied':phase==='complete'?'candidate':phase,candidateId,
|
||||
...(applied&&operation.persistence==='session'?null:{[pendingKey]:null}),
|
||||
...(applied&&!decision?{autoCandidateSetId:null}:null),
|
||||
...(!adopting?{heldGeneration:false,heldOriginalId:null,heldOriginalProjectId:null}:null)});
|
||||
if(decision&&applied)record.autoAdoptions[decision.candidateSetId]={...decision,
|
||||
if(decision&&applied)(record.autoAdoptions??={})[decision.candidateSetId]={...decision,
|
||||
state:operation.persistence==='session'?'placed':'adopted',receipt:operation};
|
||||
if(decision&&phase==='not_executed')record.autoAdoptions[decision.candidateSetId]={...decision,state:'selected'};
|
||||
if(decision&&phase==='not_executed')(record.autoAdoptions??={})[decision.candidateSetId]={...decision,state:'selected'};
|
||||
},candidateId?{evidence:[slot.id,candidateId,adopting?'adoption':'candidate',{...operation,phase,...expiry,...decision}]}:undefined);
|
||||
if(applied&&!signal?.aborted)onAdopted?.(slot.id,candidateId);
|
||||
}
|
||||
const reason=receipt?.id===candidateId?receipt?.message??operation.message:operation.message;
|
||||
return {slotId:slot.id,phase,candidateId,operationId:original.operationId,reason,...expiry};
|
||||
@ -281,6 +294,7 @@ function createImageReconciler(canvas,{outputId,variantId},readJournal,update,{p
|
||||
return original?await reconcileImageRequest(slot,original,signal):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);
|
||||
@ -316,9 +330,12 @@ const copyPage=field=>field.page??field.pageId;
|
||||
const slotPage=slot=>slot.documentId??slot.page??slot.pageId;
|
||||
const slotSignatures=slots=>Object.fromEntries(slots.map(slot=>[slot.id,slot.selectedCandidateId??null]));
|
||||
|
||||
export async function openProductionOperations(host,{maxActiveDelegates=6,maxGenerationAttempts=MAX_SLOT_GENERATIONS}={}) {
|
||||
export async function openProductionOperations(host,{maxActiveDelegates=6,maxGenerationAttempts=MAX_SLOT_GENERATIONS,
|
||||
maxTailWatchConcurrency=6,tailFastIntervalMs=8_000,tailSlowIntervalMs=20_000,tailFastWindowMs=180_000,
|
||||
tailWatchClock}={}) {
|
||||
if(!Number.isSafeInteger(maxActiveDelegates)||maxActiveDelegates<1)throw RangeError('图位子代理并发上限必须为正整数');
|
||||
if(!Number.isSafeInteger(maxGenerationAttempts)||maxGenerationAttempts<1)throw RangeError('图位生图上限必须为正整数');
|
||||
if(!Number.isSafeInteger(maxTailWatchConcurrency)||maxTailWatchConcurrency<1)throw RangeError('原请求核查并发上限必须为正整数');
|
||||
const {canvas,store,productionGoal:{outputId,variantId}}=host;
|
||||
const {plan:initialPlan,slots}=await loadSlots(canvas,outputId);
|
||||
let plan=initialPlan;
|
||||
@ -376,6 +393,7 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
const seenLayouts=new Set();
|
||||
let seenProduct=false;
|
||||
const jobs=new Map(), generation=new Map(), reviewWork=new Set(), candidates=new Map();
|
||||
const dispatchingImages=new Set();
|
||||
const screenChecks=new Map();
|
||||
const filled=new Map(slots.filter(slot=>slot.selectedCandidateId).map(slot=>[slot.id,slot.selectedCandidateId]));
|
||||
const delegateQueue=[];
|
||||
@ -410,7 +428,8 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
const written=journalWrite.then(async()=>{
|
||||
const saved=write();
|
||||
journal=saved.journal;
|
||||
await ledger.publishAudit(journal);
|
||||
try { await ledger.publishAudit(journal); }
|
||||
finally { tailWatcher.refresh(); }
|
||||
return saved;
|
||||
});
|
||||
journalWrite=written.catch(()=>{});
|
||||
@ -564,6 +583,7 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
const candidateId=adopting?values.candidateId:
|
||||
canvas.durableGenerationIds&&values.useProductReference!==true?operation.operationId:null;
|
||||
prepared={...operation,intent,candidateId,...(decision?{decision}:null)};
|
||||
dispatchingImages.add(operation.operationId);
|
||||
await save(slot,{[pendingKey]:prepared,...(!adopting?{state:'dispatching'}:null)});
|
||||
};
|
||||
const rememberAttempt=(item,candidateId)=>{
|
||||
@ -571,42 +591,47 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
const attempts=item.attempts??=[];
|
||||
if(!attempts.some(entry=>entry.candidateId===candidateId))attempts.push({candidateId,...attempt});
|
||||
};
|
||||
let operation;
|
||||
try {
|
||||
({operation}=await executeWorkflow(host,args,signal,{scope,generatedCandidates:null,detailBatch:true,keepFailedCandidate:true,timeoutMs:Infinity,
|
||||
onPrepared:archive,onSubmitted:async receipt=>{
|
||||
if(receipt.candidateId){
|
||||
prepared={...prepared,candidateId:receipt.candidateId};
|
||||
await update(journal=>{
|
||||
const item=journal.items[slot.id]??={};
|
||||
item[pendingKey]=prepared;
|
||||
rememberAttempt(item,receipt.candidateId);
|
||||
});
|
||||
}
|
||||
}}));
|
||||
}catch(error){
|
||||
if(prepared)await save(slot,{state:scope.original?'unknown':'failed',reason:error.message,
|
||||
[pendingKey]:scope.original?prepared:null});
|
||||
throw error;
|
||||
let operation;
|
||||
try {
|
||||
({operation}=await executeWorkflow(host,args,signal,{scope,generatedCandidates:null,detailBatch:true,keepFailedCandidate:true,timeoutMs:Infinity,
|
||||
onPrepared:archive,onSubmitted:async receipt=>{
|
||||
if(receipt.candidateId){
|
||||
prepared={...prepared,candidateId:receipt.candidateId};
|
||||
await update(journal=>{
|
||||
const item=journal.items[slot.id]??={};
|
||||
item[pendingKey]=prepared;
|
||||
rememberAttempt(item,receipt.candidateId);
|
||||
});
|
||||
}
|
||||
}}));
|
||||
}catch(error){
|
||||
if(prepared)await save(slot,{state:scope.original?'unknown':'failed',reason:error.message,
|
||||
[pendingKey]:scope.original?prepared:null});
|
||||
throw error;
|
||||
}
|
||||
const state=operation.phase==='complete'?(intent==='generate_candidate'?'candidate':'applied'):operation.phase;
|
||||
if(state==='applied')filled.set(slot.id,operation.candidateId??values.candidateId);
|
||||
const pending=operation.phase==='unknown'
|
||||
? {...prepared,candidateId:operation.candidateId??prepared.candidateId}
|
||||
: state==='applied'&&operation.persistence==='session'?prepared:null;
|
||||
await update(journal=>{
|
||||
const item=journal.items[slot.id]??={};
|
||||
Object.assign(item,{state,candidateId:operation.candidateId??prior?.candidateId,[pendingKey]:pending,
|
||||
...(intent==='generate_candidate'?{source:values.useProductReference?'product':'generate',prompt:values.instruction}:null),
|
||||
...(state==='applied'&&!decision?{autoCandidateSetId:null}:null)});
|
||||
if(decision&&state==='applied')item.autoAdoptions[decision.candidateSetId]={...decision,
|
||||
state:operation.persistence==='session'?'placed':'adopted',receipt:operation};
|
||||
rememberAttempt(item,operation.candidateId);
|
||||
rememberImageExpiry(item,operation.candidateId,operation);
|
||||
},operation.candidateId?{evidence:[slot.id,operation.candidateId,adopting?'adoption':'candidate',
|
||||
{...prepared,...operation,actor:'agent',fieldId:slot.fieldId,...decision}]}:undefined);
|
||||
if(state==='applied')markProgressDirty();
|
||||
return {...operation,...(operation.phase==='unknown'?{pendingOriginal:operation.candidateId??operation.operationId}:null)};
|
||||
} finally {
|
||||
if(prepared)dispatchingImages.delete(prepared.operationId);
|
||||
tailWatcher.refresh();
|
||||
}
|
||||
const state=operation.phase==='complete'?(intent==='generate_candidate'?'candidate':'applied'):operation.phase;
|
||||
if(state==='applied')filled.set(slot.id,operation.candidateId??values.candidateId);
|
||||
const pending=operation.phase==='unknown'
|
||||
? {...prepared,candidateId:operation.candidateId??prepared.candidateId}
|
||||
: state==='applied'&&operation.persistence==='session'?prepared:null;
|
||||
await update(journal=>{
|
||||
const item=journal.items[slot.id]??={};
|
||||
Object.assign(item,{state,candidateId:operation.candidateId??prior?.candidateId,[pendingKey]:pending,
|
||||
...(intent==='generate_candidate'?{source:values.useProductReference?'product':'generate',prompt:values.instruction}:null),
|
||||
...(state==='applied'&&!decision?{autoCandidateSetId:null}:null)});
|
||||
if(decision&&state==='applied')item.autoAdoptions[decision.candidateSetId]={...decision,
|
||||
state:operation.persistence==='session'?'placed':'adopted',receipt:operation};
|
||||
rememberAttempt(item,operation.candidateId);
|
||||
rememberImageExpiry(item,operation.candidateId,operation);
|
||||
},operation.candidateId?{evidence:[slot.id,operation.candidateId,adopting?'adoption':'candidate',
|
||||
{...prepared,...operation,actor:'agent',fieldId:slot.fieldId,...decision}]}:undefined);
|
||||
if(state==='applied')markProgressDirty();
|
||||
return {...operation,...(operation.phase==='unknown'?{pendingOriginal:operation.candidateId??operation.operationId}:null)};
|
||||
}
|
||||
const pendingGeneration=(slot,record=journal,requestId)=>{
|
||||
const item=record.items[slot.id];
|
||||
@ -667,9 +692,20 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
const live=await liveSlot(slot);
|
||||
approval={requestId:approval.requestId,expectedRevision:approval.expectedRevision??request.revision,
|
||||
expectedHash:approval.expectedHash??request.requestSpecHash};
|
||||
const {claimed,pending,request:record,original,generationAttempts}=await commit(()=>
|
||||
repository.claimImageRequest(approval,binding,(saved,prior)=>pendingGeneration(slot,saved)??prior,
|
||||
{maxGenerationAttempts,nativeIds:nativeGenerations(live)}));
|
||||
let claimedOperationId;
|
||||
const {claimed,pending,request:record,original,generationAttempts}=await commit(()=>{
|
||||
const claim=repository.claimImageRequest(approval,binding,(saved,prior)=>pendingGeneration(slot,saved)??prior,
|
||||
{maxGenerationAttempts,nativeIds:nativeGenerations(live)});
|
||||
if(claim.claimed){
|
||||
claimedOperationId=claim.original.operationId;
|
||||
dispatchingImages.add(claimedOperationId);
|
||||
}
|
||||
return claim;
|
||||
}).catch(error=>{
|
||||
dispatchingImages.delete(claimedOperationId);
|
||||
tailWatcher.refresh();
|
||||
throw error;
|
||||
});
|
||||
const {requestId:candidateId}=approval;
|
||||
if(generationAttempts!==undefined){
|
||||
const status=drawStatus(generationAttempts);
|
||||
@ -754,7 +790,10 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
}
|
||||
return launchImage(slot,key,number=>{
|
||||
if(claim.error)throw claim.error;
|
||||
return claim.receipt??dispatchImageRequest(slot,claim.approval,request,claim.original,signal,number);
|
||||
return claim.receipt??dispatchImageRequest(slot,claim.approval,request,claim.original,signal,number).finally(()=>{
|
||||
dispatchingImages.delete(claim.original.operationId);
|
||||
tailWatcher.refresh();
|
||||
});
|
||||
},approval.requestId,workerNumber);
|
||||
};
|
||||
const useProductImage=async(slot,options,signal)=>({
|
||||
@ -762,8 +801,10 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
requestedSource:'product',sourceNote:'仅使用或裁切原片,保留原片的背景和光线。',
|
||||
});
|
||||
|
||||
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 outstanding=async()=>{
|
||||
await journalWrite;
|
||||
@ -784,6 +825,7 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
...(models.length||images.length?{originals:{models,images}}:null),
|
||||
});
|
||||
const autoAdopt=(slot,candidateSet,signal)=>serialize(async()=>{
|
||||
signal?.throwIfAborted();
|
||||
const {id,policy}=candidateSet;
|
||||
const previous=journal.items[slot.id]?.autoAdoptions?.[id];
|
||||
if(previous&&previous.state!=='selected')return previous;
|
||||
@ -791,6 +833,7 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
const item=journal.items[slot.id];
|
||||
if(item?.autoCandidateSetId!==id)return previous;
|
||||
const copy=JSON.stringify(copySignature(await liveSlotCopy(slot)));
|
||||
signal?.throwIfAborted();
|
||||
const currentReviews=Object.fromEntries(Object.entries(item?.candidateReviews??{}).filter(([,row])=>
|
||||
row.creationRevision===plan.revisions?.creation&&
|
||||
JSON.stringify(row.observation.reviewedCopy)===copy));
|
||||
@ -810,6 +853,53 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
}
|
||||
return journal.items[slot.id].autoAdoptions[id];
|
||||
});
|
||||
const tryAutoAdopt=(slot,signal)=>{
|
||||
const {autoCandidateSetId:id,candidateReviews}=journal.items[slot.id]??{};
|
||||
const set=id&&candidateReviews&&repository.readImageRequest(id)?.prepared.candidateSet;
|
||||
if(set)return autoAdopt(slot,set,signal);
|
||||
};
|
||||
const tailsFor=slot=>slotOriginals(journal.items[slot.id]).map(tail=>{
|
||||
const {adopting,request:{candidateId,operationId,projectId}}=tail;
|
||||
return {...tail,slot,key:JSON.stringify([slot.id,Boolean(adopting),
|
||||
adopting?operationId??candidateId:candidateId??operationId,projectId])};
|
||||
});
|
||||
const tailWatcher=createTailWatcher({
|
||||
...tailWatchClock,signal:host.productionSignal,maxConcurrency:maxTailWatchConcurrency,
|
||||
fastInterval:tailFastIntervalMs,slowInterval:tailSlowIntervalMs,fastWindow:tailFastWindowMs,
|
||||
list:()=>Object.keys(journal.items).flatMap(id=>tailsFor(byId.get(id)??{id}))
|
||||
.filter(tail=>!dispatchingImages.has(tail.request.operationId)),
|
||||
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;
|
||||
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);
|
||||
signal.throwIfAborted();
|
||||
if(!adopting&&receipt.phase!=='none'){
|
||||
const original=[...generation.entries()].find(([,row])=>row.slotId===slot.id&&row.phase==='unknown'&&
|
||||
(receipt.operationId&&row.operationId===receipt.operationId||receipt.candidateId&&row.candidateId===receipt.candidateId));
|
||||
generation.set(original?.[0]??receipt.operationId??receipt.candidateId??slot.id,receipt);
|
||||
}
|
||||
const heading=recoveryNotices[receipt.phase];
|
||||
if(heading&&!(receipt.phase==='complete'&&alreadyPlaced&&journal.items[slot.id]?.pendingAdoption)){
|
||||
if(receipt.candidateId){
|
||||
if(adopting&&receipt.phase==='complete'){
|
||||
candidates.set(receipt.candidateId,{...candidates.get(receipt.candidateId),slotId:slot.id,status:'adopted'});
|
||||
}else if(!adopting&&(!candidates.has(receipt.candidateId)||receipt.phase!=='complete')){
|
||||
candidates.set(receipt.candidateId,{slotId:slot.id,status:receipt.phase,reason:receipt.reason});
|
||||
}
|
||||
}
|
||||
markProgressDirty();
|
||||
notice(heading);
|
||||
}
|
||||
if(receipt.phase==='complete'&&!adopting&&byId.has(slot.id)){
|
||||
tryAutoAdopt(slot,signal)?.catch(error=>{if(!signal.aborted)reportRecoveryError(error);});
|
||||
}
|
||||
return receipt;
|
||||
},
|
||||
onError:reportRecoveryError,
|
||||
});
|
||||
async function check(slot,candidateId,adopted,signal){
|
||||
const item=journal.items[slot.id];
|
||||
const request=repository.readImageRequest(candidateId);
|
||||
@ -845,6 +935,7 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
get active(){return jobs.size;},
|
||||
markProgressDirty,
|
||||
async close(){
|
||||
tailWatcher.close();
|
||||
await drain();
|
||||
await canvasWrite;
|
||||
await journalWrite;
|
||||
@ -1246,36 +1337,16 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
return result;
|
||||
},
|
||||
async reconcile_image_slots({slotIds},signal){
|
||||
const recover=async(slot,adopting=false,frozen)=>{
|
||||
const receipt=await recoverImage(slot,adopting,frozen,signal);
|
||||
if(!adopting&&receipt.phase!=='none'){
|
||||
const original=[...generation.entries()].find(([,row])=>row.slotId===slot.id&&row.phase==='unknown'&&
|
||||
(receipt.operationId&&row.operationId===receipt.operationId||receipt.candidateId&&row.candidateId===receipt.candidateId));
|
||||
generation.set(original?.[0]??receipt.operationId??slot.id,receipt);
|
||||
}
|
||||
return receipt;
|
||||
};
|
||||
signal?.throwIfAborted();
|
||||
const selected=selections(slotIds);
|
||||
const results=await Promise.all(selected.flatMap(slot=>{
|
||||
const item=journal.items[slot.id];
|
||||
const frozen=Object.values(item?.pendingGenerations??{});
|
||||
return [
|
||||
...(!frozen.length||pendingGeneration(slot)?[recover(slot)]:[]),
|
||||
...frozen.map(original=>recover(slot,false,original)),
|
||||
...(item?.pendingAdoption?[recover(slot,true)]:[]),
|
||||
];
|
||||
const tails=tailsFor(slot);
|
||||
const receipts=tails.map(tail=>tailWatcher.reconcile(tail));
|
||||
if(tails.every(tail=>tail.adopting))receipts.unshift({slotId:slot.id,phase:'none'});
|
||||
return receipts;
|
||||
}));
|
||||
for(const slot of selected){
|
||||
const {autoCandidateSetId:id,candidateReviews}=journal.items[slot.id]??{};
|
||||
if(id&&candidateReviews){
|
||||
const set=repository.readImageRequest(id)?.prepared.candidateSet;
|
||||
if(set)await autoAdopt(slot,set,signal);
|
||||
}
|
||||
}
|
||||
if(results.some(receipt=>receipt.phase==='complete')){
|
||||
markProgressDirty();
|
||||
notice('已核查原图片操作');
|
||||
}
|
||||
signal?.throwIfAborted();
|
||||
for(const slot of selected)await tryAutoAdopt(slot,signal);
|
||||
return results;
|
||||
},
|
||||
async read_output_screen({page=0,pages},signal){
|
||||
@ -1445,5 +1516,6 @@ export async function openProductionOperations(host,{maxActiveDelegates=6,maxGen
|
||||
}};
|
||||
},
|
||||
};
|
||||
tailWatcher.refresh();
|
||||
return operations;
|
||||
}
|
||||
|
||||
93
apps/detail-agent-pi/src/tail-watcher.mjs
Normal file
93
apps/detail-agent-pi/src/tail-watcher.mjs
Normal file
@ -0,0 +1,93 @@
|
||||
export function createTailWatcher({list,probe,onError,signal:productionSignal,maxConcurrency,
|
||||
fastInterval,slowInterval,fastWindow,now=Date.now,setTimer=setTimeout,clearTimer=clearTimeout}){
|
||||
const lifecycle=new AbortController();
|
||||
const {signal}=lifecycle;
|
||||
const dueTails=new Map(), inflightRecoveries=new Map(), queued=[];
|
||||
let timer, active=0;
|
||||
|
||||
function schedule(){
|
||||
cancelTimer();
|
||||
if(signal.aborted||active>=maxConcurrency)return;
|
||||
const ready=[...dueTails.values()].filter(({tail})=>!inflightRecoveries.has(tail.key))
|
||||
.sort((a,b)=>a.nextDueAt-b.nextDueAt);
|
||||
if(!ready.length)return;
|
||||
timer=setTimer(()=>{
|
||||
timer=undefined;
|
||||
const time=now();
|
||||
for(const {tail,nextDueAt} of ready){
|
||||
if(signal.aborted||active>=maxConcurrency||nextDueAt>time)break;
|
||||
reconcile(tail).catch(error=>{if(!signal.aborted)onError(error);});
|
||||
}
|
||||
},Math.max(0,ready[0].nextDueAt-now()));
|
||||
timer.unref?.();
|
||||
}
|
||||
|
||||
function cancelTimer(){
|
||||
if(timer!==undefined)clearTimer(timer);
|
||||
timer=undefined;
|
||||
}
|
||||
|
||||
function refresh(){
|
||||
if(signal.aborted)return;
|
||||
const time=now();
|
||||
const previous=new Map(dueTails);
|
||||
dueTails.clear();
|
||||
for(const tail of list()){
|
||||
const timing=previous.get(tail.key)??{firstSeenAt:time,nextDueAt:time};
|
||||
dueTails.set(tail.key,{...timing,tail});
|
||||
}
|
||||
schedule();
|
||||
}
|
||||
|
||||
async function run(tail,job){
|
||||
const startedAt=now();
|
||||
try {
|
||||
job.resolve(await probe(tail,signal));
|
||||
} catch(error) {
|
||||
job.reject(error);
|
||||
} finally {
|
||||
active--;
|
||||
inflightRecoveries.delete(tail.key);
|
||||
const timing=dueTails.get(tail.key);
|
||||
if(timing){
|
||||
const interval=startedAt-timing.firstSeenAt<fastWindow?fastInterval:slowInterval;
|
||||
timing.nextDueAt=startedAt+interval;
|
||||
}
|
||||
pump();
|
||||
}
|
||||
}
|
||||
|
||||
function pump(){
|
||||
while(!signal.aborted&&active<maxConcurrency&&queued.length){
|
||||
const {tail,job}=queued.shift();
|
||||
active++;
|
||||
void run(tail,job);
|
||||
}
|
||||
schedule();
|
||||
}
|
||||
|
||||
function reconcile(tail){
|
||||
if(signal.aborted)return Promise.reject(signal.reason);
|
||||
const existing=inflightRecoveries.get(tail.key);
|
||||
if(existing)return existing.promise;
|
||||
const job=Promise.withResolvers();
|
||||
inflightRecoveries.set(tail.key,job);
|
||||
queued.push({tail,job});
|
||||
pump();
|
||||
return job.promise;
|
||||
}
|
||||
|
||||
const abort=()=>close(productionSignal.reason);
|
||||
function close(reason){
|
||||
lifecycle.abort(reason);
|
||||
productionSignal?.removeEventListener('abort',abort);
|
||||
cancelTimer();
|
||||
for(const job of inflightRecoveries.values())job.reject(signal.reason);
|
||||
inflightRecoveries.clear();
|
||||
dueTails.clear();
|
||||
queued.length=0;
|
||||
}
|
||||
if(productionSignal?.aborted)abort();
|
||||
else productionSignal?.addEventListener('abort',abort,{once:true});
|
||||
return {refresh,reconcile,close};
|
||||
}
|
||||
@ -6,7 +6,7 @@ import fs from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { openProductionOperations } from '../src/production-operations.mjs';
|
||||
import { callProductionTool, mayContinueProductionGoal } from '../src/production-goal.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';
|
||||
@ -36,6 +36,265 @@ function imageBridge(host,dispatch,id=()=>randomUUID()) {
|
||||
function approve({requestId,revision,requestSpecHash}) {
|
||||
return {requestId,expectedRevision:revision,expectedHash:requestSpecHash};
|
||||
}
|
||||
|
||||
function tailClock(){
|
||||
let time=0;
|
||||
const timers=new Set();
|
||||
return {
|
||||
now:()=>time,
|
||||
setTimer(callback,delay){
|
||||
const timer={callback,due:time+delay,unref(){this.unreferenced=true;}};
|
||||
timers.add(timer);
|
||||
return timer;
|
||||
},
|
||||
clearTimer:timer=>timers.delete(timer),
|
||||
get nextDue(){return timers.values().next().value?.due;},
|
||||
async advance(ms=0){
|
||||
time+=ms;
|
||||
for(const timer of [...timers]){
|
||||
assert.equal(timer.unreferenced,true);
|
||||
if(timer.due>time)continue;
|
||||
timers.delete(timer);
|
||||
timer.callback();
|
||||
}
|
||||
await new Promise(resolve=>setImmediate(resolve));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function tailFixture(t,ids,items={}){
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-originals-'));
|
||||
t.after(()=>cleanup(dir));
|
||||
const store=productionStore(dir);
|
||||
const ledger=store.ledger('detail','oak');
|
||||
const slots=ids.map(id=>({id,fieldId:id}));
|
||||
const notices=new Map();
|
||||
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:[]}),
|
||||
async delta(_text,_thinking,{heading}){notices.get(heading)?.resolve();},
|
||||
}};
|
||||
if(Object.keys(items).length)ledger.repository.replaceLedger({binding:JSON.stringify(['studio','oak']),items});
|
||||
return {dir,host,ledger,clock:tailClock(),notice(heading){
|
||||
const gate=Promise.withResolvers();
|
||||
notices.set(heading,gate);
|
||||
return gate.promise;
|
||||
}};
|
||||
}
|
||||
|
||||
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('six original lookups run while all six generation delegates are posting',{timeout:8000},async t=>{
|
||||
const posts=Array.from({length:6},(_,index)=>'new-'+index);
|
||||
const originals=Array.from({length:6},(_,index)=>'old-'+index);
|
||||
const items=Object.fromEntries(originals.map(id=>[id,{state:'unknown',heldOriginalId:id}]));
|
||||
const {host,clock}=await tailFixture(t,[...posts,...originals],items);
|
||||
const releasePosts=Promise.withResolvers(), postsStarted=Promise.withResolvers(), releaseReads=Promise.withResolvers();
|
||||
const posting=[],reading=[];
|
||||
imageBridge(host,async({slotId},id)=>{
|
||||
posting.push(slotId);
|
||||
if(posting.length===6)postsStarted.resolve();
|
||||
await releasePosts.promise;
|
||||
return {id,status:'complete'};
|
||||
});
|
||||
host.runDetailAgent=async(slotId,_system,_prompt,tools)=>{
|
||||
const prepare=tools.find(tool=>tool.name==='prepare_image_request');
|
||||
const dispatch=tools.find(tool=>tool.name==='dispatch_image_request');
|
||||
const request=(await prepare.execute('prepare',{prompt:'展示桌面'})).details;
|
||||
assert.equal(request.slotId,slotId);
|
||||
await dispatch.execute('post',approve(request));
|
||||
};
|
||||
host.canvas.detailRecover=async(slotId,{candidateId})=>{
|
||||
reading.push(slotId);
|
||||
await releaseReads.promise;
|
||||
return {id:candidateId,status:'unknown'};
|
||||
};
|
||||
const actions=await openProductionOperations(host,{tailWatchClock:clock});
|
||||
try {
|
||||
await actions.delegate_image_slots({jobs:posts.map(slotId=>({slotId,goal:'展示桌面'}))});
|
||||
await postsStarted.promise;
|
||||
await clock.advance();
|
||||
assert.deepEqual(new Set(posting),new Set(posts));
|
||||
assert.deepEqual(reading,originals);
|
||||
} finally {
|
||||
releasePosts.resolve();
|
||||
releaseReads.resolve();
|
||||
await actions.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('original lookups have independent deadlines, retry probe errors and stop after settlement',{timeout:5000},async t=>{
|
||||
const items={
|
||||
'a-slow':{state:'unknown',heldOriginalId:'slow-id',heldOriginalProjectId:'source-project'},
|
||||
'b-fast':{state:'unknown',candidateId:'fast-id'},
|
||||
'c-queued':{pendingOperation:{candidateId:'queued-id',operationId:'queued-operation'}},
|
||||
};
|
||||
const {dir,host,ledger,clock,notice}=await tailFixture(t,Object.keys(items),items);
|
||||
const slow=Promise.withResolvers(),reads=[];
|
||||
const failed=notice('原请求已确认失败'), expired=notice('原请求结果已过期');
|
||||
const resultExpiry={httpStatus:410,requestId:'original-remote'};
|
||||
const warnings=t.mock.method(console,'warn',()=>{});
|
||||
host.canvas.detailRecover=async(slot,{candidateId,projectId})=>{
|
||||
reads.push([slot,clock.now()]);
|
||||
if(slot==='a-slow'){
|
||||
assert.equal(projectId,'source-project');
|
||||
return slow.promise;
|
||||
}
|
||||
if(slot==='c-queued')return {id:candidateId,status:'failed'};
|
||||
if(clock.now()===8_000)throw Error('原请求状态暂时不可查');
|
||||
if(clock.now()===204_000)return {id:candidateId,status:'expired',resultExpiry,requestId:'original-remote'};
|
||||
return {id:candidateId,status:'unknown'};
|
||||
};
|
||||
const actions=await openProductionOperations(host,{tailWatchClock:clock,maxTailWatchConcurrency:2});
|
||||
t.after(()=>actions.close());
|
||||
await clock.advance();
|
||||
assert.deepEqual(reads,[['a-slow',0],['b-fast',0]]);
|
||||
await clock.advance();
|
||||
await failed;
|
||||
assert.equal(ledger.read().items['c-queued'].pendingOperation,null);
|
||||
for(let time=8_000;time<=184_000;time+=8_000){
|
||||
assert.equal(clock.nextDue,time);
|
||||
await clock.advance(8_000);
|
||||
}
|
||||
assert.equal(warnings.mock.callCount(),1);
|
||||
assert.equal(clock.nextDue,204_000);
|
||||
await clock.advance(20_000);
|
||||
await expired;
|
||||
assert.deepEqual(reads.filter(([slot])=>slot==='b-fast').map(([,time])=>time),
|
||||
[...Array.from({length:24},(_,index)=>index*8_000),204_000]);
|
||||
assert.deepEqual(reads.filter(([slot])=>slot!=='b-fast'),[['a-slow',0],['c-queued',0]]);
|
||||
const saved=JSON.parse(await fs.readFile(path.join(dir,'production-detail-oak.json'),'utf8'));
|
||||
assert.equal(saved.items['b-fast'].state,'expired');
|
||||
assert.deepEqual(saved.items['b-fast'].attempts[0].resultExpiry,resultExpiry);
|
||||
assert.equal(saved.items['c-queued'].state,'failed');
|
||||
const recovered=notice('原请求结果已取回');
|
||||
slow.resolve({id:'slow-id',status:'complete'});
|
||||
await recovered;
|
||||
assert.equal(clock.nextDue,undefined);
|
||||
});
|
||||
|
||||
test('a manual adoption lookup takes priority and the watcher shares its original receipt',{timeout:5000},async t=>{
|
||||
const pendingAdoption={candidateId:'image',operationId:'adoption',run:'prior',documentId:12};
|
||||
const {host,ledger,clock,notice}=await tailFixture(t,['hero'],{hero:{pendingAdoption}});
|
||||
const checked=notice('原操作已确认未执行'), gate=Promise.withResolvers(),reads=[];
|
||||
host.canvas.workflowReconcile=async query=>{
|
||||
reads.push(query);
|
||||
await gate.promise;
|
||||
return {...pendingAdoption,phase:'not_executed'};
|
||||
};
|
||||
const actions=await openProductionOperations(host,{tailWatchClock:clock});
|
||||
t.after(()=>actions.close());
|
||||
const reconcile=()=>actions.reconcile_image_slots({slotIds:['hero']});
|
||||
const first=reconcile();
|
||||
await clock.advance();
|
||||
const second=reconcile();
|
||||
assert.equal(reads.length,1);
|
||||
assert.deepEqual(reads[0].adoption,{outputId:'detail',productVariantId:'oak',slotId:'hero'});
|
||||
gate.resolve();
|
||||
const results=await first;
|
||||
assert.deepEqual(await second,results);
|
||||
assert.equal(results[1].phase,'not_executed');
|
||||
await checked;
|
||||
assert.equal(ledger.read().items.hero.pendingAdoption,null);
|
||||
assert.equal(clock.nextDue,undefined);
|
||||
});
|
||||
|
||||
test('binding an output starts recovery before any subsequent production tool',{timeout:5000},async t=>{
|
||||
const {host,ledger,notice}=await tailFixture(t,['hero'],{hero:{state:'unknown',candidateId:'original'}});
|
||||
const settled=notice('原请求结果已取回');
|
||||
host.productionGoal={requestedOutputs:[{outputId:'detail',variantId:'oak'}]};
|
||||
host.bindGoalRequestScope=()=>{};
|
||||
host.canvas.openProductionOutput=async binding=>binding;
|
||||
host.canvas.detailRecover=async(slot,{candidateId})=>{
|
||||
assert.equal(slot,'hero');
|
||||
return {id:candidateId,status:'complete'};
|
||||
};
|
||||
t.after(()=>closeProductionTurn(host));
|
||||
await callProductionTool(host,'open_production_output',{outputId:'detail',variantId:'oak'});
|
||||
await settled;
|
||||
assert.equal(ledger.read().items.hero.state,'candidate');
|
||||
});
|
||||
|
||||
for(const stop of ['abort','close','switch'])test(`${stop} stops queued lookups and ignores a late active receipt`,{timeout:5000},async t=>{
|
||||
const controller=new AbortController();
|
||||
const {host,ledger,clock}=await tailFixture(t,['active','queued'],{
|
||||
active:{state:'unknown',candidateId:'active-id'},queued:{state:'unknown',candidateId:'queued-id'},
|
||||
});
|
||||
host.productionSignal=controller.signal;
|
||||
const gate=Promise.withResolvers(), reads=[];
|
||||
host.canvas.detailRecover=async(slotId)=>{
|
||||
reads.push(slotId);
|
||||
return gate.promise;
|
||||
};
|
||||
const actions=await openProductionOperations(host,{tailWatchClock:clock,maxTailWatchConcurrency:1});
|
||||
t.after(()=>actions.close());
|
||||
await clock.advance();
|
||||
const rejected=assert.rejects(actions.reconcile_image_slots({}),{name:'AbortError'});
|
||||
if(stop==='abort')controller.abort();
|
||||
else if(stop==='close'){
|
||||
host.productionOperations=Promise.resolve(actions);
|
||||
await closeProductionTurn(host);
|
||||
}
|
||||
else {
|
||||
host.productionOperations=Promise.resolve(actions);
|
||||
host.canvas.openProductionOutput=async()=>({outputId:null,variantId:null});
|
||||
host.bindGoalRequestScope=()=>{};
|
||||
await callProductionTool(host,'open_production_output',{});
|
||||
assert.equal(host.productionOperations,null);
|
||||
}
|
||||
await rejected;
|
||||
gate.resolve({id:'active-id',status:'complete'});
|
||||
await clock.advance(200_000);
|
||||
assert.deepEqual(reads,['active']);
|
||||
assert.equal(clock.nextDue,undefined);
|
||||
assert.equal(ledger.read().items.active.state,'unknown');
|
||||
});
|
||||
|
||||
const drawStatus=(attempts,max=4)=>({generationAttempts:attempts,maxGenerationAttempts:max,
|
||||
remainingGenerationAttempts:Math.max(0,max-attempts),drawLimitReached:attempts>=max});
|
||||
|
||||
@ -324,11 +583,13 @@ test('an unbound production turn checks project originals without opening any wo
|
||||
test('P07 waits for both candidate reviews and persists the automatic adoption decision',async t=>{
|
||||
for(const scenario of [
|
||||
{verdicts:['pass','revise'],winner:0,reason:'only_pass',recoverA:true},
|
||||
{verdicts:['pass','revise'],winner:0,reason:'only_pass',recoverA:true,watchA:true},
|
||||
{verdicts:['pass','pass'],winner:1,reason:'policy_priority'},
|
||||
{verdicts:['revise','revise'],winner:null,reason:'all_rejected'},
|
||||
{verdicts:['pass','pass'],winner:1,reason:'policy_priority',editCopy:true},
|
||||
{verdicts:['revise','pass'],manual:true,reason:'honors the explicit choice before the draw cap'},
|
||||
])await t.test(scenario.editCopy?'rechecks earlier candidates after a live copy edit':scenario.reason,async t=>{
|
||||
])await t.test(scenario.watchA?'adopts a recovered image from existing reviews':
|
||||
scenario.editCopy?'rechecks earlier candidates after a live copy edit':scenario.reason,{timeout:5000},async t=>{
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-p07-'));
|
||||
t.after(()=>cleanup(dir));
|
||||
const store=productionStore(dir);
|
||||
@ -337,6 +598,7 @@ test('P07 waits for both candidate reviews and persists the automatic adoption d
|
||||
const slotId='main-photo';
|
||||
const posts=[],placements=[],seen=[];
|
||||
const bothStarted=Promise.withResolvers(), complete=Promise.withResolvers();
|
||||
const tailWatchClock=tailClock(), placed=Promise.withResolvers();
|
||||
const image={type:'image',mimeType:'image/png',
|
||||
data:'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+j1f8AAAAASUVORK5CYII='};
|
||||
const digest='a'.repeat(64);
|
||||
@ -345,7 +607,8 @@ test('P07 waits for both candidate reviews and persists the automatic adoption d
|
||||
workflowRead:async()=>({available:true,canvasFirst:true,outputId:'detail',productVariantId:'oak',
|
||||
template:{contentHash:'studio',production:{autoAdoptionPolicy:policy}},totalSlots:1,
|
||||
slots:[{id:slotId,fieldId:'cover',documentId:'P07',relatedFields:['title']}]}),
|
||||
detailCopyFields:async()=>({fields:[{page:'P07',field:'title',currentText}]}),delta:async()=>{},
|
||||
detailCopyFields:async()=>({fields:[{page:'P07',field:'title',currentText}]}),
|
||||
async delta(_text,_thinking,{heading}){if(heading==='画布回填回执')placed.resolve();},
|
||||
async detailRecover(recoveredSlot,{candidateId}){
|
||||
assert.equal(recoveredSlot,slotId);
|
||||
assert.equal(candidateId,posts[0]);
|
||||
@ -389,7 +652,7 @@ test('P07 waits for both candidate reviews and persists the automatic adoption d
|
||||
await complete.promise;
|
||||
return {status:scenario.recoverA&&id===posts[0]?'unknown':'complete',id};
|
||||
});
|
||||
let actions=await openProductionOperations(host);
|
||||
let actions=await openProductionOperations(host,{tailWatchClock});
|
||||
assert.deepEqual((await actions.plan_production()).autoAdoptionPolicy,policy);
|
||||
const input={slotId:'cover',prompt:'保留同款原片的轮廓。\r\n窗侧光。'};
|
||||
const a=await actions.prepare_image_request(input);
|
||||
@ -407,15 +670,17 @@ test('P07 waits for both candidate reviews and persists the automatic adoption d
|
||||
assert.deepEqual(Object.keys(ledger.read().items[slotId].pendingGenerations),ids);
|
||||
complete.resolve();
|
||||
await actions.close();
|
||||
actions=await openProductionOperations(host);
|
||||
if(scenario.recoverA){
|
||||
actions=await openProductionOperations(host,{tailWatchClock});
|
||||
if(scenario.recoverA&&!scenario.watchA){
|
||||
assert.equal((await actions.dispatch_image_request(approve(a))).pendingOriginal,a.requestId);
|
||||
const [recovered]=await actions.reconcile_image_slots({slotIds:[slotId]});
|
||||
assert.equal(recovered.operationId,a.operationId);
|
||||
assert.equal(recovered.phase,'complete');
|
||||
}
|
||||
for(const draft of [a,b])await actions.dispatch_image_request(approve(draft));
|
||||
await actions.close();
|
||||
if(scenario.watchA){
|
||||
while(actions.active)await actions.await_image_slots({});
|
||||
}else await actions.close();
|
||||
assert.deepEqual(posts,ids);
|
||||
const [first]=await actions.check_image_slots({wait:true,candidates:[{slotId,candidateId:a.requestId}]});
|
||||
assert.equal(first.adoption,undefined);
|
||||
@ -430,6 +695,13 @@ test('P07 waits for both candidate reviews and persists the automatic adoption d
|
||||
if(scenario.editCopy)currentText='加厚桌腿与横梁接口';
|
||||
const [second]=await actions.check_image_slots({wait:true,candidates:[{slotId,candidateId:b.requestId}]});
|
||||
let adoption=second.adoption;
|
||||
if(scenario.watchA){
|
||||
assert.equal(adoption,undefined);
|
||||
assert.deepEqual(placements,[]);
|
||||
await tailWatchClock.advance();
|
||||
await placed.promise;
|
||||
adoption=ledger.read().items[slotId].autoAdoptions[a.candidateSet.id];
|
||||
}
|
||||
if(scenario.editCopy){
|
||||
assert.equal(adoption,undefined);
|
||||
assert.deepEqual(placements,[]);
|
||||
@ -793,6 +1065,7 @@ test('a lost native acknowledgement can be recovered with the saved generation o
|
||||
const slotId='image-front';
|
||||
const submissions=[], recoveries=[];
|
||||
let recoveredStatus='unknown';
|
||||
const tailWatchClock=tailClock();
|
||||
const canvas={
|
||||
durableGenerationIds:true,run:'original-run',documentId:23,
|
||||
workflowRead:async()=>({available:true,canvasFirst:true,version:1,outputId:'detail',productVariantId:'ink',
|
||||
@ -819,14 +1092,15 @@ test('a lost native acknowledgement can be recovered with the saved generation o
|
||||
assert.equal(pending.candidateId,operationId);
|
||||
throw new BridgeError('画布连接中断,原操作不会重发','transport_interrupted',{dispatched:true});
|
||||
});
|
||||
let actions=await openProductionOperations(host);
|
||||
let actions=await openProductionOperations(host,{tailWatchClock});
|
||||
const request={slotId,source:'generate',prompt:'保留商品比例'};
|
||||
const lost=await generateAndWait(actions,request);
|
||||
assert.equal(lost.phase,'unknown');
|
||||
assert.match(lost.reason,/画布连接中断/u);
|
||||
await actions.close();
|
||||
canvas.run='restarted-run';
|
||||
canvas.documentId=42;
|
||||
actions=await openProductionOperations(host);
|
||||
actions=await openProductionOperations(host,{tailWatchClock});
|
||||
const [originalId]=submissions;
|
||||
assert.equal((await generateAndWait(actions,request)).pendingOriginal,originalId);
|
||||
assert.equal((await actions.reconcile_image_slots({slotIds:[slotId]}))[0].phase,'unknown');
|
||||
@ -930,6 +1204,7 @@ test('Pi chooses each image operation and keeps an unresolved paid request on it
|
||||
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-'));
|
||||
t.after(()=>cleanup(dir));
|
||||
const outputId='detail', variantId='ink';
|
||||
const tailWatchClock=tailClock();
|
||||
const fields=[{layer:7,field:'compact',label:'短标题',page:'one',currentText:''}];
|
||||
const slots=[
|
||||
{id:'lamp-photo',fieldId:'lamp',label:'灯具全景',requirements:'灯具原片和室内实景',candidates:[]},
|
||||
@ -1010,7 +1285,7 @@ test('Pi chooses each image operation and keeps an unresolved paid request on it
|
||||
const nextNative={kind:'native',job:18,documentId:23,identity};
|
||||
host.canvasOperations.retain(originalNative);
|
||||
host.canvasOperations.retain(nextNative);
|
||||
let actions=await openProductionOperations(host);
|
||||
let actions=await openProductionOperations(host,{tailWatchClock});
|
||||
const plan=await actions.plan_production({});
|
||||
assert.equal(plan.pictures[0].requirements,undefined);
|
||||
assert.deepEqual(plan.template,{contentHash:'lamp-template'});
|
||||
@ -1096,8 +1371,9 @@ test('Pi chooses each image operation and keeps an unresolved paid request on it
|
||||
legacy.items['base-photo']={state:'unknown',pendingOperation:{run:'prior-run',documentId:23,
|
||||
operationId:'another-operation',intent:'generate_candidate',candidateId:null},candidateId:'unrelated-older-candidate'};
|
||||
ledger.repository.replaceLedger(legacy);
|
||||
await actions.close();
|
||||
reopened=true;
|
||||
actions=await openProductionOperations(host);
|
||||
actions=await openProductionOperations(host,{tailWatchClock});
|
||||
const [pendingLamp,idleSwitch,pendingBase]=await actions.reconcile_image_slots({slotIds:[]});
|
||||
assert.equal(idleSwitch.phase,'none');
|
||||
assert.equal(pendingLamp.phase,'unknown');
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user