- 删除生产无调用方的 receipt.mjs 和 NativeCanvas 兼容转出口 - 删除只为测试假对象写的画布方法存在性判断及生产走不到的兜底分支 - 未派发回执只认 phase 与 operationId,不再逐字段复核宿主数据 - 企业知识库去掉与 Pi 原生校验重复的本地校验,保留服务端真实校验原因 - 测试同步:删死代码用例,无画布主机工具清单补齐原生工具
191 lines
11 KiB
JavaScript
191 lines
11 KiB
JavaScript
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 { BridgeError, stoppedCanvas } from './bridge-error.mjs';
|
|
import { canvasReplyTimedOut } from './stdio-canvas.mjs';
|
|
|
|
// The native image worker can wait 10 minutes for the POST and 3 more for
|
|
// read-only recovery. Leave one minute for local preparation and final receipts.
|
|
const IMAGE_OPERATION_WAIT_MS = 14 * 60_000;
|
|
export const LOCAL_OPERATION_WAIT_MS = 120_000;
|
|
const receiptPhases = ['submitted','complete','failed','unknown','expired'];
|
|
|
|
async function acquireWrite(host, scope, signal, checkTurn, wait, onWait) {
|
|
const state=await host.canvas.read();
|
|
checkTurn();
|
|
if(state?.conversationActive===false||state?.writeBlocked||!Number.isSafeInteger(state?.revision)||state.revision<0) {
|
|
throw new BridgeError('画布已变化或用户已停止,未派发采纳',state?.conversationActive===false?'scope_changed':'write_revoked');
|
|
}
|
|
if(wait && state.detailWriteWaiting){
|
|
await onWait?.();
|
|
return null;
|
|
}
|
|
scope.writeRequested=true;
|
|
const receipt=await host.canvas.requestWrite(state.revision);
|
|
checkTurn();
|
|
if(wait && receipt?.retryWrite){
|
|
await onWait?.();
|
|
return null;
|
|
}
|
|
if(!receipt?.allowed)throw new BridgeError('用户已接手,本轮写入未获许可','write_revoked');
|
|
if(receipt.revision!==state.revision)throw new BridgeError('画布已修改,写入许可已过期,未派发采纳','revision_conflict');
|
|
signal?.throwIfAborted();
|
|
if(host.canvasNotificationsDetached||scope.writesBlocked)throw Error('原项目已切换或用户已接手,未派发采纳');
|
|
return receipt;
|
|
}
|
|
|
|
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')){
|
|
throw Error('原画布操作的核查回执与提交身份不一致');
|
|
}
|
|
return receipt;
|
|
}
|
|
|
|
// One new operation, then only read its status. No transport or model retry.
|
|
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 || scope.writesBlocked) throw Error('原项目已切换或原操作需核查,本轮不再派发');
|
|
if (scope.original) throw Error('原操作结果未知,先核查原请求;可使用 native_reconcile 只读核查,不会重发');
|
|
if (scope.active) throw Error('已有原生操作正在执行,请依次等待');
|
|
const epoch = host.turnEpoch, run = host.canvas.run, documentId = host.canvas.documentId, owner = Symbol('workflow operation');
|
|
const identity = {scope:host.store.identity?.scope, project:host.store.identity?.project, accountId:host.canvas.identity?.accountId, origin:host.canvas.identity?.origin};
|
|
scope.active=owner;
|
|
let dispatched = false, terminal = false;
|
|
const checkTurn = () => { if (host.turnEpoch !== epoch) throw Error('原回合已结束,旧工作流操作不会继续或重发'); };
|
|
const operationId = randomUUID();
|
|
try {
|
|
signal?.throwIfAborted();
|
|
const saveDeadline = Date.now() + (timeoutMs ?? LOCAL_OPERATION_WAIT_MS);
|
|
const adoption=args.intent==='adopt_candidate';
|
|
const requestWrite=async()=>{
|
|
while(!await acquireWrite(host,scope,signal,checkTurn,detailBatch,onWriteWaiting)){
|
|
signal?.throwIfAborted();
|
|
if(Date.now()>=saveDeadline)throw Error('当前编辑尚未落定,已保留候选');
|
|
await pause(150,undefined,{signal});
|
|
checkTurn();
|
|
}
|
|
};
|
|
if(adoption)await requestWrite();
|
|
let observedOriginal=false;
|
|
const reconcileOriginal=async()=>{
|
|
signal?.throwIfAborted();
|
|
checkTurn();
|
|
observedOriginal=true;
|
|
return reconcileWorkflowReceipt(host.canvas,{run,documentId,operationId});
|
|
};
|
|
const pollReceipt=async()=>{
|
|
if(observedOriginal)return reconcileOriginal();
|
|
try { return await host.canvas.workflowPoll(operationId); }
|
|
catch(error) {
|
|
if(!canvasReplyTimedOut(error))throw error;
|
|
return reconcileOriginal();
|
|
}
|
|
};
|
|
const submit=async()=>{
|
|
try { return await host.canvas.workflowExecute({...args,operationId}); }
|
|
catch(error) {
|
|
if(!canvasReplyTimedOut(error))throw error;
|
|
return reconcileOriginal();
|
|
}
|
|
};
|
|
if(adoption&&onAdoptionPrepared){
|
|
await onAdoptionPrepared({run,documentId,operationId});
|
|
signal?.throwIfAborted();
|
|
checkTurn();
|
|
}
|
|
if(onPrepared){
|
|
await onPrepared({run,documentId,operationId});
|
|
signal?.throwIfAborted();
|
|
checkTurn();
|
|
}
|
|
dispatched = true;
|
|
let result=await submit();
|
|
while (!observedOriginal && result?.operationId === operationId && result.phase === 'waiting_save' && result.dispatched === false) {
|
|
dispatched = false;
|
|
checkTurn();
|
|
signal?.throwIfAborted();
|
|
if (Date.now() >= saveDeadline) throw Error('项目仍在保存,本次尚未开始处理');
|
|
await pause(100, undefined, { signal });
|
|
checkTurn();
|
|
signal?.throwIfAborted();
|
|
const state = await host.canvas.read();
|
|
checkTurn();
|
|
if (state?.conversationActive === false || state?.writeBlocked || (!detailBatch && state?.revision !== result.revision)) throw new BridgeError('画布已变化或用户已接手,尚未派发操作','write_revoked');
|
|
if (!detailBatch && state?.error) throw Error(state.error);
|
|
if(detailBatch && adoption)await requestWrite();
|
|
dispatched = true;
|
|
result = await submit();
|
|
}
|
|
const notDispatched = result?.phase === 'not_dispatched' && result.operationId === operationId;
|
|
if (notDispatched) { dispatched = false; terminal = true; }
|
|
checkTurn();
|
|
if (notDispatched) {
|
|
const message = `本次操作未派发:${workflowResult({message:result.error.message}).message}`;
|
|
if(!detailBatch){
|
|
scope.writesBlocked = true;
|
|
scope.stopReason = 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);
|
|
}
|
|
const phases=observedOriginal?receiptPhases:['submitted'];
|
|
if (result?.operationId !== operationId || !phases.includes(result.phase)) throw Error('工作流操作提交状态无效,原操作需核查;不会重发');
|
|
await onSubmitted?.(result);
|
|
if (result.phase !== 'unknown') {
|
|
await host.store.appendEvent({ type:'workflow_operation_submitted', run, operationId, intent:args.intent,
|
|
slotId:args.slotId, productVariantId:args.productVariantId, ...(observedOriginal ? { acknowledgment:'reconciled' } : {}) });
|
|
}
|
|
const deadline = Date.now() + (timeoutMs ?? (args.intent === 'generate_candidate' ? IMAGE_OPERATION_WAIT_MS : LOCAL_OPERATION_WAIT_MS));
|
|
while (result.phase === 'submitted' && Date.now() < deadline) {
|
|
signal?.throwIfAborted();
|
|
await pause(args.intent === 'generate_candidate' ? 500 : 200, undefined, { signal });
|
|
result = await pollReceipt();
|
|
checkTurn();
|
|
if (result?.operationId !== operationId || !receiptPhases.includes(result.phase)) throw Error('工作流操作回执无效,原操作需核查;不会重发');
|
|
}
|
|
terminal = ['complete','failed','expired'].includes(result.phase);
|
|
if (keepFailedCandidate && args.intent === 'generate_candidate' && ['failed','expired'].includes(result.phase)
|
|
&& typeof result.candidateId === 'string' && result.candidateId) {
|
|
const message = workflowResult(result).message || '这次生图已失败,请查看图位记录';
|
|
await host.store.appendEvent({type:'whole_detail_generation_failed',slotId:args.slotId,operationId,candidateId:result.candidateId,message});
|
|
return {operation:{candidateId:result.candidateId,phase:result.phase,message,
|
|
...(result.phase==='expired'?{requestId:result.requestId,retryable:false,resultExpiry:result.resultExpiry}:null),
|
|
...(result.retryableFailure===true?{retryableFailure:true,retryAfterSeconds:result.retryAfterSeconds}:{})}};
|
|
}
|
|
if (detailBatch && args.intent==='generate_candidate' && !terminal) {
|
|
scope.retain({kind:'workflow',operationId,run,documentId,identity,epoch});
|
|
return {operation:{phase:'unknown',operationId,candidateId:result.candidateId}};
|
|
}
|
|
if (result.phase === 'failed' && result.writeBlockReason) {
|
|
throw new BridgeError(workflowResult(result).message,result.writeBlockReason,{dispatched:true});
|
|
}
|
|
if (result.phase !== 'complete') throw Error(workflowResult(result).message || (result.phase === 'failed' ? '原工作流操作失败,请核查结果;不会重发' : '原工作流操作结果未知,请核查原请求;不会重发'));
|
|
const operation = workflowResult({
|
|
...result, intent: args.intent, outputId: args.outputId, slotId: args.slotId, productVariantId: args.productVariantId,
|
|
});
|
|
const candidateId = typeof result.candidateId === 'string' && result.candidateId.trim() ? result.candidateId : null;
|
|
const generated = args.intent === 'generate_candidate' && candidateId !== null;
|
|
if (generated) generatedCandidates?.set(candidateId, false);
|
|
if (args.intent === 'adopt_candidate' && generatedCandidates?.has(candidateId)) generatedCandidates.set(candidateId, true);
|
|
await host.store.appendEvent({ type:'workflow_operation_completed', run, operationId, intent:args.intent, slotId:args.slotId,
|
|
productVariantId:args.productVariantId, ...(generated ? { candidateId:result.candidateId } : {}) });
|
|
if(detailBatch)return {operation};
|
|
let current;
|
|
try { current = await readWorkflow({ section:'slots', outputId:args.outputId }); }
|
|
catch { throw Error('原工作流操作已完成,但刷新状态失败;请核查,禁止重发'); }
|
|
return { operation, workflow: current };
|
|
} catch (error) {
|
|
if (dispatched && !terminal) scope.retain({kind:'workflow',operationId,run,documentId,identity,epoch});
|
|
if (host.turnEpoch === epoch && (dispatched || signal?.aborted || stoppedCanvas(error))) {
|
|
scope.writesBlocked = true;
|
|
if (dispatched) scope.stopReason = workflowResult({message:error?.message || '原操作未完成,请核查原请求;不会重发'}).message;
|
|
}
|
|
throw error;
|
|
} finally { if (scope.active===owner) scope.active=null; }
|
|
}
|