diff --git a/apps/detail-agent-pi/src/production-operations.mjs b/apps/detail-agent-pi/src/production-operations.mjs index 7578297d..5c5584fd 100644 --- a/apps/detail-agent-pi/src/production-operations.mjs +++ b/apps/detail-agent-pi/src/production-operations.mjs @@ -96,6 +96,13 @@ export async function openProductionOperations(host) { return written; }; const save=(slot,fields)=>update(()=>{journal.items[slot.id]={...journal.items[slot.id],...fields};}); + const originalCandidate=item=>{ + if(item?.heldOriginalId)return item.heldOriginalId; + const operation=item?.pendingOperation; + if(operation&&Object.hasOwn(operation,'candidateId'))return operation.candidateId; + // Older records kept the candidate from an unknown result on the slot. + return item?.state==='unknown'&&(!operation||!item.reason)?item.candidateId:undefined; + }; const operationHost=()=>Object.assign(Object.create(host,{nativeUnresolved:{value:null,writable:true}}),{ nativeToolActive:false,nativeToolOwner:null,generatedCandidates:new Map(), }); @@ -140,7 +147,7 @@ export async function openProductionOperations(host) { const pendingKey=adopting?'pendingAdoption':'pendingOperation'; const original=prior?.[pendingKey]; if(original){ - const candidateId=original.candidateId??prior.candidateId; + const candidateId=adopting?original.candidateId:originalCandidate(prior); return {phase:'unknown',...original,candidateId,pendingOriginal:candidateId??original.operationId}; } if(!adopting&&(prior?.heldOriginalId||prior?.state==='unknown')){ @@ -150,7 +157,7 @@ export async function openProductionOperations(host) { const args={version:(await current()).version,intent,outputId,slotId:slot.id,productVariantId:variantId,...values}; let prepared; const archive=async operation=>{ - prepared={...operation,intent,...(adopting?{candidateId:values.candidateId}:null)}; + prepared={...operation,intent,candidateId:adopting?values.candidateId:null}; await save(slot,{[pendingKey]:prepared,...(!adopting?{state:'dispatching'}:null)}); }; try { @@ -163,8 +170,10 @@ export async function openProductionOperations(host) { }}); const state=operation.phase==='complete'?(intent==='generate_candidate'?'candidate':'applied'):operation.phase; if(state==='applied')filled.add(slot.id); - await save(slot,{state,candidateId:operation.candidateId??prior?.candidateId, - [pendingKey]:operation.phase==='unknown'||state==='applied'&&operation.persistence==='session'?prepared:null, + const pending=operation.phase==='unknown' + ? {...prepared,candidateId:operation.candidateId??prepared.candidateId} + : state==='applied'&&operation.persistence==='session'?prepared:null; + await save(slot,{state,candidateId:operation.candidateId??prior?.candidateId,[pendingKey]:pending, ...(intent==='generate_candidate'?{source:values.useProductReference?'product':'generate',prompt:values.instruction}:null)}); return {...operation,...(operation.phase==='unknown'?{pendingOriginal:operation.candidateId??operation.operationId}:null)}; }catch(error){ @@ -187,21 +196,22 @@ export async function openProductionOperations(host) { }; const reconcile=async(slot,signal,adopting=false)=>{ const item=journal.items[slot.id]; - const heldId=item?.heldOriginalId??(item?.state==='unknown'?item.candidateId:undefined); const pendingKey=adopting?'pendingAdoption':'pendingOperation'; const original=item?.[pendingKey]; + const archivedCandidate=adopting?undefined:originalCandidate(item); signal?.throwIfAborted(); - if(!adopting&&!original&&heldId){ - const receipt=await canvas.detailRecover(slot.id,{projectId:item.heldOriginalProjectId,candidateId:heldId}); - const phase=receipt?.id===heldId&&['complete','failed'].includes(receipt.status)?receipt.status:'unknown'; - if(phase!=='unknown')await save(slot,{state:phase==='complete'?'candidate':'failed',candidateId:heldId, - heldOriginalId:null,heldOriginalProjectId:null}); - return {slotId:slot.id,candidateId:heldId,phase}; + if(archivedCandidate){ + if(original&&original.candidateId!==archivedCandidate)await save(slot,{pendingOperation:{...original,candidateId:archivedCandidate}}); + const receipt=await canvas.detailRecover(slot.id,{projectId:item.heldOriginalProjectId,candidateId:archivedCandidate}); + const phase=receipt?.id===archivedCandidate&&['complete','failed'].includes(receipt.status)?receipt.status:'unknown'; + if(phase!=='unknown')await save(slot,{state:phase==='complete'?'candidate':'failed',candidateId:archivedCandidate, + pendingOperation:null,heldOriginalId:null,heldOriginalProjectId:null}); + return {slotId:slot.id,candidateId:archivedCandidate,phase,...(original?{operationId:original.operationId}:null)}; } 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}); - const candidateId=operation.candidateId??original.candidateId??item.candidateId; + const candidateId=operation.candidateId??original.candidateId; const receipt=!adoption&&candidateId&&operation.phase==='unknown' ? await canvas.detailRecover(slot.id,{candidateId}) : null; const phase=receipt?.id===candidateId&&['complete','failed'].includes(receipt.status)?receipt.status:operation.phase; @@ -367,9 +377,19 @@ export async function openProductionOperations(host) { return result; }, async reconcile_image_slots({slotIds},signal){ + const recover=async(slot,adopting=false)=>{ + try {return await reconcile(slot,signal,adopting);} + catch(error){ + signal?.throwIfAborted(); + const item=journal.items[slot.id]; + const original=item?.[adopting?'pendingAdoption':'pendingOperation']; + const candidateId=adopting?original?.candidateId:originalCandidate(item); + return {slotId:slot.id,operationId:original?.operationId,candidateId,phase:'unknown',reason:error.message}; + } + }; return Promise.all(selections(slotIds).flatMap(slot=>[ - reconcile(slot,signal), - ...(journal.items[slot.id]?.pendingAdoption?[reconcile(slot,signal,true)]:[]), + recover(slot), + ...(journal.items[slot.id]?.pendingAdoption?[recover(slot,true)]:[]), ])); }, async read_output_screen({page}){return imageResult(await canvas.detailRender({page}));}, diff --git a/apps/detail-agent-pi/test/production-operations.test.mjs b/apps/detail-agent-pi/test/production-operations.test.mjs index 85614e81..3899cc59 100644 --- a/apps/detail-agent-pi/test/production-operations.test.mjs +++ b/apps/detail-agent-pi/test/production-operations.test.mjs @@ -15,10 +15,11 @@ test('Pi chooses each image operation and keeps an unresolved paid request on it const slots=[ {id:'lamp-photo',fieldId:'lamp',label:'灯具全景',candidates:[]}, {id:'switch-photo',fieldId:'switch',label:'开关局部',candidates:[]}, + {id:'base-photo',fieldId:'base',label:'灯座局部',candidates:[]}, ]; const pixels={type:'image',data:'evidence',mimeType:'image/jpeg'}; - const submissions=[]; - let revision=3,modelCalls=0,lookups=0,recovered=false,reviewGate,waitingAt; + const submissions=[], lookups=[]; + let revision=3,modelCalls=0,recovered=false,reopened=false,reviewGate,waitingAt; const identity={scope:'scope',project:'project',documentId:23,accountId:'account',origin:'local'}; const canvas={ run:'native-run',documentId:23,identity, @@ -28,7 +29,7 @@ test('Pi chooses each image operation and keeps an unresolved paid request on it detailRender:async({page})=>({page,revision,images:[pixels]}), detailImages:async(_slot,candidateId)=>({candidateId,referenceCount:1,images:candidateId?[pixels,pixels]:[pixels]}), detailRecover:async(_slot,{candidateId})=>{ - lookups++; + lookups.push(candidateId); return {id:candidateId,status:recovered?'complete':'unknown'}; }, read:async()=>({conversationActive:true,revision,detailWriteWaiting:!!waitingAt}),delta:async()=>{}, @@ -44,13 +45,16 @@ test('Pi chooses each image operation and keeps an unresolved paid request on it }, workflowExecute:async input=>{ submissions.push(input); - return {phase:'submitted',operationId:input.operationId,candidateId:input.candidateId??'existing-candidate'}; + return {phase:'submitted',operationId:input.operationId}; }, workflowPoll:async operationId=>{ const input=submissions.find(row=>row.operationId===operationId); return {operationId,candidateId:input.candidateId??'existing-candidate',phase:input.intent==='generate_candidate'&&!input.useProductReference?'unknown':'complete'}; }, - workflowReconcile:async operation=>({...operation,phase:'unknown',candidateId:'existing-candidate'}), + workflowReconcile:async operation=>{ + if(reopened)throw Error('原操作不存在或不属于当前项目'); + return {...operation,phase:'unknown',candidateId:'existing-candidate'}; + }, }; const host={canvas,productionGoal:{outputId,variantId}, store:{dir,identity,get:async()=>null,appendEvent:async()=>{}}, @@ -68,7 +72,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.nativeUnresolved=originalNative; host.nativeUnresolved=nextNative; - const actions=await openProductionOperations(host); + let actions=await openProductionOperations(host); await actions.plan_production({}); assert.deepEqual(await actions.read_copy_fields({pageId:''}), await actions.read_copy_fields({})); assert.deepEqual(await actions.write_copy_fields({revision,items:[]}), {appliedLayers:[],revision}); @@ -98,8 +102,24 @@ test('Pi chooses each image operation and keeps an unresolved paid request on it assert.match(submissions[0].instruction,/场景桌面上的一盏灯$/u); assert.equal((await actions.generate_slot_image({slotId:'lamp',source:'generate',prompt:'更换灯罩角度'})).phase,'unknown'); assert.equal(submissions.length,1); - assert.equal((await actions.reconcile_image_slots({slotIds:['lamp']}))[0].phase,'unknown'); - assert.equal(lookups,1); + const resumeFile=path.join(dir,'production-detail-ink.json'); + const legacy=JSON.parse(await fs.readFile(resumeFile,'utf8')); + delete legacy.items['lamp-photo'].pendingOperation.candidateId; + legacy.items['base-photo']={state:'unknown',pendingOperation:{run:'prior-run',documentId:23, + operationId:'another-operation',intent:'generate_candidate',candidateId:null},candidateId:'unrelated-older-candidate'}; + await fs.writeFile(resumeFile,JSON.stringify(legacy)); + reopened=true; + host.store.get=async name=>JSON.parse(await fs.readFile(path.join(dir,name),'utf8')); + actions=await openProductionOperations(host); + const [pendingLamp,idleSwitch,pendingBase]=await actions.reconcile_image_slots({slotIds:[]}); + assert.equal(idleSwitch.phase,'none'); + assert.equal(pendingLamp.phase,'unknown'); + assert.equal(pendingLamp.operationId,first.operationId); + assert.equal(pendingLamp.candidateId,'existing-candidate'); + assert.equal(pendingBase.phase,'unknown'); + assert.equal(pendingBase.operationId,'another-operation'); + assert.match(pendingBase.reason,/原操作不存在/u); + assert.deepEqual(lookups,['existing-candidate']); assert.equal(submissions.length,1); assert.equal((await actions.adopt_production_image({slotId:'lamp',candidateId:'older-candidate'})).phase,'complete'); assert.equal((await actions.generate_slot_image({slotId:'lamp',source:'generate',prompt:'动作已调整'})).phase,'unknown'); @@ -118,6 +138,8 @@ test('Pi chooses each image operation and keeps an unresolved paid request on it assert.equal(submissions.length,2,'verifying must not adopt or generate'); assert.equal((await actions.adopt_production_image({slotId:'lamp',candidateId:'existing-candidate',fit:'contain'})).phase,'complete'); assert.deepEqual(submissions.map(row=>row.intent),['generate_candidate','adopt_candidate','adopt_candidate']); + const savedBeforeLocal=JSON.parse(await fs.readFile(resumeFile,'utf8')); + assert.equal(savedBeforeLocal.items['base-photo'].pendingOperation.operationId,'another-operation'); const local=await actions.generate_slot_image({slotId:'switch',source:'product',prompt:'把开关放进夜景'}); assert.equal(local.phase,'complete'); assert.equal(local.requestedSource,'product');