让小壹按屏分派并跨成品后台生图
This commit is contained in:
parent
05878e4992
commit
ea7a6d0a4a
@ -68,6 +68,7 @@ const PRODUCTION_SYSTEM = `你是小壹的制作助手。依据本项目发布
|
||||
${PRODUCT_VOICE}
|
||||
用 plan_production 查看待交付项,open_production_output 切换可写画布,保留各成品在途工作。用 list_project_images 查询本项目可复用的候选。用户附带引用时,用其中的输出、花色、图位、候选或原生图层身份定位目标。
|
||||
读实时文案并使画面与对应卖点一致。子代理读取本屏实时文案,验图回执绑定当时的文案签名。文案更新后可按新文案复核。安排图位任务时写清需呈现的内容,避免把模板原文当成当前卖点。
|
||||
一屏文案定下来就可以参考 dispatchReady 分派这屏图位,后台生图期间继续制作其他屏或成品。用 review_image_slots 查看各成品回执,waiting_canvas 表示切回后可继续处理的图位。
|
||||
用 tool_search 查找按需工具。企业指引中的命令行编修可用等价的画布命令完成。通过 native_catalog 查原生命令与完整参数,复用已取得的 parameterDocs。连续的确定操作可用 codemode 依次 await,用真实回执衔接各步。脚本可用 store() 留存需要复用的大对象,只输出本次判断所需的字段、状态和失败原因。查图层树时可用 layer.list,并在脚本内筛选目标。
|
||||
按实际像素和企业 Skill 复核成片。结果未知的付费请求用 reconcile_image_slots 按原编号核查。以文件与版本回执确认交付,用简短中文汇报实际进展。`;
|
||||
|
||||
@ -564,7 +565,9 @@ export class DetailPiAgent {
|
||||
await resources.reload();
|
||||
return resources;
|
||||
};
|
||||
host.runDetailAgent = async (slotId, systemPrompt, prompt, tools, images, requestScope=slotId, captions, signal) => {
|
||||
host.runDetailAgent = async (slotId, systemPrompt, prompt, tools, images, requestScope=slotId, captions, signal, output=host.productionGoal) => {
|
||||
const workerActivityScope={...(host.activityScope||activityScope(store.identity)),
|
||||
...(output?{outputId:output.outputId,variantId:output.variantId}:null)};
|
||||
const signals = [productionSignal,signal].filter(Boolean);
|
||||
const activeSignal = signals.length ? AbortSignal.any(signals) : undefined;
|
||||
activeSignal?.throwIfAborted();
|
||||
@ -604,8 +607,9 @@ export class DetailPiAgent {
|
||||
const unsubscribe = workerSession.subscribe(event=>{
|
||||
budget.observe(event);
|
||||
if(event.type==='tool_execution_start'||event.type==='tool_execution_end'){
|
||||
const activity=toolActivity(event,host.activityScope||activityScope(store.identity));
|
||||
void recordToolEvent(event,activity,{slotId,requestScope})
|
||||
const activity=toolActivity(event,workerActivityScope);
|
||||
void recordToolEvent(event,activity,{slotId,requestScope,
|
||||
outputId:workerActivityScope.outputId,variantId:workerActivityScope.variantId})
|
||||
.catch(error=>console.warn('子代理工具事件未保存',error.code??error.name));
|
||||
}
|
||||
});
|
||||
|
||||
@ -174,7 +174,7 @@ export async function callProductionTool(host, name, args, signal) {
|
||||
const {id,name,version,productionRoute}=goal.template??{};
|
||||
const {product,dimensions,note}=host.productEvidence??{};
|
||||
return {requestedOutputs:goal.requestedOutputs,pendingOutputs:goal.pendingOutputs,
|
||||
workingOutput:null,template:{id,name,version,productionRoute},product:{...product,dimensions,note},
|
||||
workingOutput:null,dispatchReady:[],template:{id,name,version,productionRoute},product:{...product,dimensions,note},
|
||||
...(host.productionSkills?.versionNotice?{knowledgeVersionNotice:host.productionSkills.versionNotice}:null),
|
||||
...(args.includeKnowledge?{knowledgeFiles:host.productionSkills?.files??[]}:null)};
|
||||
}
|
||||
|
||||
@ -78,12 +78,12 @@ const dispatchArgs={requestId:text,expectedRevision:optional(rev),expectedHash:o
|
||||
const outputScope={outputId:optional(text),variantId:optional(text)};
|
||||
|
||||
export const productionOperationTools = [
|
||||
['open_production_output','打开本轮指定输出和花色。切换前保存原工程,返回保存结果、新画布绑定及各成品的在途工作。已有工作会保留。',obj({outputId:text,variantId:text})],
|
||||
['plan_production','读取当前商品规格与备注、模板、图位、成品进度和本轮其它待处理输出。可指定输出和花色,省略时读取当前工作画布。按 slotIds 获取指定图位及其发布要求;includeKnowledge=true 列出固定版本的规则路径,可用 read 读取。生图上限及来源适用于所有图位。pictures 中的 copyReady 表示关联字段没有待写文案。图位工具优先使用 fieldId,重名时使用完整 id。',obj({...outputScope,slotIds:optional(ids),includeKnowledge:optional(Type.Boolean())})],
|
||||
['open_production_output','打开本轮指定输出和花色。切换前保存原工程,返回保存结果、新画布绑定及各成品的在途工作。work 中的 waitingCanvas 列出仍在等切回的图位。',obj({outputId:text,variantId:text})],
|
||||
['plan_production','读取当前商品规格与备注、模板、图位、成品进度和本轮其它待处理输出。可指定输出和花色,省略时读取当前工作画布。按 slotIds 获取指定图位及其发布要求;includeKnowledge=true 列出固定版本的规则路径,可用 read 读取。生图上限及来源适用于所有图位。dispatchReady 列出关联文案已写好且尚未派发或采纳的图位。图位工具优先使用 fieldId,重名时使用完整 id。',obj({...outputScope,slotIds:optional(ids),includeKnowledge:optional(Type.Boolean())})],
|
||||
['read_copy_fields','省略 pageId 和 fieldId 返回全页字段身份、当前文字、约束及修订号;指定页面或字段可读取图层样式、范围及关联字段。',obj({
|
||||
pageId:optional(Type.String()),fieldId:optional(Type.String()),
|
||||
})],
|
||||
['write_copy_fields','按 revision 原位写入指定文字格。可传 expectedText 让画布核对原文,修订已变化时用于匹配未改动的字段。每个 layer 只传一次。可按屏或模块分批写入,原生命令已经写过时可用 recordOnly 登记现有文字。retryWrite 表示画布暂不可写,rejected 列出保留原文的格子。模板规定缺资料时留空的字段,可传空文字并用 reason 记录依据。',obj({
|
||||
['write_copy_fields','按 revision 原位写入指定文字格。可传 expectedText 核对原文,每个 layer 只传一次。原生命令已写过时可用 recordOnly 登记。某一屏文案定下来就可以按 dispatchReady 派这一屏的图位,不必等整页文案;子代理在后台生图时继续写下一屏。retryWrite 表示画布暂不可写,rejected 列出保留原文的格子。模板规定缺资料时留空的字段,可传空文字并用 reason 记录依据。',obj({
|
||||
revision:rev,recordOnly:optional(Type.Boolean()),items:optional(Type.Array(obj({layer,text:Type.String(),expectedText:optional(Type.String()),sources:ids,pictures:ids,reason:optional(Type.String())}))),
|
||||
})],
|
||||
['read_slot_images','查看指定成品图位的同款实拍、模板构图和候选。adopted=true 读取当前可写画布上的实际回填。候选只返回候选画面;需要同时查看或重新查看参考时传 includeReferences=true。',obj({
|
||||
@ -96,8 +96,8 @@ export const productionOperationTools = [
|
||||
['delegate_image_slots','异步分派一批图位,空闲的制作助手立即开始,其余图位顺序排队。每个 goal 写明对应屏的核心卖点与画面要证明的细节。逐图位返回接收情况及待写文案字段。生图派发后宿主继续跟踪原请求,可用 await_image_slots 查看回执。',obj({
|
||||
...outputScope,jobs:Type.Array(obj({slotId:slotRef,goal:text,reworkCandidateId:optional(Type.String({description:'返工时,指定之前被退回的候选号。'}))})),
|
||||
})],
|
||||
['await_image_slots','等待任一在途制作、验图或生图请求返回,并读取已有回执。省略 slotIds 时也关注按屏复核,结论见 screenChecks。已返回结果未知的原请求用 reconcile_image_slots 核查。可指定成品和花色,非当前可写成品直接返回已有回执和在途状态。',obj({...outputScope,slotIds:optional(ids)})],
|
||||
['review_image_slots','只读查看指定成品和花色的候选、验图、原请求、覆盖统计与整屏复核进度。默认逐图位返回状态和尝试次数。指定 slotIds 获取候选、退回原因、原请求和验图详细结论。',obj({...outputScope,slotIds:optional(Type.Array(Type.String()))})],
|
||||
['await_image_slots','等待任一在途制作、验图或生图请求返回,并读取已有回执。省略 slotIds 时也关注按屏复核,结论见 screenChecks。已返回结果未知的原请求用 reconcile_image_slots 核查。可指定成品和花色,非当前可写成品直接返回已有回执和在途状态,waiting_canvas 表示等切回可写画布。',obj({...outputScope,slotIds:optional(ids)})],
|
||||
['review_image_slots','只读查看指定成品和花色的候选、验图、原请求、覆盖统计与整屏复核进度。dispatchReady 列出关联文案已写好且尚未派发或采纳的图位;waiting_canvas 的图位在等待切回可写画布。指定 slotIds 获取候选、退回原因、原请求和验图详细结论。',obj({...outputScope,slotIds:optional(Type.Array(Type.String()))})],
|
||||
['list_project_images','列出本项目已完成且可读的候选,包括有采纳记录的图。可按来源成品和花色筛选,生图次数取自宿主已派发的记录。用候选号在当前目标图位做本地变换或复用。',obj(outputScope)],
|
||||
['read_archived_images','只读查找其他本机项目同款的历史候选。可选 slotIds 查看有对应图位的结果。不同模板或花色的已完成候选也可放入当前图位复核。',obj({
|
||||
slotIds:optional(Type.Array(Type.String())),
|
||||
@ -324,19 +324,63 @@ export async function reconcileProjectImageSlots(host,{slotIds},signal) {
|
||||
|
||||
const copyPage=field=>field.page??field.pageId;
|
||||
|
||||
const delegatePools=new WeakMap();
|
||||
|
||||
function delegatePool(host,limit){
|
||||
if(delegatePools.has(host))return delegatePools.get(host);
|
||||
const queue=[];
|
||||
let active=0;
|
||||
function startNext(){
|
||||
if(active>=limit||!queue.length)return;
|
||||
active++;
|
||||
queue.shift()();
|
||||
}
|
||||
function release(){
|
||||
active--;
|
||||
startNext();
|
||||
}
|
||||
function acquire(signal){
|
||||
signal.throwIfAborted();
|
||||
return new Promise((resolve,reject)=>{
|
||||
const start=()=>{
|
||||
signal.removeEventListener('abort',cancel);
|
||||
resolve(release);
|
||||
};
|
||||
const cancel=()=>{
|
||||
queue.splice(queue.indexOf(start),1);
|
||||
reject(signal.reason);
|
||||
};
|
||||
signal.addEventListener('abort',cancel,{once:true});
|
||||
queue.push(start);
|
||||
startNext();
|
||||
});
|
||||
}
|
||||
const pool={acquire};
|
||||
delegatePools.set(host,pool);
|
||||
return pool;
|
||||
}
|
||||
|
||||
export async function openProductionOperations(host,{target=host.productionGoal,maxActiveDelegates=6,
|
||||
maxTailWatchConcurrency=6,tailFastIntervalMs=8_000,tailSlowIntervalMs=20_000,tailFastWindowMs=180_000,
|
||||
tailWatchClock}={}) {
|
||||
if(!Number.isSafeInteger(maxActiveDelegates)||maxActiveDelegates<1)throw RangeError('图位子代理并发上限必须为正整数');
|
||||
if(!Number.isSafeInteger(maxTailWatchConcurrency)||maxTailWatchConcurrency<1)throw RangeError('原请求核查并发上限必须为正整数');
|
||||
const {canvas,store}=host;
|
||||
const pool=delegatePool(host,maxActiveDelegates);
|
||||
const {outputId,variantId}=target;
|
||||
const output={outputId,variantId};
|
||||
const runDetailAgent=(...args)=>host.runDetailAgent(...args,output);
|
||||
let canvasReady=host.productionGoal.outputId===outputId&&host.productionGoal.variantId===variantId
|
||||
? null : Promise.withResolvers();
|
||||
const canvasTasks=new Set();
|
||||
const trackCanvas=async running=>{
|
||||
canvasTasks.add(running);
|
||||
try { return await running; }
|
||||
finally { canvasTasks.delete(running); }
|
||||
};
|
||||
const scopedPlan=()=>canvas.detailHistory({projectPlan:true,targetOutput:output});
|
||||
const readSlots=async()=>{
|
||||
if(!canvasReady)return loadSlots(canvas,outputId);
|
||||
if(!canvasReady)return trackCanvas(loadSlots(canvas,outputId));
|
||||
const {slots,...plan}=await scopedPlan();
|
||||
return {plan,slots};
|
||||
};
|
||||
@ -346,6 +390,7 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
const byId=new Map(slots.map(slot=>[slot.id,slot]));
|
||||
const byField=Map.groupBy(slots,slot=>slot.fieldId);
|
||||
const binding=JSON.stringify([plan.template.contentHash,variantId]);
|
||||
const imageScope={...output,templateHash:plan.template.contentHash};
|
||||
const configuredLimit=plan.template.production?.maxGenerationAttempts;
|
||||
const hasTemplateLimit=Number.isSafeInteger(configuredLimit)&&configuredLimit>0;
|
||||
const maxGenerationAttempts=hasTemplateLimit?configuredLimit:defaultGenerationLimit;
|
||||
@ -390,48 +435,56 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
const dispatchingImages=new Map();
|
||||
const screenChecks=new Map();
|
||||
const filled=new Map(slots.filter(slot=>slot.selectedCandidateId).map(slot=>[slot.id,slot.selectedCandidateId]));
|
||||
const delegateQueue=[];
|
||||
const waitingCanvas=new Map();
|
||||
let suspendedCopy;
|
||||
const stageController=new AbortController();
|
||||
const stageSignal=host.productionSignal
|
||||
? AbortSignal.any([host.productionSignal,stageController.signal]):stageController.signal;
|
||||
const canvasTasks=new Set();
|
||||
const onCanvas=async(signal,task)=>{
|
||||
while(canvasReady&&!stageSignal.aborted)await canvasReady.promise;
|
||||
const onCanvas=async(signal,task,permit,row)=>{
|
||||
while(canvasReady&&!stageSignal.aborted){
|
||||
const step=row?.step;
|
||||
if(permit){
|
||||
waitingCanvas.set(row.slotId,row.label);
|
||||
publishWaitingCanvas();
|
||||
permit.release();
|
||||
permit.release=null;
|
||||
}
|
||||
try {
|
||||
await awaitCanvas(canvasReady.promise,signal);
|
||||
} finally {
|
||||
if(permit){
|
||||
waitingCanvas.delete(row.slotId);
|
||||
publishWaitingCanvas();
|
||||
}
|
||||
}
|
||||
if(permit){
|
||||
row.step='排队中';
|
||||
notice('图位已排队');
|
||||
permit.release=await pool.acquire(signal);
|
||||
row.step=step;
|
||||
}
|
||||
}
|
||||
stageSignal.throwIfAborted();
|
||||
signal?.throwIfAborted();
|
||||
const running=task();
|
||||
canvasTasks.add(running);
|
||||
try { return await running; }
|
||||
finally { canvasTasks.delete(running); }
|
||||
return trackCanvas(task());
|
||||
};
|
||||
stageSignal.addEventListener('abort',()=>{
|
||||
canvasReady?.resolve();
|
||||
for(const settle of delegateQueue.splice(0))settle(false);
|
||||
},{once:true});
|
||||
let activeDelegates=0;
|
||||
const startNextDelegate=()=>{
|
||||
if(stageSignal.aborted||activeDelegates>=maxActiveDelegates||!delegateQueue.length)return;
|
||||
activeDelegates++;
|
||||
delegateQueue.shift()(true);
|
||||
};
|
||||
const acquireDelegate=()=>{
|
||||
const permit=Promise.withResolvers();
|
||||
delegateQueue.push(permit.resolve);
|
||||
startNextDelegate();
|
||||
return permit.promise;
|
||||
};
|
||||
const releaseDelegate=()=>{
|
||||
activeDelegates--;
|
||||
startNextDelegate();
|
||||
};
|
||||
const scheduleDelegate=async(signal,task)=>{
|
||||
stageSignal.addEventListener('abort',()=>canvasReady?.resolve(),{once:true});
|
||||
async function awaitCanvas(ready,signal){
|
||||
if(!signal)return ready;
|
||||
signal.throwIfAborted();
|
||||
const acquired=await acquireDelegate();
|
||||
const aborted=Promise.withResolvers();
|
||||
const cancel=()=>aborted.reject(signal.reason);
|
||||
signal.addEventListener('abort',cancel,{once:true});
|
||||
try { await Promise.race([ready,aborted.promise]); }
|
||||
finally { signal.removeEventListener('abort',cancel); }
|
||||
}
|
||||
const scheduleDelegate=async(signal,task)=>{
|
||||
const permit={release:await pool.acquire(signal)};
|
||||
try{
|
||||
signal.throwIfAborted();
|
||||
return await task();
|
||||
return await task(permit);
|
||||
}finally{
|
||||
if(acquired)releaseDelegate();
|
||||
permit.release?.();
|
||||
}
|
||||
};
|
||||
const slotWorking=id=>[...jobs.values()].some(job=>job.row.slotId===id);
|
||||
@ -483,7 +536,7 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
candidates:slot.candidates??[],
|
||||
reason:`该图位已用完 ${maxGenerationAttempts} 次生图额度。来源:${generationLimitSource}。`,
|
||||
});
|
||||
const readPlan=()=>canvasReady?scopedPlan():canvas.workflowRead({section:'overview',outputId});
|
||||
const readPlan=()=>canvasReady?scopedPlan():trackCanvas(canvas.workflowRead({section:'overview',outputId}));
|
||||
const current=async({refresh=false}={})=>{
|
||||
const value=await readPlan();
|
||||
if(value.outputId!==outputId||value.productVariantId!==variantId||
|
||||
@ -504,18 +557,23 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
};
|
||||
const copySnapshot=async(options={})=>{
|
||||
if(canvasReady)return {};
|
||||
const snapshot=await canvas.detailCopyFields?.({includeFilled:true,...options});
|
||||
const snapshot=await trackCanvas(canvas.detailCopyFields?.({includeFilled:true,...options}));
|
||||
return Array.isArray(snapshot)?{fields:snapshot}:snapshot??{};
|
||||
};
|
||||
const pendingCopyBySlot=async selected=>{
|
||||
const linked=selected.filter(slot=>slot.relatedFields?.length);
|
||||
if(canvasReady||!linked.length)return new Map();
|
||||
const pending=await canvas.detailCopyFields({includeFilled:false});
|
||||
if(!linked.length)return new Map();
|
||||
const pending=canvasReady?(await suspendedCopy)?.pending:await trackCanvas(canvas.detailCopyFields({includeFilled:false}));
|
||||
if(!pending)return new Map();
|
||||
return new Map(linked.map(slot=>[slot.id,pending.filter(row=>slot.relatedFields.includes(row.field))
|
||||
.map(({field,label,currentText})=>({fieldId:field,label,currentText}))]));
|
||||
};
|
||||
const dispatchReady=(selected,pending)=>selected.filter(slot=>
|
||||
(!slot.relatedFields?.length||pending.has(slot.id)&&!pending.get(slot.id).length)
|
||||
&& !slotWorking(slot.id)&&!slot.selectedCandidateId&&!(canvasReady&&filled.has(slot.id))
|
||||
&& !nativeGenerations(slot).length).map(({fieldId,label})=>({fieldId,label}));
|
||||
const liveSlotCopy=async slot=>{
|
||||
const {fields:copyFields}=await copySnapshot();
|
||||
const {fields:copyFields}=(canvasReady?(await suspendedCopy)?.snapshot:await copySnapshot())??{};
|
||||
const journalCopy=Object.values(evidenceMatches(plan)?journal.copyEvidence??{}:{});
|
||||
return resolveLiveSlotCopy({slot,copyFields,journalCopy});
|
||||
};
|
||||
@ -584,14 +642,20 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
};
|
||||
const display=new PresentationBatch(progress);
|
||||
const notice=heading=>{if(!stageSignal.aborted)return display.push({heading,epoch:displayEpoch});};
|
||||
const waitingDisplay=new PresentationBatch(async()=>
|
||||
host.canvasEndAttempted||stageSignal.aborted?undefined:
|
||||
canvas.delta('',undefined,{...output,waitingCanvas:waitingCanvas.size}));
|
||||
const publishWaitingCanvas=()=>waitingDisplay.push(true);
|
||||
const readImages=(slotId,args={})=>{
|
||||
const candidateId=args.candidateId?.trim()||undefined;
|
||||
return canvas.detailImages(matches(slotId).id,candidateId,{
|
||||
...(canvasReady?{targetOutput:output}:null),
|
||||
const background=Boolean(canvasReady);
|
||||
const images=canvas.detailImages(matches(slotId).id,candidateId,{
|
||||
...(background?{targetOutput:output}:null),
|
||||
...(args.adopted?{adopted:true}:null),...(candidateId?{inspectCandidate:true}:null),
|
||||
...(args.includeProductReferences===false?{includeProductReferences:false}:null),
|
||||
...(args.includeTemplateReference===false?{includeTemplateReference:false}:null),
|
||||
});
|
||||
return background?images:trackCanvas(images);
|
||||
};
|
||||
async function operate(slot,intent,values,signal,attempt) {
|
||||
const scope=new CanvasOperations();
|
||||
@ -685,7 +749,8 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
if(status.drawLimitReached)return drawLimit(live,status);
|
||||
const receipt=await canvas.imageRequest('prepare',{slotId:slot.id,instructions:prompt,retryOf:retryOf?.trim()||undefined,useTemplateReference,
|
||||
prefer2k,geometryReferenceIndex,reworkOf:reworkCandidateId,reworkChange,
|
||||
...(referenceIndexes?{referenceIndexes}:null),...(useSceneComposite!==undefined?{useSceneComposite}:null)}).catch(async error=>{
|
||||
...(referenceIndexes?{referenceIndexes}:null),...(useSceneComposite!==undefined?{useSceneComposite}:null)},
|
||||
undefined,imageScope).catch(async error=>{
|
||||
if(error.message!=='同款原图编号无效')throw error;
|
||||
const {referenceCount}=await readImages(slot.id,{includeTemplateReference:false});
|
||||
const range=referenceCount ? `可用编号 0–${referenceCount-1}` : '当前没有同款原图';
|
||||
@ -695,7 +760,7 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
return {...receipt,operationId:receipt.requestId};
|
||||
};
|
||||
const preparedRequest=async(requestId,slot)=>{
|
||||
const receipt=await canvas.imageRequest('read',{requestId});
|
||||
const receipt=await canvas.imageRequest('read',{requestId},undefined,imageScope);
|
||||
if(receipt.requestId!==requestId||receipt.templateHash!==plan.template.contentHash||
|
||||
receipt.outputId!==outputId||receipt.variantId!==variantId){
|
||||
throw Error(`requestId ${JSON.stringify(requestId)} 不属于当前模板、成品或花色,请使用当前画布生图准备回执中的 requestId`);
|
||||
@ -707,7 +772,7 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
const {requestId:candidateId}=approval;
|
||||
const receipt=await canvas.imageRequest('dispatch',{requestId:candidateId,slotId:slot.id,workerNumber,
|
||||
expectedRevision:approval.expectedRevision??request.revision,expectedHash:approval.expectedHash??request.requestSpecHash},
|
||||
{operationId:candidateId,requestId:candidateId,onEnqueued});
|
||||
{operationId:candidateId,requestId:candidateId,onEnqueued},imageScope);
|
||||
if(host.productionSignal?.aborted)return {candidateId,operationId:candidateId,phase:'cancelled'};
|
||||
const phase=receipt.status??receipt.phase;
|
||||
return {candidateId,operationId:candidateId,phase:phase==='running'?'unknown':phase,reason:receipt.message,
|
||||
@ -842,7 +907,7 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
const readCanvas={detailImages:(id,candidate,options)=>canvas.detailImages(id,candidate,{
|
||||
...options,...(canvasReady?{targetOutput:output}:null),
|
||||
})};
|
||||
const {referenceCount,...review}=await reviewProductionCandidate({canvas:readCanvas,runAgent:host.runDetailAgent,
|
||||
const {referenceCount,...review}=await reviewProductionCandidate({canvas:readCanvas,runAgent:runDetailAgent,
|
||||
slot,candidateId,signal,liveScreenCopy,rule:slot.productionRule,source,adopted});
|
||||
const {verdict,checks,reason,observation,recommendedAction,canvasTransform}=review;
|
||||
const row={candidateId,decision:verdict,checks,reason,observation,original:review.original,recommendedAction,canvasTransform,
|
||||
@ -872,9 +937,20 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
canvasReady??=Promise.withResolvers();
|
||||
displayEpoch++;
|
||||
tailWatcher.refresh();
|
||||
await Promise.allSettled(canvasTasks);
|
||||
await canvasWrite;
|
||||
await journalWrite;
|
||||
suspendedCopy=(async()=>{
|
||||
await Promise.allSettled(canvasTasks);
|
||||
await canvasWrite;
|
||||
await journalWrite;
|
||||
const [{slots:leavingSlots},snapshot,pending]=await Promise.all([
|
||||
loadSlots(canvas,outputId),
|
||||
canvas.detailCopyFields?.({includeFilled:true}),
|
||||
slots.some(slot=>slot.relatedFields?.length)?canvas.detailCopyFields({includeFilled:false}):undefined,
|
||||
]);
|
||||
filled.clear();
|
||||
for(const slot of leavingSlots)if(slot.selectedCandidateId)filled.set(slot.id,slot.selectedCandidateId);
|
||||
return {snapshot:Array.isArray(snapshot)?{fields:snapshot}:snapshot,pending};
|
||||
})();
|
||||
await suspendedCopy;
|
||||
await Promise.all([...dispatchingImages.values()].map(job=>job?.enqueued));
|
||||
return (await outstanding()).originals.images;
|
||||
},
|
||||
@ -889,6 +965,7 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
},
|
||||
workStatus(originals){
|
||||
return {...output,slots:[...new Set(running().map(job=>job.row.slotId))],
|
||||
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)};
|
||||
@ -932,14 +1009,16 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
const {generationAttempts,remainingGenerationAttempts,drawLimitReached}=statuses.get(id);
|
||||
return {id,fieldId,label,generationAttempts,remainingGenerationAttempts,drawLimitReached,
|
||||
filled:canvasReady?undefined:Boolean(selectedCandidateId),
|
||||
completedCandidates:candidates?.filter(row=>row.status==='complete').length??0,copyReady:canvasReady?undefined:!pendingCopy.get(id)?.length,
|
||||
completedCandidates:candidates?.filter(row=>row.status==='complete').length??0,
|
||||
copyReady:!slot.relatedFields?.length||pendingCopy.has(id)?!pendingCopy.get(id)?.length:undefined,
|
||||
...(requested.size?{productionRule,requirements,sourcePolicy}:null)};
|
||||
});
|
||||
const {production,skillSources,resourceSetId,...template}=plan.template;
|
||||
const {outputId:workingOutputId,variantId:workingVariantId}=host.productionGoal;
|
||||
return {outputId,variantId,workingOutput:workingOutputId?{outputId:workingOutputId,variantId:workingVariantId}:null,
|
||||
template,product:{name,dimensions,note,variant:variant&&{id:variant.id,colorName:variant.colorName}},
|
||||
maxGenerationAttempts,generationLimitSource,pictures,inFlightImages:(await pendingNative()).map(row=>row.candidateId),
|
||||
maxGenerationAttempts,generationLimitSource,pictures,dispatchReady:dispatchReady(selected,pendingCopy),
|
||||
inFlightImages:(await pendingNative()).map(row=>row.candidateId),
|
||||
...(includeKnowledge?{knowledgeFiles:host.productionSkills?.files??[]}:null),
|
||||
...(host.productionSkills?.versionNotice?{knowledgeVersionNotice:host.productionSkills.versionNotice}:null),
|
||||
requestedOutputs:host.productionGoal.requestedOutputs,
|
||||
@ -958,7 +1037,8 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
write_copy_fields({revision,recordOnly,items=[]},signal){
|
||||
return serialize(async()=>{
|
||||
const noUpdates={total:0,truncated:false,items:[]};
|
||||
if(!items.length)return {appliedLayers:[],revision:(await canvas.read()).revision,copyUpdates:noUpdates};
|
||||
const ready=async()=>dispatchReady(await liveSlots(),await pendingCopyBySlot(slots));
|
||||
if(!items.length)return {appliedLayers:[],revision:(await canvas.read()).revision,copyUpdates:noUpdates,dispatchReady:await ready()};
|
||||
const layers=new Set();
|
||||
for(const {layer} of items){
|
||||
if(!Number.isSafeInteger(layer)||layer<1)throw Error(`无效的文字格 layer ${layer},请使用文案读取回执中的编号`);
|
||||
@ -970,7 +1050,7 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
if(!recordOnly){
|
||||
const edits=items.map(({layer,text,expectedText})=>({layer,text,...(expectedText===undefined?null:{expectedText})}));
|
||||
result=await canvas.commitDetailCopy(edits,revision,signal);
|
||||
if(result.retryWrite || !result.appliedLayers?.length)return {...result,appliedLayers:[],copyUpdates:noUpdates};
|
||||
if(result.retryWrite || !result.appliedLayers?.length)return {...result,appliedLayers:[],copyUpdates:noUpdates,dispatchReady:await ready()};
|
||||
}
|
||||
return await registerCopy(result);
|
||||
|
||||
@ -1002,7 +1082,7 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
return copyUpdateItem(field,row.text);
|
||||
}),
|
||||
};
|
||||
return {...result,appliedLayers:applied.map(row=>row.layer),revision:snapshot.revision,copyUpdates};
|
||||
return {...result,appliedLayers:applied.map(row=>row.layer),revision:snapshot.revision,copyUpdates,dispatchReady:await ready()};
|
||||
}
|
||||
});
|
||||
},
|
||||
@ -1075,15 +1155,15 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
},
|
||||
};
|
||||
};
|
||||
const makeTools=()=>[
|
||||
const makeTools=permit=>[
|
||||
workerTool('use_product_image','用本款实拍创建图位候选',productImageArgs,
|
||||
(args,activeSignal)=>onCanvas(activeSignal,()=>useProductImage(slot,args,activeSignal)),true),
|
||||
(args,activeSignal)=>onCanvas(activeSignal,()=>useProductImage(slot,args,activeSignal),permit,row),true),
|
||||
workerTool('transform_slot_image','用本款实拍或本项目候选裁切、镜像、旋转、缩放或位移',transformImageArgs,
|
||||
(args,activeSignal)=>onCanvas(activeSignal,()=>serialize(()=>transformImage(slot,args,activeSignal)))),
|
||||
(args,activeSignal)=>onCanvas(activeSignal,()=>serialize(()=>transformImage(slot,args,activeSignal)),permit,row)),
|
||||
workerTool('prepare_image_request','准备并持久保存完整生图请求。',preparationArgs,
|
||||
(args,activeSignal)=>onCanvas(activeSignal,()=>prepareImageRequest(slot,{...args,reworkCandidateId:rework?.candidateId},activeSignal))),
|
||||
(args,activeSignal)=>prepareImageRequest(slot,{...args,reworkCandidateId:rework?.candidateId},activeSignal)),
|
||||
workerTool('dispatch_image_request','审阅准备回执后填写 requestId 确认派发',dispatchArgs,
|
||||
(approval,activeSignal)=>onCanvas(activeSignal,async()=>{
|
||||
async(approval,activeSignal)=>{
|
||||
const request=await preparedRequest(approval.requestId,slot).catch(error=>{
|
||||
throw Error(`requestId ${JSON.stringify(approval.requestId)},slotId ${JSON.stringify(slot.id)}。请核对当前图位的生图准备回执。原因:${error.message}`,{cause:error});
|
||||
});
|
||||
@ -1101,14 +1181,14 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
if(receipt.operationId)dispatched.add(receipt.operationId);
|
||||
await dispatchingImages.get(receipt.operationId)?.enqueued;
|
||||
return receipt;
|
||||
}),result=>!result.limitReached),
|
||||
},result=>!result.limitReached),
|
||||
];
|
||||
const readTool={name:'read_slot_images',label:'查看本图位实拍与构图',description:'读取本图位的原片与模板构图。',
|
||||
parameters:obj({}),execute:async()=>{
|
||||
delegateSignal.throwIfAborted();
|
||||
return imageResult(await readImages(slot.id));
|
||||
}};
|
||||
const run=scheduleDelegate(delegateSignal,async()=>{
|
||||
const run=scheduleDelegate(delegateSignal,async permit=>{
|
||||
row.step='正在准备';
|
||||
notice('子代理正在制作');
|
||||
const prior=journal.items[slot.id];
|
||||
@ -1141,8 +1221,8 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
(rework?'\n先看随消息附上的退回图、验图回执和上次实发提示词。按发布规则处理,用 reworkChange 记录改动。':'');
|
||||
const screenCopy=await liveSlotCopy(slot);
|
||||
delegateSignal.throwIfAborted();
|
||||
await host.runDetailAgent(slot.id,instructions,
|
||||
JSON.stringify({rework,goal,screenCopy,...status,field:slot.fieldId,label:slot.label,rule:slot.productionRule,requirements:slot.requirements}),[readTool,...makeTools()],
|
||||
await runDetailAgent(slot.id,instructions,
|
||||
JSON.stringify({rework,goal,screenCopy,...status,field:slot.fieldId,label:slot.label,rule:slot.productionRule,requirements:slot.requirements}),[readTool,...makeTools(permit)],
|
||||
rejectedImage?[rejectedImage]:[],productRequestScope('slot',slot.id),undefined,delegateSignal);
|
||||
if(!produced)generation.set(workerId,{slotId:slot.id,phase:'no_candidate'});
|
||||
}).catch(async error=>{
|
||||
@ -1160,7 +1240,7 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
jobs.set(workerId,{row,run,dispatched});
|
||||
assigned.push({id:slot.id,state:'assigned',...status});
|
||||
}
|
||||
if(delegateQueue.length)notice('图位已排队');
|
||||
if(assigned.some(row=>row.state==='assigned'))notice('图位已排队');
|
||||
return {assigned,...(unmatched.length?{unmatched}:null),
|
||||
...(assigned.some(row=>row.pendingCopyFields)?{copyContext:'子代理按本屏实时已写文案理解卖点和验图。待写字段仍为模板原文或空白,写进 goal 的模板原文会作为制作要求传给子代理。'}:null)};
|
||||
},
|
||||
@ -1169,15 +1249,16 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
const selected=running().filter(job=>wanted.has(job.row.slotId));
|
||||
const scope=slotIds?.length||!selected.length?wanted:new Set(selected.map(job=>job.row.slotId));
|
||||
const screens=slotIds?.length?[]:[...screenChecks.values()];
|
||||
const pending=[...selected,...screens.filter(job=>job.run)].map(job=>job.run);
|
||||
const pending=[...selected.filter(job=>!waitingCanvas.has(job.row.slotId)),...screens.filter(job=>job.run)].map(job=>job.run);
|
||||
const receipt=pending.length&&!canvasReady?await Promise.race(pending):undefined;
|
||||
const native=(await liveSlots()).filter(slot=>scope.has(slot.id)).flatMap(slot=>
|
||||
(slot.candidates??[]).filter(row=>!row.sourceType&&!row.reusedFrom).map(row=>
|
||||
({...row,slotId:slot.id,candidateId:row.id,operationId:row.id,phase:row.status,reason:row.message??row.error})))
|
||||
.sort((a,b)=>(b.sequence??0)-(a.sequence??0));
|
||||
const completed=receipt?.operationId&&scope.has(receipt.slotId)?[receipt]:[];
|
||||
const waiting=[...waitingCanvas.keys()].filter(id=>wanted.has(id)).map(slotId=>({slotId,phase:'waiting_canvas'}));
|
||||
return {...output,active:jobs.size,checking:pendingReviews().length,
|
||||
generation:[...completed,...generationReceipts(scope),...native.filter(row=>row.candidateId!==completed[0]?.candidateId)],
|
||||
generation:[...waiting,...completed,...generationReceipts(scope),...native.filter(row=>row.candidateId!==completed[0]?.candidateId)],
|
||||
checks:[...reviewWork].filter(job=>scope.has(job.row.slotId)).map(job=>job.receipt),
|
||||
...(screens.length?{screenChecks:screens.map(job=>job.receipt)}:null)};
|
||||
},
|
||||
@ -1200,6 +1281,7 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
const selected=live.filter(slot=>!requested.size||matched.has(slot.id));
|
||||
const statuses=drawStatuses(selected);
|
||||
return {outputId,variantId,active:jobs.size,coverage,progressSummary:await progressSummary(),
|
||||
dispatchReady:dispatchReady(selected,await pendingCopyBySlot(selected)),
|
||||
pictures:selected.map(slot=>{
|
||||
const {id,fieldId,label,selectedCandidateId,candidates}=slot;
|
||||
const record=journal.items[id];
|
||||
@ -1216,10 +1298,11 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
const latestCandidateId=latest?.id??generationReceipt?.candidateId??record?.candidateId;
|
||||
const reviews=checks.get(id)??[];
|
||||
if(requested.size)return {id,fieldId,label,selectedCandidateId,attemptCount,...status,rejections,candidates,working:slotWorking(id),
|
||||
...(waitingCanvas.has(id)?{state:'waiting_canvas'}:null),
|
||||
record,generation:generationReceipt,...(generations.length>1?{generations}:null),checks:reviews.map(job=>job.receipt)};
|
||||
const decision=record?.review?.candidateId===latestCandidateId?record?.review?.decision:undefined;
|
||||
const adopted=selectedCandidateId&&selectedCandidateId===latestCandidateId;
|
||||
const state=slotWorking(id)?'generating':reviews.some(job=>job.run)?'checking':
|
||||
const state=waitingCanvas.has(id)?'waiting_canvas':slotWorking(id)?'generating':reviews.some(job=>job.run)?'checking':
|
||||
slotOriginals(record).length?'unknown':
|
||||
adopted?'applied':
|
||||
decision??generationReceipt?.phase??latest?.status??record?.state??'empty';
|
||||
@ -1406,7 +1489,7 @@ export async function openProductionOperations(host,{target=host.productionGoal,
|
||||
const screen=await onCanvas(activeSignal,()=>operations.read_output_screen({page:page-1},activeSignal));
|
||||
const screenSlots=slots.filter(slot=>screen.details.fields?.includes(slot.fieldId))
|
||||
.map(({id,fieldId,label,nativeLayerId})=>({id,fieldId,label,nativeLayerId}));
|
||||
const receipt=await reviewOutputScreen({runAgent:host.runDetailAgent,page,screen,references,
|
||||
const receipt=await reviewOutputScreen({runAgent:runDetailAgent,page,screen,references,
|
||||
slots:screenSlots,outputId,variantId,signal:activeSignal});
|
||||
job.inputSignature=(await references()).inputSignature;
|
||||
if(receipt.verdict==='pass'){
|
||||
|
||||
@ -88,7 +88,11 @@ export class StdioCanvas {
|
||||
return receipt;
|
||||
}
|
||||
readCanvas(input = {}) { return this.action('pi-canvas-read', input); }
|
||||
imageRequest(action,request,execution) { return this.action('pi-image-request',{action,request},execution); }
|
||||
imageRequest(action,request,execution,targetOutput) {
|
||||
if(targetOutput||action==='pending')
|
||||
return this.call('pi-image-request',{action,request,targetOutput,run:this.run,documentId:this.documentId},execution);
|
||||
return this.action('pi-image-request',{action,request},execution);
|
||||
}
|
||||
detailRender(options) { return this.#observe('pi-product-screen', options); }
|
||||
detailCopyFields(options) { return this.#observe('pi-detail-copy-fields', options); }
|
||||
detailApplyCopy(items,revision) { return this.action('pi-detail-copy-apply',{items,revision}); }
|
||||
@ -128,6 +132,8 @@ export class StdioCanvas {
|
||||
uiCancel(id) { return this.action('pi-ui-cancel', { id }); }
|
||||
async delta(text, thinking, production, output) {
|
||||
try {
|
||||
if(typeof production?.waitingCanvas==='number')
|
||||
return await this.call('pi-delta',{text,production,run:this.run,documentId:this.documentId});
|
||||
return await this.action('pi-delta',{text,...(thinking===undefined?{}:{thinking}),...(production?{production}:{}),...(output?{output}:{})});
|
||||
} catch(error) {
|
||||
if(!production||!canvasReplyTimedOut(error))throw error;
|
||||
|
||||
@ -832,6 +832,33 @@ test('a worker can change course after many identical calls without terminating'
|
||||
assert.equal(x.requests.length,10);
|
||||
});
|
||||
|
||||
test('worker tool events retain their output and variant after the working canvas changes',async t=>{
|
||||
const x=await setup(()=>sse({tool_calls:[{index:0,id:'scope-worker',type:'function',
|
||||
function:{name:'prepare_image_request',arguments:'{}'}}]},'tool_calls'),undefined,undefined,{canvas:{}});
|
||||
t.after(x.close);
|
||||
const detail={outputId:'detail',variantId:randomUUID()};
|
||||
const main={outputId:'main_images',variantId:randomUUID()};
|
||||
x.host.activityScope=main;
|
||||
x.store.executionScope=main;
|
||||
const recorded=Promise.withResolvers();
|
||||
const append=x.store.appendEvent.bind(x.store);
|
||||
x.store.appendEvent=async event=>{
|
||||
await append(event);
|
||||
if(event.type==='tool_execution_end')recorded.resolve();
|
||||
};
|
||||
const tool={name:'prepare_image_request',label:'准备生图',description:'准备生图',parameters:{type:'object',properties:{}},
|
||||
async execute(){
|
||||
x.host.activityScope={outputId:'sku_images',variantId:randomUUID()};
|
||||
return {content:[{type:'text',text:'准备完成'}],terminate:true};
|
||||
}};
|
||||
await x.host.runDetailAgent('slot-a','Inspect.','Prepare.',[tool],[],'product/slot/slot-a',undefined,undefined,detail);
|
||||
await recorded.promise;
|
||||
const events=(await fs.readFile(path.join(x.store.dir,'events.jsonl'),'utf8')).trim().split('\n').map(line=>JSON.parse(line));
|
||||
const worker=events.filter(event=>event.toolCallId==='scope-worker');
|
||||
assert.equal(worker.length,2);
|
||||
assert.ok(worker.every(event=>event.outputId===detail.outputId && event.variantId===detail.variantId));
|
||||
});
|
||||
|
||||
test('a retryable response at the worker limit does not trigger another Pi request',async t=>{
|
||||
const x=await setup((_payload,round)=>{
|
||||
if(round>=WORKER_TURN_LIMIT)return new Response('overloaded',{status:503});
|
||||
|
||||
@ -328,7 +328,7 @@ test('explicit tools share one Pi transcript and submit each real canvas revisio
|
||||
assert.match(instructions,/由你决定[^。]*顺序、并行和返工/);
|
||||
assert.match(instructions,/命令行编修可用等价的画布命令完成/);
|
||||
const write=context.messages.find(message=>message.role==='toolResult'&&message.toolName==='write_copy_fields');
|
||||
if(write)assert.deepEqual(JSON.parse(write.content[0].text),{appliedLayers:[1],revision:8});
|
||||
if(write)assert.deepEqual(JSON.parse(write.content[0].text),{appliedLayers:[1],revision:8,dispatchReady:[]});
|
||||
const call=steps.shift();
|
||||
return call?stream([{type:'toolCall',name:call[0],id:'tool-'+(++serial),arguments:call[1]??{}}]):
|
||||
stream([{type:'text',text:'当前进展已记在项目里。'}]);
|
||||
|
||||
@ -42,7 +42,7 @@ function imageBridge(host,dispatch,id=()=>randomUUID()) {
|
||||
if(receipt)settle(receipt,result);
|
||||
return result;
|
||||
};
|
||||
canvas.imageRequest=async(action,args,execution)=>{
|
||||
canvas.imageRequest=async(action,args,execution,targetOutput)=>{
|
||||
if(action==='pending')return [...prepared.values()].filter(({receipt})=>
|
||||
['dispatched','running','unknown'].includes(receipt.phase)).map(({receipt})=>({
|
||||
slotId:receipt.slotId,candidateId:receipt.requestId,operationId:receipt.requestId,
|
||||
@ -50,15 +50,18 @@ function imageBridge(host,dispatch,id=()=>randomUUID()) {
|
||||
}));
|
||||
if(action==='prepare'){
|
||||
const requestId=id();
|
||||
const {outputId,variantId}=targetOutput??host.productionGoal;
|
||||
const receipt={requestId,revision:1,requestSpecHash:'fixture-digest',frozen:false,phase:'prepared',
|
||||
templateHash:(await workflowRead({section:'overview',outputId:host.productionGoal.outputId})).template.contentHash,
|
||||
outputId:host.productionGoal.outputId,variantId:host.productionGoal.variantId,slotId:args.slotId,
|
||||
templateHash:targetOutput?.templateHash??(await workflowRead({section:'overview',outputId})).template.contentHash,
|
||||
outputId,variantId,slotId:args.slotId,
|
||||
reworkOf:args.reworkOf,reworkChange:args.reworkChange,spec:{prompt:args.instructions}};
|
||||
prepared.set(requestId,{receipt,args});
|
||||
return structuredClone(receipt);
|
||||
}
|
||||
const request=prepared.get(args.requestId);
|
||||
if(!request)throw Error('未找到原生生图请求');
|
||||
if(targetOutput)for(const key of ['outputId','variantId','templateHash'])
|
||||
assert.equal(request.receipt[key],targetOutput[key]);
|
||||
if(action==='read')return structuredClone(request.receipt);
|
||||
assert.equal(action,'dispatch');
|
||||
assert.equal(args.slotId,request.receipt.slotId);
|
||||
@ -597,6 +600,118 @@ test('switch keeps other output workers and their original requests without wait
|
||||
await closeProductionTurn(host);
|
||||
});
|
||||
|
||||
test('a switched-away worker prepares and dispatches under its original output and copy', {timeout:5000}, async t=>{
|
||||
const {host}=await tailFixture(t,[]);
|
||||
const detail={outputId:'detail',variantId:'oak'};
|
||||
const main={outputId:'main_images',variantId:'oak'};
|
||||
const slot={id:'detail-slot',fieldId:'S01-I01',label:'首屏',documentId:'S01',relatedFields:['title']};
|
||||
const queued={...slot,id:'queued-slot',fieldId:'S01-I02',label:'另一张首屏图'};
|
||||
const view=outputId=>({available:true,canvasFirst:true,outputId,productVariantId:'oak',
|
||||
template:{contentHash:outputId},totalSlots:outputId==='detail'?2:0,slots:outputId==='detail'?[slot,queued]:[]});
|
||||
const started=Promise.withResolvers(), proceed=Promise.withResolvers(), posted=Promise.withResolvers(), queuedCopy=Promise.withResolvers();
|
||||
host.productionGoal.requestedOutputs=[detail,main];
|
||||
host.bindGoalRequestScope=()=>{};
|
||||
host.canvas.openProductionOutput=async target=>target;
|
||||
host.canvas.workflowRead=async()=>view(host.productionGoal.outputId);
|
||||
host.canvas.detailHistory=async({targetOutput})=>view(targetOutput.outputId);
|
||||
host.canvas.detailCopyFields=async({includeFilled})=>includeFilled?{fields:[
|
||||
{field:'title',page:'S01',currentText:host.productionGoal.outputId==='detail'?'榫接结构':'另一成品'},
|
||||
]}:[];
|
||||
const {prepared}=imageBridge(host,async({slotId,instructions},id)=>{
|
||||
posted.resolve({slotId,instructions,id});
|
||||
return {status:'complete'};
|
||||
});
|
||||
host.runDetailAgent=async(slotId,_system,prompt,tools,_images,_scope,_captions,_signal,output)=>{
|
||||
if(slotId===queued.id){
|
||||
queuedCopy.resolve(JSON.parse(prompt).screenCopy.map(row=>row.text));
|
||||
return;
|
||||
}
|
||||
started.resolve({prompt:JSON.parse(prompt),output});
|
||||
await proceed.promise;
|
||||
const prepare=tools.find(tool=>tool.name==='prepare_image_request');
|
||||
const dispatch=tools.find(tool=>tool.name==='dispatch_image_request');
|
||||
const result=await prepare.execute('',{prompt:'呈现榫接结构'});
|
||||
await dispatch.execute('',approve(result.details));
|
||||
};
|
||||
const operations=await openProductionOperations(host,{maxActiveDelegates:1});
|
||||
host.productionWork=new Map([[JSON.stringify(['detail','oak']),Promise.resolve(operations)]]);
|
||||
t.after(async()=>{proceed.resolve();await closeProductionTurn(host);});
|
||||
await callProductionTool(host,'delegate_image_slots',{jobs:[slot,queued].map(({fieldId})=>({slotId:fieldId,goal:'展示卖点'}))});
|
||||
const worker=await started.promise;
|
||||
assert.deepEqual(worker.output,detail);
|
||||
assert.deepEqual(worker.prompt.screenCopy.map(row=>row.text),['榫接结构']);
|
||||
await callProductionTool(host,'open_production_output',main);
|
||||
assert.deepEqual((await callProductionTool(host,'review_image_slots',detail)).dispatchReady,[]);
|
||||
proceed.resolve();
|
||||
const {slotId,instructions,id}=await posted.promise;
|
||||
assert.deepEqual({slotId,instructions},{slotId:slot.id,instructions:'呈现榫接结构'});
|
||||
assert.deepEqual(host.productionGoal.outputId,main.outputId);
|
||||
assert.equal(prepared.get(id).receipt.outputId,detail.outputId);
|
||||
assert.equal(prepared.get(id).receipt.variantId,detail.variantId);
|
||||
assert.deepEqual(await queuedCopy.promise,['榫接结构']);
|
||||
});
|
||||
|
||||
test('one six-worker pool spans all outputs and admits another worker when a canvas write waits', {timeout:5000}, async t=>{
|
||||
const {host}=await tailFixture(t,[]);
|
||||
const outputs=['detail','main_images','sku_images'].map(outputId=>({outputId,variantId:'oak'}));
|
||||
host.productionGoal.requestedOutputs=outputs;
|
||||
host.bindGoalRequestScope=()=>{};
|
||||
const started=[], enter=new Map(), release=new Map();
|
||||
const drafts=new Map(outputs.map(({outputId},index)=>[outputId,Array.from({length:index===0?4:3},(_,n)=>{
|
||||
const id=outputId+'-'+n;
|
||||
enter.set(id,Promise.withResolvers());
|
||||
release.set(id,Promise.withResolvers());
|
||||
return {id,fieldId:id,label:id};
|
||||
})]));
|
||||
host.canvas.openProductionOutput=async target=>target;
|
||||
const view=outputId=>({available:true,canvasFirst:true,outputId,productVariantId:'oak',
|
||||
template:{contentHash:outputId},totalSlots:drafts.get(outputId).length,slots:drafts.get(outputId)});
|
||||
host.canvas.workflowRead=async()=>view(host.productionGoal.outputId);
|
||||
host.canvas.detailHistory=async({targetOutput})=>view(targetOutput.outputId);
|
||||
const waitShown=Promise.withResolvers(), waitCleared=Promise.withResolvers(), transform=Promise.withResolvers();
|
||||
host.canvas.delta=async(_text,_thinking,progress)=>{
|
||||
if(progress.outputId==='detail'&&progress.waitingCanvas===1)waitShown.resolve();
|
||||
if(progress.outputId==='detail'&&progress.waitingCanvas===0)waitCleared.resolve();
|
||||
};
|
||||
host.canvas.imageRequest=async(action,args)=>{
|
||||
if(action==='pending')return [];
|
||||
assert.equal(action,'transform');
|
||||
assert.equal(host.productionGoal.outputId,'detail');
|
||||
transform.resolve(args.slotId);
|
||||
return {id:'transformed',status:'complete'};
|
||||
};
|
||||
host.runDetailAgent=async(id,_system,_prompt,tools)=>{
|
||||
started.push(id);
|
||||
enter.get(id).resolve();
|
||||
await release.get(id).promise;
|
||||
if(id==='detail-0')await tools.find(tool=>tool.name==='transform_slot_image')
|
||||
.execute('',{sourceCandidateId:'original',flipX:true});
|
||||
};
|
||||
t.after(async()=>{release.forEach(gate=>gate.resolve());await closeProductionTurn(host);});
|
||||
for(const output of outputs){
|
||||
await callProductionTool(host,'open_production_output',output);
|
||||
await callProductionTool(host,'delegate_image_slots',{jobs:drafts.get(output.outputId).map(({id})=>({slotId:id,goal:'展示实拍'}))});
|
||||
}
|
||||
await enter.get('main_images-1').promise;
|
||||
assert.deepEqual(started,['detail-0','detail-1','detail-2','detail-3','main_images-0','main_images-1']);
|
||||
release.get('detail-0').resolve();
|
||||
await waitShown.promise;
|
||||
await enter.get('main_images-2').promise;
|
||||
const waiting={slotId:'detail-0',phase:'waiting_canvas'};
|
||||
assert.equal((await callProductionTool(host,'review_image_slots',{...outputs[0],slotIds:['detail-0']})).pictures[0].state,waiting.phase);
|
||||
assert.deepEqual((await callProductionTool(host,'await_image_slots',{...outputs[0],slotIds:['detail-0']})).generation,[waiting]);
|
||||
const switched=await callProductionTool(host,'open_production_output',outputs[1]);
|
||||
assert.deepEqual(switched.work.find(row=>row.outputId==='detail').waitingCanvas,[{fieldId:'detail-0',label:'detail-0'}]);
|
||||
await callProductionTool(host,'open_production_output',outputs[0]);
|
||||
await waitCleared.promise;
|
||||
for(let n=0;n<3;n++){
|
||||
release.get('detail-'+(n+1)).resolve();
|
||||
await enter.get('sku_images-'+n).promise;
|
||||
}
|
||||
release.get('sku_images-0').resolve();
|
||||
assert.equal(await transform.promise,'detail-0');
|
||||
});
|
||||
|
||||
test('project image discovery can stage a completed image on another output without generation',async t=>{
|
||||
const {host}=await tailFixture(t,['target']);
|
||||
const source={outputId:'main_images',variantId:'oak'};
|
||||
@ -926,9 +1041,9 @@ test('a malformed slot reference does not strand the other explicitly delegated
|
||||
test('plans and delegate receipts report only linked pending copy and enqueue every requested slot',async t=>{
|
||||
const {host}=await tailFixture(t,[]);
|
||||
const slots=[
|
||||
{id:'front',fieldId:'front-image',documentId:'front',relatedFields:['title','tagline','detail-image']},
|
||||
{id:'detail',fieldId:'detail-image',documentId:'detail',relatedFields:['caption']},
|
||||
{id:'photo',fieldId:'photo-image',documentId:'front',relatedFields:[]},
|
||||
{id:'front',fieldId:'front-image',label:'首屏图',documentId:'front',relatedFields:['title','tagline','detail-image']},
|
||||
{id:'detail',fieldId:'detail-image',label:'细节图',documentId:'detail',relatedFields:['caption']},
|
||||
{id:'photo',fieldId:'photo-image',label:'实拍图',documentId:'front',relatedFields:[]},
|
||||
];
|
||||
const title={field:'title',label:'标题',page:'front',currentText:'模板原文',templateSample:true};
|
||||
const tagline={field:'tagline',label:'副标题',page:'front',currentText:''};
|
||||
@ -946,6 +1061,9 @@ test('plans and delegate receipts report only linked pending copy and enqueue ev
|
||||
t.after(()=>actions.close());
|
||||
const readiness=async()=>Object.fromEntries((await actions.plan_production()).pictures.map(row=>[row.id,row.copyReady]));
|
||||
assert.deepEqual(await readiness(),{front:false,detail:true,photo:true});
|
||||
const ready=[{fieldId:'detail-image',label:'细节图'},{fieldId:'photo-image',label:'实拍图'}];
|
||||
assert.deepEqual((await actions.plan_production()).dispatchReady,ready);
|
||||
assert.deepEqual((await actions.review_image_slots({})).dispatchReady,ready);
|
||||
|
||||
const receipt=await actions.delegate_image_slots({jobs:slots.map(({fieldId})=>({slotId:fieldId,goal:'展示本款实拍细节'}))});
|
||||
assert.deepEqual(receipt.assigned.map(({id,state,pendingCopyFields})=>({id,state,pendingCopyFields})),[
|
||||
@ -959,6 +1077,25 @@ test('plans and delegate receipts report only linked pending copy and enqueue ev
|
||||
assert.match(receipt.copyContext,/实时已写文案.*goal 的模板原文/);
|
||||
await Promise.all(slots.map(({id})=>actions.await_image_slots({slotIds:[id]})));
|
||||
assert.deepEqual(started.sort(([a],[b])=>a.localeCompare(b)),[['detail',['榫接结构']],['front',[]],['photo',[]]]);
|
||||
|
||||
Object.assign(title,{layer:1});
|
||||
Object.assign(tagline,{layer:2});
|
||||
host.canvas.commitDetailCopy=async items=>{
|
||||
for(const {layer,text} of items) {
|
||||
const field=fields.find(row=>row.layer===layer);
|
||||
Object.assign(field,{currentText:text,templateSample:false});
|
||||
pending.splice(pending.indexOf(field),1);
|
||||
}
|
||||
return {appliedLayers:items.map(row=>row.layer)};
|
||||
};
|
||||
slots[1].generationRequestIds=['dispatched-request'];
|
||||
slots[2].selectedCandidateId='adopted-photo';
|
||||
const written=await actions.write_copy_fields({revision:1,items:[
|
||||
{layer:1,text:'榫卯结构'},{layer:2,text:'牢固连接'},
|
||||
]});
|
||||
assert.deepEqual(written.dispatchReady,[{fieldId:'front-image',label:'首屏图'}]);
|
||||
assert.deepEqual((await actions.plan_production()).dispatchReady,written.dispatchReady);
|
||||
assert.deepEqual((await actions.review_image_slots({})).dispatchReady,written.dispatchReady);
|
||||
Object.assign(title,{currentText:'实木餐椅',templateSample:false});
|
||||
tagline.currentText='弧形靠背';
|
||||
pending.splice(0,2);
|
||||
@ -1439,7 +1576,8 @@ test('Pi chooses each image operation and keeps an unresolved paid request on it
|
||||
await actions.read_copy_fields({pageId:' one ',fieldId:' compact '});
|
||||
assert.deepEqual(copyReads.at(-1),{includeFilled:true,pageId:'one',fieldId:'compact'});
|
||||
assert.deepEqual(await actions.write_copy_fields({revision,items:[]}),
|
||||
{appliedLayers:[],revision,copyUpdates:{total:0,truncated:false,items:[]}});
|
||||
{appliedLayers:[],revision,copyUpdates:{total:0,truncated:false,items:[]},
|
||||
dispatchReady:slots.map(({fieldId,label})=>({fieldId,label}))});
|
||||
assert.deepEqual(await actions.review_image_slots({slotIds:[]}), await actions.review_image_slots({}));
|
||||
assert.deepEqual(await actions.review_image_slots({slotIds:[' ']}), await actions.review_image_slots({}));
|
||||
const mixedLookup=await actions.review_image_slots({slotIds:['main-only-field',' lamp ','lamp-photo','']});
|
||||
@ -1784,7 +1922,7 @@ test('copy progress verifies each screen fingerprint and clears reviews when pro
|
||||
const first=new Map(saved.screenReviews).get(0);
|
||||
assert.equal(first.screenFingerprint,fingerprint(0));
|
||||
await observe(()=>write([[9,'浅色自然木纹']]),['verified','verified','filled','empty']);
|
||||
assert.equal(slotReads,beforeHeartbeat.slotReads);
|
||||
assert.equal(slotReads,beforeHeartbeat.slotReads+1,'the copy receipt checks current slot readiness once');
|
||||
await observe(()=>review(1),['verified','verified','verified','empty']);
|
||||
slots[1].selectedCandidateId='replacement';
|
||||
revision++;
|
||||
|
||||
@ -1088,6 +1088,16 @@ fn production_image_presentation(doc: u64, binding: &Value, account: &Value, ori
|
||||
"workerNumber":binding["request"]["workerNumber"]})
|
||||
}
|
||||
|
||||
fn production_image_target(state: Value, scope: &Value) -> R<Value> {
|
||||
let output = scope["outputId"].as_str().ok_or("成品编号缺失")?;
|
||||
let variant = scope["variantId"].as_str().ok_or("花色编号缺失")?;
|
||||
let state = production_output_state(state, output, variant)?;
|
||||
if state["id"] != scope["id"] || state["template"]["contentHash"] != scope["templateHash"] {
|
||||
return Err("生图请求的项目或模板已变化".into());
|
||||
}
|
||||
Ok(state)
|
||||
}
|
||||
|
||||
fn candidate_receipt(record: &Value) -> Value {
|
||||
let mut receipt = json!({"id":record["id"],"slotId":record["binding"]["slotId"],"variantId":record["binding"]["variantId"],
|
||||
"status":record["phase"],"message":record["message"]});
|
||||
@ -3417,6 +3427,27 @@ impl Backend {
|
||||
return pending_production_images(&dir, &load(&dir)?).map_err(BridgeFailure::from);
|
||||
}
|
||||
check_image_dispatch_cancelled(cancellation)?;
|
||||
let mut scoped_binding;
|
||||
let binding = if binding["projectScope"] == true {
|
||||
let state = production_image_target(load_detail_workspace(&dir)?, &binding["scope"])?;
|
||||
let variant = state["activeVariantId"].as_str().ok_or("花色编号缺失")?;
|
||||
let id = request["slotId"].as_str().ok_or("图片图位缺失")?;
|
||||
let (output, field) = definition(&state, id, variant)?;
|
||||
if output["component"] != state["activeOutput"] {
|
||||
return Err("图片图位不属于所选制作输出".into());
|
||||
}
|
||||
let mapped = mapped_slot(&state, id, variant)
|
||||
.filter(|slot| slot["nativeLayerId"].is_u64()).ok_or("请先打开对应模板画布,核对图片图层范围")?;
|
||||
scoped_binding = binding.clone();
|
||||
scoped_binding["scope"]["structureHash"] = state["structureHash"].clone();
|
||||
if scoped_binding["revision"].is_null() {
|
||||
scoped_binding["revision"] = state["revision"].clone();
|
||||
}
|
||||
scoped_binding["slotLabel"] = field.get("name").or(field.get("label")).unwrap_or(&field["fieldId"]).clone();
|
||||
let frame = slot_frame(field, Some(mapped)).ok_or("当前图片图层缺少已核对的范围")?;
|
||||
scoped_binding["imageFrame"] = json!({"width":frame["width"],"height":frame["height"]});
|
||||
&scoped_binding
|
||||
} else { binding };
|
||||
if matches!(phase, "prepare" | "transform") {
|
||||
let mut input = request.clone();
|
||||
input["doc"] = json!(doc);
|
||||
@ -3424,6 +3455,7 @@ impl Backend {
|
||||
input["variantId"] = binding["scope"]["variantId"].clone();
|
||||
input["detailBatch"] = json!(true);
|
||||
input["detailWorkspace"] = binding["scope"].clone();
|
||||
input["projectScopedPrepare"] = binding["projectScope"].clone();
|
||||
let action = if phase == "transform" { "slot-transform-image" } else { "slot-prepare-image" };
|
||||
return self.canvas_workspace_action(action, &input, events, ctx).map_err(BridgeFailure::from);
|
||||
}
|
||||
@ -3439,6 +3471,10 @@ impl Backend {
|
||||
let _ = events.send(Event::Json("image".into(), Ok(image)));
|
||||
if !cancelled {
|
||||
match self.canvas_workspace_result(doc, &dir) {
|
||||
Ok(workspace) if binding["projectScope"] == true => {
|
||||
// Refresh the current project index even if the original canvas has since changed.
|
||||
let _ = events.send(Event::Json("slot-progress".into(), Ok(workspace)));
|
||||
}
|
||||
Ok(workspace) => {
|
||||
let mut snapshot = operation_receipt(workspace, Some(receipt.clone()), None);
|
||||
snapshot["writeEpoch"] = binding["writeEpoch"].clone();
|
||||
@ -3685,6 +3721,9 @@ impl Backend {
|
||||
}
|
||||
let batch = input["detailBatch"] == true && matches!(method, "slot-prepare-image" | "slot-append" | "slot-adopt-prep" | "slot-transform-image");
|
||||
let mut state = if batch { load_detail_workspace(&dir)? } else { load(&dir)? };
|
||||
if batch && method == "slot-prepare-image" && input["projectScopedPrepare"] == true {
|
||||
state = production_image_target(state, &input["detailWorkspace"])?;
|
||||
}
|
||||
if batch && input["detailWorkspace"] != json!({"id":state["id"],"templateHash":state["template"]["contentHash"],
|
||||
"structureHash":state["structureHash"],"outputId":state["activeOutput"],"variantId":state["activeVariantId"]})
|
||||
{
|
||||
@ -5827,6 +5866,61 @@ mod tests {
|
||||
assert!(!candidate_path(&dir, record["id"].as_str().unwrap()).unwrap().with_file_name("task.json").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn switched_output_prepares_from_saved_mapping_and_validates_its_frozen_request() {
|
||||
let fixture = fixture();
|
||||
let mut backend = Backend::new(fixture.dir.join("profile")).unwrap();
|
||||
let doc = 1;
|
||||
backend.bind_new(doc);
|
||||
let dir = backend.project_dir(doc).unwrap();
|
||||
write_json(&dir.join("context.json"), &json!({"doc":doc})).unwrap();
|
||||
let creation = creation::load(&dir).unwrap();
|
||||
write_json(&dir.join("creation.json"), &creation).unwrap();
|
||||
let mut state = load(&fixture.dir).unwrap();
|
||||
let detail = state["template"].clone();
|
||||
let mut main = pack();
|
||||
main["outputs"][0]["component"] = json!("main_images");
|
||||
main["contentHash"] = json!(template_slots::pack_hash(&main).unwrap());
|
||||
let variant = state["activeVariantId"].as_str().unwrap().to_owned();
|
||||
let slot = slot_id(&detail["contentHash"], &variant, "S01-I01");
|
||||
state["productTemplates"] = json!({"detail":detail,"main_images":main});
|
||||
state["template"] = main;
|
||||
state["activeOutput"] = json!("main_images");
|
||||
state["structureHash"] = json!(hash(&json!([state["template"]["contentHash"],state["width"]]).to_string()));
|
||||
state["activeMapping"] = json!(mapping_key(&variant, "main_images", None));
|
||||
let detail_mapping = mapping_key(&variant, "detail", None);
|
||||
state["mappings"][&detail_mapping] = json!({"variantId":variant,
|
||||
"fields":[{"slotId":slot,"nativeLayerId":17}]});
|
||||
persist(&dir, state.clone(), 0).unwrap();
|
||||
let scope = json!({"id":state["id"],"templateHash":detail["contentHash"],"outputId":"detail","variantId":variant});
|
||||
let (events, _) = mpsc::channel();
|
||||
let ctx = egui::Context::default();
|
||||
let prepare = json!({"action":"prepare","projectScope":true,"scope":scope,
|
||||
"request":{"slotId":slot,"instructions":"展示真实商品"}});
|
||||
let error = backend.production_image_request(doc, &prepare, &events, &ctx, None).unwrap_err();
|
||||
assert!(error.message.contains("为当前花色添加至少一张产品实拍"), "{}", error.message);
|
||||
|
||||
let id = Uuid::new_v4().to_string();
|
||||
let scoped = production_image_target(state.clone(), &scope).unwrap();
|
||||
let mut task = json!({"id":id,"doc":doc,"localProjectId":backend.locations.get(&doc),
|
||||
"accountScope":backend.scope(),"origin":backend.origin,"outputScope":"detail","phase":"prepared",
|
||||
"requestSpecRevision":1,"references":[],"prompt":"展示真实商品","candidateRecord":{"inputHash":"stale"},
|
||||
"slotBinding":{"slotId":slot,"fieldId":"S01-I01","outputId":"S01",
|
||||
"workspaceId":scope["id"],"templateHash":scope["templateHash"],
|
||||
"structureHash":scoped["structureHash"],"variantId":variant,"detailBatch":true}});
|
||||
let spec = super::super::images::image_request_receipt(&task)["spec"].to_string();
|
||||
task["requestSpecHash"] = json!(hash(&spec));
|
||||
let file = dir.join("image-jobs").join(&id).join("task.json");
|
||||
write_json(&file, &task).unwrap();
|
||||
let dispatch = json!({"action":"dispatch","projectScope":true,"scope":scope,
|
||||
"request":{"requestId":id,"slotId":slot,"expectedRevision":1,"expectedHash":task["requestSpecHash"]}});
|
||||
let error = backend.production_image_request(doc, &dispatch, &events, &ctx, None).unwrap_err();
|
||||
assert!(error.message.contains("商品资料或制作依据已变化"), "{}", error.message);
|
||||
assert!(read_json(&file).unwrap()["frozenAt"].is_number());
|
||||
assert!(!error.dispatched);
|
||||
assert_eq!(load(&dir).unwrap()["activeOutput"], "main_images");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_original_reads_the_host_expiry_without_recovering_or_rewriting() {
|
||||
let fixture = fixture();
|
||||
|
||||
@ -2476,6 +2476,7 @@ impl Workspace {
|
||||
let (done, total, unit) = if selected && show_work { (current_counts.0, current_counts.1, "图位") }
|
||||
else { (usize::from(pipeline.contains(&(*name, StagePhase::Done))), 1, "份") };
|
||||
GoalStage { name, done, total, unit, elapsed: None, tokens: None,
|
||||
waiting_canvas: self.workflow.waiting_canvas(output),
|
||||
slots: if selected && show_work { slots() } else { Vec::new() } }
|
||||
}).collect();
|
||||
let budget = if let Some(run) = run {
|
||||
|
||||
@ -336,7 +336,10 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
|
||||
let scoped_read = private && (method == "pi-detail-archive" && input["source"].is_null()
|
||||
&& (input["projectPlan"] == true || input["projectImages"] == true)
|
||||
|| method == "pi-detail-images" && input["targetOutput"].is_object() && input["adopted"] != true);
|
||||
if w.production_boundary_pending() && !scoped_read && !matches!(method,
|
||||
let scoped_image = private && method == "pi-image-request"
|
||||
&& (input["action"] == "pending" || input["targetOutput"].is_object()
|
||||
&& matches!(input["action"].as_str(), Some("read" | "prepare" | "dispatch")));
|
||||
if w.production_boundary_pending() && !scoped_read && !(opening && scoped_image) && !matches!(method,
|
||||
"pi-state" | "pi-activity" | "pi-delta" | "pi-context-usage" | "pi-production-open"
|
||||
| "pi-production-finish" | "pi-production-finish-status" | "pi-workflow-poll" | "pi-native-poll" | "pi-end") {
|
||||
return Err(BridgeFailure::new("production_canvas_pending", true, false, "请等待画布保存或交付回执"));
|
||||
@ -572,7 +575,7 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
|
||||
"pi-image-request" => {
|
||||
let action = input["action"].as_str().filter(|action| matches!(*action,"prepare"|"dispatch"|"transform"|"read"|"pending"))
|
||||
.ok_or("生图请求动作无效")?;
|
||||
if matches!(action, "read" | "pending") {
|
||||
if action == "pending" || action == "read" && !scoped_image {
|
||||
if w.pi_request_scope["productProduction"] != true {
|
||||
return Err("本轮没有制作请求的读取授权".into());
|
||||
}
|
||||
@ -581,9 +584,9 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
|
||||
"outputId":w.pi_request_scope["outputId"],
|
||||
"variantId":w.pi_request_scope["variantId"]}}));
|
||||
}
|
||||
if w.pi_request_scope["productProduction"] != true || !w.canvas_scope_valid(app)
|
||||
if !scoped_image && (w.pi_request_scope["productProduction"] != true || !w.canvas_scope_valid(app)
|
||||
|| w.pi_request_scope["outputId"] != w.template_workflow["outputId"]
|
||||
|| w.pi_request_scope["variantId"] != w.template_workflow["variantId"] {
|
||||
|| w.pi_request_scope["variantId"] != w.template_workflow["variantId"]) {
|
||||
return Err(BridgeFailure::new("scope_changed", false, false, "生图请求未绑定本轮工作画布"));
|
||||
}
|
||||
if w.pi_write_blocked || w.agent_effects_paused {
|
||||
@ -594,6 +597,7 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
|
||||
"prepare" => &["slotId","instructions","geometryReferenceIndex","prefer2k","retryOf","reworkOf","reworkChange",
|
||||
"referenceIndexes","useTemplateReference","useSceneComposite"],
|
||||
"transform" => &["slotId","sourceCandidateId","referenceIndex","transform"],
|
||||
"read" => &["requestId"],
|
||||
_ => &["requestId","expectedRevision","expectedHash","slotId","workerNumber"],
|
||||
};
|
||||
if request.as_object().is_none_or(|fields| fields.keys().any(|key| !allowed.contains(&key.as_str()))) {
|
||||
@ -603,6 +607,18 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
|
||||
&& !number.as_u64().is_some_and(|number| number > 0) {
|
||||
return Err("子代理编号无效".into());
|
||||
}
|
||||
if scoped_image {
|
||||
let target = &input["targetOutput"];
|
||||
if w.pi_request_scope["productProduction"] != true || !requested_production_output(w, target) {
|
||||
return Err("生图请求不属于本轮制作输出".into());
|
||||
}
|
||||
let bound = !opening && ["outputId","variantId"].into_iter()
|
||||
.all(|field| target[field] == w.pi_request_scope[field]);
|
||||
return Ok(json!({"action":action,"request":request,"projectScope":true,
|
||||
"run":w.pi_run,"revision":bound.then_some(w.expected_revision),
|
||||
"scope":{"id":w.template_workflow["workspaceId"],"templateHash":target["templateHash"],
|
||||
"outputId":target["outputId"],"variantId":target["variantId"]}}));
|
||||
}
|
||||
let slot = w.template_workflow["slots"].as_array().into_iter().flatten().find(|slot|
|
||||
slot["id"] == request["slotId"] && slot["outputId"] == w.pi_request_scope["outputId"]
|
||||
&& slot["variantId"] == w.pi_request_scope["variantId"] && slot["nativeLayerId"].is_u64())
|
||||
@ -697,7 +713,14 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
|
||||
};
|
||||
let production_progress = private && w.pi_request_scope["productProduction"] == true && input["production"].is_object();
|
||||
if !production_progress && (!text.is_empty() || thinking.is_none()) { w.stream_reply = text.into(); }
|
||||
if production_progress
|
||||
if production_progress && let Some(count) = input["production"]["waitingCanvas"].as_u64() {
|
||||
let progress = &input["production"];
|
||||
if requested_production_output(w, progress)
|
||||
&& let Some((output, variant)) = progress["outputId"].as_str().zip(progress["variantId"].as_str())
|
||||
{
|
||||
w.workflow.set_waiting_canvas(output, variant, count);
|
||||
}
|
||||
} else if production_progress
|
||||
&& input["production"]["outputId"] == w.pi_request_scope["outputId"]
|
||||
&& input["production"]["variantId"] == w.pi_request_scope["variantId"]
|
||||
{
|
||||
@ -976,6 +999,48 @@ mod tests {
|
||||
assert!(private_action_in_ui(&mut w, &mut app, &ctx, "pi-image-request", &input).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn background_image_requests_and_waiting_counts_keep_the_requested_output_scope() {
|
||||
let (mut w, mut app, mut input) = activity_fixture();
|
||||
let detail = json!({"outputId":"detail","variantId":"oak","templateHash":"detail-pack"});
|
||||
w.pi_request_scope["productProduction"] = json!(true);
|
||||
w.pi_request_scope["outputId"] = json!("main_images");
|
||||
w.pi_request_scope["variantId"] = json!("oak");
|
||||
w.pi_request_scope["requestedOutputs"] = json!([detail]);
|
||||
w.template_workflow = json!({"workspaceId":"workspace","outputId":"main_images",
|
||||
"variantId":"oak","templateHash":"main-pack","slots":[]});
|
||||
let ctx = egui::Context::default();
|
||||
input["targetOutput"] = detail.clone();
|
||||
for action in ["prepare", "dispatch", "read"] {
|
||||
input["action"] = json!(action);
|
||||
input["request"] = match action {
|
||||
"prepare" => json!({"slotId":"detail-slot","instructions":"准备首屏"}),
|
||||
"dispatch" => json!({"slotId":"detail-slot","requestId":"saved-request"}),
|
||||
_ => json!({"requestId":"saved-request"}),
|
||||
};
|
||||
let reply = private_action_in_ui(&mut w, &mut app, &ctx, "pi-image-request", &input).unwrap();
|
||||
assert_eq!(reply["projectScope"], true);
|
||||
assert_eq!(reply["scope"], json!({"id":"workspace","outputId":"detail","variantId":"oak","templateHash":"detail-pack"}));
|
||||
assert!(reply["writeEpoch"].is_null());
|
||||
}
|
||||
input["targetOutput"]["variantId"] = json!("other");
|
||||
assert!(private_action_in_ui(&mut w, &mut app, &ctx, "pi-image-request", &input).is_err());
|
||||
input["action"] = json!("transform");
|
||||
input["targetOutput"] = detail;
|
||||
input["request"] = json!({"slotId":"detail-slot","referenceIndex":0,"transform":{}});
|
||||
assert!(private_action_in_ui(&mut w, &mut app, &ctx, "pi-image-request", &input).is_err());
|
||||
input["text"] = json!("");
|
||||
input["production"] = json!({"outputId":"detail","variantId":"oak","waitingCanvas":2});
|
||||
private_action_in_ui(&mut w, &mut app, &ctx, "pi-delta", &input).unwrap();
|
||||
assert_eq!(w.workflow.waiting_canvas("detail"), 2);
|
||||
assert_eq!(w.workflow.waiting_canvas("main_images"), 0);
|
||||
w.workflow.clear_production_progress();
|
||||
assert_eq!(w.workflow.waiting_canvas("detail"), 2);
|
||||
input["production"]["waitingCanvas"] = json!(0);
|
||||
private_action_in_ui(&mut w, &mut app, &ctx, "pi-delta", &input).unwrap();
|
||||
assert_eq!(w.workflow.waiting_canvas("detail"), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn public_pi_action_cannot_expose_private_workflow_delegation() {
|
||||
let (mut w, mut app, mut input) = activity_fixture();
|
||||
|
||||
@ -392,6 +392,7 @@ pub(super) struct GoalStage<'a> {
|
||||
pub done: usize,
|
||||
pub total: usize,
|
||||
pub unit: &'a str,
|
||||
pub waiting_canvas: u64,
|
||||
/// 时段明细接口:本阶段已用的时间。
|
||||
pub elapsed: Option<Duration>,
|
||||
/// Token 明细接口:本阶段已用的 Token。
|
||||
@ -556,7 +557,10 @@ fn roadmap(ui: &mut Ui, id: egui::Id, stages: &[GoalStage<'_>], panel: &GoalProg
|
||||
ui.spacing_mut().item_spacing.x = space::SM;
|
||||
ui.add_sized(vec2(STAGE_NAME_WIDTH, agent_stream::ROW),
|
||||
egui::Label::new(RichText::new(stage.name).font(Type::Meta.font_id()).color(t.text)).truncate());
|
||||
let count = format!("{}/{} {}", stage.done, stage.total, stage.unit);
|
||||
let mut count = format!("{}/{} {}", stage.done, stage.total, stage.unit);
|
||||
if stage.waiting_canvas > 0 {
|
||||
count.push_str(&format!(" · 等切回 {}", stage.waiting_canvas));
|
||||
}
|
||||
let width = ui.painter().layout_no_wrap(count.clone(), Type::Meta.font_id(), t.text_dim).size().x;
|
||||
let track = ui.available_width().max(1.0) - width - space::SM;
|
||||
ui.allocate_ui_with_layout(vec2(track.max(1.0), agent_stream::ROW), Layout::left_to_right(egui::Align::Center), |ui| {
|
||||
@ -1075,9 +1079,9 @@ mod tests {
|
||||
WorkerState { number: 9, stage: WorkerStage::Preparing, slot: "没有代号的", active: false },
|
||||
];
|
||||
let stages = vec![
|
||||
GoalStage { name: "详情页", done: 6, total: 6, unit: "屏", elapsed: Some(Duration::from_secs(240)), tokens: Some(1200),
|
||||
GoalStage { name: "详情页", done: 6, total: 6, unit: "屏", waiting_canvas: 0, elapsed: Some(Duration::from_secs(240)), tokens: Some(1200),
|
||||
slots: vec![GoalSlot { label: "第 1 屏 · 首屏卖点", state: SlotState::Done }] },
|
||||
GoalStage { name: "主图", done: 3, total: 5, unit: "张", elapsed: None, tokens: None,
|
||||
GoalStage { name: "主图", done: 3, total: 5, unit: "张", waiting_canvas: 0, elapsed: None, tokens: None,
|
||||
slots: (0..7).map(|index| GoalSlot { label: "主图", state: if index < 3 { SlotState::Done } else if index == 3 { SlotState::Failed } else { SlotState::Queued } }).collect() },
|
||||
];
|
||||
Fixture { pipeline, image_cells, copy_cells, workers, stages }
|
||||
@ -1085,7 +1089,11 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn goal_progress_panel_fits_narrow_and_wide_docks_and_opens_its_roadmap_on_click() {
|
||||
let Fixture { pipeline, image_cells, copy_cells, workers, stages } = fixture();
|
||||
let Fixture { pipeline, image_cells, copy_cells, workers, mut stages } = fixture();
|
||||
stages[0].done = 0;
|
||||
stages[0].total = 1;
|
||||
stages[0].unit = "份";
|
||||
stages[0].waiting_canvas = 2;
|
||||
let budget = GoalBudget::Time { elapsed: Duration::from_secs(240), limit: None };
|
||||
let show = |ui: &mut Ui, state: RunState| {
|
||||
kit::scope(ui, |ui| {
|
||||
@ -1130,7 +1138,7 @@ mod tests {
|
||||
assert!(worker["rect"].is_array() && worker["indicator"].is_array() && worker["step"].is_string(), "{worker}");
|
||||
}
|
||||
let drawn = texts(&output);
|
||||
for expected in ["详情页", "6/6 屏", "3/5 张", "4m", "1.2k tokens", "主图 4 · 细节特写", "等结果"] {
|
||||
for expected in ["详情页", "0/1 份 · 等切回 2", "3/5 张", "4m", "1.2k tokens", "主图 4 · 细节特写", "等结果"] {
|
||||
assert!(drawn.iter().any(|text| text == expected || text.ends_with(expected)), "{name}: {expected} is drawn: {drawn:?}");
|
||||
}
|
||||
assert!(drawn.iter().any(|text| text == "没有代号的"), "a worker beyond the original four is still listed");
|
||||
|
||||
@ -33,6 +33,7 @@ pub(super) struct State {
|
||||
// Frozen image requests publish presentation records independently of workflow proposals.
|
||||
production_images: Vec<Value>,
|
||||
production_progress: Value,
|
||||
waiting_canvas: std::collections::HashMap<(String, String), u64>,
|
||||
/// A human-reviewed PSD export is independent of the consumed Pi proposal.
|
||||
pub(super) psd_review: Option<workflow_export::Review>,
|
||||
}
|
||||
@ -50,6 +51,7 @@ impl State {
|
||||
|
||||
pub(super) fn clear(&mut self) {
|
||||
self.pending = None;
|
||||
self.waiting_canvas.clear();
|
||||
self.clear_production_progress();
|
||||
}
|
||||
|
||||
@ -77,6 +79,14 @@ impl State {
|
||||
&self.production_progress
|
||||
}
|
||||
|
||||
pub(super) fn waiting_canvas(&self, output: &str) -> u64 {
|
||||
self.waiting_canvas.iter().filter(|((id, _), _)| id == output).map(|(_, count)| count).sum()
|
||||
}
|
||||
|
||||
pub(super) fn set_waiting_canvas(&mut self, output: &str, variant: &str, count: u64) {
|
||||
self.waiting_canvas.insert((output.into(), variant.into()), count);
|
||||
}
|
||||
|
||||
pub(super) fn set_production_progress(&mut self, progress: &Value) -> Option<String> {
|
||||
let notice = &progress["notice"];
|
||||
let changed = notice["key"].is_string() && notice["key"] != self.production_progress["notice"]["key"];
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user