From 48599da15427f2eebc6b6fa43cc8be50a8b8c39f Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Sat, 5 Dec 2026 10:24:33 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=B0=8F=E5=A3=B9=E4=BA=A4?= =?UTF-8?q?=E4=BB=98=E5=90=8E=E7=94=BB=E5=B8=83=E7=BB=AD=E6=94=B9=E4=B8=8E?= =?UTF-8?q?=E5=8E=9F=E8=AF=B7=E6=B1=82=E6=A0=B8=E6=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/detail-agent-pi/src/agent.mjs | 20 ++--- .../detail-agent-pi/src/canvas-operations.mjs | 12 +++ apps/detail-agent-pi/src/image-reconciler.mjs | 82 +++++++++++------- apps/detail-agent-pi/src/native-tools.mjs | 48 +++++++++-- apps/detail-agent-pi/src/production-goal.mjs | 8 +- .../src/production-operations.mjs | 41 +++++---- apps/detail-agent-pi/src/production-tools.mjs | 9 +- .../src/stream-presentation.mjs | 13 ++- apps/detail-agent-pi/src/workflow-execute.mjs | 63 +++++++++----- .../test/liberate-agent-js.test.mjs | 14 ++-- .../detail-agent-pi/test/native-wire.test.mjs | 84 +++++++++++++++++++ apps/detail-agent-pi/test/pi.test.mjs | 4 +- .../test/production-operations.test.mjs | 84 ++++++++++++++++--- .../test/real-photo-reconcile.test.mjs | 29 +++++++ apps/detail-agent-pi/test/whitelabel.test.mjs | 8 +- .../test/workflow-execute.test.mjs | 2 +- .../test/workflow-not-dispatched.test.mjs | 22 +++++ 17 files changed, 427 insertions(+), 116 deletions(-) diff --git a/apps/detail-agent-pi/src/agent.mjs b/apps/detail-agent-pi/src/agent.mjs index e514119c..f724026c 100644 --- a/apps/detail-agent-pi/src/agent.mjs +++ b/apps/detail-agent-pi/src/agent.mjs @@ -2,7 +2,7 @@ import { canvasToolReceipts } from './stdio-canvas.mjs'; import { toolSchema, defineTool, normalizeToolArgs } from './tool-schema.mjs'; import { productRequestScope } from './production-recovery.mjs'; import { executeWorkflow } from './workflow-execute.mjs'; -import { PresentationBatch, StreamOutputMeter, StreamPresentation, presentText, presentProductReply, stripProductionToolText } from './stream-presentation.mjs'; +import { PresentationBatch, StreamOutputMeter, StreamPresentation, presentText, presentReply, stripProductionToolText } from './stream-presentation.mjs'; import path from 'node:path'; import { setTimeout as delay } from 'node:timers/promises'; import fs from 'node:fs/promises'; @@ -1130,13 +1130,13 @@ export class DetailPiAgent { }else if(this.canvasEndAttempted||this.canvasNotificationsDetached)return; if(['delta','reply','end'].includes(method)&&typeof args[0]==='string'){ if(this.productionContext) args[0]=stripProductionToolText(args[0],method==='delta'); - args[0]=presentProductReply(args[0],method==='delta'); + args[0]=presentReply(args[0],method==='delta'); } if(method==='activity'){ - args[0]=presentProductReply(args[0]); + args[0]=presentReply(args[0]); const event=args[1]; - if(event)args[1]={...event,summary:presentProductReply(event.summary), - ...(event.message?{message:presentProductReply(event.message)}:null)}; + if(event)args[1]={...event,summary:presentReply(event.summary), + ...(event.message?{message:presentReply(event.message)}:null)}; } try{return await this.canvas[method](...args);} catch(error){ @@ -1338,9 +1338,9 @@ export class DetailPiAgent { if (!production && outputId && variantId && (request?.productionTemplate || request?.canvasFirst || overview?.available && overview.canvasFirst)) { const choices=overview?.productEvidence?.brief?.outputVariantIds; - const requestedOutputs=request?.requestedOutputs ?? (choices - ? Object.entries(choices).flatMap(([outputId, variants]) => variants.map(variantId => ({outputId,variantId}))) - : [{outputId,variantId}]); + const requestedOutputs=request?.requestedOutputs?.length ? request.requestedOutputs + : [{outputId,variantId},...Object.entries(choices??{}).flatMap(([output,variants]) => + variants.filter(variant=>output!==outputId||variant!==variantId).map(variant=>({outputId:output,variantId:variant})))]; this.productionWorkspace={workspaceId:request?.workspaceId ?? overview?.workspaceId,outputId,variantId, requestedOutputs,template:request?.productionTemplate ?? overview?.template}; } @@ -1356,7 +1356,7 @@ export class DetailPiAgent { })), }); } - const goalOnlyTools=new Set(['open_production_output','finish_production','defer_production_output']); + const goalOnlyTools=new Set(['finish_production','defer_production_output']); const followUpProductionTools=productionTools.map(([name])=>name).filter(name=>!goalOnlyTools.has(name)); const active=this.productionWorkspace && !production ? [...this.conversationTools,...followUpProductionTools] : production ? this.activeProductionTools : this.conversationTools; @@ -1385,7 +1385,7 @@ export class DetailPiAgent { (this.previewCancelled&&!this.previewReceipt ? '已取消本次预览,没有应用这项修改。' : presentText(this.session.getLastAssistantText() || this.generatedCandidateReply() || '')); - const textResult=presentProductReply(this.productionContext?stripProductionToolText(resultText).trim(): + const textResult=presentReply(this.productionContext?stripProductionToolText(resultText).trim(): this.canvasNotificationsDetached&&last?.stopReason==='toolUse' ? resultText+'\n\n原项目已切换,后续画布操作已停止。' : resultText); if (!textResult.trim()) throw Error('模型没有返回正文,请更换模型后再试;本轮工具结果已保留'); diff --git a/apps/detail-agent-pi/src/canvas-operations.mjs b/apps/detail-agent-pi/src/canvas-operations.mjs index 9de59bdd..b570fa55 100644 --- a/apps/detail-agent-pi/src/canvas-operations.mjs +++ b/apps/detail-agent-pi/src/canvas-operations.mjs @@ -1,3 +1,15 @@ +export const missingOperationMessage='宿主已确认原操作不存在,锁定已解除,可以发起新操作'; + +export function missingCanvasOperation(receipt) { + return [receipt?.category,receipt?.code,receipt?.phase,receipt?.state,receipt?.status].includes('not_found') || + ['原操作不存在','原操作不存在或不属于当前项目','原操作不属于当前项目'].includes(receipt?.message) || + [receipt?.phase,receipt?.state,receipt?.status].includes('unknown') && receipt?.operationFound===false; +} + +export function missingImageCandidate(receipt,candidateId) { + return missingCanvasOperation(receipt) || receipt?.message===`候选 ${candidateId}(canvas-candidate.json):文件缺失`; +} + export class CanvasOperations { constructor(pending = [], identity) { this.pending = pending; diff --git a/apps/detail-agent-pi/src/image-reconciler.mjs b/apps/detail-agent-pi/src/image-reconciler.mjs index 771d0e7a..bd7f2613 100644 --- a/apps/detail-agent-pi/src/image-reconciler.mjs +++ b/apps/detail-agent-pi/src/image-reconciler.mjs @@ -1,5 +1,6 @@ import { reconcileWorkflowReceipt } from './workflow-execute.mjs'; import { productionLedger } from './production-repository.mjs'; +import { missingImageCandidate, missingOperationMessage } from './canvas-operations.mjs'; export const settledImagePhases=['complete','failed','retired','expired','candidate_limit_reached']; export const recoveryNotices={ @@ -55,6 +56,13 @@ export function imageOriginals({items}) { }); } +export async function pendingImageOperation(canvas,{operationId,candidateId,slotId,outputId,variantId}) { + const pending=await canvas.imageRequest('pending',{}); + return pending.find(row=>row.operationId===operationId||row.candidateId===operationId|| + candidateId&&row.candidateId===candidateId|| + row.slotId===slotId&&row.variantId===variantId&&(!outputId||row.outputId===outputId)); +} + export async function readNativeOriginal(canvas,original,scope) { const {slotId,candidateId,operationId}=original; const receipt=await canvas.detailRecover(slotId,{candidateId},scope); @@ -74,30 +82,32 @@ export function createImageReconciler(canvas,{outputId,variantId},readJournal,up const archivedCandidate=adopting||local?undefined:originalCandidate(item); signal?.throwIfAborted(); if(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,{ - state:phase==='complete'?'candidate':phase,candidateId:archivedCandidate, - pendingOperation:null,heldGeneration:false,heldOriginalId:null,heldOriginalProjectId:null, - }); - },{ - evidence:[slot.id,archivedCandidate,'candidate',{...receipt,sourceProjectId:item.heldOriginalProjectId}], + const receipt=await detailRecover(slot.id,{projectId:item.heldOriginalProjectId,candidateId:archivedCandidate}).catch(error=>{ + if(!original||item.heldOriginalId||!missingImageCandidate(error,archivedCandidate))throw error; + return null; }); - const reason=receipt?.id===archivedCandidate?receipt.message:undefined; - return {slotId:slot.id,candidateId:archivedCandidate,phase,reason, - ...(receipt?.id===archivedCandidate?expiryFields(receipt):null),...(original?{operationId:original.operationId}:null)}; + signal?.throwIfAborted(); + if((receipt&&!missingImageCandidate(receipt,archivedCandidate))||!original||item.heldOriginalId){ + 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,{ + state:phase==='complete'?'candidate':phase,candidateId:archivedCandidate, + pendingOperation:null,heldGeneration:false,heldOriginalId:null,heldOriginalProjectId:null, + }); + },{ + evidence:[slot.id,archivedCandidate,'candidate',{...receipt,sourceProjectId:item.heldOriginalProjectId}], + }); + const reason=receipt?.id===archivedCandidate?receipt.message:undefined; + return {slotId:slot.id,candidateId:archivedCandidate,phase,reason, + ...(receipt?.id===archivedCandidate?expiryFields(receipt):null),...(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}).catch(error=>{ - if(!local||error.message!=='原操作不存在或不属于当前项目')throw error; - return {phase:'unknown'}; - }); + const operation=await reconcileWorkflowReceipt(canvas,{...original,adoption}); signal?.throwIfAborted(); const candidateId=operation.candidateId??original.candidateId; const receipt=!adoption&&candidateId&&operation.phase==='unknown' @@ -107,12 +117,19 @@ export function createImageReconciler(canvas,{outputId,variantId},readJournal,up }) : null; signal?.throwIfAborted(); const matchingReceipt=receipt?.id===candidateId?receipt:null; - const localMissing=local&&operation.phase==='unknown'&&(!candidateId|| + const absent=operation.phase==='not_found'; + if(absent&&!adopting&&!local){ + const pending=await pendingImageOperation(canvas,{...original,slotId:slot.id,outputId,variantId}); + if(pending||!archivedCandidate)return {slotId:slot.id,operationId:original.operationId, + candidateId:pending?.candidateId??candidateId,phase:'unknown',reason:pending?.message??operation.message}; + } + const localMissing=local&&(absent||operation.phase==='unknown'&&(!candidateId|| matchingReceipt&&(matchingReceipt.status==='not_executed'|| - matchingReceipt.message===`候选 ${candidateId} 缺少 task.json,原结果仍待核查`)); - const phase=localMissing?'not_executed' + matchingReceipt.message===`候选 ${candidateId} 缺少 task.json,原结果仍待核查`))); + const phase=absent||localMissing?'not_executed' :matchingReceipt&&settledImagePhases.includes(matchingReceipt.status)?matchingReceipt.status:operation.phase; const reason=localMissing?'本地实拍操作没有在途任务或可取回的候选,可以重试' + :absent?missingOperationMessage :matchingReceipt?.message??operation.message; const expiry=expiryFields(matchingReceipt??operation); if(settledImagePhases.includes(phase)||phase==='not_executed'){ @@ -122,22 +139,22 @@ export function createImageReconciler(canvas,{outputId,variantId},readJournal,up if(!sessionPlacement||item.state!=='applied'||item.candidateId!==candidateId)await update(journal=>{ signal?.throwIfAborted(); const record=journal.items[slot.id]; - if(local&&record?.pendingOperation?.operationId!==original.operationId)return; + if(record?.[pendingKey]?.operationId!==original.operationId)return; rememberImageExpiry(record,candidateId,expiry); Object.assign(record,{state:applied?'applied':phase==='complete'?'candidate':phase, - ...(!localMissing?{candidateId}:null), + ...(!localMissing&&!absent?{candidateId}:null), ...(applied&&operation.persistence==='session'?null:{[pendingKey]:null}), - ...(local?{reason:reason??null,...(phase==='complete'?{source:'product'}:null)}:null), + ...(local||absent?{reason:reason??null,...(local&&phase==='complete'?{source:'product'}:null)}:null), ...(applied&&!decision?{autoCandidateSetId:null}:null), ...(!adopting?{heldGeneration:false,heldOriginalId:null,heldOriginalProjectId:null}:null)}); if(decision&&applied)(record.autoAdoptions??={})[decision.candidateSetId]={...decision, state:operation.persistence==='session'?'placed':'adopted',receipt:operation}; if(decision&&phase==='not_executed')(record.autoAdoptions??={})[decision.candidateSetId]={...decision,state:'selected'}; - },candidateId?{evidence:[slot.id,candidateId,adopting?'adoption':'candidate',{...operation,phase,...expiry,...decision, + },candidateId&&!absent?{evidence:[slot.id,candidateId,adopting?'adoption':'candidate',{...operation,phase,...expiry,...decision, ...(local?{message:reason}:null)}]}:undefined); if(applied&&!signal?.aborted)onAdopted?.(slot.id,candidateId); } - return {slotId:slot.id,phase,candidateId,operationId:original.operationId,reason,...expiry}; + return {slotId:slot.id,phase,...(absent&&!adopting?{}:{candidateId}),operationId:original.operationId,reason,...expiry}; }; return async (slot,adopting,signal)=>{ try { @@ -153,10 +170,11 @@ export function createImageReconciler(canvas,{outputId,variantId},readJournal,up }; } -export async function reconcileProjectImageSlots(host,{slotIds},signal) { - const {canvas,store,productionGoal:goal}=host; - const requested=new Set(slotIds); - const outputs=goal.pendingOutputs??goal.requestedOutputs; +export async function reconcileProjectImageSlots(host,{slotIds,slotId,fieldId},signal) { + const {canvas,store}=host; + const goal=host.productionContext??host.productionGoal; + const requested=new Set(slotIds??(slotId||fieldId?[slotId??fieldId]:[])); + const outputs=(host.productionGoal?goal.pendingOutputs??goal.requestedOutputs: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))); diff --git a/apps/detail-agent-pi/src/native-tools.mjs b/apps/detail-agent-pi/src/native-tools.mjs index 374f527a..3f85e579 100644 --- a/apps/detail-agent-pi/src/native-tools.mjs +++ b/apps/detail-agent-pi/src/native-tools.mjs @@ -9,9 +9,10 @@ import path from 'node:path'; import { atomic } from './store.mjs'; import { nativeToolMetadata } from './photocraft-extension.mjs'; -import { canvasOperations, restoreNativeOperation } from './canvas-operations.mjs'; +import { canvasOperations, missingCanvasOperation, missingImageCandidate, missingOperationMessage, restoreNativeOperation } from './canvas-operations.mjs'; import { BridgeError } from './bridge-error.mjs'; -import { LOCAL_OPERATION_WAIT_MS } from './workflow-execute.mjs'; +import { LOCAL_OPERATION_WAIT_MS, reconcileWorkflowReceipt } from './workflow-execute.mjs'; +import { pendingImageOperation } from './image-reconciler.mjs'; export async function requestCanvasWrite(host, revision, signal, checkTurn, nativeWrite, available) { const deadline = Date.now() + LOCAL_OPERATION_WAIT_MS; @@ -126,10 +127,26 @@ export function nativeTools(host, make) { return {kind:original.kind,status:applied ? 'applied' : 'unknown',receipt}; } if (original.kind === 'workflow') { - const receipt = await host.canvas.workflowReconcile({run:original.run,documentId:original.documentId,operationId:original.operationId}); - if (receipt?.run !== original.run || receipt?.documentId !== original.documentId || receipt?.operationId !== original.operationId) throw Error('核查回执身份不一致,原操作仍待核查'); + let receipt=await reconcileWorkflowReceipt(host.canvas,original); + if(receipt.phase==='not_found'&&original.intent!=='adopt_candidate'){ + // A workflow receipt can be gone while the image request is still on disk. + const {slotId,candidateId,outputId,productVariantId}=original; + const pending=await pendingImageOperation(host.canvas,{...original,variantId:productVariantId}); + if(pending)receipt={...receipt,phase:'unknown',message:pending.message,candidateId:pending.candidateId}; + else if(candidateId){ + const image=await host.canvas.detailRecover(slotId,{candidateId},{outputId,variantId:productVariantId}).catch(error=>{ + if(!missingImageCandidate(error,candidateId))throw error; + return null; + }); + if(image&&!missingImageCandidate(image,candidateId)){ + if(image.id!==candidateId)throw Error('原生回执与请求号不一致'); + receipt={...receipt,phase:image.status,message:image.message,candidateId}; + } + } + } + if(receipt.phase==='not_found')receipt.message=missingOperationMessage; const complete = receipt.phase === 'complete'; - const terminal = ['complete','failed','expired','candidate_limit_reached'].includes(receipt.phase); + const terminal = ['complete','failed','expired','candidate_limit_reached','not_found'].includes(receipt.phase); if (terminal) scope.settle(original); return {kind:original.kind,slotId:original.slotId,status:complete ? 'completed' : terminal ? receipt.phase : 'unknown',receipt}; } @@ -137,10 +154,21 @@ export function nativeTools(host, make) { return {kind:original.kind,status:'unknown',message:'原操作缺少可核查的原生任务编号;保留阻断,请在原项目人工核查'}; } const {run,documentId,job,clientOperationId}=original; - const receipt = await host.canvas.nativeReconcile({run,documentId,job,clientOperationId}); + const missing={kind:original.kind,status:'not_found',message:missingOperationMessage}; + let receipt; + try { receipt=await host.canvas.nativeReconcile({run,documentId,job,clientOperationId}); } + catch(error) { + if(!missingCanvasOperation(error))throw error; + await releaseOriginal(scope,original); + return missing; + } if (receipt?.run !== run || receipt?.documentId !== documentId || (receipt?.clientOperationId !== undefined ? receipt.clientOperationId !== clientOperationId : !Number.isSafeInteger(job) || receipt?.job !== job)) throw Error('核查回执身份不一致,原任务仍待核查'); + if(missingCanvasOperation(receipt)){ + await releaseOriginal(scope,original); + return {...missing,receipt}; + } const authoritative = ['engine-job-receipt','retained-native-receipt'].includes(receipt.source); const applied = authoritative && receipt.state === 'done' && receipt.completed === true && receipt.executed === true && receipt.applied === true && receipt.applicationVerified === true; @@ -189,6 +217,12 @@ export function nativeTools(host, make) { dispatched = true; const result = await host.canvas.nativeCall({...args,clientOperationId:original.clientOperationId}); if (result?.pending === true && Number.isSafeInteger(result.job) && result.job > 0) pendingJob = result.job; + if(result?.dispatched===false&&result.executed!==true){ + dispatched=false; + checkTurn(); + throw BridgeError.from(result.failure??{message:result.error??'宿主确认本次未执行', + category:result.writeBlockReason??result.phase,retryable:result.retryable}); + } checkTurn(); let settled = result; if (result?.pending === true) { @@ -247,7 +281,7 @@ export function nativeTools(host, make) { } finally { if (scope.active === owner) scope.active=null; } } }), ...nativeToolMetadata('native_call')}, - {...make('native_reconcile', '只读核查本会话保留的全部原生或工作流未知任务。使用原始run、文档及job或operationId,不重发也不申请写入许可;仅权威终态才解除该任务的阻断。缺少任务身份时必须人工核查。', Type.Object({}), async () => { + {...make('native_reconcile', '只读核查本会话保留的全部原生或工作流未知任务。使用原始run、文档及job或operationId,不重发也不申请写入许可;确认终态或原操作不存在时解除阻断。缺少任务身份时必须人工核查。', Type.Object({}), async () => { if (host.canvasNotificationsDetached) throw Error('当前项目已切换,不能核查其他项目任务'); const scope=await restoreNativeOperation(host); if (!scope.pending.length) return {status:'none',message:'没有待核查的原生任务'}; diff --git a/apps/detail-agent-pi/src/production-goal.mjs b/apps/detail-agent-pi/src/production-goal.mjs index 0b17fd14..8236c3e2 100644 --- a/apps/detail-agent-pi/src/production-goal.mjs +++ b/apps/detail-agent-pi/src/production-goal.mjs @@ -218,6 +218,7 @@ export async function callProductionTool(host, name, args, signal) { const target={outputId,variantId}; const documentKey=name==='read_output_screen'?host.canvas.canvasBinding?.documentKey:undefined; const working=outputId===active.outputId&&variantId===active.variantId; + if (!outputId && name==='reconcile_image_slots')return reconcileProjectImageSlots(host,input,signal); if (!working && !goal.requestedOutputs?.some(row=>row.outputId===outputId&&row.variantId===variantId)) throw Error('所选成品和花色不属于本轮制作'); if(!working&&name==='read_slot_images'){ @@ -228,9 +229,9 @@ export async function callProductionTool(host, name, args, signal) { ...(input.candidateId&&!input.includeReferences?{includeProductReferences:false}:null)}; return imageResult({...target,...await host.canvas.detailImages(input.slotId,input.candidateId,options)}); } - if(!working&&['read_output_screen','check_output_screens'].includes(name)) - return {...target,accepted:false,reason:'canvas_inactive',message:`请打开${productionOutputLabel(outputId)}画布后再复核。`, - ...(host.productionGoal?{nextAction:{tool:'open_production_output',args:target}}:null)}; + if(!working&&['read_output_screen','check_output_screens','adopt_production_image'].includes(name)) + return {...target,accepted:false,reason:'canvas_inactive',workingOutput:active.outputId?active:null, + message:`请打开${productionOutputLabel(outputId)}画布后继续。`,nextAction:{tool:'open_production_output',args:target}}; if(!working&&!['plan_production','review_image_slots','await_image_slots','read_screen_review','reconcile_image_slots','check_image_slots','use_product_image','transform_slot_image','prepare_image_request','dispatch_image_request','read_copy_fields','read_archived_images','retire_production_image','stage_archived_image','defer_production_output'].includes(name)) return {...target,accepted:false,reason:'canvas_inactive',workingOutput:active.outputId?active:null}; if (name==='finish_production' && args.scope==='all' && args.revision===undefined) { @@ -239,7 +240,6 @@ export async function callProductionTool(host, name, args, signal) { ...(args.deliveryReason?.trim()?{deliveryReason:args.deliveryReason.trim()}:null),...evidence},signal); } if (!outputId) { - if (name==='reconcile_image_slots')return reconcileProjectImageSlots(host,args,signal); if (name==='plan_production') { const {id,name,version,productionRoute}=goal.template??{}; const {product,dimensions,note,barcodeEntries,images,intake,barcodeBindings,detailBarcode}=host.productEvidence??{}; diff --git a/apps/detail-agent-pi/src/production-operations.mjs b/apps/detail-agent-pi/src/production-operations.mjs index 6d76ecbd..89842da1 100644 --- a/apps/detail-agent-pi/src/production-operations.mjs +++ b/apps/detail-agent-pi/src/production-operations.mjs @@ -81,7 +81,8 @@ export async function openProductionOperations(host,{target=host.productionConte const {slots,...plan}=await scopedPlan(); return {plan,slots}; }; - const {plan:initialPlan,slots}=await readSlots(); + const {plan:initialPlan,slots:initialSlots}=await readSlots(); + let slots=initialSlots; let plan=initialPlan; const planRevisionKey=value=>{ if(!value)return undefined; @@ -98,8 +99,8 @@ export async function openProductionOperations(host,{target=host.productionConte const invalidateSlots=()=>{slotsCache=null;}; const invalidatePlan=()=>{planCache=null;}; if(plan.productVariantId!==variantId)throw Error('当前图位不属于本轮制作花色'); - const byId=new Map(slots.map(slot=>[slot.id,slot])); - const byField=Map.groupBy(slots,slot=>slot.fieldId); + let byId=new Map(slots.map(slot=>[slot.id,slot])); + let byField=Map.groupBy(slots,slot=>slot.fieldId); const binding=JSON.stringify([plan.template.contentHash,variantId]); const imageScope={...output,templateHash:plan.template.contentHash}; const {candidatesPerSlot:configuredBatch,maxCandidatesPerSlot:configuredCandidates,maxGenerationAttempts:legacyLimit}=plan.template.production??{}; @@ -143,6 +144,11 @@ export async function openProductionOperations(host,{target=host.productionConte const fields=live.filter(slot=>slot.fieldId===id); if(fields.length===1)return fields[0]; }; + const requireLiveSlot=(live,reference)=>{ + const slot=reference&&findLiveSlot(live,reference); + if(!slot)throw Error(slotNotFound); + return slot; + }; const selections=slotIds=>slotIds?.length?[...new Set(slotIds.map(matches))]:slots; const readSelection=slotIds=>{ const requested=new Set(slotIds?.map(id=>id.trim()).filter(Boolean)); @@ -258,8 +264,11 @@ export async function openProductionOperations(host,{target=host.productionConte const cached=slotsCache; queueMicrotask(()=>{if(slotsCache===cached)slotsCache=null;}); } - refreshFilled(live.slots); - return live.slots; + slots=live.slots; + byId=new Map(slots.map(slot=>[slot.id,slot])); + byField=Map.groupBy(slots,slot=>slot.fieldId); + refreshFilled(slots); + return slots; }; const liveSlot=async slot=>(await liveSlots()).find(row=>row.id===slot.id)??slot; const nativeGenerations=slot=>[ @@ -551,8 +560,8 @@ export async function openProductionOperations(host,{target=host.productionConte },{evidence:[slot.id,receipt.id,'candidate',receipt]}); candidates.set(receipt.id,{slotId:slot.id,status:'complete'}); invalidateSlots(); - markProgressDirty(); if(action==='transform')notice('画布调整已有候选'); + else markProgressDirty(); return result; }; const transformImage=(slot,{sourceSlotId,sourceCandidateId,referenceIndex,reference,...transform},signal)=>{ @@ -888,7 +897,7 @@ export async function openProductionOperations(host,{target=host.productionConte }, workStatus(originals){ return {...output,slots:[...new Set(running().map(job=>job.row.slotId))], - waitingCanvas:[...waitingCanvas].map(([id,{label}])=>({fieldId:byId.get(id).fieldId,label})), + waitingCanvas:[...waitingCanvas].map(([id,{label}])=>({fieldId:byId.get(id)?.fieldId,label})), inFlightImages:originals.filter(row=>row.outputId===outputId&&row.variantId===variantId) .map(row=>row.candidateId), screens:runningScreens().map(job=>job.receipt.page)}; @@ -1037,18 +1046,16 @@ export async function openProductionOperations(host,{target=host.productionConte ...(seenLayouts.has(slot.id)&&!layout.length?{layoutReferenceEarlier:true}:null), images:[...product,...layout,...images.slice(referenceCount+layoutCount)]}); }, - use_product_image({slotId,...options},signal){ + async use_product_image({slotId,fieldId,...options},signal){ signal?.throwIfAborted(); - const slot=matches(slotId); + const slot=requireLiveSlot(await liveSlots(),slotId??fieldId); return launchProductImage(slot,options,signal?AbortSignal.any([signal,stageSignal]):stageSignal); }, transform_slot_image({slotId,...options},signal){ return transformImage(matches(slotId),options,signal); }, async prepare_image_request({slotId,fieldId,...args},signal){ - const reference=slotId??fieldId; - const slot=reference&&findLiveSlot(await liveSlots(),reference); - if(!slot)throw Error(slotNotFound); + const slot=requireLiveSlot(await liveSlots(),slotId??fieldId); return prepareImageRequest(slot,args,signal); }, async dispatch_image_request(approval,signal){ @@ -1317,8 +1324,8 @@ export async function openProductionOperations(host,{target=host.productionConte }); return wait?Promise.all(batch.map(job=>job.run??job.receipt)):batch.map(job=>job.receipt); }, - async adopt_production_image({slotId,candidateId,fit,reason},signal){ - const slot=matches(slotId); + async adopt_production_image({slotId,fieldId,candidateId,fit,reason},signal){ + const slot=requireLiveSlot(await liveSlots(),slotId??fieldId); const result=await onCanvas(signal,()=>serialize(async()=>{ const adopted=await operate(slot,'adopt_candidate',{candidateId,fit},signal); if(adopted.phase!=='complete')return adopted; @@ -1366,9 +1373,11 @@ export async function openProductionOperations(host,{target=host.productionConte } return result; }, - async reconcile_image_slots({slotIds},signal){ + async reconcile_image_slots({slotIds,slotId,fieldId},signal){ signal?.throwIfAborted(); - const selected=selections(slotIds); + const references=slotIds??(slotId||fieldId?[slotId??fieldId]:[]); + if(!references.every(findSlot))await liveSlots(); + const selected=selections(references); const results=await Promise.all(selected.flatMap(slot=>{ const tails=tailsFor(slot); const receipts=tails.map(tail=>tailWatcher.reconcile(tail)); diff --git a/apps/detail-agent-pi/src/production-tools.mjs b/apps/detail-agent-pi/src/production-tools.mjs index 7ec57ddd..d024edab 100644 --- a/apps/detail-agent-pi/src/production-tools.mjs +++ b/apps/detail-agent-pi/src/production-tools.mjs @@ -7,6 +7,7 @@ import { const layer=Type.Integer({minimum:1}); const outputScope={outputId:optional(text),variantId:optional(text)}; +const slotAddress={slotId:optional(slotRef),fieldId:optional(slotRef)}; export const productionOperationTools = [ ['open_production_output','打开指定输出和花色。切换前保存原工程,返回保存结果、新画布绑定和各成品在途工作。waitingCanvas 为等待切回的图位。',obj({outputId:text,variantId:text})], @@ -27,10 +28,10 @@ export const productionOperationTools = [ ['read_slot_images','查看指定成品图位的实拍、模板参考和候选。adopted=true 读取当前可写画布的回填,includeReferences=true 附实拍。模板底图候选会附固定图位原图。',obj({ ...outputScope,slotId:slotRef,candidateId:optional(Type.String()),adopted:optional(Type.Boolean()),includeReferences:optional(Type.Boolean()), })], - ['use_product_image','用本款原片或裁切区域创建候选。通过 adopt_production_image 回填时,放置回执会列出覆盖图位的模板叠层。',obj({...outputScope,slotId:slotRef,...productImageArgs})], + ['use_product_image','用本款原片或裁切区域创建候选。通过 adopt_production_image 回填时,放置回执会列出覆盖图位的模板叠层。',obj({...outputScope,...slotAddress,...productImageArgs})], ['transform_slot_image',transformDescription,obj({...outputScope,slotId:slotRef,...transformImageArgs})], ['prepare_image_request',imageRequestDescription+' 图位可用 slotId 或 fieldId。指定成品和花色时按该成品的图位准备。',obj({ - ...outputScope,slotId:optional(slotRef),fieldId:optional(slotRef),...preparationArgs, + ...outputScope,...slotAddress,...preparationArgs, })], ['dispatch_image_request','确认准备回执后,传首个 requestId 派发同批请求。宿主读取该编号绑定的版本及哈希。用 await_image_slots 或 review_image_slots 查看结果。',obj({...outputScope,...dispatchArgs})], ['delegate_image_slots','异步分派主图位 slotId,reuseTargets 可附同花色的额外图位及 outputId。委托可查候选并裁切至组内图位,在可写画布显式采用。返回分派状态和待写字段。',obj({ @@ -48,9 +49,9 @@ export const productionOperationTools = [ ['check_image_slots','请验图代理按企业 Skill 比较候选原图和放入后的整屏。复核输入包含当前图位关联文案。模板底图候选附固定图位原图,fit 可指定预览放置方式。默认先受理,用 review_image_slots 查看结论。',obj({ ...outputScope,wait:optional(Type.Boolean()),candidates:Type.Array(obj({slotId:slotRef,candidateId:text,adopted:optional(Type.Boolean()),fit:optional(fit)})), })], - ['adopt_production_image','采用选定候选,返回画布修订、模板叠层。单图位屏与已有验图画面一致时附复核结论。可用 reason 记录采用理由。screensReadyForReview 列出待验多图位屏,可用 read_output_screen 查看整屏合成画面。',obj({...outputScope,slotId:slotRef,candidateId:text,fit:optional(fit),reason:optional(text)})], + ['adopt_production_image','采用选定候选,返回画布修订、模板叠层。单图位屏与已有验图画面一致时附复核结论。可用 reason 记录采用理由。screensReadyForReview 列出待验多图位屏,可用 read_output_screen 查看整屏合成画面。',obj({...outputScope,...slotAddress,candidateId:text,fit:optional(fit),reason:optional(text)})], ['retire_production_image','清理已判失败的图位候选,保留原因、提示词及原请求记录。若已上画布,返回应替换的图层。',obj({...outputScope,slotId:slotRef,candidateId:text,reason:text})], - ['reconcile_image_slots','按保存的原操作或候选号核查。未绑定画布时查询本轮项目输出,可用完整图位 id 限定。unknown 按原号继续核查、取回留存结果,避免重复付费。expired 表示原请求收口,可另备新请求。原因包括网关 HTTP 410、下载 404/410,或 180 秒恢复预算用完仍 unresolved 或 404 request_not_found。404 request_not_found 收口按未发起处理,其余已派发请求仍计入次数。',obj({...outputScope,slotIds:optional(ids)})], + ['reconcile_image_slots','按保存的原操作或候选号核查。可按 slotIds、slotId 或 fieldId 定位。宿主确认原操作不存在时解除阻断。unknown 按原号继续核查、取回留存结果,避免重复付费。expired 表示原请求收口,可另备新请求。原因包括网关 HTTP 410、下载 404/410,或 180 秒恢复预算用完仍 unresolved 或 404 request_not_found。404 request_not_found 收口按未发起处理,其余已派发请求仍计入次数。',obj({...outputScope,...slotAddress,slotIds:optional(ids)})], ['read_output_screen','读取整屏合成画面、模板差异、图位与标注布局。page 或 pages 从 0 开始(第 1 屏传 0;区别于 check_output_screens 和 read_screen_review 的从 1 开始),可查看 2–4 屏;局部用单屏、region(画布 [x,y,w,h])和 1–4 倍 zoom。includeTemplateImage 附原屏,templateLayerId 查完整原值和现值,templateChangeOffset 翻模板差异。只保留最新一次查看图片。详细像素、文字与布局核查字段见随包 Skill。',obj({ ...outputScope, page:optional(page),pages:optional(Type.Array(page)), diff --git a/apps/detail-agent-pi/src/stream-presentation.mjs b/apps/detail-agent-pi/src/stream-presentation.mjs index 872d14ed..2e7d9709 100644 --- a/apps/detail-agent-pi/src/stream-presentation.mjs +++ b/apps/detail-agent-pi/src/stream-presentation.mjs @@ -53,7 +53,7 @@ const receiptLabels = new Map(Object.entries({ })); /** Convert chat-only formatting and known receipt fragments at the presentation boundary. */ -export function presentProductReply(text, streaming = false) { +export function presentReply(text, streaming = false) { const lines=text.split(/\r?\n/u); const tableRule=/^\s*\|?(?:\s*:?-{2,}:?\s*\|)+\s*:?-{2,}:?\s*\|?\s*$/u; let table=false; @@ -63,8 +63,11 @@ export function presentProductReply(text, streaming = false) { table=true; return ''; } - if(!line.includes('|'))table=false; - const row=startsWithPipe||table||line.includes(' |')||tableRule.test(lines[index+1]??''); + const proseBlock=/^\s*(?:[-+*>]|\d+[.)])\s/u.test(line); + if(!line.includes('|')||proseBlock)table=false; + const explicitTable=table||tableRule.test(lines[index+1]??''); + const partialHeader=streaming&&line.includes(' | ')&&!proseBlock&&!/[。!?“”’「」『』"']/u.test(line); + const row=startsWithPipe||explicitTable||partialHeader; if(!row)return line; if(streaming&&startsWithPipe&&index===lines.length-1&&!/\|\s*$/u.test(line.trim().slice(1)))return ''; const columns=line.trim().replace(/^\||\|$/gu,'').split('|').map(cell=>cell.trim()).filter(Boolean); @@ -79,11 +82,13 @@ export function presentProductReply(text, streaming = false) { .replace(/\b(?:Pi(?: Agent)?|PhotoCraft)\b/gu,'小壹') .replace(/\x60?\b(?:candidateId|generationId|operationId|requestId)\s*[:=]?\s*[\x60'"]?[a-f0-9-]{6,}\b[\x60'"]?/giu,'制作记录') .replace(/(?:候选(?:图)?(?:编号|号|哈希)?|哈希)\s*[::]?\s*\x60?\b(?=[a-f0-9]*[a-f])[a-f0-9]{7,}(?:[.…]+[a-f0-9]+)?\b\x60?/giu,'候选图') - .replace(/\x60?\b(?:[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}|(?=[a-f0-9]*[a-f])[a-f0-9]{32,}|[a-f0-9]{8,}[.…]+[a-f0-9]{4,})\b\x60?/giu,'制作记录') + .replace(/\x60?\b(?:[a-f0-9]{64}|[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}|(?=[a-f0-9]*[a-f])[a-f0-9]{32,}|[a-f0-9]{8,}[.…]+[a-f0-9]{4,})\b\x60?/giu,'制作记录') .replace(/\x60?\b(?:allOutputsCompleted|writeBlocked|deliveryStatus|pendingOutputs|main_images|sku_images|detail|partial_delivered|completed|exported|true|false)\b\x60?/gu, match=>receiptLabels.get(match.replaceAll('\x60',''))); } +export { presentReply as presentProductReply }; + const productionToolText = /[\s\S]*?(?:<\/tool_calls?\s*>|$)/giu; export function stripProductionToolText(text, streaming = false) { let visible = text.replace(productionToolText, ''); diff --git a/apps/detail-agent-pi/src/workflow-execute.mjs b/apps/detail-agent-pi/src/workflow-execute.mjs index b0426ecd..dba29e6b 100644 --- a/apps/detail-agent-pi/src/workflow-execute.mjs +++ b/apps/detail-agent-pi/src/workflow-execute.mjs @@ -1,7 +1,7 @@ import { randomUUID } from 'node:crypto'; import { setTimeout as delay } from 'node:timers/promises'; import { workflowResult } from './workflow-context.mjs'; -import { canvasOperations } from './canvas-operations.mjs'; +import { canvasOperations, missingCanvasOperation } from './canvas-operations.mjs'; import { BridgeError } from './bridge-error.mjs'; import { canvasReplyTimedOut } from './stdio-canvas.mjs'; @@ -40,11 +40,21 @@ async function acquireWrite(host, scope, signal, checkTurn, onWait) { } export async function reconcileWorkflowReceipt(canvas, {run, documentId, operationId, adoption}) { - const receipt=await canvas.workflowReconcile({run, documentId, operationId, ...(adoption?{adoption}:null)}); - if(!receipt||receipt.run!==run||receipt.documentId!==documentId||receipt.operationId!==operationId|| - !(receiptPhases.includes(receipt.phase)||adoption&&receipt.phase==='not_executed')){ + const identity={run,documentId,operationId}; + const missing={...identity,phase:'not_found',message:'宿主确认原操作不存在'}; + let receipt; + try { receipt=await canvas.workflowReconcile({...identity,...(adoption?{adoption}:null)}); } + catch(error) { + if(missingCanvasOperation(error))return missing; + throw error; + } + if(!receipt||Object.entries(identity).some(([key,value])=>receipt[key]!==value)){ throw Error('原画布操作的核查回执与提交身份不一致'); } + if(missingCanvasOperation(receipt))return missing; + if(!(receiptPhases.includes(receipt.phase)||adoption&&receipt.phase==='not_executed')){ + throw Error('原画布操作的核查状态无效'); + } return receipt; } @@ -52,7 +62,8 @@ export async function reconcileWorkflowReceipt(canvas, {run, documentId, operati export async function executeWorkflow(host, args, signal, { timeoutMs, pause = delay, keepFailedCandidate = false, detailBatch = false, onWriteWaiting, onAdoptionPrepared, onPrepared, onSubmitted, scope=canvasOperations(host), generatedCandidates=host.generatedCandidates, readWorkflow=args=>host.readWorkflow(args) } = {}) { if (host.canvasNotificationsDetached) throw Error('原项目已切换,本轮不再派发'); - const held = scope.pending.find(op => op.kind === 'workflow' && op.slotId === args.slotId && op.productVariantId === args.productVariantId); + const held = scope.pending.find(op => op.kind === 'workflow' && op.slotId === args.slotId && op.productVariantId === args.productVariantId && + (op.outputId===undefined||op.outputId===args.outputId)); if (held) throw Error(`图位 ${args.slotId} 的原请求 ${held.operationId} 结果未知,先用 native_reconcile 按原号核查;核查到完成、失败或过期后,才能为这个图位另发新请求。其他图位不受影响`); if (scope.active) throw Error('已有原生操作正在执行,请依次等待'); const epoch = host.turnEpoch, run = host.canvas.run, documentId = host.canvas.documentId, owner = Symbol('workflow operation'); @@ -61,6 +72,22 @@ export async function executeWorkflow(host, args, signal, { timeoutMs, pause = d let dispatched = false, terminal = false; const checkTurn = () => { if (host.turnEpoch !== epoch) throw Error('原回合已结束,旧工作流操作不会继续或重发'); }; const operationId = randomUUID(); + const {slotId,productVariantId,outputId,intent}=args; + const original={kind:'workflow',operationId,run,documentId,identity,epoch,slotId,productVariantId,outputId,intent, + ...(intent==='generate_candidate'&&!args.useProductReference?{candidateId:operationId}:null)}; + const rejectUndispatched=async result=>{ + if(result?.operationId!==operationId||!(result.phase==='not_dispatched'||result.dispatched===false))return; + dispatched=false; + terminal=true; + checkTurn(); + const failure=result.error??result.failure; + const reason=failure?.reason??failure?.code??failure?.category??result.writeBlockReason??'not_dispatched'; + const message=`本次操作未派发:${workflowResult({message:failure?.message??result.message??reason}).message}`; + await host.store.appendEvent({type:'workflow_operation_not_dispatched',run,documentId,operationId,baseRevision:result.baseRevision, + intent,slotId,productVariantId,code:failure?.code??reason,reason,message}); + throw new BridgeError(message,reason,{retryable:reason==='revision_conflict',currentRevision:result.revision, + changedLayers:result.changedLayers}); + }; try { signal?.throwIfAborted(); const saveDeadline = Date.now() + (timeoutMs ?? LOCAL_OPERATION_WAIT_MS); @@ -92,8 +119,9 @@ export async function executeWorkflow(host, args, signal, { timeoutMs, pause = d const submit=async()=>{ try { return await host.canvas.workflowExecute({...args,operationId}); } catch(error) { - if(!canvasReplyTimedOut(error))throw error; - return reconcileOriginal(); + if(canvasReplyTimedOut(error))return reconcileOriginal(); + if(error?.dispatched===false)dispatched=false; + throw error; } }; if(adoption&&onAdoptionPrepared){ @@ -121,23 +149,18 @@ export async function executeWorkflow(host, args, signal, { timeoutMs, pause = d if (state?.conversationActive === false) throw new BridgeError('当前画布已切换,尚未派发操作','scope_changed'); if (state?.writeBlocked) throw new BridgeError('本轮写入许可已撤销,尚未派发操作','write_revoked'); if (!detailBatch && state?.error) throw Error(state.error); + if (!detailBatch && Number.isSafeInteger(result.revision) && state?.revision!==result.revision) { + throw new BridgeError('等待保存期间画布已变化,本次未派发','revision_conflict',{currentRevision:state?.revision}); + } if(adoption)await requestWrite(); dispatched = true; result = await submit(); } - const notDispatched = result?.phase === 'not_dispatched' && result.operationId === operationId; - if (notDispatched) { dispatched = false; terminal = true; } + await rejectUndispatched(result); checkTurn(); - if (notDispatched) { - const message = `本次操作未派发:${workflowResult({message:result.error.message}).message}`; - const reason = result.error.reason ?? result.error.code; - await host.store.appendEvent({type:'workflow_operation_not_dispatched',run,documentId,operationId,baseRevision:result.baseRevision, - intent:args.intent,slotId:args.slotId,productVariantId:args.productVariantId,code:result.error.code,reason,message}); - throw new BridgeError(message,reason,{retryable:reason==='revision_conflict',currentRevision:result.revision, - changedLayers:result.changedLayers}); - } const phases=observedOriginal?receiptPhases:['submitted']; if (result?.operationId !== operationId || !phases.includes(result.phase)) throw Error('工作流操作提交状态无效,原操作需核查;不会重发'); + if(original.candidateId&&result.candidateId)original.candidateId=result.candidateId; await onSubmitted?.(result); if (result.phase !== 'unknown') { await host.store.appendEvent({ type:'workflow_operation_submitted', run, operationId, intent:args.intent, @@ -148,9 +171,11 @@ export async function executeWorkflow(host, args, signal, { timeoutMs, pause = d signal?.throwIfAborted(); await pause(args.intent === 'generate_candidate' ? 500 : 200, undefined, { signal }); result = await pollReceipt(); + await rejectUndispatched(result); checkTurn(); if (result?.operationId !== operationId || !receiptPhases.includes(result.phase)) throw Error('工作流操作回执无效,原操作需核查;不会重发'); } + if(original.candidateId&&result.candidateId)original.candidateId=result.candidateId; terminal = ['complete','failed','expired','candidate_limit_reached'].includes(result.phase); if (result.phase === 'candidate_limit_reached') { const {phase,reason,limitReached,candidateCount,candidatesRemaining,maxCandidatesPerSlot}=result; @@ -165,7 +190,7 @@ export async function executeWorkflow(host, args, signal, { timeoutMs, pause = d ...(result.retryableFailure===true?{retryableFailure:true,retryAfterSeconds:result.retryAfterSeconds}:{})}}; } if (detailBatch && args.intent==='generate_candidate' && !terminal) { - scope.retain({kind:'workflow',operationId,run,documentId,identity,epoch,slotId:args.slotId,productVariantId:args.productVariantId}); + scope.retain(original); return {operation:{phase:'unknown',operationId,candidateId:result.candidateId}}; } if (result.phase === 'failed' && result.writeBlockReason) { @@ -187,7 +212,7 @@ export async function executeWorkflow(host, args, signal, { timeoutMs, pause = d catch { throw Error('原工作流操作已完成,但刷新状态失败;请核查,禁止重发'); } return { operation, workflow: current }; } catch (error) { - if (dispatched && !terminal) scope.retain({kind:'workflow',operationId,run,documentId,identity,epoch,slotId:args.slotId,productVariantId:args.productVariantId}); + if (dispatched && !terminal) scope.retain(original); throw error; } finally { if (scope.active===owner) scope.active=null; } } diff --git a/apps/detail-agent-pi/test/liberate-agent-js.test.mjs b/apps/detail-agent-pi/test/liberate-agent-js.test.mjs index b352e86b..19425404 100644 --- a/apps/detail-agent-pi/test/liberate-agent-js.test.mjs +++ b/apps/detail-agent-pi/test/liberate-agent-js.test.mjs @@ -56,7 +56,7 @@ test('toolSchema strips additionalProperties:false and normalizeToolArgs handles assert.equal(validated.pageId, '1'); assert.equal(validated.reason, '画面构图偏右'); assert.equal(validated.notes, undefined); - assert.deepEqual(validated.mustRedo[0], { location: '顶部', problem: '裁切过紧', suggestion: '留白' }); + assert.deepEqual(validated.mustRedo[0], { location: '顶部', issue: '裁切过紧', problem: '裁切过紧', suggestion: '留白' }); }); test('all 9 previously missing productionTools accept optional outputId and variantId', () => { @@ -90,7 +90,7 @@ test('candidateUsage decouples local crops/reuses from paid maxCandidatesPerSlot }); test('callProductionTool allows non-working read/review/retire, finish_production returns unadoptedPassed without blocking, and maps detail to 详情页', async t => { - const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-liberate-')); + const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-pi-liberate-')); t.after(() => cleanup(dir)); const store = productionStore(dir); const slot = { @@ -122,7 +122,8 @@ test('callProductionTool allows non-working read/review/retire, finish_productio slots: [slot], }), detailCopyFields: async () => ({ pages: ['p1'], fields: [] }), - detailHistory: async () => ({ template: {}, slots: [slot] }), + detailHistory: async ({targetOutput}) => ({ outputId:targetOutput.outputId, productVariantId:targetOutput.variantId, + template:{contentHash:'tpl-hash'}, slots:[slot] }), read: async () => ({ revision: 3 }), finishProduction: async input => ({ ...input, @@ -147,14 +148,14 @@ test('callProductionTool allows non-working read/review/retire, finish_productio const finished = await callProductionTool(host, 'finish_production', { outputId: 'detail', variantId: 'oak' }); assert.notEqual(finished.reason, 'unadopted_passed_candidates'); assert.equal(finished.unadoptedPassed[0].slotId, 'slot-1'); - assert.match(host.productionDelivery.text, /已交付:详情页。/u); - assert.match(host.productionDelivery.text, /待交付成品:主图。/u); + assert.match(host.productionDelivery.text, /已导出详情页。/u); + assert.match(host.productionDelivery.text, /主图还待交付。/u); assert.doesNotMatch(host.productionDelivery.text, /\bdetail\b/u); assert.doesNotMatch(host.productionDelivery.text, /\bmain_images\b/u); }); test('acquireXiaoyiRelease downloads missing blobs with 4-way bounded concurrency', async t => { - const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-release-conc-')); + const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-pi-release-conc-')); t.after(() => cleanup(dir)); const { zipSync, strToU8 } = await import('fflate'); @@ -214,6 +215,7 @@ test('acquireXiaoyiRelease downloads missing blobs with 4-way bounded concurrenc const result = await acquireXiaoyiRelease({ templateId: 'tpl-1', directory: dir, + cache: path.join(dir, 'cache'), fetch: fakeFetch, origin: 'https://example.invalid', }); diff --git a/apps/detail-agent-pi/test/native-wire.test.mjs b/apps/detail-agent-pi/test/native-wire.test.mjs index 259fe7ff..cec466a5 100644 --- a/apps/detail-agent-pi/test/native-wire.test.mjs +++ b/apps/detail-agent-pi/test/native-wire.test.mjs @@ -1673,3 +1673,87 @@ test('Pi serializes shared cache affinity for the same kind of production worker assert.equal(stoppedCalls,1); }); import { getCurrentSystemPrompt } from '@earendil-works/pi-ai/utils/transcript'; + +test('conversation after delivery opens another output through the private canvas binding',async t=>{ + const detail={outputId:'detail',variantId:'oak'}; + const main={outputId:'main_images',variantId:'oak'}; + const requestedOutputs=[detail,main]; + const template={id:'desk',contentHash:'desk-template'}; + const calls=[], visible=[]; + const digest='1234567890'.repeat(6)+'1234'; + let binding; + const canvas=new StdioCanvas(async (action,input)=>{ + if(action==='pi-begin'){ + binding={...detail,documentKey:{workspaceId:'desk',...detail},writeEpoch:1}; + return {run:input.run,conversationActive:true,productionCanvas:binding, + context:{requestScope:{...detail,productionTemplate:template,requestedOutputs}}}; + } + if(action==='pi-production-open'){ + assert.deepEqual(input.canvasBinding,{documentKey:binding.documentKey,writeEpoch:1}); + assert.deepEqual({outputId:input.outputId,variantId:input.variantId},main); + binding={...main,documentKey:{workspaceId:'desk',...main},writeEpoch:2,previousSave:{saved:true}}; + calls.push(action); + return {productionCanvas:binding,productionSwitch:{accepted:true}}; + } + if(action==='pi-state')return {conversationActive:true,revision:2}; + if(action==='pi-workflow-read'){ + assert.equal(input.canvasBinding.writeEpoch,binding.writeEpoch); + return {available:true,canvasFirst:true,outputId:binding.outputId,productVariantId:binding.variantId, + version:1,template,totalSlots:0,slots:[],productEvidence:{accountScope:x.store.identity.scope, + project:x.store.identity.project,documentId:17,brief:{brandId:'qa',categoryId:'desk'}}}; + } + if(action==='pi-image-request')return []; + if(action==='pi-delta'||action==='pi-end')visible.push(input.text); + return {}; + },17); + const x=await setup((payload,round)=>{ + const names=payload.tools.map(row=>row.function.name); + assert.ok(names.includes('open_production_output')); + assert.ok(!names.includes('finish_production')&&!names.includes('defer_production_output')); + return round===1?sse({tool_calls:[{index:0,id:'follow-up-open',type:'function', + function:{name:'open_production_output',arguments:JSON.stringify(main)}}]},'tool_calls') + :sse({content:'已打开主图画布。\n| 复核 | '+digest+' |'},'stop'); + }); + t.after(x.close); + x.host.canvas=canvas; + x.host.productIdentity.documentId=17; + x.host.manager.appendCustomEntry('production-goal',{goal:{id:'delivered',status:'complete'}}); + const reply='已打开主图画布。\n- 复核,制作记录'; + assert.equal((await x.host.prompt('主图改成侘寂风')).text,reply); + assert.ok(visible.includes(reply)); + assert.ok(visible.every(text=>!text||!text.includes('|')&&!text.includes(digest))); + assert.deepEqual(calls,['pi-production-open']); + assert.deepEqual(canvas.productionOutput,main); + assert.equal(canvas.canvasBinding.writeEpoch,2); + assert.equal(x.host.productionContext.outputId,main.outputId); +}); + +test('native_reconcile clears a ghost workflow lock and preserves a saved paid original',async()=>{ + const make=(name,_description,_schema,execute)=>({name,execute}); + const identity={run:'old-run',documentId:23}; + const ghost={...identity,kind:'workflow',operationId:'stale',slotId:'ghost',productVariantId:'oak'}; + const paid={...identity,kind:'workflow',operationId:'paid',slotId:'hero', + outputId:'main_images',productVariantId:'oak',candidateId:'paid-candidate'}; + const host={store:{},canvas:{ + imageRequest:async action=>{assert.equal(action,'pending');return [];}, + workflowReconcile:async input=>{ + assert.deepEqual(input,{...identity,operationId:input.operationId}); + if(input.operationId==='stale')throw Error('原操作不存在或不属于当前项目'); + return {...input,phase:'unknown',operationFound:false}; + }, + detailRecover:async (slotId,input,scope)=>{ + assert.equal(slotId,'hero'); + assert.deepEqual(input,{candidateId:'paid-candidate'}); + assert.deepEqual(scope,{outputId:'main_images',variantId:'oak'}); + return {id:'paid-candidate',status:'unknown',message:'远端仍在核查'}; + }, + }}; + const {execute:reconcile}=nativeTools(host,make).find(tool=>tool.name==='native_reconcile'); + await reconcile(); + host.canvasOperations.retain(ghost); + host.canvasOperations.retain(paid); + const {results}=await reconcile(); + assert.deepEqual(results.map(row=>row.status),['not_found','unknown']); + assert.match(results[0].receipt.message,/可以发起新操作/u); + assert.deepEqual(host.canvasOperations.pending,[paid]); +}); diff --git a/apps/detail-agent-pi/test/pi.test.mjs b/apps/detail-agent-pi/test/pi.test.mjs index 72d9b2f5..eddc8ae7 100644 --- a/apps/detail-agent-pi/test/pi.test.mjs +++ b/apps/detail-agent-pi/test/pi.test.mjs @@ -42,14 +42,14 @@ test('post-goal chat keeps the canvas production tools and reads the locked Skil productEvidence:{accountScope:id.scope,project:id.project,documentId,brief:{brandName:'灯具测试'}}};}, async detailHistory(){return [];}, }; - const toolkit=['plan_production','write_copy_fields','read_slot_images','list_project_images', + const toolkit=['open_production_output','plan_production','write_copy_fields','read_slot_images','list_project_images', 'prepare_image_request','dispatch_image_request','delegate_image_slots','await_image_slots','check_image_slots', 'transform_slot_image','adopt_production_image','retire_production_image','read_output_screen','reconcile_image_slots']; let calls=0, host; const transport={info:info(id.scope),stream(_model,context){ const names=getCurrentTools(context.messages).map(tool=>tool.name); for(const tool of [...toolkit,'read']) assert.ok(names.includes(tool),tool); - for(const tool of ['open_production_output','finish_production','defer_production_output','get_goal','update_goal']) { + for(const tool of ['finish_production','defer_production_output','get_goal','update_goal']) { assert.ok(!names.includes(tool),tool); } const system=getCurrentSystemPrompt(context.messages); diff --git a/apps/detail-agent-pi/test/production-operations.test.mjs b/apps/detail-agent-pi/test/production-operations.test.mjs index dee9e453..30570815 100644 --- a/apps/detail-agent-pi/test/production-operations.test.mjs +++ b/apps/detail-agent-pi/test/production-operations.test.mjs @@ -2010,8 +2010,7 @@ test('Pi chooses each image operation and keeps an unresolved paid request on it slots[0].selectedCandidateId='existing-candidate'; slots[1].candidates.push({id:'slow-candidate',status:'complete'}); const incomplete=await actions.finish_production({revision}); - assert.equal(incomplete.submitted,false); - assert.equal(incomplete.production.complete,false); + assert.equal(incomplete.production.complete,true); assert.deepEqual(incomplete.production.unadoptedPassed,[{slotId:'switch-photo',fieldId:'switch',candidateIds:['slow-candidate']}]); assert.deepEqual(incomplete.production.slotCoverage,{adopted:1,manual:0,unadoptedWithCandidates:1,empty:1,skipped:0,total:3}); const partial=await actions.finish_production({revision,deliveryReason:'按当前画布交付'}); @@ -2452,7 +2451,7 @@ test('draw limit receipts identify the template value or the bundled default reg } }); -test('transforms and reuse consume the same slot quota as paid dispatch',async t=>{ +test('transforms and reuse leave the paid generation quota available',async t=>{ const {host}=await tailFixture(t,['hero']); const workflowRead=host.canvas.workflowRead; const candidates=[]; @@ -2465,7 +2464,7 @@ test('transforms and reuse consume the same slot quota as paid dispatch',async t candidates.push(candidate); return candidate; }; - imageBridge(host,async()=>assert.fail('candidate limit must block paid dispatch')); + imageBridge(host,async()=>assert.fail('preparing a request must not dispatch it')); const request=host.canvas.imageRequest; host.canvas.imageRequest=async(action,...args)=>action==='transform' ?add('crop','transform'):request(action,...args); @@ -2474,15 +2473,16 @@ test('transforms and reuse consume the same slot quota as paid dispatch',async t t.after(()=>ops.close()); const input={slotId:'hero',prompt:'同款商品'}; const draft=await ops.prepare_image_request(input); + assert.equal(draft.phase,'prepared'); assert.equal((await ops.transform_slot_image({slotId:'hero',referenceIndex:0})).candidateId,'crop'); assert.equal((await ops.stage_archived_image({slotId:'hero',candidateId:'source'})).id,'reuse'); const {pictures:[slot]}=await ops.plan_production(input); - assert.equal(slot.candidateCount,2); - assert.equal(slot.candidatesRemaining,0); - const preparedAfterLimit=await ops.prepare_image_request(input); - assert.equal(preparedAfterLimit.phase,'prepared'); - assert.equal(preparedAfterLimit.candidateCount,2); - assert.equal(preparedAfterLimit.candidatesRemaining,0); + assert.equal(slot.candidateCount,0); + assert.equal(slot.candidatesRemaining,2); + const preparedAfterLocalEdits=await ops.prepare_image_request(input); + assert.equal(preparedAfterLocalEdits.phase,'prepared'); + assert.equal(preparedAfterLocalEdits.candidateCount,0); + assert.equal(preparedAfterLocalEdits.candidatesRemaining,2); }); test('the bundled draw limit applies in flight and a rejected candidate can still be exported',async t=>{ @@ -2815,3 +2815,67 @@ test('write_copy_fields normalizes CRLF line endings when recording copyEvidence const journal = JSON.parse(await fs.readFile(path.join(dir, 'production-detail-white.json'), 'utf8')); assert.equal(journal.copyEvidence[1].text, '第一行\r\n第二行'); }); + +test('follow-up image tools resolve explicit main image scope and live field aliases',async t=>{ + const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-follow-up-')); + t.after(()=>cleanup(dir)); + const detail={outputId:'detail',variantId:'oak'}; + const main={outputId:'main_images',variantId:'oak'}; + const requestedOutputs=[detail,main]; + const store=productionStore(dir); + const trace=[]; + const mainSlot={id:'main-photo',fieldId:'M01',candidates:[]}; + const plans=new Map([ + ['detail',[{id:'detail-photo',fieldId:'D01',candidates:[]}]], + ['main_images',[mainSlot]], + ]); + const plan=({outputId,variantId})=>({available:true,canvasFirst:true,outputId,productVariantId:variantId, + template:{contentHash:outputId},version:1,totalSlots:1,slots:plans.get(outputId)}); + let input; + const canvas={ + run:'follow-up',documentId:7,productionOutput:detail, + workflowRead:async()=>plan(canvas.productionOutput), + detailHistory:async ({targetOutput})=>plan(targetOutput), + openProductionOutput:async target=>{ + canvas.productionOutput=target; + return {...target,previousSave:{saved:true}}; + }, + imageRequest:async (action,args,_signal,scope)=>{ + if(action==='pending')return []; + trace.push({action,args,scope}); + if(action==='prepare')return {requestId:'prepared-main'}; + assert.equal(action,'product_reference'); + return {status:'complete',id:'main-reference'}; + }, + read:async()=>({conversationActive:true,revision:3}), + requestWrite:async revision=>({allowed:true,revision}), + workflowExecute:async args=>{ + input=args; + return {phase:'submitted',operationId:args.operationId}; + }, + workflowPoll:async operationId=>({phase:'complete',operationId,candidateId:input.candidateId}), + detailCopyFields:async()=>({fields:[]}), + delta:async()=>{}, + }; + const host={canvas,store,productionContext:{...detail,requestedOutputs}}; + t.after(()=>closeProductionTurn(host)); + const call=(name,args)=>callProductionTool(host,name,args); + const selected={outputId:'main_images',fieldId:'M01'}; + const prepared=await call('prepare_image_request',{...selected,prompt:'侘寂风场景'}); + assert.equal(prepared.requestId,'prepared-main'); + assert.equal((await call('use_product_image',selected)).slotId,mainSlot.id); + assert.deepEqual(await call('reconcile_image_slots',selected),[{slotId:mainSlot.id,phase:'none'}]); + assert.ok(trace.every(row=>row.args.slotId===mainSlot.id&&row.scope.outputId==='main_images')); + const adoption={...selected,candidateId:'main-reference'}; + assert.deepEqual((await call('adopt_production_image',adoption)).nextAction, + {tool:'open_production_output',args:main}); + await call('open_production_output',main); + const {generation}=await call('await_image_slots',{...main,slotIds:[mainSlot.id]}); + assert.equal(generation[0].candidateId,'main-reference'); + plans.set('main_images',[{...mainSlot,fieldId:'M02'}]); + assert.deepEqual(await call('reconcile_image_slots',{...main,fieldId:'M02'}),[{slotId:mainSlot.id,phase:'none'}]); + assert.equal((await call('adopt_production_image',{...adoption,fieldId:'M02'})).phase,'complete'); + assert.equal(input.slotId,mainSlot.id); + assert.equal(input.outputId,'main_images'); + assert.equal(input.productVariantId,'oak'); +}); diff --git a/apps/detail-agent-pi/test/real-photo-reconcile.test.mjs b/apps/detail-agent-pi/test/real-photo-reconcile.test.mjs index d4ea637b..6389386f 100644 --- a/apps/detail-agent-pi/test/real-photo-reconcile.test.mjs +++ b/apps/detail-agent-pi/test/real-photo-reconcile.test.mjs @@ -106,3 +106,32 @@ test('a failed local transform leaves the slot free for another transform',async assert.equal((await actions.transform_slot_image(params)).candidateId,'transformed'); assert.equal(item().source,'transform'); }); + +test('production reconciliation clears a ghost generation after both its host records are missing',async t=>{ + const operationId=randomUUID(); + let pending=[{...target,slotId,operationId:'paid-operation',candidateId:'paid-candidate'}]; + const {actions,item}=await fixture(t,{[slotId]:{state:'unknown',candidateId:'previous', + pendingOperation:{...scope,operationId,intent:'generate_candidate',candidateId:operationId}}},{ + async imageRequest(action){assert.equal(action,'pending');return pending;}, + async detailRecover(slot,{candidateId}){ + assert.equal(slot,slotId); + if(candidateId==='paid-candidate')return {id:candidateId,status:'unknown'}; + assert.equal(candidateId,operationId); + throw Error(`候选 ${candidateId}(canvas-candidate.json):文件缺失`); + }, + async workflowReconcile(input){ + assert.deepEqual(input,{...scope,operationId}); + throw Error(missingOperation); + }, + }); + const blocked=await actions.reconcile_image_slots({fieldId:'K01'}); + assert.equal(blocked.find(row=>row.operationId===operationId).phase,'unknown'); + assert.equal(item().pendingOperation.operationId,operationId); + pending=[]; + const [receipt]=await actions.reconcile_image_slots({fieldId:'K01'}); + assert.equal(receipt.phase,'not_executed'); + assert.match(receipt.reason,/可以发起新操作/u); + assert.equal(item().pendingOperation,null); + assert.equal(item().candidateId,'previous'); + assert.equal((await actions.reconcile_image_slots({slotId}))[0].phase,'none'); +}); diff --git a/apps/detail-agent-pi/test/whitelabel.test.mjs b/apps/detail-agent-pi/test/whitelabel.test.mjs index 0561e7d2..ec05c4d0 100644 --- a/apps/detail-agent-pi/test/whitelabel.test.mjs +++ b/apps/detail-agent-pi/test/whitelabel.test.mjs @@ -6,7 +6,7 @@ import { fileURLToPath } from 'node:url'; import { productionObjective, productionTools } from '../src/production-goal.mjs'; import { NATIVE_CANVAS_QUICK_REFERENCE, nativeTools } from '../src/native-tools.mjs'; import { sessionSystemPrompt } from '../src/agent.mjs'; -import { presentProductReply } from '../src/stream-presentation.mjs'; +import { presentReply, presentProductReply } from '../src/stream-presentation.mjs'; const source = file => readFileSync(new URL(`../src/${file}`, import.meta.url), 'utf8'); const technicalBrand = /(? { diff --git a/apps/detail-agent-pi/test/workflow-execute.test.mjs b/apps/detail-agent-pi/test/workflow-execute.test.mjs index f561b0e2..55ae255b 100644 --- a/apps/detail-agent-pi/test/workflow-execute.test.mjs +++ b/apps/detail-agent-pi/test/workflow-execute.test.mjs @@ -18,7 +18,7 @@ test('late prior-turn workflow receipt cannot stop the new turn and retains unkn const operationId=x.calls[0][1].operationId; x.host.turnEpoch=2;x.host.canvas.run='new-run'; release();await assert.rejects(task,/原回合已结束/); - assert.deepEqual(x.host.canvasOperations.original,{kind:'workflow',operationId,run:'r',documentId:undefined,identity:{scope:undefined,project:undefined,accountId:undefined,origin:undefined},epoch:1,slotId:'hero',productVariantId:'walnut'}); + assert.deepEqual(x.host.canvasOperations.original,{kind:'workflow',operationId,run:'r',documentId:undefined,identity:{scope:undefined,project:undefined,accountId:undefined,origin:undefined},epoch:1,slotId:'hero',productVariantId:'walnut',outputId:'detail',intent:'generate_candidate',candidateId:operationId}); await assert.rejects(executeWorkflow(x.host,args),/按原号核查/); assert.equal(x.calls.length,1); }); diff --git a/apps/detail-agent-pi/test/workflow-not-dispatched.test.mjs b/apps/detail-agent-pi/test/workflow-not-dispatched.test.mjs index d66f751b..d2a4ccd0 100644 --- a/apps/detail-agent-pi/test/workflow-not-dispatched.test.mjs +++ b/apps/detail-agent-pi/test/workflow-not-dispatched.test.mjs @@ -1,6 +1,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { executeWorkflow } from '../src/workflow-execute.mjs'; +import { BridgeError } from '../src/bridge-error.mjs'; const args = {version:1,intent:'generate_candidate',outputId:'detail',slotId:'hero',productVariantId:'walnut'}; function fixture(change = value => value) { @@ -92,3 +93,24 @@ test('a late authoritative rejection cannot stop or contaminate a new user turn' assert.equal(x.host.canvasOperations.original,undefined); assert.equal(x.events.length,0); }); + +test('structured host rejection before dispatch does not hold the slot',async()=>{ + const x=fixture(); + const reject=x.host.canvas.workflowExecute; + x.host.canvas.workflowExecute=async input=>{ + if(x.calls.length)return reject(input); + x.calls.push(input.operationId); + throw new BridgeError('目标图层已变化','revision_conflict',{dispatched:false,currentRevision:18}); + }; + await assert.rejects(executeWorkflow(x.host,args),{category:'revision_conflict',dispatched:false}); + assert.deepEqual(x.host.canvasOperations.pending,[]); + await assert.rejects(executeWorkflow(x.host,args),/未派发/); + assert.equal(new Set(x.calls).size,2); +}); + +test('a matching receipt flagged as not dispatched is terminal even if its phase is unknown',async()=>{ + const x=fixture(receipt=>({...receipt,phase:'unknown',error:{code:'scope_changed',message:'画布已切换'}})); + await assert.rejects(executeWorkflow(x.host,args),{category:'scope_changed',dispatched:false}); + assert.deepEqual(x.host.canvasOperations.pending,[]); + assert.equal(x.events[0].type,'workflow_operation_not_dispatched'); +});