refactor(xiaoyi): split production modules and trim tool guidance
This commit is contained in:
parent
9adba649e0
commit
cef79a9a39
@ -256,17 +256,16 @@ const SYSTEM = `你是由壹点详情页的本地协作助手“小壹”。使
|
||||
|
||||
${PRODUCT_VOICE}
|
||||
用「workflow_read」读取项目目标、商品、实时进度和图位分页。以 status 和 selectedCandidateId 为准。canvasFirst 项目直接用模板画布,不把旧向导空状态当阻塞。
|
||||
用「context_read」读取当前绑定的规则。缺少关键资料时询问,用户新确认的信息覆盖旧信息。用「memory_set」保存明确确认的事实,引用用户原话;用「memory_search」读取历史。
|
||||
按照「context_read」返回的本项目锁定 Skill 和补充规则工作。通用建议可以直接讨论,不借用其他品牌的规则或臆测产品事实。
|
||||
依「context_read」返回的锁定 Skill 和补充规则工作。缺少关键资料时询问,按用户最新确认的信息处理。用「memory_set」引用原话保存已确认事实,用「memory_search」查历史。通用建议可直接讨论,避免借用其他品牌规则或臆测产品事实。
|
||||
用「copywriting_options」提供卖点选项,用「copywriting_fields」提供逐格预览和采纳。「workflow_propose」只创建待审核建议,「workflow_navigate」只切换视图。用户取消表示未决定。
|
||||
${LIVE_CANVAS_WRITES}
|
||||
申请写入许可后执行实际修改。只确认经回执验证的结果;未知的付费或写入操作按原编号核查。`;
|
||||
|
||||
const PRODUCTION_SYSTEM = `你是小壹的制作助手,当前为无人值守制作。以项目锁定的企业 Skill、模板和补充规则为准,自主决定操作顺序、并行、复核及返工。
|
||||
${PRODUCT_VOICE}
|
||||
「plan_production」返回制作状态,设置 includeKnowledge=true 可列出锁定资料路径,用「read」按需读取。「open_production_output」打开目标画布,「list_project_images」查询项目候选。
|
||||
用「plan_production」查制作状态,includeKnowledge=true 列出锁定规则路径,按需「read」。用「tool_search」查工具。
|
||||
${LIVE_CANVAS_WRITES}
|
||||
「write_copy_fields」可注明刻意留空的依据。「check_output_screens」记录整屏复核,「read_screen_review」读取结论。用「tool_search」查找工具。用「native_catalog」查询原生命令,复用 parameterDocs。用「codemode」组合操作,依次 await 真实回执。
|
||||
用「native_catalog」查询原生命令并复用 parameterDocs,用「codemode」组合操作时依次 await 真实回执。
|
||||
用「reconcile_image_slots」按原编号核查未知付费请求。用「finish_production」提交并核对文件和交付回执,按实际缺项汇报。`;
|
||||
|
||||
export const sessionSystemPrompt = production => production ? PRODUCTION_SYSTEM : SYSTEM;
|
||||
|
||||
177
apps/detail-agent-pi/src/production-image-worker.mjs
Normal file
177
apps/detail-agent-pi/src/production-image-worker.mjs
Normal file
@ -0,0 +1,177 @@
|
||||
import { Type } from '@sinclair/typebox';
|
||||
import { slotAttempts } from './production-progress.mjs';
|
||||
import { productRequestScope } from './production-recovery.mjs';
|
||||
import { candidateReceipt, imageResult } from './production-receipts.mjs';
|
||||
import { scopedProductionBrief } from './production-repository.mjs';
|
||||
import { productReferences, slotTarget } from './production-slots.mjs';
|
||||
import {
|
||||
dispatchArgs, fit, ids, imageRequestDescription, obj, optional, preparationArgs, productImageArgs,
|
||||
slotRef, text, transformDescription, transformImageArgs,
|
||||
} from './production-tool-schema.mjs';
|
||||
import { validateWorkerArguments } from './worker-receipts.mjs';
|
||||
|
||||
export function productionImageWorker({
|
||||
slot, goal, reworkCandidateId, groupTargets, pendingCopyFields, status, outputId, variantId, row,
|
||||
groupCall, awaitCanvas, findSlot, current, getReferenceMode, getSlotRecord, readSlot, readImages, listProjectImages,
|
||||
liveSlot, slotDrawStatus, liveSlotCopy, runDetailAgent, notice,
|
||||
recordLocalCandidate, recordNoCandidate, pendingDispatch, dispatchEnqueued,
|
||||
useProductImage, transformImage, prepareImageRequest, preparedRequest, queueDispatch,
|
||||
}, delegateSignal) {
|
||||
const grouped=groupTargets.length>1;
|
||||
let rework, latestPrepared, produced=false;
|
||||
const dispatched=new Map();
|
||||
const workerTool=(name,description,properties,execute,terminate=false)=>{
|
||||
const parameters=obj(properties);
|
||||
return {
|
||||
name,label:description,description,parameters,executionMode:'sequential',
|
||||
...(terminate?{prepareArguments:args=>validateWorkerArguments(name,parameters,args,()=>`本次委托图位 slotId ${JSON.stringify(slot.id)}`)}:null),
|
||||
execute:async(_id,args,workerSignal)=>{
|
||||
const activeSignal=workerSignal?AbortSignal.any([workerSignal,delegateSignal]):delegateSignal;
|
||||
activeSignal.throwIfAborted();
|
||||
const result=await execute(args,activeSignal);
|
||||
const done=typeof terminate==='function'?terminate(result):terminate;
|
||||
if(done||name==='use_product_image'||name==='transform_slot_image'||name==='dispatch_image_request'&&result.operationId){
|
||||
produced=true;
|
||||
if(name==='use_product_image'||name==='transform_slot_image')recordLocalCandidate(result);
|
||||
}
|
||||
return {...imageResult(result),...(done?{terminate:true}:null)};
|
||||
},
|
||||
};
|
||||
};
|
||||
const workerTools=[
|
||||
workerTool('use_product_image','用本款实拍创建图位候选',productImageArgs,
|
||||
(args,activeSignal)=>useProductImage(args,activeSignal),()=>!grouped),
|
||||
workerTool('transform_slot_image',transformDescription,
|
||||
{...transformImageArgs,...(grouped?{outputId:optional(text),slotId:optional(slotRef)}:null)},
|
||||
async(args,activeSignal)=>{
|
||||
if(!grouped)return transformImage(args,activeSignal);
|
||||
const result=await groupCall('transform_slot_image',args,activeSignal);
|
||||
return {...result,outputId:args.outputId??outputId,slotId:args.slotId??slot.id};
|
||||
}),
|
||||
...(grouped?[
|
||||
workerTool('list_project_images','列出同花色的本项目候选,可按来源成品筛选。',{
|
||||
outputId:optional(text),candidateId:optional(text),offset:optional(Type.Integer({minimum:0})),
|
||||
},async({outputId,candidateId,offset})=>candidateReceipt(
|
||||
await listProjectImages({outputId,variantId}),{},{candidateId,offset})),
|
||||
workerTool('adopt_production_image','在可写画布采用指定图位的候选。',{
|
||||
outputId:optional(text),slotId:slotRef,candidateId:text,fit:optional(fit),reason:optional(text),
|
||||
},(args,activeSignal)=>groupCall('adopt_production_image',args,activeSignal)),
|
||||
workerTool('await_image_slots','等待本次委托派发的原请求。operationIds 可一次接收多份回执。',{
|
||||
operationId:optional(text),operationIds:optional(ids),
|
||||
},async({operationId,operationIds},activeSignal)=>{
|
||||
const requested=operationIds??(operationId?[operationId]:[...dispatched.keys()]);
|
||||
if(requested.some(id=>!dispatched.has(id)))throw Error('原请求不属于本次委托');
|
||||
const generation=await awaitCanvas(Promise.all([...new Set(requested)].map(id=>dispatched.get(id))),activeSignal);
|
||||
return operationId&&!operationIds?generation[0]:{generation};
|
||||
}),
|
||||
]:[]),
|
||||
workerTool('prepare_image_request',imageRequestDescription,preparationArgs,
|
||||
async(args,activeSignal)=>{
|
||||
latestPrepared=undefined;
|
||||
const receipt=await prepareImageRequest({...args,reworkCandidateId:rework?.candidateId},activeSignal);
|
||||
if(receipt.requestId)latestPrepared=receipt.requestId;
|
||||
return receipt;
|
||||
}),
|
||||
workerTool('dispatch_image_request','传空对象确认派发本子任务最近一次准备的请求。需选择另一份准备回执时传 requestId。', {...dispatchArgs,requestId:optional(text)},
|
||||
async(args,activeSignal)=>{
|
||||
const requestId=args.requestId ?? latestPrepared;
|
||||
if(!requestId)throw Error('本图位还没有准备回执。先用 prepare_image_request 准备请求,再用空对象确认派发。');
|
||||
const approval={...args,requestId};
|
||||
const request=await preparedRequest(approval.requestId).catch(error=>{
|
||||
throw Error(`requestId ${JSON.stringify(approval.requestId)},slotId ${JSON.stringify(slot.id)}。请核对当前图位的生图准备回执。原因:${error.message}`,{cause:error});
|
||||
});
|
||||
const errors=[];
|
||||
if(approval.expectedRevision!==undefined&&approval.expectedRevision!==request.revision){
|
||||
errors.push(`expectedRevision ${approval.expectedRevision} 与准备回执不一致,可用值为 ${request.revision}`);
|
||||
}
|
||||
if(approval.expectedHash!==undefined&&approval.expectedHash!==request.requestSpecHash){
|
||||
errors.push(`expectedHash ${JSON.stringify(approval.expectedHash)} 与准备回执不一致,可用值为 ${JSON.stringify(request.requestSpecHash)}`);
|
||||
}
|
||||
if(errors.length)throw Error([`requestId ${JSON.stringify(approval.requestId)},slotId ${JSON.stringify(slot.id)}`,...errors].join('\n'));
|
||||
row.step='正在生图';
|
||||
notice('子代理正在生图');
|
||||
const receipt=await queueDispatch(approval,request,activeSignal);
|
||||
if(receipt.operationId)dispatched.set(receipt.operationId,pendingDispatch(receipt));
|
||||
await dispatchEnqueued(receipt.operationId);
|
||||
return receipt;
|
||||
},result=>!grouped&&!result.limitReached),
|
||||
];
|
||||
let referenceSnapshot;
|
||||
const readReferences=async includeTemplateReference=>{
|
||||
const snapshot=await current();
|
||||
const {creation,slots,canvas}=snapshot.revisions??{};
|
||||
const version=creation??snapshot.version;
|
||||
const revision=version==null?undefined:JSON.stringify([version,slots,canvas]);
|
||||
if(revision!==undefined&&referenceSnapshot?.revision===revision&&
|
||||
referenceSnapshot.includeTemplateReference===includeTemplateReference){
|
||||
return referenceSnapshot.result;
|
||||
}
|
||||
const result=await readImages({includeTemplateReference});
|
||||
referenceSnapshot={revision,includeTemplateReference,result};
|
||||
return result;
|
||||
};
|
||||
const readTool={name:'read_slot_images',label:'查看图位图片',
|
||||
description:grouped?'读取组内图位的参考或指定候选的实际图片。':'读取本款实拍。按制作配置返回模板参考。',
|
||||
parameters:grouped
|
||||
?obj({outputId:optional(text),slotId:optional(slotRef),candidateId:optional(text),includeTemplateReference:optional(Type.Boolean())})
|
||||
:obj({includeTemplateReference:optional(Type.Boolean())}),
|
||||
execute:async(_id,args={})=>{
|
||||
const {includeTemplateReference}=args;
|
||||
delegateSignal.throwIfAborted();
|
||||
if(grouped&&(args.candidateId||args.outputId&&args.outputId!==outputId||args.slotId&&findSlot(args.slotId)?.id!==slot.id)){
|
||||
return groupCall('read_slot_images',args,delegateSignal);
|
||||
}
|
||||
const referenceMode=getReferenceMode();
|
||||
const result=await readReferences(includeTemplateReference??['template-base','composition-only'].includes(referenceMode));
|
||||
return imageResult({...result,productReferences:productReferences(result.referenceCount)});
|
||||
}};
|
||||
async function run(){
|
||||
row.step='正在准备';
|
||||
notice('子代理正在制作');
|
||||
const prior=getSlotRecord();
|
||||
const candidateId=reworkCandidateId?.trim();
|
||||
let rejectedImage;
|
||||
if(candidateId){
|
||||
const live=await readSlot();
|
||||
const {attemptCount,rejections,reviews}=slotAttempts(live,prior);
|
||||
const feedback=reviews.findLast(entry=>entry.candidateId===candidateId);
|
||||
const old=await readImages({candidateId,includeProductReferences:false,includeTemplateReference:false})
|
||||
.catch(error=>({unavailable:error.message}));
|
||||
if(old.candidateId===candidateId&&old.images?.at(-1)?.type==='image')rejectedImage=old.images.at(-1);
|
||||
const attempt=prior?.attempts?.find(entry=>entry.candidateId===candidateId);
|
||||
rework={candidateId,attempt:attemptCount+1,reason:feedback?.reason,
|
||||
recommendedAction:feedback?.recommendedAction,canvasTransform:feedback?.canvasTransform,
|
||||
suggestions:feedback?.mustRedo,generationFixes:feedback?.generationFixes,
|
||||
previousPrompt:old.candidateId===candidateId?old.candidatePrompt??undefined:undefined,
|
||||
previousInstruction:attempt?.prompt,
|
||||
previousOutcomes:rejections,
|
||||
...(!feedback?{reviewUnavailable:'此候选号没有留存退回回执'}:null),
|
||||
...(rejectedImage?{imageAttached:true}:{unavailable:old.unavailable??'未读到这张候选的原图'}),
|
||||
};
|
||||
}
|
||||
const live=await liveSlot();
|
||||
const status=slotDrawStatus(live);
|
||||
const referenceMode=getReferenceMode();
|
||||
const instructions='按锁定的企业 Skill 及小壹补充完成委托。完成主代理委托的图位。goal 是本次任务,screenCopy 是画布实时文案。pendingCopyFields 中的 templateExample 是模板样例。首条消息包含有编号的实拍和可用的模板参考。可用 transform_slot_image 调整已有图像并查看像素指标。派发回执会带原请求号,宿主继续跟踪结果。'+
|
||||
(rework?'\n附件含退回图、验图回执和上次实发提示词。reworkChange 记录改动。':'');
|
||||
const screenCopy=await liveSlotCopy();
|
||||
const references=await readReferences(['template-base','composition-only'].includes(referenceMode))
|
||||
.catch(error=>({unavailable:error.message}));
|
||||
const {images=[],referenceCount=0,layoutCount=0,layoutIssue,unavailable,prompt:templatePrompt,outputSpec,
|
||||
referenceBindings=[],supplementalBindings=[]}=references;
|
||||
const productIds=productReferences(referenceCount);
|
||||
const attachments=[...images.slice(0,referenceCount+layoutCount),
|
||||
...(supplementalBindings.length?images.slice(-supplementalBindings.length):[]),...(rejectedImage?[rejectedImage]:[])];
|
||||
const captions=[...productIds,...Array.from({length:layoutCount},()=> '模板构图参考'),
|
||||
...(rejectedImage?['退回候选原图']:[])];
|
||||
delegateSignal.throwIfAborted();
|
||||
await runDetailAgent(instructions,
|
||||
JSON.stringify({rework,goal,referenceMode,screenCopy,pendingCopyFields,target:slotTarget(live),
|
||||
product:scopedProductionBrief((await current()).productEvidence?.brief??{},variantId,outputId),
|
||||
productReferences:productIds,referenceBindings,supplementalBindings,layoutCount,layoutIssue,templatePrompt,outputSpec,referenceError:unavailable,...status,...(grouped?{groupTargets}:null),field:slot.fieldId,label:slot.label,rule:slot.productionRule,requirements:slot.requirements}),[readTool,...workerTools],
|
||||
attachments,productRequestScope('slot',slot.id),captions,delegateSignal);
|
||||
if(!produced)recordNoCandidate();
|
||||
}
|
||||
|
||||
return {run,dispatched};
|
||||
}
|
||||
@ -2,139 +2,34 @@ import { productionCopyCells, productionImageProgress, slotAttempts } from './pr
|
||||
import { changedProductionFields, copyPage, productionInputs } from './production-copy.mjs';
|
||||
import { allocateWorkerNumber, delegatePool } from './production-delegate.mjs';
|
||||
import { createImageReconciler, expiryFields, imageOriginals, isLocalProductOperation, originalCandidate, readNativeOriginal, recoveryNotices, rememberImageExpiry, settledImagePhases, slotOriginals } from './image-reconciler.mjs';
|
||||
import { StringEnum } from '@earendil-works/pi-ai';
|
||||
import { candidateReceipt, compactProgress, receiptPage, reviewSlotSummary } from './production-receipts.mjs';
|
||||
import { candidateReceipt, compactProgress, imageResult, receiptPage, reviewSlotSummary } from './production-receipts.mjs';
|
||||
import { compactTemplateFidelity } from './template-fidelity.mjs';
|
||||
import { compareTemplateFields, visibleTemplateConflicts } from './field-requirements.mjs';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { isDeepStrictEqual } from 'node:util';
|
||||
import path from 'node:path';
|
||||
import { CanvasOperations } from './canvas-operations.mjs';
|
||||
import { Type } from '@sinclair/typebox';
|
||||
import { formatDimensionNote, parseFrontmatter, resizeImage } from '@earendil-works/pi-coding-agent';
|
||||
import { parseFrontmatter, resizeImage } from '@earendil-works/pi-coding-agent';
|
||||
import { productionLedger, recordProductionInputs, scopedProductionBrief } from './production-repository.mjs';
|
||||
import { PresentationBatch } from './stream-presentation.mjs';
|
||||
import { candidateUsage, loadSlots, productionFacts, productionPicturePlan, productionSettings } from './production-slots.mjs';
|
||||
import { candidateUsage, loadSlots, productionFacts, productionPicturePlan, productionSettings, productReferences, referenceIndexOf, slotTarget } from './production-slots.mjs';
|
||||
import { productRequestScope } from './production-recovery.mjs';
|
||||
import { canvasTransformArgs, reviewProductionCandidate } from './candidate-review.mjs';
|
||||
import { OVERLAY_SCREEN_FIELDS, extractPageLiveCopy, resolveLiveSlotCopy } from './copy-image-alignment.mjs';
|
||||
import { extractPageLiveCopy, resolveLiveSlotCopy } from './copy-image-alignment.mjs';
|
||||
import { executeWorkflow, LOCAL_OPERATION_WAIT_MS } from './workflow-execute.mjs';
|
||||
import { createVideoToolExecutors, videoTools } from './video-tools.mjs';
|
||||
import { activityToolLabel, COPY_UPDATE_LIMIT, copyUpdateItem } from './activity-event.mjs';
|
||||
import { reviewOutputScreen, summarizeOverlayGroups } from './screen-review.mjs';
|
||||
import { createTailWatcher } from './tail-watcher.mjs';
|
||||
import { validateWorkerArguments } from './worker-receipts.mjs';
|
||||
import { summarizeImageWait } from './image-wait-summary.mjs';
|
||||
import { productionImageWorker } from './production-image-worker.mjs';
|
||||
import { createProductionScreenTools } from './production-screen-tools.mjs';
|
||||
|
||||
export { productionOperationTools } from './production-tools.mjs';
|
||||
export { imageResult } from './production-receipts.mjs';
|
||||
|
||||
const {frontmatter: {maxGenerationAttempts: defaultGenerationLimit}} = parseFrontmatter(
|
||||
readFileSync(new URL('./skills/product-image-sources/SKILL.md', import.meta.url), 'utf8'),
|
||||
);
|
||||
|
||||
const obj=fields=>Type.Object(fields,{additionalProperties:false});
|
||||
const text=Type.String({minLength:1});
|
||||
const ids=Type.Array(text);
|
||||
const slotRef=text;
|
||||
const layer=Type.Integer({minimum:1});
|
||||
const page=Type.Integer({minimum:0});
|
||||
const rev=Type.Integer({minimum:0});
|
||||
const optional=Type.Optional;
|
||||
const fit=StringEnum(['cover', 'contain']);
|
||||
const productReference=Type.String({pattern:'^P[0-9]{2,}$',description:'从 read_slot_images 的 productReferences 清单选择,例如 P01。'});
|
||||
const referenceIndexOf=id=>Number(id.slice(1))-1;
|
||||
const productReferences=count=>Array.from({length:count??0},(_,index)=>'P'+String(index+1).padStart(2,'0'));
|
||||
const productImageArgs={
|
||||
reference:optional(productReference),
|
||||
referenceIndex:optional(page),referenceCrop:optional(Type.Array(Type.Integer({minimum:0,maximum:1000}),{minItems:4,maxItems:4,description:'归一化裁切 [x,y,w,h]。'})),
|
||||
};
|
||||
const reuseTarget=obj({outputId:optional(text),slotId:slotRef});
|
||||
const transformDescription='在本机裁切、镜像、旋转、缩放或位移本款实拍及任一成品的同花色候选。sourceSlotId 精确匹配本项目的完整 slotId、fieldId 或图位标签,使用该图位当前采用的同花色候选,可跨成品。sourceCandidateId 接收候选编号,referenceIndex 接收从 0 开始的实拍序号,三种来源互斥。来源编号无效时返回匹配图位或目标图位的已完成候选。返回新候选、实际来源 sourceCandidateId、cropSourcePixels、targetFrame、resolutionRatio 和 resolutionSufficient。';
|
||||
const transformImageArgs={
|
||||
reference:optional(productReference),
|
||||
sourceSlotId:optional(Type.String({description:'来源图位的完整 slotId、fieldId 或标签,使用当前采用的同花色候选。'})),
|
||||
sourceCandidateId:optional(Type.String({description:'本项目当前花色的已完成候选号,可来自其他图位。'})),
|
||||
referenceIndex:optional(Type.Integer({minimum:0,maximum:7,description:'本款实拍的零起始编号。'})),
|
||||
...canvasTransformArgs,
|
||||
};
|
||||
const preparationArgs={
|
||||
prompt:text,
|
||||
reworkChange:optional(Type.String({description:'返工时记录这次改变了什么。'})),
|
||||
reworkCandidateId:optional(text),
|
||||
references:optional(Type.Array(productReference,{minItems:1})),
|
||||
referenceIndexes:optional(Type.Array(page,{minItems:1,description:'本款原片的零起始编号,按实际发送顺序填写。'})),
|
||||
useTemplateBase:optional(Type.Boolean({description:'使用本图位固定模板原稿像素作为第一张图,随后发送本款实拍。false 表示本请求不使用模板底图。'})),
|
||||
prefer2k:optional(Type.Boolean({description:'传 true 可请求 2K。'})),
|
||||
retryOf:optional(Type.String({description:'仅限已确认可重试的失败候选。'})),
|
||||
};
|
||||
const imageRequestDescription='保存完整生图请求,返回正式文本、参考顺序、模型参数与请求编号。';
|
||||
const dispatchArgs={requestId:text,expectedRevision:optional(rev),expectedHash:optional(text)};
|
||||
|
||||
const outputScope={outputId:optional(text),variantId:optional(text)};
|
||||
|
||||
export const productionOperationTools = [
|
||||
['open_production_output','打开本轮指定输出和花色。切换前保存原工程,返回保存结果、新画布绑定及各成品的在途工作。work 中的 waitingCanvas 列出仍在等切回的图位。',obj({outputId:text,variantId:text})],
|
||||
['set_production_settings','记录当前项目的参考偏好或主图画幅。template-base 表示用原图换商品,composition-only 表示只参考构图,none 表示不参考。单个生图请求可自行选择是否使用模板底图。',obj({
|
||||
referenceMode:optional(StringEnum(['template-base', 'composition-only', 'none'])),
|
||||
mainImageAspects:optional(Type.Array(Type.String({pattern:'^[1-9][0-9]*:[1-9][0-9]*$'}),{minItems:1})),
|
||||
})],
|
||||
['plan_production','读取商品、模板和成品进度。projectSlots 按成品和花色列出本轮所有图位的屏、图框像素、模板主体事实和候选号。framePending 表示像素值来自模板,实际图框待核对。adoptionRecorded 是已有采用记录的候选号,selectedCandidateId 是画布读到的当前采用。可指定输出和花色,省略时读取当前工作画布。按 slotIds 获取指定图位及其发布要求;includeKnowledge=true 列出固定版本的规则路径,可用 read 读取。返回已声明的参考方式和主图画幅。mode 为制作模式,budget 为制作时间,limits 为候选上限。candidateCount 和 candidatesRemaining 为图位已用和剩余候选数。pictures 中的 copyReady 表示关联文案是否已写好。图位工具优先使用 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 登记。copyUpdates 返回本次写入的文案事实。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({
|
||||
...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})],
|
||||
['transform_slot_image',transformDescription,obj({...outputScope,slotId:slotRef,...transformImageArgs})],
|
||||
['prepare_image_request',imageRequestDescription,obj({...outputScope,slotId:slotRef,...preparationArgs})],
|
||||
['dispatch_image_request','审阅准备回执后填写首个 requestId 确认派发生图批次。宿主从该编号绑定的请求读取版本和哈希。使用 await_image_slots 或 review_image_slots 查看实际结果,状态为 complete 的候选可用 check_image_slots 验图。',obj({...outputScope,...dispatchArgs})],
|
||||
['delegate_image_slots','异步分派制作任务。每个 job 的 slotId 是主图位,reuseTargets 可列同花色的额外目标图位,每项含 slotId 和可选 outputId。组内助手可查同花色候选并裁切到组内图位,可写画布上的候选可显式采用。返回分派状态与待写文案字段。',obj({
|
||||
...outputScope,jobs:Type.Array(obj({slotId:slotRef,goal:text,reuseTargets:optional(Type.Array(reuseTarget)),reworkCandidateId:optional(Type.String({description:'返工时,指定之前被退回的候选号。'}))})),
|
||||
})],
|
||||
['await_image_slots','等待在途制作、验图或生图请求返回,提供状态、编号和修改摘要。状态为 complete 的候选可用 check_image_slots 验图。waitForAll=true 等待选中范围内调用时已在途的工作。单次最多等待 3 分钟,超时后原工作继续。省略 slotIds 时也关注整屏复核,完整意见用 read_screen_review 按屏读取;图位详情用 review_image_slots。omitted 是因体积限制省略的条数。expired 表示原请求已收口,可为同图位另备新请求。未知结果用 reconcile_image_slots 核查,waiting_canvas 表示等待可写画布。',obj({...outputScope,slotIds:optional(ids),waitForAll:optional(Type.Boolean())})],
|
||||
['review_image_slots','只读查看指定成品和花色的候选、验图、原请求、覆盖统计与整屏复核进度。screensReadyForReview 是图位已齐、当前画面待复核的多图位屏。waiting_canvas 的图位在等待切回可写画布。指定 slotIds 查看详情,或在 slotIds 填写一个图位并指定 candidateId 查看实际候选像素;批量详情超出预算时返回摘要,用 nextOffset 作为 offset 翻页,再用单个 slotId 查看全文。',obj({...outputScope,slotIds:optional(Type.Array(Type.String())),candidateId:optional(text),offset:optional(Type.Integer({minimum:0}))})],
|
||||
['list_project_images','列出本项目已完成且可读的候选,包括有采纳记录的图。可按来源成品和花色筛选,生图次数取自宿主已派发的记录。sourceCandidateId 可引用任一成品的同花色候选做本地变换或复用。用 nextOffset 作为 offset 翻页,candidateId 展开单条。',obj({...outputScope,candidateId:optional(Type.String()),offset:optional(Type.Integer({minimum:0}))})],
|
||||
['read_archived_images','只读查找其他本机项目同款的历史候选。可选 slotIds 查看有对应图位的结果。不同模板或花色的已完成候选也可放入当前图位复核。用 nextOffset 作为 offset 翻页,candidateId 展开单条,可用 projectId 指定来源项目。',obj({
|
||||
slotIds:optional(Type.Array(Type.String())),candidateId:optional(Type.String()),projectId:optional(Type.String()),offset:optional(Type.Integer({minimum:0})),
|
||||
})],
|
||||
['stage_archived_image','把已完成的候选加入当前目标图位待验,沿用其原素材任务。来源是本项目任一成品的同花色候选时省略 projectId,来源是另一同款项目时使用 read_archived_images 返回的 projectId。',obj({
|
||||
...outputScope,slotId:slotRef,projectId:optional(Type.String()),candidateId:text,
|
||||
})],
|
||||
['check_image_slots','请验图代理按企业 Skill 同看候选原图及候选放入后的整屏画面,模板底图候选也会附上固定图位原图。复核输入包含当前图位关联文案。可用 fit 指定预览放置方式。默认先返回受理结果,可用 review_image_slots 查看结论,用 adopt_production_image 采用你选定的候选。',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({slotId:slotRef,candidateId:text,fit:optional(fit),reason:optional(text)})],
|
||||
['retire_production_image','清理你已判为失败的当前图位候选,保留原因、提示词和原请求记录。若该图已在画布上,回执会给出应替换的图层。',obj({slotId:slotRef,candidateId:text,reason:text})],
|
||||
['reconcile_image_slots','按已保存的原操作或原候选号核查结果。状态为 complete 的候选可用 check_image_slots 验图。未绑定画布时核查本轮项目输出,可用完整图位 id 缩小范围。unknown 继续核查原号,结果有留存时按原号取回,不重新付费。expired 表示原请求已收口。网关确认结果过期(HTTP 410)、结果链接下载返回 404 或 410,或 180 秒恢复预算用完后原查询仍是 unresolved 或 404 request_not_found,都会进入此终态。404 request_not_found 收口时按未发起处理。expired 可以为同图位另备新请求;按未发起处理的请求不计入该图位的生图次数,其他已派发请求仍计入。',obj({...outputScope,slotIds:optional(ids)})],
|
||||
['read_output_screen',`读取整屏合成画面、模板差异摘要、overlayLayers、slotGeometry、annotationLayout 和 textClipping。slotImageFacts 逐图位列出已采用图片的 source(来源类别、候选或请求号、上游图位或实拍文件)、当前与模板图框的近白平坦像素比例 nearWhiteFlatRatio / templateNearWhiteFlatRatio(0–1,缺样本为空),以及 nearest 中本成品最相近的最多三个其它图位的屏号和 64 位 dHash 汉明距离 distance(0–64,越小越相似)。textLayers 逐层返回样式差异、当前和模板的字形附近对比度 P10/P50(WCAG 公式)及底色亮度标准差,缺少样本时对应值为空。annotationLayout.dimensionGroups 按模板图层编号列出标签和线,subjectBoundsOffsets 为端点减去主体框左、上、右、下边界的坐标差。guides 的 visibility 和 templateVisibility 分别是当前成图和模板原屏同层的像素回执。contrastP10 和 contrastP50 是标记像素与紧邻一像素背景的 WCAG 对比度百分位。lineWidthsPx 与 lines 顺序一致,diameterPx 是无标线几何时标记像素包围盒的最长边。textClipping 列出越出当前屏的文字图层和墨迹边界矩形 [x,y,w,h]。局部查看用 page 和 region(画布坐标 [x,y,w,h]),zoom 为 1–4 倍,图上网格标的是原画布坐标。annotationLayout 提供可见文字、线端点、穿线长度、主体框重叠比例和双向最近距离。用 includeTemplateImage 读取模板原屏,用 templateLayerId 查具体图层的完整原值与现值。若返回 nextChangeOffset,可用 templateChangeOffset 继续读差异。subjectBounds 是画布坐标 [x,y,w,h],由放置后的像素与边缘背景的色差估测,并裁到图位可见框内。测不出时由 subjectBoundsReason 说明原因。page 指定单屏,pages 可按需查看 2–4 屏,屏号从 0 开始。reviewRound 为已完成的整屏复核次数,issueHistory 为此前各轮问题数。只保留最新一次查看图片。${OVERLAY_SCREEN_FIELDS}`,obj({
|
||||
page:optional(page),pages:optional(Type.Array(page)),
|
||||
region:optional(Type.Array(Type.Integer(),{minItems:4,maxItems:4,description:'画布坐标 [x,y,w,h],宽高至少 1 像素。'})),
|
||||
zoom:optional(Type.Number({minimum:1,maximum:4})),
|
||||
includeTemplateImage:optional(Type.Boolean()),templateLayerId:optional(Type.Integer({minimum:1})),templateChangeOffset:optional(Type.Integer({minimum:0})),
|
||||
})],
|
||||
['check_output_screens','按企业 Skill 并行复核整屏合成画面、商品实拍、实时文案与叠加图层。pages 从 1 编号,以当前画布实际屏数为准。默认等待结论,保存通过和需要修正的屏。reviewRound 为整屏复核轮次,issueHistory 为此前各轮问题数。问题按图位、原生图层或文案字段定位。wait=false 可用不带 slotIds 的 await_image_slots 收取摘要。',obj({
|
||||
pages:Type.Array(Type.Integer({minimum:1}),{minItems:1}),
|
||||
wait:optional(Type.Boolean({default:true})),
|
||||
})],
|
||||
['read_screen_review','读取指定成品最近一次完整的整屏复核回执。page 从 1 编号。不启动新的复核。',obj({...outputScope,page:Type.Integer({minimum:1})})],
|
||||
['defer_production_output','挂起当前输出并记录需要外部处理的原因和所需动作。可用 await_image_slots 或 reconcile_image_slots 查询在途请求。',obj({
|
||||
blocker:obj({kind:StringEnum(['missing_required_input', 'authorization_required', 'permanent_service_failure']),reason:text,requiredAction:text}),
|
||||
})],
|
||||
['finish_production','保存并导出当前画布修订,返回成品状态、落盘文件、尺寸和工程重开结果。slotCoverage 统计已采用、人工置入、有候选待采用、空白与跳过的图位。若仍有通过复核的图位尚未填入,返回待采用候选;明确交付现状时可填写 deliveryReason。fidelityReport 包含差异总条数、按屏分类计数和待复核差异,reportPath 可用 read 读取完整报告。scope=all 按实际文件核验本轮交付,可附当前画布修订同时导出。用 issues 记录已知问题。',obj({
|
||||
...outputScope,revision:optional(rev),scope:optional(StringEnum(['current', 'all'])),issues:optional(Type.Array(obj({outputId:optional(text),variantId:optional(text),page:optional(Type.Integer({minimum:1})),field:optional(text),reason:text}))),
|
||||
deliveryReason:optional(text),
|
||||
})],
|
||||
];
|
||||
|
||||
const slotTarget=({fieldId,width,height,aspectRatio})=>Object.fromEntries(
|
||||
Object.entries({fieldId,width,height,aspectRatio}).filter(([,value])=>value!=null));
|
||||
|
||||
export const imageResult = ({images=[],...details})=>({
|
||||
content:[{type:'text',text:JSON.stringify(details)},...images],details,
|
||||
});
|
||||
|
||||
export function productionVideoTools(host, make) {
|
||||
const { productionGoal, videoRuntime } = host;
|
||||
const outputs = productionGoal?.requestedOutputs ?? [];
|
||||
@ -881,6 +776,19 @@ export async function openProductionOperations(host,{target=host.productionConte
|
||||
return {slotId:slot.id,candidateId,error:error.message};
|
||||
}
|
||||
}
|
||||
|
||||
const screenTools=createProductionScreenTools({
|
||||
host,canvas,outputId,variantId,slots,screenChecks,stageSignal,runDetailAgent,
|
||||
copySnapshot,current,onCanvas,scheduleDelegate,readImages,notice,
|
||||
onScreenRead:revision=>{
|
||||
if(progressSnapshot&&revision!==progressSnapshot.revision)markProgressDirty();
|
||||
},
|
||||
requirementsForPage:page=>fieldRequirements(plan).filter(row=>row.page===page),
|
||||
screenFactConflicts:(fields,overlays,page)=>screenFactConflicts(fields,overlays,plan,page),
|
||||
recordedScreenReview:page=>new Map(journal.screenReviews??[]).get(page),
|
||||
screenReviewFacts,saveOutputScreenReview,
|
||||
});
|
||||
|
||||
const operations = {
|
||||
get active(){return jobs.size;},
|
||||
markProgressDirty,
|
||||
@ -1128,164 +1036,32 @@ export async function openProductionOperations(host,{target=host.productionConte
|
||||
const status={target:slotTarget(liveById.get(slot.id)??slot),...statuses.get(slot.id),...(pendingCopyFields?.length?{pendingCopyFields}:null)};
|
||||
if(slotWorking(slot.id)){assigned.push({id:slot.id,state:'already_running',...status});continue;}
|
||||
const row={number:nextWorkerNumber(),slotId:slot.id,label:slot.label,step:'排队中',active:true};
|
||||
let rework, latestPrepared, produced=false;
|
||||
const dispatched=new Map();
|
||||
const workerTool=(name,description,properties,execute,terminate=false)=>{
|
||||
const parameters=obj(properties);
|
||||
return {
|
||||
name,label:description,description,parameters,executionMode:'sequential',
|
||||
...(terminate?{prepareArguments:args=>validateWorkerArguments(name,parameters,args,()=>`本次委托图位 slotId ${JSON.stringify(slot.id)}`)}:null),
|
||||
execute:async(_id,args,workerSignal)=>{
|
||||
const activeSignal=workerSignal?AbortSignal.any([workerSignal,delegateSignal]):delegateSignal;
|
||||
activeSignal.throwIfAborted();
|
||||
const result=await execute(args,activeSignal);
|
||||
const done=typeof terminate==='function'?terminate(result):terminate;
|
||||
if(done||name==='use_product_image'||name==='transform_slot_image'||name==='dispatch_image_request'&&result.operationId){
|
||||
produced=true;
|
||||
if(name==='use_product_image'||name==='transform_slot_image'){
|
||||
const previous=generation.get(workerId);
|
||||
if(grouped&&previous?.candidateId)generation.set(previous.candidateId,previous);
|
||||
generation.set(workerId,{slotId:slot.id,...result});
|
||||
}
|
||||
}
|
||||
return {...imageResult(result),...(done?{terminate:true}:null)};
|
||||
},
|
||||
};
|
||||
};
|
||||
const workerTools=[
|
||||
workerTool('use_product_image','用本款实拍创建图位候选',productImageArgs,
|
||||
(args,activeSignal)=>useProductImage(slot,args,activeSignal),()=>!grouped),
|
||||
workerTool('transform_slot_image',transformDescription,
|
||||
{...transformImageArgs,...(grouped?{outputId:optional(text),slotId:optional(slotRef)}:null)},
|
||||
async(args,activeSignal)=>{
|
||||
if(!grouped)return transformImage(slot,args,activeSignal);
|
||||
const result=await groupCall('transform_slot_image',args,activeSignal);
|
||||
return {...result,outputId:args.outputId??outputId,slotId:args.slotId??slot.id};
|
||||
}),
|
||||
...(grouped?[
|
||||
workerTool('list_project_images','列出同花色的本项目候选,可按来源成品筛选。',{
|
||||
outputId:optional(text),candidateId:optional(text),offset:optional(Type.Integer({minimum:0})),
|
||||
},async({outputId,candidateId,offset})=>candidateReceipt(
|
||||
await canvas.detailHistory({projectImages:true,outputId,variantId}),{},{candidateId,offset})),
|
||||
workerTool('adopt_production_image','在可写画布采用指定图位的候选。',{
|
||||
outputId:optional(text),slotId:slotRef,candidateId:text,fit:optional(fit),reason:optional(text),
|
||||
},(args,activeSignal)=>groupCall('adopt_production_image',args,activeSignal)),
|
||||
workerTool('await_image_slots','等待本次委托派发的原请求。operationIds 可一次接收多份回执。',{
|
||||
operationId:optional(text),operationIds:optional(ids),
|
||||
},async({operationId,operationIds},activeSignal)=>{
|
||||
const requested=operationIds??(operationId?[operationId]:[...dispatched.keys()]);
|
||||
if(requested.some(id=>!dispatched.has(id)))throw Error('原请求不属于本次委托');
|
||||
const generation=await awaitCanvas(Promise.all([...new Set(requested)].map(id=>dispatched.get(id))),activeSignal);
|
||||
return operationId&&!operationIds?generation[0]:{generation};
|
||||
}),
|
||||
]:[]),
|
||||
workerTool('prepare_image_request',imageRequestDescription,preparationArgs,
|
||||
async(args,activeSignal)=>{
|
||||
latestPrepared=undefined;
|
||||
const receipt=await prepareImageRequest(slot,{...args,reworkCandidateId:rework?.candidateId},activeSignal);
|
||||
if(receipt.requestId)latestPrepared=receipt.requestId;
|
||||
return receipt;
|
||||
}),
|
||||
workerTool('dispatch_image_request','传空对象确认派发本子任务最近一次准备的请求。需选择另一份准备回执时传 requestId。', {...dispatchArgs,requestId:optional(text)},
|
||||
async(args,activeSignal)=>{
|
||||
const requestId=args.requestId ?? latestPrepared;
|
||||
if(!requestId)throw Error('本图位还没有准备回执。先用 prepare_image_request 准备请求,再用空对象确认派发。');
|
||||
const approval={...args,requestId};
|
||||
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});
|
||||
});
|
||||
const errors=[];
|
||||
if(approval.expectedRevision!==undefined&&approval.expectedRevision!==request.revision){
|
||||
errors.push(`expectedRevision ${approval.expectedRevision} 与准备回执不一致,可用值为 ${request.revision}`);
|
||||
}
|
||||
if(approval.expectedHash!==undefined&&approval.expectedHash!==request.requestSpecHash){
|
||||
errors.push(`expectedHash ${JSON.stringify(approval.expectedHash)} 与准备回执不一致,可用值为 ${JSON.stringify(request.requestSpecHash)}`);
|
||||
}
|
||||
if(errors.length)throw Error([`requestId ${JSON.stringify(approval.requestId)},slotId ${JSON.stringify(slot.id)}`,...errors].join('\n'));
|
||||
row.step='正在生图';
|
||||
notice('子代理正在生图');
|
||||
const receipt=await queueDispatch(slot,approval,request,activeSignal,row.number);
|
||||
if(receipt.operationId)dispatched.set(receipt.operationId,jobs.get(receipt.operationId)?.run??Promise.resolve(receipt));
|
||||
await dispatchingImages.get(receipt.operationId)?.enqueued;
|
||||
return receipt;
|
||||
},result=>!grouped&&!result.limitReached),
|
||||
];
|
||||
let referenceSnapshot;
|
||||
const readReferences=async includeTemplateReference=>{
|
||||
const snapshot=await current();
|
||||
const {creation,slots,canvas}=snapshot.revisions??{};
|
||||
const version=creation??snapshot.version;
|
||||
const revision=version==null?undefined:JSON.stringify([version,slots,canvas]);
|
||||
if(revision!==undefined&&referenceSnapshot?.revision===revision&&
|
||||
referenceSnapshot.includeTemplateReference===includeTemplateReference){
|
||||
return referenceSnapshot.result;
|
||||
}
|
||||
const result=await readImages(slot.id,{includeTemplateReference});
|
||||
referenceSnapshot={revision,includeTemplateReference,result};
|
||||
return result;
|
||||
};
|
||||
const readTool={name:'read_slot_images',label:'查看图位图片',
|
||||
description:grouped?'读取组内图位的参考或指定候选的实际图片。':'读取本款实拍。按制作配置返回模板参考。',
|
||||
parameters:grouped
|
||||
?obj({outputId:optional(text),slotId:optional(slotRef),candidateId:optional(text),includeTemplateReference:optional(Type.Boolean())})
|
||||
:obj({includeTemplateReference:optional(Type.Boolean())}),
|
||||
execute:async(_id,args={})=>{
|
||||
const {includeTemplateReference}=args;
|
||||
delegateSignal.throwIfAborted();
|
||||
if(grouped&&(args.candidateId||args.outputId&&args.outputId!==outputId||args.slotId&&findSlot(args.slotId)?.id!==slot.id)){
|
||||
return groupCall('read_slot_images',args,delegateSignal);
|
||||
}
|
||||
const {referenceMode}=productionSettings(store,plan.template.production);
|
||||
const result=await readReferences(includeTemplateReference??['template-base','composition-only'].includes(referenceMode));
|
||||
return imageResult({...result,productReferences:productReferences(result.referenceCount)});
|
||||
}};
|
||||
const run=scheduleDelegate(delegateSignal,async()=>{
|
||||
row.step='正在准备';
|
||||
notice('子代理正在制作');
|
||||
const prior=journal.items[slot.id];
|
||||
const candidateId=reworkCandidateId?.trim();
|
||||
let rejectedImage;
|
||||
if(candidateId){
|
||||
const live=(await readSlots()).slots.find(next=>next.id===slot.id)??slot;
|
||||
const {attemptCount,rejections,reviews}=slotAttempts(live,prior);
|
||||
const feedback=reviews.findLast(entry=>entry.candidateId===candidateId);
|
||||
const old=await readImages(slot.id,{candidateId,includeProductReferences:false,includeTemplateReference:false})
|
||||
.catch(error=>({unavailable:error.message}));
|
||||
if(old.candidateId===candidateId&&old.images?.at(-1)?.type==='image')rejectedImage=old.images.at(-1);
|
||||
const attempt=prior?.attempts?.find(entry=>entry.candidateId===candidateId);
|
||||
rework={candidateId,attempt:attemptCount+1,reason:feedback?.reason,
|
||||
recommendedAction:feedback?.recommendedAction,canvasTransform:feedback?.canvasTransform,
|
||||
suggestions:feedback?.mustRedo,generationFixes:feedback?.generationFixes,
|
||||
previousPrompt:old.candidateId===candidateId?old.candidatePrompt??undefined:undefined,
|
||||
previousInstruction:attempt?.prompt,
|
||||
previousOutcomes:rejections,
|
||||
...(!feedback?{reviewUnavailable:'此候选号没有留存退回回执'}:null),
|
||||
...(rejectedImage?{imageAttached:true}:{unavailable:old.unavailable??'未读到这张候选的原图'}),
|
||||
};
|
||||
}
|
||||
const live=await liveSlot(slot);
|
||||
const status=slotDrawStatus(live);
|
||||
const {referenceMode}=productionSettings(store,plan.template.production);
|
||||
const instructions='按锁定的企业 Skill 及小壹补充完成委托。完成主代理委托的图位。goal 是本次任务,screenCopy 是画布实时文案。pendingCopyFields 中的 templateExample 是模板样例。首条消息包含有编号的实拍和可用的模板参考。可用 transform_slot_image 调整已有图像并查看像素指标。派发回执会带原请求号,宿主继续跟踪结果。'+
|
||||
(rework?'\n附件含退回图、验图回执和上次实发提示词。reworkChange 记录改动。':'');
|
||||
const screenCopy=await liveSlotCopy(slot);
|
||||
const references=await readReferences(['template-base','composition-only'].includes(referenceMode))
|
||||
.catch(error=>({unavailable:error.message}));
|
||||
const {images=[],referenceCount=0,layoutCount=0,layoutIssue,unavailable,prompt:templatePrompt,outputSpec,
|
||||
referenceBindings=[],supplementalBindings=[]}=references;
|
||||
const productIds=productReferences(referenceCount);
|
||||
const attachments=[...images.slice(0,referenceCount+layoutCount),
|
||||
...(supplementalBindings.length?images.slice(-supplementalBindings.length):[]),...(rejectedImage?[rejectedImage]:[])];
|
||||
const captions=[...productIds,...Array.from({length:layoutCount},()=> '模板构图参考'),
|
||||
...(rejectedImage?['退回候选原图']:[])];
|
||||
delegateSignal.throwIfAborted();
|
||||
await runDetailAgent(slot.id,instructions,
|
||||
JSON.stringify({rework,goal,referenceMode,screenCopy,pendingCopyFields,target:slotTarget(live),
|
||||
product:scopedProductionBrief((await current()).productEvidence?.brief??{},variantId,outputId),
|
||||
productReferences:productIds,referenceBindings,supplementalBindings,layoutCount,layoutIssue,templatePrompt,outputSpec,referenceError:unavailable,...status,...(grouped?{groupTargets}:null),field:slot.fieldId,label:slot.label,rule:slot.productionRule,requirements:slot.requirements}),[readTool,...workerTools],
|
||||
attachments,productRequestScope('slot',slot.id),captions,delegateSignal);
|
||||
if(!produced)generation.set(workerId,{slotId:slot.id,phase:'no_candidate'});
|
||||
}).catch(async error=>{
|
||||
const worker=productionImageWorker({
|
||||
slot,goal,reworkCandidateId,groupTargets,pendingCopyFields,status,outputId,variantId,row,
|
||||
groupCall,awaitCanvas,findSlot,current,slotDrawStatus,notice,
|
||||
getReferenceMode:()=>productionSettings(store,plan.template.production).referenceMode,
|
||||
getSlotRecord:()=>journal.items[slot.id],
|
||||
readSlot:async()=>(await readSlots()).slots.find(next=>next.id===slot.id)??slot,
|
||||
readImages:args=>readImages(slot.id,args),
|
||||
listProjectImages:scope=>canvas.detailHistory({projectImages:true,...scope}),
|
||||
liveSlot:()=>liveSlot(slot),
|
||||
liveSlotCopy:()=>liveSlotCopy(slot),
|
||||
runDetailAgent:(...args)=>runDetailAgent(slot.id,...args),
|
||||
recordLocalCandidate:result=>{
|
||||
const previous=generation.get(workerId);
|
||||
if(grouped&&previous?.candidateId)generation.set(previous.candidateId,previous);
|
||||
generation.set(workerId,{slotId:slot.id,...result});
|
||||
},
|
||||
recordNoCandidate:()=>generation.set(workerId,{slotId:slot.id,phase:'no_candidate'}),
|
||||
pendingDispatch:receipt=>jobs.get(receipt.operationId)?.run??Promise.resolve(receipt),
|
||||
dispatchEnqueued:id=>dispatchingImages.get(id)?.enqueued,
|
||||
useProductImage:(...args)=>useProductImage(slot,...args),
|
||||
transformImage:(...args)=>transformImage(slot,...args),
|
||||
prepareImageRequest:(...args)=>prepareImageRequest(slot,...args),
|
||||
preparedRequest:id=>preparedRequest(id,slot),
|
||||
queueDispatch:(approval,request,signal)=>queueDispatch(slot,approval,request,signal,row.number),
|
||||
},delegateSignal);
|
||||
const run=scheduleDelegate(delegateSignal,worker.run).catch(async error=>{
|
||||
if(delegateSignal.aborted){
|
||||
generation.set(workerId,{slotId:slot.id,phase:'cancelled'});
|
||||
return;
|
||||
@ -1297,7 +1073,7 @@ export async function openProductionOperations(host,{target=host.productionConte
|
||||
notice('子代理已有回执');
|
||||
});
|
||||
generation.delete(workerId);
|
||||
jobs.set(workerId,{row,run,dispatched,startedAt:performance.now()});
|
||||
jobs.set(workerId,{row,run,dispatched:worker.dispatched,startedAt:performance.now()});
|
||||
assigned.push({id:slot.id,state:'assigned',...status,...(grouped?{groupTargets}:null)});
|
||||
}
|
||||
if(assigned.some(row=>row.state==='assigned'))notice('图位已排队');
|
||||
@ -1539,143 +1315,7 @@ export async function openProductionOperations(host,{target=host.productionConte
|
||||
const pendingSlots=new Set(originals.map(row=>row.slotId));
|
||||
return [...originals,...results.filter(row=>row.phase!=='none'||!pendingSlots.has(row.slotId))];
|
||||
},
|
||||
async read_output_screen({page=0,pages,includeTemplateImage=false,templateLayerId,templateChangeOffset=0,region,zoom},signal){
|
||||
if(region && (region[2]<1 || region[3]<1)) throw Error('局部读取的宽高至少为 1 像素');
|
||||
if(region && pages?.length) throw Error('局部读取请用 page 指定单屏');
|
||||
const render=async page=>{
|
||||
const {images=[],overlayLayers,templateFidelity:templateEvidence,...details}=await canvas.detailRender({
|
||||
page,templateComparison:true,...(region?{region,zoom}:null),...(includeTemplateImage?{includeTemplateImage:true}:null),
|
||||
...(templateLayerId?{templateLayerId}:null),
|
||||
});
|
||||
const snapshot=await copySnapshot({screenFingerprintPage:page});
|
||||
if(progressSnapshot&&snapshot.revision!==progressSnapshot.revision)markProgressDirty();
|
||||
const {pages:copyPages=[],fields:copyFields=[]}=snapshot;
|
||||
const pageId=copyPages[page];
|
||||
const pageFields=pageId==null?[]:copyFields.filter(field=>(field.page??field.pageId)===pageId&&field.currentText?.trim());
|
||||
// 画布文案回执提供实时文字,图层回执提供包含父组的实际可见性。
|
||||
const visibleCopy=await Promise.all(pageFields.map(async field=>{
|
||||
if(field.visible!=null||!field.layer)return field;
|
||||
const {context}=await canvas.readCanvas({layer:field.layer});
|
||||
return {...field,visible:context?.layers?.[0]?.effectiveVisible};
|
||||
}));
|
||||
const screenCopy=extractPageLiveCopy({pageIndex:page,pages:copyPages,fields:visibleCopy});
|
||||
const previews=await Promise.all(images.map(async image=>{
|
||||
if(image.type!=='image'||(region&&image===images[0]))return {image};
|
||||
const resized=await resizeImage(Buffer.from(image.data,'base64'),image.mimeType,host.info?.model?.inputLimits?.images?.resize);
|
||||
if(!resized)return {image};
|
||||
return {image:{type:'image',data:resized.data,mimeType:resized.mimeType},note:formatDimensionNote(resized)};
|
||||
}));
|
||||
const notes=previews.map(preview=>preview.note).filter(Boolean);
|
||||
const requirements=fieldRequirements(plan).filter(row=>row.page===pageId);
|
||||
const overlayGroups=summarizeOverlayGroups(overlayLayers??[]);
|
||||
const factConflicts=screenFactConflicts(visibleCopy,overlayLayers??[],plan,pageId);
|
||||
return imageResult({...details,...screenReviewFacts(page),...(overlayLayers===undefined?null:{overlayLayers}),
|
||||
...(overlayGroups.length?{overlayGroups}:null),
|
||||
...(snapshot.revision!=null&&snapshot.revision!==details.revision?{copyRevision:snapshot.revision}:null),
|
||||
...(snapshot.screenFingerprint!==details.screenFingerprint?{screenChanged:true}:null),
|
||||
...(screenCopy.length?{screenCopy}:null),
|
||||
...(requirements.length?{fieldRequirements:requirements}:null),
|
||||
...((templateEvidence||factConflicts.length)?{templateFidelity:compactTemplateFidelity(templateEvidence,factConflicts,templateChangeOffset)}:null),
|
||||
...(notes.length?{previewDimensions:notes}:null),images:previews.map(preview=>preview.image)});
|
||||
};
|
||||
if(!pages?.length){
|
||||
const screen=await render(page);
|
||||
notice('已读取实际画布');
|
||||
return screen;
|
||||
}
|
||||
const content=[], screens=[];
|
||||
for(const page of new Set(pages)){
|
||||
signal?.throwIfAborted();
|
||||
let screen;
|
||||
try {screen=await render(page);}
|
||||
catch(error){
|
||||
signal?.throwIfAborted();
|
||||
const details={page,error:error.message};
|
||||
screen=imageResult(details);
|
||||
}
|
||||
screens.push(screen.details);
|
||||
content.push(...screen.content);
|
||||
}
|
||||
notice('已读取实际画布');
|
||||
return {content,details:{screens}};
|
||||
},
|
||||
async check_output_screens({pages,wait=true},signal){
|
||||
if(!Array.isArray(pages)||!pages.length||pages.some(page=>!Number.isSafeInteger(page)||page<1)){
|
||||
throw Error('请填写有效屏号,屏号从 1 开始');
|
||||
}
|
||||
const activeSignal=signal?AbortSignal.any([signal,stageSignal]):stageSignal;
|
||||
activeSignal.throwIfAborted();
|
||||
const {pages:canvasPages=[]}=await copySnapshot();
|
||||
activeSignal.throwIfAborted();
|
||||
let referenceRead;
|
||||
const references=()=>referenceRead??=readReferences();
|
||||
async function readReferences(){
|
||||
const inputPlan=await current();
|
||||
const {brief,variant}=scopedProductionBrief(inputPlan.productEvidence?.brief??{},variantId,outputId);
|
||||
const product={...brief,variant,
|
||||
sellingPoints:inputPlan.productEvidence?.sellingPoints?.selected};
|
||||
if(!slots.length)throw Error('当前画布没有可读取本款实拍的图位');
|
||||
const {images=[],referenceCount=0}=await readImages(slots[0].id,{includeTemplateReference:false});
|
||||
const photos=images.slice(0,referenceCount);
|
||||
if(!referenceCount||photos.length!==referenceCount||photos.some(image=>image.type!=='image')){
|
||||
throw Error('未读取到当前款式的商品实拍');
|
||||
}
|
||||
return {product,photos,inputSignature:productionInputs(inputPlan,variantId)};
|
||||
}
|
||||
const batch=[...new Set(pages)].map(page=>{
|
||||
if(page>canvasPages.length)return {receipt:{page,error:'此屏不属于当前工作画布'}};
|
||||
const existing=screenChecks.get(page);
|
||||
if(existing?.run)return existing;
|
||||
const job={startedAt:performance.now(),receipt:{page,state:'queued'}};
|
||||
job.run=scheduleDelegate(activeSignal,async permit=>{
|
||||
job.receipt={page,state:'checking'};
|
||||
notice('正在按屏复核');
|
||||
const screen=await onCanvas(activeSignal,()=>operations.read_output_screen({page:page-1,includeTemplateImage:true},activeSignal),permit);
|
||||
const {revision,screenFingerprint,screenChanged,fieldRequirements:requirements=[],slotImageFacts}=screen.details;
|
||||
const previous=new Map(journal.screenReviews??[]).get(page-1);
|
||||
if(previous?.receipt && previous.screenFingerprint && !screenChanged &&
|
||||
previous.screenFingerprint===screenFingerprint &&
|
||||
isDeepStrictEqual(requirements,previous.receipt.fieldRequirements??[]) &&
|
||||
isDeepStrictEqual(slotImageFacts??[],previous.slotImageFacts??[]) &&
|
||||
previous.copyInputs===productionInputs(await current(),variantId)){
|
||||
job.receipt={...previous.receipt,revision,...screenReviewFacts(page-1),reused:true};
|
||||
return;
|
||||
}
|
||||
if(previous?.candidateReview && !slotImageFacts?.length && (!screen.details.templateFidelity || previous.candidateReview.templateEvidence) && !screen.details.screenChanged &&
|
||||
previous.screenFingerprint===screen.details.screenFingerprint &&
|
||||
previous.copyInputs===productionInputs(await current(),variantId)){
|
||||
job.receipt={...previous.candidateReview,...screenReviewFacts(page-1),revision:screen.details.revision,...(screen.details.fieldRequirements?{fieldRequirements:screen.details.fieldRequirements}:null),reused:true};
|
||||
return;
|
||||
}
|
||||
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:runDetailAgent,page,screen,references,
|
||||
slots:screenSlots,outputId,variantId,signal:activeSignal});
|
||||
const {inputSignature}=await references();
|
||||
const confirmed=screen.details.fieldRequirements?{...receipt,fieldRequirements:screen.details.fieldRequirements}:receipt;
|
||||
const reviewFacts=await onCanvas(activeSignal,()=>saveOutputScreenReview({
|
||||
page:page-1,screenFingerprint:receipt.screenFingerprint,slotImageFacts,
|
||||
issues:[...receipt.imageIssues,...receipt.overlayFixes,...receipt.copyFixes],
|
||||
},activeSignal,inputSignature,confirmed),permit);
|
||||
job.receipt={...confirmed,...reviewFacts};
|
||||
}).catch(error=>{
|
||||
job.receipt={page,error:error.message};
|
||||
}).finally(()=>{
|
||||
job.run=null;
|
||||
notice('按屏复核已有回执');
|
||||
});
|
||||
screenChecks.set(page,job);
|
||||
return job;
|
||||
});
|
||||
if(wait)await Promise.all(batch.map(job=>job.run));
|
||||
return batch.map(job=>job.receipt);
|
||||
},
|
||||
read_screen_review({page}){
|
||||
const recorded=new Map(journal.screenReviews??[]).get(page-1);
|
||||
const persisted=recorded?.receipt??recorded?.candidateReview;
|
||||
return screenChecks.get(page)?.receipt ?? (persisted?{...persisted,...screenReviewFacts(page-1)}:null) ??
|
||||
(recorded?{page,screenFingerprint:recorded.screenFingerprint,issues:recorded.issues}:{page,state:'no_review'});
|
||||
},
|
||||
...screenTools,
|
||||
async defer_production_output({blocker}){
|
||||
if(!blocker?.reason?.trim()||!blocker.requiredAction?.trim()){
|
||||
const slotIds=[...new Set(running().map(job=>job.row.slotId))];
|
||||
|
||||
@ -64,3 +64,7 @@ export function reviewSlotSummary(slot) {
|
||||
checks:checks?.map(summarizeCheck),
|
||||
comparison:comparison?.map(summarizeCheck)};
|
||||
}
|
||||
|
||||
export const imageResult = ({images=[],...details})=>({
|
||||
content:[{type:'text',text:JSON.stringify(details)},...images],details,
|
||||
});
|
||||
|
||||
155
apps/detail-agent-pi/src/production-screen-tools.mjs
Normal file
155
apps/detail-agent-pi/src/production-screen-tools.mjs
Normal file
@ -0,0 +1,155 @@
|
||||
import { formatDimensionNote, resizeImage } from '@earendil-works/pi-coding-agent';
|
||||
import { isDeepStrictEqual } from 'node:util';
|
||||
import { extractPageLiveCopy } from './copy-image-alignment.mjs';
|
||||
import { productionInputs } from './production-copy.mjs';
|
||||
import { scopedProductionBrief } from './production-repository.mjs';
|
||||
import { imageResult } from './production-receipts.mjs';
|
||||
import { reviewOutputScreen, summarizeOverlayGroups } from './screen-review.mjs';
|
||||
import { compactTemplateFidelity } from './template-fidelity.mjs';
|
||||
|
||||
export function createProductionScreenTools({
|
||||
host, canvas, outputId, variantId, slots, screenChecks, stageSignal, runDetailAgent,
|
||||
copySnapshot, current, onCanvas, scheduleDelegate, readImages, notice,
|
||||
onScreenRead, requirementsForPage, screenFactConflicts, recordedScreenReview, screenReviewFacts, saveOutputScreenReview,
|
||||
}) {
|
||||
const tools = {
|
||||
async read_output_screen({page=0,pages,includeTemplateImage=false,templateLayerId,templateChangeOffset=0,region,zoom},signal){
|
||||
if(region && (region[2]<1 || region[3]<1)) throw Error('局部读取的宽高至少为 1 像素');
|
||||
if(region && pages?.length) throw Error('局部读取请用 page 指定单屏');
|
||||
const render=async page=>{
|
||||
const {images=[],overlayLayers,templateFidelity:templateEvidence,...details}=await canvas.detailRender({
|
||||
page,templateComparison:true,...(region?{region,zoom}:null),...(includeTemplateImage?{includeTemplateImage:true}:null),
|
||||
...(templateLayerId?{templateLayerId}:null),
|
||||
});
|
||||
const snapshot=await copySnapshot({screenFingerprintPage:page});
|
||||
onScreenRead(snapshot.revision);
|
||||
const {pages:copyPages=[],fields:copyFields=[]}=snapshot;
|
||||
const pageId=copyPages[page];
|
||||
const pageFields=pageId==null?[]:copyFields.filter(field=>(field.page??field.pageId)===pageId&&field.currentText?.trim());
|
||||
// 画布文案回执提供实时文字,图层回执提供包含父组的实际可见性。
|
||||
const visibleCopy=await Promise.all(pageFields.map(async field=>{
|
||||
if(field.visible!=null||!field.layer)return field;
|
||||
const {context}=await canvas.readCanvas({layer:field.layer});
|
||||
return {...field,visible:context?.layers?.[0]?.effectiveVisible};
|
||||
}));
|
||||
const screenCopy=extractPageLiveCopy({pageIndex:page,pages:copyPages,fields:visibleCopy});
|
||||
const previews=await Promise.all(images.map(async image=>{
|
||||
if(image.type!=='image'||(region&&image===images[0]))return {image};
|
||||
const resized=await resizeImage(Buffer.from(image.data,'base64'),image.mimeType,host.info?.model?.inputLimits?.images?.resize);
|
||||
if(!resized)return {image};
|
||||
return {image:{type:'image',data:resized.data,mimeType:resized.mimeType},note:formatDimensionNote(resized)};
|
||||
}));
|
||||
const notes=previews.map(preview=>preview.note).filter(Boolean);
|
||||
const requirements=requirementsForPage(pageId);
|
||||
const overlayGroups=summarizeOverlayGroups(overlayLayers??[]);
|
||||
const factConflicts=screenFactConflicts(visibleCopy,overlayLayers??[],pageId);
|
||||
return imageResult({...details,...screenReviewFacts(page),...(overlayLayers===undefined?null:{overlayLayers}),
|
||||
...(overlayGroups.length?{overlayGroups}:null),
|
||||
...(snapshot.revision!=null&&snapshot.revision!==details.revision?{copyRevision:snapshot.revision}:null),
|
||||
...(snapshot.screenFingerprint!==details.screenFingerprint?{screenChanged:true}:null),
|
||||
...(screenCopy.length?{screenCopy}:null),
|
||||
...(requirements.length?{fieldRequirements:requirements}:null),
|
||||
...((templateEvidence||factConflicts.length)?{templateFidelity:compactTemplateFidelity(templateEvidence,factConflicts,templateChangeOffset)}:null),
|
||||
...(notes.length?{previewDimensions:notes}:null),images:previews.map(preview=>preview.image)});
|
||||
};
|
||||
if(!pages?.length){
|
||||
const screen=await render(page);
|
||||
notice('已读取实际画布');
|
||||
return screen;
|
||||
}
|
||||
const content=[], screens=[];
|
||||
for(const page of new Set(pages)){
|
||||
signal?.throwIfAborted();
|
||||
let screen;
|
||||
try {screen=await render(page);}
|
||||
catch(error){
|
||||
signal?.throwIfAborted();
|
||||
const details={page,error:error.message};
|
||||
screen=imageResult(details);
|
||||
}
|
||||
screens.push(screen.details);
|
||||
content.push(...screen.content);
|
||||
}
|
||||
notice('已读取实际画布');
|
||||
return {content,details:{screens}};
|
||||
},
|
||||
async check_output_screens({pages,wait=true},signal){
|
||||
if(!Array.isArray(pages)||!pages.length||pages.some(page=>!Number.isSafeInteger(page)||page<1)){
|
||||
throw Error('请填写有效屏号,屏号从 1 开始');
|
||||
}
|
||||
const activeSignal=signal?AbortSignal.any([signal,stageSignal]):stageSignal;
|
||||
activeSignal.throwIfAborted();
|
||||
const {pages:canvasPages=[]}=await copySnapshot();
|
||||
activeSignal.throwIfAborted();
|
||||
let referenceRead;
|
||||
const references=()=>referenceRead??=readReferences();
|
||||
async function readReferences(){
|
||||
const inputPlan=await current();
|
||||
const {brief,variant}=scopedProductionBrief(inputPlan.productEvidence?.brief??{},variantId,outputId);
|
||||
const product={...brief,variant,
|
||||
sellingPoints:inputPlan.productEvidence?.sellingPoints?.selected};
|
||||
if(!slots.length)throw Error('当前画布没有可读取本款实拍的图位');
|
||||
const {images=[],referenceCount=0}=await readImages(slots[0].id,{includeTemplateReference:false});
|
||||
const photos=images.slice(0,referenceCount);
|
||||
if(!referenceCount||photos.length!==referenceCount||photos.some(image=>image.type!=='image')){
|
||||
throw Error('未读取到当前款式的商品实拍');
|
||||
}
|
||||
return {product,photos,inputSignature:productionInputs(inputPlan,variantId)};
|
||||
}
|
||||
const batch=[...new Set(pages)].map(page=>{
|
||||
if(page>canvasPages.length)return {receipt:{page,error:'此屏不属于当前工作画布'}};
|
||||
const existing=screenChecks.get(page);
|
||||
if(existing?.run)return existing;
|
||||
const job={startedAt:performance.now(),receipt:{page,state:'queued'}};
|
||||
job.run=scheduleDelegate(activeSignal,async permit=>{
|
||||
job.receipt={page,state:'checking'};
|
||||
notice('正在按屏复核');
|
||||
const screen=await onCanvas(activeSignal,()=>tools.read_output_screen({page:page-1,includeTemplateImage:true},activeSignal),permit);
|
||||
const {revision,screenFingerprint,screenChanged,fieldRequirements:requirements=[],slotImageFacts}=screen.details;
|
||||
const previous=recordedScreenReview(page-1);
|
||||
if(previous?.receipt && previous.screenFingerprint && !screenChanged &&
|
||||
previous.screenFingerprint===screenFingerprint &&
|
||||
isDeepStrictEqual(requirements,previous.receipt.fieldRequirements??[]) &&
|
||||
isDeepStrictEqual(slotImageFacts??[],previous.slotImageFacts??[]) &&
|
||||
previous.copyInputs===productionInputs(await current(),variantId)){
|
||||
job.receipt={...previous.receipt,revision,...screenReviewFacts(page-1),reused:true};
|
||||
return;
|
||||
}
|
||||
if(previous?.candidateReview && !slotImageFacts?.length && (!screen.details.templateFidelity || previous.candidateReview.templateEvidence) && !screen.details.screenChanged &&
|
||||
previous.screenFingerprint===screen.details.screenFingerprint &&
|
||||
previous.copyInputs===productionInputs(await current(),variantId)){
|
||||
job.receipt={...previous.candidateReview,...screenReviewFacts(page-1),revision:screen.details.revision,...(screen.details.fieldRequirements?{fieldRequirements:screen.details.fieldRequirements}:null),reused:true};
|
||||
return;
|
||||
}
|
||||
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:runDetailAgent,page,screen,references,
|
||||
slots:screenSlots,outputId,variantId,signal:activeSignal});
|
||||
const {inputSignature}=await references();
|
||||
const confirmed=screen.details.fieldRequirements?{...receipt,fieldRequirements:screen.details.fieldRequirements}:receipt;
|
||||
const reviewFacts=await onCanvas(activeSignal,()=>saveOutputScreenReview({
|
||||
page:page-1,screenFingerprint:receipt.screenFingerprint,slotImageFacts,
|
||||
issues:[...receipt.imageIssues,...receipt.overlayFixes,...receipt.copyFixes],
|
||||
},activeSignal,inputSignature,confirmed),permit);
|
||||
job.receipt={...confirmed,...reviewFacts};
|
||||
}).catch(error=>{
|
||||
job.receipt={page,error:error.message};
|
||||
}).finally(()=>{
|
||||
job.run=null;
|
||||
notice('按屏复核已有回执');
|
||||
});
|
||||
screenChecks.set(page,job);
|
||||
return job;
|
||||
});
|
||||
if(wait)await Promise.all(batch.map(job=>job.run));
|
||||
return batch.map(job=>job.receipt);
|
||||
},
|
||||
read_screen_review({page}){
|
||||
const recorded=recordedScreenReview(page-1);
|
||||
const persisted=recorded?.receipt??recorded?.candidateReview;
|
||||
return screenChecks.get(page)?.receipt ?? (persisted?{...persisted,...screenReviewFacts(page-1)}:null) ??
|
||||
(recorded?{page,screenFingerprint:recorded.screenFingerprint,issues:recorded.issues}:{page,state:'no_review'});
|
||||
},
|
||||
};
|
||||
return tools;
|
||||
}
|
||||
@ -79,3 +79,9 @@ export async function loadSlots(canvas, outputId) {
|
||||
}
|
||||
return {plan,slots};
|
||||
}
|
||||
|
||||
export const referenceIndexOf=id=>Number(id.slice(1))-1;
|
||||
export const productReferences=count=>Array.from({length:count??0},(_,index)=>'P'+String(index+1).padStart(2,'0'));
|
||||
|
||||
export const slotTarget=({fieldId,width,height,aspectRatio})=>Object.fromEntries(
|
||||
Object.entries({fieldId,width,height,aspectRatio}).filter(([,value])=>value!=null));
|
||||
|
||||
38
apps/detail-agent-pi/src/production-tool-schema.mjs
Normal file
38
apps/detail-agent-pi/src/production-tool-schema.mjs
Normal file
@ -0,0 +1,38 @@
|
||||
import { StringEnum } from '@earendil-works/pi-ai';
|
||||
import { Type } from '@sinclair/typebox';
|
||||
import { canvasTransformArgs } from './candidate-review.mjs';
|
||||
|
||||
export const obj=fields=>Type.Object(fields,{additionalProperties:false});
|
||||
export const text=Type.String({minLength:1});
|
||||
export const ids=Type.Array(text);
|
||||
export const slotRef=text;
|
||||
export const page=Type.Integer({minimum:0});
|
||||
export const rev=Type.Integer({minimum:0});
|
||||
export const optional=Type.Optional;
|
||||
export const fit=StringEnum(['cover', 'contain']);
|
||||
const productReference=Type.String({pattern:'^P[0-9]{2,}$',description:'从 read_slot_images 的 productReferences 清单选择,例如 P01。'});
|
||||
export const productImageArgs={
|
||||
reference:optional(productReference),
|
||||
referenceIndex:optional(page),referenceCrop:optional(Type.Array(Type.Integer({minimum:0,maximum:1000}),{minItems:4,maxItems:4,description:'归一化裁切 [x,y,w,h]。'})),
|
||||
};
|
||||
export const reuseTarget=obj({outputId:optional(text),slotId:slotRef});
|
||||
export const transformDescription='本机裁切、镜像、旋转、缩放或位移实拍及同花色候选,支持跨成品。来源图位、候选、实拍三选一。来源编号无效时返回匹配图位或目标图位的已完成候选。回执给出新候选、实际来源 sourceCandidateId、裁切像素 cropSourcePixels、目标图框 targetFrame、分辨率比 resolutionRatio 和是否达标 resolutionSufficient。';
|
||||
export const transformImageArgs={
|
||||
reference:optional(productReference),
|
||||
sourceSlotId:optional(Type.String({description:'来源图位的完整 slotId、fieldId 或标签,使用当前采用的同花色候选。'})),
|
||||
sourceCandidateId:optional(Type.String({description:'本项目当前花色的已完成候选号,可来自其他图位。'})),
|
||||
referenceIndex:optional(Type.Integer({minimum:0,maximum:7,description:'本款实拍的零起始编号。'})),
|
||||
...canvasTransformArgs,
|
||||
};
|
||||
export const preparationArgs={
|
||||
prompt:text,
|
||||
reworkChange:optional(Type.String({description:'返工时记录这次改变了什么。'})),
|
||||
reworkCandidateId:optional(text),
|
||||
references:optional(Type.Array(productReference,{minItems:1})),
|
||||
referenceIndexes:optional(Type.Array(page,{minItems:1,description:'本款原片的零起始编号,按实际发送顺序填写。'})),
|
||||
useTemplateBase:optional(Type.Boolean({description:'使用本图位固定模板原稿像素作为第一张图,随后发送本款实拍。false 表示本请求不使用模板底图。'})),
|
||||
prefer2k:optional(Type.Boolean({description:'传 true 可请求 2K。'})),
|
||||
retryOf:optional(Type.String({description:'仅限已确认可重试的失败候选。'})),
|
||||
};
|
||||
export const imageRequestDescription='保存完整生图请求,返回正式文本、参考顺序、模型参数与请求编号。';
|
||||
export const dispatchArgs={requestId:text,expectedRevision:optional(rev),expectedHash:optional(text)};
|
||||
68
apps/detail-agent-pi/src/production-tools.mjs
Normal file
68
apps/detail-agent-pi/src/production-tools.mjs
Normal file
@ -0,0 +1,68 @@
|
||||
import { StringEnum } from '@earendil-works/pi-ai';
|
||||
import { Type } from '@sinclair/typebox';
|
||||
import { OVERLAY_SCREEN_FIELDS } from './copy-image-alignment.mjs';
|
||||
import {
|
||||
dispatchArgs, fit, ids, imageRequestDescription, obj, optional, page, preparationArgs, productImageArgs,
|
||||
reuseTarget, rev, slotRef, text, transformDescription, transformImageArgs,
|
||||
} from './production-tool-schema.mjs';
|
||||
|
||||
const layer=Type.Integer({minimum:1});
|
||||
const outputScope={outputId:optional(text),variantId:optional(text)};
|
||||
|
||||
export const productionOperationTools = [
|
||||
['open_production_output','打开指定输出和花色。切换前保存原工程,返回保存结果、新画布绑定和各成品在途工作。waitingCanvas 为等待切回的图位。',obj({outputId:text,variantId:text})],
|
||||
['set_production_settings','记录参考偏好和主图画幅。template-base 用原图换商品,composition-only 只参考构图,none 不参考。单笔请求可另选是否用模板底图。',obj({
|
||||
referenceMode:optional(StringEnum(['template-base', 'composition-only', 'none'])),
|
||||
mainImageAspects:optional(Type.Array(Type.String({pattern:'^[1-9][0-9]*:[1-9][0-9]*$'}),{minItems:1})),
|
||||
})],
|
||||
['plan_production','读取商品、模板、进度和设置,默认当前工作画布。projectSlots 按成品和花色列出屏、图框像素、模板主体和候选号。framePending 表示图框像素暂取模板值。adoptionRecorded 为采用记录,selectedCandidateId 为画布当前采用。按 slotIds 查询图位发布要求,优先用 fieldId,重名用完整 id。includeKnowledge=true 列出固定版本的规则路径,可用 read 读取。mode、budget、limits 分别是制作模式、预算时间(含已用和剩余)和候选上限。candidateCount、candidatesRemaining 为已用及剩余候选数,copyReady 为关联文案就绪状态。',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 原位写入文字,每个 layer 只传一次。expectedText 核对原文,recordOnly 登记已原生写入的文字。copyUpdates 记录写入事实,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({
|
||||
...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})],
|
||||
['transform_slot_image',transformDescription,obj({...outputScope,slotId:slotRef,...transformImageArgs})],
|
||||
['prepare_image_request',imageRequestDescription,obj({...outputScope,slotId:slotRef,...preparationArgs})],
|
||||
['dispatch_image_request','确认准备回执后,传首个 requestId 派发同批请求。宿主读取该编号绑定的版本及哈希。用 await_image_slots 或 review_image_slots 查看结果。',obj({...outputScope,...dispatchArgs})],
|
||||
['delegate_image_slots','异步分派主图位 slotId,reuseTargets 可附同花色的额外图位及 outputId。委托可查候选并裁切至组内图位,在可写画布显式采用。返回分派状态和待写字段。',obj({
|
||||
...outputScope,jobs:Type.Array(obj({slotId:slotRef,goal:text,reuseTargets:optional(Type.Array(reuseTarget)),reworkCandidateId:optional(Type.String({description:'返工时,指定之前被退回的候选号。'}))})),
|
||||
})],
|
||||
['await_image_slots','按图位等待在途制作、验图和生图,返回状态、编号及修改摘要。waitForAll=true 等待调用时已在途的工作。单次最多 3 分钟,超时工作继续。省略 slotIds 时也看整屏复核,完整意见用 read_screen_review。omitted 是省略条数,waiting_canvas 等待可写画布。未知结果用 reconcile_image_slots。',obj({...outputScope,slotIds:optional(ids),waitForAll:optional(Type.Boolean())})],
|
||||
['review_image_slots','查看指定成品和花色的候选、验图、原请求、覆盖及整屏进度。screensReadyForReview 为图位已齐的待验多图位屏。slotIds 查看详情,单图位配合 candidateId 查看像素。按 nextOffset 翻页,单图位看全文。',obj({...outputScope,slotIds:optional(Type.Array(Type.String())),candidateId:optional(text),offset:optional(Type.Integer({minimum:0}))})],
|
||||
['list_project_images','列出本项目已完成且可读的候选,包括已采用图。可按成品和花色筛选。生图次数来自宿主派发记录。同花色候选可用 sourceCandidateId 跨成品变换或复用。按 nextOffset 翻页,candidateId 展开单条。',obj({...outputScope,candidateId:optional(Type.String()),offset:optional(Type.Integer({minimum:0}))})],
|
||||
['read_archived_images','查找本机其他同款项目的历史候选。按 slotIds 匹配图位,projectId 指定来源。不同模板或花色的已完成候选也可加入当前图位复核。按 nextOffset 翻页,candidateId 展开单条。',obj({
|
||||
slotIds:optional(Type.Array(Type.String())),candidateId:optional(Type.String()),projectId:optional(Type.String()),offset:optional(Type.Integer({minimum:0})),
|
||||
})],
|
||||
['stage_archived_image','把已完成的候选加入目标图位待验,沿用原素材任务。本项目同花色候选省略 projectId,其他同款项目用 read_archived_images 返回的 projectId。',obj({
|
||||
...outputScope,slotId:slotRef,projectId:optional(Type.String()),candidateId:text,
|
||||
})],
|
||||
['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({slotId:slotRef,candidateId:text,fit:optional(fit),reason:optional(text)})],
|
||||
['retire_production_image','清理已判失败的图位候选,保留原因、提示词及原请求记录。若已上画布,返回应替换的图层。',obj({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)})],
|
||||
['read_output_screen',`读取整屏合成画面、模板差异、overlayLayers、slotGeometry、annotationLayout 和 textClipping。page 或 pages 从 0 开始,可查看 2–4 屏;局部用单屏、region(画布 [x,y,w,h])和 1–4 倍 zoom,网格为原坐标。includeTemplateImage 附原屏,templateLayerId 查完整原值和现值,以 nextChangeOffset 翻模板差异。slotImageFacts 给出来源、当前与原屏近白平坦像素比例 nearWhiteFlatRatio / templateNearWhiteFlatRatio(0–1,缺样本为空)及本成品最多三个最近图位的 64 位 dHash 汉明距离(越小越相似)。subjectBounds 按像素与边缘背景色差估测并裁到可见图框,失败见 subjectBoundsReason。textLayers 给出样式、字形对比度 P10/P50 和底色亮度标准差。annotationLayout 给出文字、线端点、穿线长度、与主体的重叠及最近距离;dimensionGroups 给出标签、线和相对主体边界的像素偏移,guides 给出当前和原屏同层的对比度、线宽和端点直径。textClipping 给出墨迹边界及越屏部分。reviewRound 是已完成的整屏复核次数,issueHistory 是历轮问题数。只保留最新一次查看图片。${OVERLAY_SCREEN_FIELDS}`,obj({
|
||||
page:optional(page),pages:optional(Type.Array(page)),
|
||||
region:optional(Type.Array(Type.Integer(),{minItems:4,maxItems:4,description:'画布坐标 [x,y,w,h],宽高至少 1 像素。'})),
|
||||
zoom:optional(Type.Number({minimum:1,maximum:4})),
|
||||
includeTemplateImage:optional(Type.Boolean()),templateLayerId:optional(Type.Integer({minimum:1})),templateChangeOffset:optional(Type.Integer({minimum:0})),
|
||||
})],
|
||||
['check_output_screens','按企业 Skill 并行复核整屏合成画面、实拍、实时文案和叠加层。pages 从 1 开始,以实际屏数为准。默认等待结论,保存通过及待修正意见,按图位、图层或字段定位。wait=false 时可用省略 slotIds 的 await_image_slots 取摘要。',obj({
|
||||
pages:Type.Array(Type.Integer({minimum:1}),{minItems:1}),
|
||||
wait:optional(Type.Boolean({default:true})),
|
||||
})],
|
||||
['read_screen_review','读取指定成品最近一次完整的整屏复核回执。page 从 1 开始。',obj({...outputScope,page:Type.Integer({minimum:1})})],
|
||||
['defer_production_output','挂起当前成品,记录需外部处理的原因和所需动作。可查在途制作及原请求。',obj({
|
||||
blocker:obj({kind:StringEnum(['missing_required_input', 'authorization_required', 'permanent_service_failure']),reason:text,requiredAction:text}),
|
||||
})],
|
||||
['finish_production','保存并导出当前修订,返回成品状态、文件、尺寸和工程重开结果。slotCoverage 统计采用、人工置入、有候选、空白及跳过。若有通过复核的候选待采用,回执列出候选,可用 deliveryReason 说明按现状交付的依据。fidelityReport 概括总差异和分屏计数,可用 read 查看 reportPath。scope=all 按实际文件核验本轮交付,可附当前修订一并导出。issues 记录已知问题。',obj({
|
||||
...outputScope,revision:optional(rev),scope:optional(StringEnum(['current', 'all'])),issues:optional(Type.Array(obj({outputId:optional(text),variantId:optional(text),page:optional(Type.Integer({minimum:1})),field:optional(text),reason:text}))),
|
||||
deliveryReason:optional(text),
|
||||
})],
|
||||
];
|
||||
@ -14,18 +14,14 @@ maxGenerationAttempts: 4
|
||||
|
||||
## 图位与生图
|
||||
|
||||
- `plan_production` 的 `mode` 是制作模式,`budget` 是开始时间、预算与已用及剩余分钟,`limits` 是候选上限。整屏读取和复核的 `reviewRound` 是已完成的整屏复核轮数,`issueHistory` 是此前各轮问题数。
|
||||
- `read_slot_images` 读取图位实拍、模板参考和候选。 `use_product_image` 用 `reference` 或零起始的 `referenceIndex` 指定实拍,`referenceCrop` 指定裁切区域。
|
||||
- `prepare_image_request` 保存生图请求并返回正式提示词、参考顺序、模型参数及候选请求号。`useTemplateBase: true` 将该图位的固定模板原图作为第一张输入,`false` 不发送该底图。`referenceIndexes` 按数组顺序选取本款实拍,编号从 0 开始。`prefer2k: true` 请求 2K。`reworkCandidateId` 标识原候选,`reworkChange` 记录改动。
|
||||
- `dispatch_image_request` 接收准备回执的首个 `requestId` 并派发同批请求。宿主通过该编号读取绑定的版本和哈希。`candidatesPerSlot` 是一批请求的目标候选数,`maxCandidatesPerSlot` 是图位的累计候选上限,涵盖生图、变换、复用及实拍引用。candidateCount 和 candidatesRemaining 分别是已用和剩余候选数。
|
||||
- `transform_slot_image` 可裁切、镜像、旋转、缩放或平移实拍及任一成品的同花色候选。`sourceSlotId` 精确匹配本项目的完整 slotId、fieldId 或图位标签,使用该图位当前采用的同花色候选,支持跨成品。`sourceCandidateId` 指定候选编号,`referenceIndex` 指定从 0 开始的实拍序号,三种来源互斥。回执的 `sourceCandidateId` 是实际使用的候选编号。`cropSourcePixels` 是裁切使用的源像素尺寸,`targetFrame` 是目标图框,`resolutionRatio` 是裁切像素相对图框的分辨率比,`resolutionSufficient` 表示源像素是否达到该图框所需分辨率。
|
||||
- `write_copy_fields` 原位写入文案。需要刻意留空时,将该字段的 `text` 设为空字符串,并在 `reason` 说明依据。
|
||||
- `check_output_screens` 按 `pages` 复核并保存整屏意见。`read_screen_review` 按 `page` 查询最近一次整屏意见。屏号从 1 开始。
|
||||
- `review_image_slots` 返回候选、`comparison`、实际像素、画幅、请求和验图回执。`check_image_slots` 委托验图。`adopt_production_image` 用候选号回填,`reason` 记录采用理由。`reconcile_image_slots` 按原编号查询或取回请求结果。
|
||||
- 实拍的 reference 用清单中的编号,referenceIndex 从 0 开始,referenceCrop 是归一化裁切区域。useTemplateBase 选择是否以固定图位原图为第一张输入,referenceIndexes 控制实拍顺序,prefer2k 请求 2K。reworkCandidateId 和 reworkChange 记录返工来源与改动。
|
||||
- candidatesPerSlot 是一批请求的目标候选数,maxCandidatesPerSlot 是生图、变换、复用和实拍引用的累计上限。
|
||||
- 裁切回执的 sourceCandidateId 是实际来源候选号。cropSourcePixels 是裁切使用的源像素尺寸,targetFrame 是目标图框,resolutionRatio 是两者的分辨率比,resolutionSufficient 表示源像素是否达到目标图框所需分辨率。
|
||||
- 复查候选的 comparison 可比较实际像素、画幅、请求与验图回执。退回或不采用的理由应保留在对应回执中。
|
||||
|
||||
## 画布回执
|
||||
|
||||
- `read_output_screen` 返回合成画面与图层差异。`page` 从 0 开始,`region` 为画布像素坐标 `[x,y,w,h]`,`zoom` 为 1–4 倍。网格刻度使用原画布坐标。`includeTemplateImage` 返回原屏,`templateLayerId` 返回指定图层的完整原值与现值。
|
||||
- 查看合成画面时,工具说明列出取图和分页参数。以下字段用于核对像素与模板差异。
|
||||
- `slotImageFacts` 描述本屏已采用图位。`source.kind` 分为 `generation`、`transform`、`reused`、`product-reference` 和 `unrecorded`。`candidateId`、`requestId` 分别是采用候选号和对应生图请求号。`sourceCandidateId`、`sourceProjectId`、`sourceSlotId`、`sourceOutputId` 标识上游候选、工程、图位和模板输出。`photoSource`、`photoName` 是实拍文件引用和名称。`nearest` 列出本成品中最相近的最多三个其它采用图位,包含图位号、字段号和从零计数的页码。`distance` 是 64 位 dHash 的汉明距离,越小越相似。`nearWhiteFlatRatio` 和 `templateNearWhiteFlatRatio` 是当前和模板图框合成取样中近白且局部平坦的像素比例,范围 0–1。取样像素的 RGB 各通道至少为 235,且与上下左右相邻像素的各通道差不超过 8。`templateRatioSource: "original-screen-preview"` 表示从已存模板原屏预览取样。缺样本时比例为空。
|
||||
- `canvasFacts` 描述图层与画布关系。`outsideCanvas` 为 true 表示完全在画布外,`emptyBounds` 为 true 表示边界为空。`layerVisible` 是图层自身的可见性,`ancestorsVisible` 是祖先图层的可见性。
|
||||
- `overlayLayers` 中的 `group` 是直属组,`overlayGroups` 列出各组的本屏成员 ID。`knots` 是形状锚点数,`subjectHit` 表示标注框与估测主体框是否相交。`belowSlot` 按 `fieldId` 列出上方图位,`coverage` 是图位覆盖屏内图层边界的比例,`opacity` 和 `blendMode` 是图位内容的不透明度和混合模式。
|
||||
@ -68,4 +64,4 @@ maxGenerationAttempts: 4
|
||||
|
||||
## 交付回执
|
||||
|
||||
`finish_production` 返回成品状态、落盘文件和已知问题。`fidelityReport.changeCount` 是全稿差异条数,`screens` 按屏列出 `changeCount`、各差异类型的数量 `byType` 和待复核示例 `examples`。示例带原生图层号 `nativeLayerId` 与差异类型 `types`。跨屏图层计入对应的每屏,未归屏的条目归入 `pageId: null`。完整报告可用 `read` 读取 `reportPath`,成品版本清单中的完整报告位于 `fidelityReport` 字段。
|
||||
交付差异的 `fidelityReport.screens` 含分屏 `changeCount`、分类计数 `byType` 和示例 `examples`(图层 `nativeLayerId` 和差异 `types`)。跨屏图层计入每个涉及的屏,未归屏的条目归入 `pageId: null`。成品版本清单也保存完整的 `fidelityReport`。
|
||||
|
||||
@ -11,7 +11,8 @@ test('conversation status, errors and tool guidance use product terminology', ()
|
||||
for (const file of [
|
||||
'agent.mjs', 'desktop-host.mjs', 'xiaoyi-release.mjs', 'native-tools.mjs',
|
||||
'image-context-pruning.mjs', 'photocraft-extension.mjs', 'production-goal.mjs',
|
||||
'production-operations.mjs', 'runtime-policy.mjs',
|
||||
'production-operations.mjs', 'production-tools.mjs', 'production-tool-schema.mjs',
|
||||
'production-image-worker.mjs', 'production-screen-tools.mjs', 'runtime-policy.mjs',
|
||||
'screen-review.mjs',
|
||||
]) {
|
||||
for (const [index, line] of source(file).split('\n').entries()) {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,236 @@
|
||||
use super::{Phase, Run, Stage};
|
||||
use crate::jiansun::{PhotocraftApp, Request, Value, Workspace, json};
|
||||
use std::collections::HashSet;
|
||||
use std::sync::{Arc, mpsc, atomic::Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const MAX_DEFERRED_IMAGE_CONCURRENCY: usize = 6;
|
||||
|
||||
pub(super) struct DeferredImageRecovery {
|
||||
stage: Stage,
|
||||
id: String,
|
||||
cancellation: Arc<std::sync::atomic::AtomicBool>,
|
||||
receipt: mpsc::Receiver<Result<Value, String>>,
|
||||
}
|
||||
|
||||
impl Drop for DeferredImageRecovery {
|
||||
fn drop(&mut self) {
|
||||
self.cancellation.store(true, Ordering::Release);
|
||||
}
|
||||
}
|
||||
|
||||
impl Run {
|
||||
pub(in crate::jiansun) fn cancel_deferred_image_recovery(&mut self) {
|
||||
for pending in self.deferred_image_in_flight.drain(..) {
|
||||
pending.cancellation.store(true, Ordering::Release);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn defer_images(&mut self, stage: Stage, ids: Vec<String>) {
|
||||
if ids.is_empty() { return; }
|
||||
let originals = self.deferred_images.entry(stage).or_default();
|
||||
for id in ids {
|
||||
if !originals.contains(&id) { originals.push(id); }
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn clear_deferred(&mut self, stage: &Stage) {
|
||||
if let Some(ids) = self.deferred_images.remove(stage) {
|
||||
for id in ids {
|
||||
self.deferred_image_due.remove(&id);
|
||||
self.deferred_image_stopped.remove(&id);
|
||||
}
|
||||
}
|
||||
self.deferred_image_in_flight.retain(|pending| {
|
||||
if &pending.stage != stage { return true; }
|
||||
pending.cancellation.store(true, Ordering::Release);
|
||||
false
|
||||
});
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn owns_deferred_image(&self, id: &str) -> bool {
|
||||
self.deferred_images.values().flatten().any(|pending| pending == id)
|
||||
}
|
||||
|
||||
fn recovering_deferred_image(&self, id: &str) -> bool {
|
||||
self.deferred_image_in_flight.iter().any(|pending| pending.id == id)
|
||||
}
|
||||
|
||||
pub(super) fn queued_deferred_images(&self) -> impl Iterator<Item = (Option<Instant>, &Stage, &String)> {
|
||||
self.stages.iter()
|
||||
.flat_map(move |stage| self.deferred_images.get(stage).into_iter().flatten().map(move |id| (stage, id)))
|
||||
.filter(move |(_, id)| !self.recovering_deferred_image(id) && !self.deferred_image_stopped.contains(*id))
|
||||
.map(move |(stage, id)| (self.deferred_image_due.get(id).map(|(due, _)| *due), stage, id))
|
||||
}
|
||||
|
||||
fn settle_deferred_image(&mut self, stage: &Stage, id: &str) -> bool {
|
||||
let Some(ids) = self.deferred_images.get_mut(stage) else { return false; };
|
||||
let before = ids.len();
|
||||
ids.retain(|pending| pending != id);
|
||||
if ids.len() == before { return false; }
|
||||
if ids.is_empty() { self.deferred_images.remove(stage); }
|
||||
self.deferred_image_due.remove(id);
|
||||
self.deferred_image_stopped.remove(id);
|
||||
true
|
||||
}
|
||||
|
||||
pub(super) fn restore_deferred_images(&mut self, checkpoint: &Value) {
|
||||
for row in checkpoint["deferredImages"].as_array().into_iter().flatten() {
|
||||
let Some(stage) = Stage::read(&row["stage"]).filter(|stage| self.stages.contains(stage)) else { continue };
|
||||
let ids: Vec<_> = row["candidateIds"].as_array().into_iter().flatten()
|
||||
.filter_map(Value::as_str).map(str::to_owned).collect();
|
||||
if !ids.is_empty() { self.deferred_images.insert(stage, ids); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Workspace {
|
||||
pub(in crate::jiansun) fn cancel_deferred_image_recovery(&mut self) {
|
||||
if let Some(run) = self.product_production.as_mut() {
|
||||
run.cancel_deferred_image_recovery();
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn seed_deferred_images(run: &mut Run, workflow: &Value) {
|
||||
let mut requests = HashSet::new();
|
||||
for row in workflow["pendingImageRequests"].as_array().into_iter().flatten() {
|
||||
if let Some(stage) = Stage::read(row).filter(|stage| run.stages.contains(stage))
|
||||
&& let Some(id) = row["candidateId"].as_str()
|
||||
&& row["requestId"].as_str().is_none_or(|request| requests.insert(request))
|
||||
&& !run.owns_deferred_image(id) {
|
||||
run.defer_images(stage, vec![id.into()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn tick_deferred_image_recovery(&mut self, app: &PhotocraftApp, ctx: &egui::Context, now: Instant) {
|
||||
if !self.authority_active() || self.library_blocked() || self.production_exit.is_some()
|
||||
|| self.product_production.as_ref().is_none_or(|run| !run.current(self, app) || matches!(run.phase, Phase::Paused(_)))
|
||||
{
|
||||
self.cancel_deferred_image_recovery();
|
||||
return;
|
||||
}
|
||||
let Some(run) = self.product_production.as_mut() else { return; };
|
||||
// Both the bound output and previously opened outputs use the same queue.
|
||||
// The workspace snapshot supplies original identities after a restart.
|
||||
Self::seed_deferred_images(run, &self.template_workflow);
|
||||
let mut settled = Vec::new();
|
||||
let mut retry = Vec::new();
|
||||
let mut stopped = Vec::new();
|
||||
run.deferred_image_in_flight.retain(|pending| match pending.receipt.try_recv() {
|
||||
Err(mpsc::TryRecvError::Empty) => true,
|
||||
Ok(Ok(value)) if value["id"] == pending.id
|
||||
&& matches!(value["status"].as_str(), Some("complete" | "failed" | "expired")) => {
|
||||
settled.push((pending.stage.clone(), value));
|
||||
false
|
||||
}
|
||||
Ok(Ok(value)) if value["id"] == pending.id
|
||||
&& matches!(value["status"].as_str(), Some("unknown" | "running" | "dispatched")) => {
|
||||
retry.push(pending.id.clone());
|
||||
false
|
||||
}
|
||||
Ok(Err(error)) if error == "原候选仍在处理" => {
|
||||
retry.push(pending.id.clone());
|
||||
false
|
||||
}
|
||||
result => {
|
||||
let error = match result {
|
||||
Ok(Err(error)) => error,
|
||||
_ => "原生图核查回执不可用,可手动核查原请求".into(),
|
||||
};
|
||||
stopped.push((pending.id.clone(), error));
|
||||
false
|
||||
}
|
||||
});
|
||||
for id in retry {
|
||||
let delay = match run.deferred_image_due.get(&id).map(|(_, previous)| *previous) {
|
||||
None => 8,
|
||||
Some(8) => 15,
|
||||
Some(15) => 30,
|
||||
_ => 60,
|
||||
};
|
||||
run.deferred_image_due.insert(id, (now + Duration::from_secs(delay), delay));
|
||||
}
|
||||
for (id, error) in stopped {
|
||||
run.deferred_image_stopped.insert(id);
|
||||
self.error = error;
|
||||
}
|
||||
let mut changed = false;
|
||||
for (stage, receipt) in &settled {
|
||||
let id = receipt["id"].as_str().unwrap();
|
||||
changed |= run.settle_deferred_image(stage, id);
|
||||
if let Some(rows) = self.template_workflow.get_mut("pendingImageRequests").and_then(Value::as_array_mut) {
|
||||
rows.retain(|row| row["candidateId"] != id);
|
||||
}
|
||||
if let Some(ids) = self.template_workflow.get_mut("recoveryCandidateIds").and_then(Value::as_array_mut) {
|
||||
ids.retain(|candidate| candidate != id);
|
||||
self.template_workflow["recoveryCandidateId"] = ids.first().cloned().unwrap_or(Value::Null);
|
||||
}
|
||||
}
|
||||
while run.deferred_image_in_flight.len() < MAX_DEFERRED_IMAGE_CONCURRENCY {
|
||||
let next = run.queued_deferred_images()
|
||||
.filter(|(due, _, _)| due.is_none_or(|due| now >= due))
|
||||
.min_by_key(|(due, _, _)| *due)
|
||||
.map(|(_, stage, id)| (stage.clone(), id.clone()));
|
||||
let Some((stage, id)) = next else { break; };
|
||||
let (reply, receipt) = mpsc::channel();
|
||||
let cancellation = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let input = json!({"doc":run.doc,"project":run.project.rsplit('|').next(),
|
||||
"workspaceId":run.workspace,"outputId":stage.output,"variantId":stage.variant,
|
||||
"taskId":id,"accountId":self.account["id"],"origin":self.origin,
|
||||
"accountEpoch":self.accepted_account_epoch,"writeEpoch":self.write_epoch,"recoveryBudgetMs":9000});
|
||||
if self.tx.send(Request::RecoverDeferredImage(input, cancellation.clone(), reply)).is_err() {
|
||||
break;
|
||||
}
|
||||
run.deferred_image_in_flight.push(DeferredImageRecovery { stage, id, cancellation, receipt });
|
||||
}
|
||||
if let Some(next_due) = run.queued_deferred_images()
|
||||
.filter_map(|(due, _, _)| due.filter(|due| *due > now)).min()
|
||||
{
|
||||
ctx.request_repaint_after(next_due.saturating_duration_since(now));
|
||||
}
|
||||
let workspace = run.workspace.clone();
|
||||
let doc = run.doc;
|
||||
let bound = run.bound.clone();
|
||||
if changed { self.checkpoint_production(); }
|
||||
for (stage, mut receipt) in settled {
|
||||
let workflow = std::mem::take(&mut receipt["workflow"]);
|
||||
if workflow["workspaceId"] == workspace && Stage::read(&workflow) == Stage::read(&self.template_workflow)
|
||||
&& !self.product_view_detached() && self.receive_template_snapshot(&workflow, true) && self.busy.is_none() {
|
||||
self.unknown = workflow["pending"] == true;
|
||||
}
|
||||
if bound.as_ref() == Some(&stage) {
|
||||
self.production_recovery_received(app, &json!({"doc":doc,"accountId":self.account["id"],"origin":self.origin,
|
||||
"workflow":{"workspaceId":workspace},"candidateResult":receipt}));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn production_recovery_received(&mut self, app: &PhotocraftApp, value: &Value) {
|
||||
let Some(run) = self.product_production.as_ref().filter(|run| run.current(self, app)) else { return };
|
||||
if !run.waiting_for_originals() { return; }
|
||||
if value["accountId"] != self.account["id"] || value["origin"] != self.origin
|
||||
|| value["doc"].as_u64() != Some(run.doc) || value["workflow"]["workspaceId"] != run.workspace
|
||||
|| self.pi_write_blocked || self.pi_review {
|
||||
return;
|
||||
}
|
||||
let settled_models = &value["settledOriginalIds"];
|
||||
let Some(run) = self.product_production.as_mut() else { return };
|
||||
let stage = run.bound.clone();
|
||||
let Phase::WaitingOriginals { models, images, goal } = &mut run.phase else { return };
|
||||
let has_result = |id: &str| settled_models.as_array().into_iter().flatten().any(|value| value == id);
|
||||
let count = models.len() + images.len();
|
||||
models.retain(|id| !has_result(id));
|
||||
let candidate = &value["candidateResult"];
|
||||
let terminal_image = candidate["id"].as_str().filter(|_| stage.as_ref().is_some_and(|stage| candidate["variantId"] == stage.variant)
|
||||
&& matches!(candidate["status"].as_str(), Some("complete" | "failed" | "expired")));
|
||||
if let Some(id) = terminal_image { images.retain(|pending| pending != id); }
|
||||
if goal.as_deref().map_or_else(|| models.len() + images.len() < count, has_result) {
|
||||
if let Some(stage) = &stage && let Some(id) = terminal_image { run.settle_deferred_image(stage, id); }
|
||||
run.await_canvas_save();
|
||||
self.checkpoint_production();
|
||||
} else if stage.as_ref().zip(terminal_image).is_some_and(|(stage,id)| run.settle_deferred_image(stage, id)) {
|
||||
self.checkpoint_production();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,348 @@
|
||||
use super::{Phase, Run, Stage, original_ids, output_has_no_missing_images, production_time, slot_coverage_label};
|
||||
use crate::jiansun::{PhotocraftApp, Request, Value, Workspace, json};
|
||||
use crate::jiansun::multi_project_state::ProjectRunVisualStatus;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
impl Workspace {
|
||||
pub(in crate::jiansun) fn production_finish_status(&self, id: &str) -> Value {
|
||||
let Some(run) = self.product_production.as_ref() else { return Value::Null; };
|
||||
if run.finish.as_ref().is_some_and(|finish| finish["operationId"] == id) {
|
||||
return json!({"operationId":id,"pending":true});
|
||||
}
|
||||
if run.finish_receipt["operationId"] == id { return run.finish_receipt.clone(); }
|
||||
Value::Null
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn finish_production(&mut self, app: &PhotocraftApp, input: &Value) -> Result<Value, String> {
|
||||
let run = self.product_production.as_ref().filter(|run| run.current(self, app))
|
||||
.ok_or("原制作项目已切换")?;
|
||||
let id = input["operationId"].as_str().ok_or("缺少交付操作编号")?;
|
||||
if run.finish_receipt["operationId"] == id { return Ok(run.finish_receipt.clone()); }
|
||||
if run.finish.as_ref().is_some_and(|finish| finish["operationId"] == id) {
|
||||
return Ok(json!({"operationId":id,"pending":true}));
|
||||
}
|
||||
let stopped = self.production_stop["state"] == "delivering" && input["deliveryReason"].is_string()
|
||||
&& input["deliveryReason"] == self.production_stop["reason"];
|
||||
if (!stopped && (self.pi_write_blocked || self.busy.as_deref() != Some("pi-agent"))) || run.phase != Phase::Agent
|
||||
|| run.opening.is_some() || run.finish_receipt["finalized"] == true
|
||||
|| self.production_write_pending() {
|
||||
return Err("当前画布已有操作或已交接,请查看制作状态".into());
|
||||
}
|
||||
let export = input["complete"] == true || input["stageStatus"] == "hard-blocked"
|
||||
|| input["originals"].is_object();
|
||||
let all = input["scope"] == "all";
|
||||
if !export && input["scope"] != "all" {
|
||||
let revision = app.session.active().map(|state| state.revision.to_string()).unwrap_or_else(|| "未知".into());
|
||||
return Err(format!("请提交当前画布修订。当前修订号为 {revision},请填写 canvasRevision。"));
|
||||
}
|
||||
if export && (run.bound.is_none() || Stage::read(input) != run.bound
|
||||
|| input["complete"] == true && input["canvasRevision"].as_u64() != app.session.active().map(|s| s.revision)) {
|
||||
return Err("画布已更新,请读取当前工作画布再提交".into());
|
||||
}
|
||||
let summary = run.bound.as_ref().and_then(|stage| {
|
||||
let (state, workflow) = self.production_canvas(app)?;
|
||||
let mapping = super::super::canvas_workspace::document_mapping(&state.doc)?;
|
||||
if mapping["component"] != stage.output || mapping["variantId"] != stage.variant {
|
||||
return None;
|
||||
}
|
||||
let fields = super::super::pi_bridge::detail_copy_fields(&state.doc, None, None);
|
||||
let mut summary = super::super::production_facts::progress_summary(
|
||||
&state.doc, &mapping, state.revision, &fields, &input["screenReviewFingerprints"],
|
||||
);
|
||||
let aspects = input.get("mainImageAspects").unwrap_or(
|
||||
&self.template_workflow["template"]["production"]["mainImageAspects"]);
|
||||
if stage.output == "main_images" && let Some(aspects) = aspects.as_array() {
|
||||
super::super::production_facts::retain_planned_main_image_progress(&mut summary, &mapping,
|
||||
&self.template_workflow["slots"], aspects);
|
||||
}
|
||||
let slots: Vec<_> = workflow["slots"].as_array().into_iter().flatten().filter(|slot|
|
||||
slot["outputId"] == stage.output && slot["variantId"] == stage.variant
|
||||
&& (stage.output != "main_images" || aspects.as_array().is_none_or(|aspects| aspects.contains(&slot["aspectRatio"]))))
|
||||
.collect();
|
||||
let missing = summary["unfilledImageSlots"].as_array().map_or(0, Vec::len);
|
||||
let preview = summary["unfilledImageSlots"].as_array().into_iter().flatten().filter(|row|
|
||||
slots.iter().any(|slot| slot["id"] == row["slotId"] && slot["candidates"].as_array().into_iter().flatten()
|
||||
.any(|candidate| candidate["status"] == "complete"))).count();
|
||||
summary["slotCoverage"] = json!({"total":slots.len().max(missing),"preview":preview,"empty":missing-preview});
|
||||
Some(summary)
|
||||
});
|
||||
let run = self.product_production.as_mut().ok_or("原制作项目已切换")?;
|
||||
let mut finish = json!({"operationId":id,"all":all,"issues":input["issues"],"deliveryReason":stopped.then_some(&input["deliveryReason"])});
|
||||
if let Some(summary) = summary { finish["progressSummary"] = summary; }
|
||||
run.finish = Some(finish);
|
||||
run.phase = Phase::Export;
|
||||
if export {
|
||||
run.all_outputs_completed = false;
|
||||
let mut request = input.clone();
|
||||
request["workspaceId"] = run.workspace.clone();
|
||||
if !stopped {
|
||||
request["writeEpoch"] = self.pi_request_scope["writeEpoch"].clone();
|
||||
request["documentKey"] = self.pi_request_scope["documentKey"].clone();
|
||||
}
|
||||
self.product_export = Some(request);
|
||||
self.production_tick(app);
|
||||
} else {
|
||||
self.complete_production_export(json!({}));
|
||||
}
|
||||
Ok(self.production_finish_status(id))
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn production_export_received(&mut self, app: &PhotocraftApp, value: &Value) {
|
||||
if !self.product_production.as_ref().is_some_and(|run| run.phase == Phase::Export && run.finish.is_some()
|
||||
&& run.current(self, app) && run.same_project(value) && Stage::read(value) == run.bound
|
||||
&& run.finish.as_ref().is_some_and(|finish| finish["operationId"] == value["operationId"])) { return; }
|
||||
let Some(run) = self.product_production.as_mut() else { return; };
|
||||
let Some(stage) = run.bound.clone() else { return; };
|
||||
if let Some(finish) = run.finish.as_mut().filter(|finish| finish["deliveryReason"].is_string()) {
|
||||
finish["issues"] = value["issues"].clone();
|
||||
}
|
||||
if let Some(complete) = value["allOutputsCompleted"].as_bool() {
|
||||
run.all_outputs_completed = complete;
|
||||
}
|
||||
if let Some(generation) = value["generationId"].as_str()
|
||||
&& value["files"].as_array().is_some_and(|files| !files.is_empty()) {
|
||||
run.clear_deferred(&stage);
|
||||
run.stages.retain(|pending| *pending != stage);
|
||||
run.drafts.retain(|draft| Stage::read(draft).as_ref() != Some(&stage));
|
||||
run.published.retain(|receipt| Stage::read(receipt).as_ref() != Some(&stage));
|
||||
run.published.push(json!({"outputId":stage.output,"variantId":stage.variant,
|
||||
"generationId":generation,"progressSummary":run.finish.as_ref().map(|finish| &finish["progressSummary"]),
|
||||
"missingImages":value["missingImages"],
|
||||
"allOutputsCompleted":value["allOutputsCompleted"],
|
||||
"issues":run.finish.as_ref().map(|finish| &finish["issues"])}));
|
||||
run.delivery_id = None;
|
||||
} else if value["stageStatus"] == "hard-blocked" {
|
||||
run.clear_deferred(&stage);
|
||||
let mut draft = value.clone();
|
||||
draft["reason"] = value["blocker"]["reason"].clone();
|
||||
run.stages.retain(|pending| *pending != stage);
|
||||
run.drafts.retain(|previous| Stage::read(previous).as_ref() != Some(&stage));
|
||||
run.drafts.push(draft);
|
||||
} else {
|
||||
let images = original_ids(&value["originals"], "images");
|
||||
run.defer_images(stage, images);
|
||||
}
|
||||
if value["productionStages"].is_array() {
|
||||
self.template_workflow["productionStages"] = value["productionStages"].clone();
|
||||
}
|
||||
self.complete_production_export(value.clone());
|
||||
}
|
||||
|
||||
pub(super) fn complete_production_export(&mut self, mut receipt: Value) {
|
||||
let Some(mut run) = self.product_production.take() else { return; };
|
||||
let Some(finish) = run.finish.take() else {
|
||||
self.product_production = Some(run);
|
||||
return;
|
||||
};
|
||||
receipt["operationId"] = finish["operationId"].clone();
|
||||
if let Some(version) = self.pi_request_scope["productionKnowledge"]["knowledgeVersion"].as_str() {
|
||||
receipt["knowledgeVersion"] = json!(version);
|
||||
}
|
||||
if let Some(summary) = finish.get("progressSummary") {
|
||||
receipt["progressSummary"] = summary.clone();
|
||||
}
|
||||
receipt["complete"] = json!(receipt["generationId"].is_string()
|
||||
&& run.published.last().is_some_and(output_has_no_missing_images));
|
||||
receipt["allOutputsCompleted"] = json!(run.all_outputs_completed);
|
||||
receipt["pendingOutputs"] = run.pending_outputs();
|
||||
receipt["published"] = json!(run.published);
|
||||
receipt["drafts"] = json!(run.drafts);
|
||||
|
||||
let stopped = finish["deliveryReason"].is_string();
|
||||
receipt["deliveryReason"] = finish["deliveryReason"].clone();
|
||||
let finalize = finish["all"] == true && (stopped || run.stages.is_empty() && !receipt["error"].is_string());
|
||||
if finish["all"] == true {
|
||||
let mut pending_reviews = Vec::new();
|
||||
let mut known_issues = Vec::new();
|
||||
for output in &run.published {
|
||||
let summary = &output["progressSummary"];
|
||||
if summary.is_null() {
|
||||
pending_reviews.push(json!({"outputId":output["outputId"],"variantId":output["variantId"],
|
||||
"state":"reviewEvidenceMissing","reason":"这版导出没有按屏复核记录"}));
|
||||
}
|
||||
for key in ["unreviewedScreens", "screensWithOpenIssues"] {
|
||||
for page in summary[key].as_array().into_iter().flatten() {
|
||||
let mut row = page.clone();
|
||||
row["outputId"] = output["outputId"].clone();
|
||||
row["variantId"] = output["variantId"].clone();
|
||||
row["state"] = json!(key);
|
||||
pending_reviews.push(row);
|
||||
}
|
||||
}
|
||||
if stopped {
|
||||
for page in summary["screensWithOpenIssues"].as_array().into_iter().flatten() {
|
||||
for issue in page["issues"].as_array().into_iter().flatten() {
|
||||
let reason = issue["issue"].as_str().or_else(|| issue["reason"].as_str());
|
||||
if let Some(reason) = reason {
|
||||
let row = json!({"outputId":output["outputId"],"variantId":output["variantId"],
|
||||
"page":page["page"],"reason":reason});
|
||||
if !known_issues.contains(&row) { known_issues.push(row); }
|
||||
}
|
||||
}
|
||||
}
|
||||
for field in summary["unfilledImageSlots"].as_array().into_iter().flatten() {
|
||||
let row = json!({"outputId":output["outputId"],"variantId":output["variantId"],
|
||||
"field":field["fieldId"],"reason":"图位尚未采用图片"});
|
||||
if !known_issues.contains(&row) { known_issues.push(row); }
|
||||
}
|
||||
}
|
||||
for issue in output["issues"].as_array().into_iter().flatten() {
|
||||
let mut row = issue.clone();
|
||||
if row["outputId"].is_null() { row["outputId"] = output["outputId"].clone(); }
|
||||
if row["variantId"].is_null() { row["variantId"] = output["variantId"].clone(); }
|
||||
if !known_issues.contains(&row) { known_issues.push(row); }
|
||||
}
|
||||
}
|
||||
for issue in finish["issues"].as_array().into_iter().flatten() {
|
||||
if !known_issues.contains(issue) { known_issues.push(issue.clone()); }
|
||||
}
|
||||
receipt["pendingScreenReviews"] = json!(pending_reviews);
|
||||
receipt["knownIssues"] = json!(known_issues);
|
||||
}
|
||||
receipt["completed"] = json!(run.delivery_completed(&receipt["knownIssues"]));
|
||||
receipt["finalized"] = json!(finalize && !stopped && (run.delivery_dir.is_none() || run.published.is_empty()));
|
||||
run.phase = Phase::Agent;
|
||||
if self.pi_run.is_some() { self.busy = Some("pi-agent".into()); }
|
||||
run.finish_receipt = receipt;
|
||||
if finalize && run.finish_receipt["finalized"] != true {
|
||||
run.finish = Some(finish);
|
||||
self.finish_production_outputs(run);
|
||||
} else {
|
||||
self.product_production = Some(run);
|
||||
self.checkpoint_production();
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn finish_production_outputs(&mut self, mut run: Run) {
|
||||
if !run.finish_receipt["deliveryReason"].is_string() && (run.delivery_dir.is_none() || run.published.is_empty()) {
|
||||
self.note_production_summary(run);
|
||||
return;
|
||||
}
|
||||
if !self.authority_active() {
|
||||
run.delivery_receipt = json!({"state":"failed","error":"授权已失效,成品仍保存在本机项目中"});
|
||||
self.complete_production_bundle(run);
|
||||
return;
|
||||
}
|
||||
let id = run.delivery_id.get_or_insert_with(|| uuid::Uuid::new_v4().to_string()).clone();
|
||||
let cancellation = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
run.delivery_cancellation = Some(cancellation.clone());
|
||||
run.delivery_write_epoch = Some(self.write_epoch);
|
||||
run.phase = Phase::DeliveringBundle;
|
||||
let input = json!({"doc":run.doc,"project":run.project.rsplit('|').next(),
|
||||
"workspaceId":run.workspace,"accountId":self.account["id"],"origin":self.origin,
|
||||
"accountEpoch":self.accepted_account_epoch,
|
||||
"writeEpoch":self.write_epoch,"deliveryDir":run.delivery_dir,"deliveryId":id,
|
||||
"published":run.published,"remainingOutputs":run.pending_outputs(),"knownIssues":run.finish_receipt["knownIssues"],"deliveryReason":run.finish_receipt["deliveryReason"],"knowledgeVersion":run.finish_receipt["knowledgeVersion"],"total":run.total,"execution":{"runId":id,"operationId":id,"uiHeartbeat":production_time() * 1000}});
|
||||
self.write_production_checkpoint(&run, true);
|
||||
if self.tx.send(Request::DeliverProductionBundle(input, cancellation)).is_err() {
|
||||
run.delivery_receipt = json!({"state":"failed","error":"本机交付服务已断开"});
|
||||
self.complete_production_bundle(run);
|
||||
} else {
|
||||
self.product_production = Some(run);
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn production_bundle_received(&mut self, value: &Value) {
|
||||
if !self.product_production.as_ref().is_some_and(|run| run.phase == Phase::DeliveringBundle
|
||||
&& value["doc"].as_u64() == Some(run.doc) && value["deliveryId"].as_str() == run.delivery_id.as_deref()
|
||||
&& value["writeEpoch"].as_u64() == run.delivery_write_epoch
|
||||
&& run.delivery_write_epoch == Some(self.write_epoch)
|
||||
&& value["accountEpoch"].as_u64() == Some(self.accepted_account_epoch))
|
||||
{
|
||||
return;
|
||||
}
|
||||
let Some(mut run) = self.product_production.take() else { return; };
|
||||
if let Some(exit) = &mut self.production_exit {
|
||||
exit.deadline = Instant::now() + Duration::from_secs(90);
|
||||
}
|
||||
if !self.authority_active() { return; }
|
||||
run.delivery_receipt = value["productionDelivery"].clone();
|
||||
self.complete_production_bundle(run);
|
||||
}
|
||||
|
||||
pub(super) fn complete_production_bundle(&mut self, mut run: Run) {
|
||||
if self.production_stop["state"] == "delivering" {
|
||||
let delivered = run.delivery_receipt["path"].is_string();
|
||||
self.production_stop["state"] = json!(if delivered {"delivered"} else {"failed"});
|
||||
self.production_stop["error"] = run.delivery_receipt["error"].clone();
|
||||
if !delivered {
|
||||
run.pause(json!({"reason":run.delivery_receipt["error"]}));
|
||||
run.finish = None;
|
||||
self.product_production = Some(run);
|
||||
self.checkpoint_production();
|
||||
return;
|
||||
}
|
||||
}
|
||||
let delivered = run.delivery_receipt["path"].is_string();
|
||||
run.all_outputs_completed = run.delivery_receipt["allOutputsCompleted"] == true;
|
||||
run.finish_receipt["completed"] = json!(delivered && run.delivery_completed(&run.finish_receipt["knownIssues"]));
|
||||
if run.finish.take().is_some() && self.pi_run.is_some() && self.production_exit.is_none() {
|
||||
run.phase = Phase::Agent;
|
||||
run.finish_receipt["productionDelivery"] = run.delivery_receipt.clone();
|
||||
run.finish_receipt["finalized"] = json!(delivered);
|
||||
if !delivered { run.finish_receipt["error"] = run.delivery_receipt["error"].clone(); }
|
||||
self.product_production = Some(run);
|
||||
self.checkpoint_production();
|
||||
} else {
|
||||
self.note_production_summary(run);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn note_production_summary(&mut self, mut run: Run) {
|
||||
let complete = run.delivery_completed(&run.finish_receipt["knownIssues"]);
|
||||
let partial = !complete && (!run.published.is_empty() || run.delivery_receipt["path"].is_string());
|
||||
if partial {
|
||||
run.prepare_partial_continuation();
|
||||
}
|
||||
let status = if complete { ProjectRunVisualStatus::Completed } else if partial {
|
||||
ProjectRunVisualStatus::PartialDelivered
|
||||
} else { ProjectRunVisualStatus::Failed };
|
||||
self.last_production_summary = Some((run.doc, status));
|
||||
|
||||
if self.production_exit.is_some() {
|
||||
let checkpoint = self.send_exit_checkpoint(Self::production_checkpoint_request(&run, partial));
|
||||
self.production_exit.as_mut().unwrap().checkpoint = checkpoint;
|
||||
} else {
|
||||
self.write_production_checkpoint(&run, partial);
|
||||
}
|
||||
let mut coverage = [0u64; 3];
|
||||
for output in run.published.iter().chain(&run.drafts) {
|
||||
let counts = &output["progressSummary"]["slotCoverage"];
|
||||
let missing = output["missingImages"].as_array().map_or_else(
|
||||
|| output["missingImages"].as_u64().unwrap_or(0), |rows| rows.len() as u64);
|
||||
let preview = counts["preview"].as_u64().unwrap_or(0);
|
||||
let empty = counts["empty"].as_u64().unwrap_or(missing);
|
||||
coverage[0] += counts["total"].as_u64().unwrap_or(0).max(preview + empty);
|
||||
coverage[1] += preview;
|
||||
coverage[2] += empty;
|
||||
}
|
||||
let coverage = json!({"total":coverage[0],"preview":coverage[1],"empty":coverage[2]});
|
||||
let mut text = if let Some(label) = slot_coverage_label(&coverage) {
|
||||
label
|
||||
} else if run.finish_receipt["deliveryReason"].is_string() && complete {
|
||||
format!("{},已交付 {} 份当前成果。", run.finish_receipt["deliveryReason"].as_str().unwrap_or_default(), run.total)
|
||||
} else if complete {
|
||||
format!("整套制作完成 · {} 份可编辑画布与 JPG 已保存", run.total)
|
||||
} else if partial {
|
||||
format!("已保存 {} 份阶段成果,可继续补齐制作。", run.published.len())
|
||||
} else {
|
||||
"本轮制作已结束,已有编辑已保存。".into()
|
||||
};
|
||||
let receipt = &run.delivery_receipt;
|
||||
if let Some(path) = receipt["path"].as_str() {
|
||||
let counts = ["工程文件", "PSD", "详情页长图", "详情页切片", "主图", "SKU"]
|
||||
.map(|category| format!("{category} {} 份", receipt["counts"][category].as_u64().unwrap_or(0)));
|
||||
text.push_str(&format!("\n成品已保存到 {path}\n{}", counts.join("、")));
|
||||
if let Some(warning) = receipt["durabilityWarning"].as_str() {
|
||||
text.push_str(&format!("\n目录已落位,写入确认失败。{warning}"));
|
||||
}
|
||||
} else if let Some(error) = receipt["error"].as_str() {
|
||||
text.push_str(&format!("\n自动保存成品失败。{error}。可通过「保存工程」手动保存。"));
|
||||
}
|
||||
self.messages.push(json!({"role":"assistant","kind":"reply","text":text,
|
||||
"productionDelivery":receipt,
|
||||
"productionSummary":{"exported":receipt["completedOutputs"].as_u64().unwrap_or(run.published.len() as u64),"total":run.total,"drafts":run.drafts,"slotCoverage":coverage}}));
|
||||
self.draft_changed = true;
|
||||
if partial { self.product_production = Some(run); }
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,239 @@
|
||||
use super::{Phase, Run};
|
||||
use crate::jiansun::{PhotocraftApp, Request, Value, Workspace, json};
|
||||
use std::sync::{mpsc, atomic::Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
pub(in crate::jiansun) struct PendingExit {
|
||||
draft: Option<u64>,
|
||||
pub(super) deadline: Instant,
|
||||
daemon: Option<mpsc::Receiver<Result<(), String>>>,
|
||||
composers: Option<mpsc::Receiver<Result<(), String>>>,
|
||||
pub(in crate::jiansun) checkpoint: Option<Result<(), String>>,
|
||||
pub(in crate::jiansun) save_error: Option<String>,
|
||||
save_requested: bool,
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) struct ExitState {
|
||||
run: Option<Run>,
|
||||
checkpoint: Value,
|
||||
}
|
||||
|
||||
impl PendingExit {
|
||||
fn poll_receipts(&mut self) -> Option<Result<(), String>> {
|
||||
let checkpoint = self.checkpoint.clone()?;
|
||||
for pending in [&mut self.daemon, &mut self.composers] {
|
||||
let Some(receipt) = pending else { continue };
|
||||
let result = match receipt.try_recv() {
|
||||
Ok(result) => result,
|
||||
Err(mpsc::TryRecvError::Empty) => return None,
|
||||
Err(mpsc::TryRecvError::Disconnected) => Err("退出保存回执未确认".into()),
|
||||
};
|
||||
if let Err(error) = result { self.save_error.get_or_insert(error); }
|
||||
*pending = None;
|
||||
}
|
||||
Some(self.save_error.clone().map_or(checkpoint, Err))
|
||||
}
|
||||
}
|
||||
|
||||
impl Workspace {
|
||||
pub(in crate::jiansun) fn begin_production_exit(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context) -> bool {
|
||||
if self.production_exit.is_some() { return true; }
|
||||
let draft = self.exit_draft_target(app);
|
||||
let dirty_tabs = app.session.documents().iter().any(|state| state.is_dirty()
|
||||
&& self.open_projects.contains_key(&state.doc.id.0));
|
||||
if self.exit_admission_closed.load(Ordering::Acquire)
|
||||
|| !app.explicit_exit && !(draft.is_some_and(|(_, dirty)| dirty) || self.product_production.is_some()
|
||||
|| dirty_tabs
|
||||
|| self.background_status(app).is_some() || app.services.app_tray.is_some() && (app.saving() || app.exporting()))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
self.exit_admission_closed.store(true, Ordering::Release);
|
||||
let deadline = Instant::now() + Duration::from_secs(90);
|
||||
let daemon = self.prepare_daemon_exit.as_ref().map(|prepare| prepare());
|
||||
let composers = self.save_exit_composers(ctx);
|
||||
for doc in self.parked_project_docs(app) {
|
||||
self.with_parked_project(app, doc, |w, app| {
|
||||
let draft = w.exit_draft_target(app);
|
||||
w.begin_project_exit(app, deadline, draft, None, None);
|
||||
});
|
||||
}
|
||||
self.begin_project_exit(app, deadline, draft, daemon, composers);
|
||||
app.ui.status = "正在保存小壹制作进度…".into();
|
||||
app.ui.status_error = false;
|
||||
ctx.request_repaint();
|
||||
true
|
||||
}
|
||||
|
||||
fn exit_draft_target(&mut self, app: &mut PhotocraftApp) -> Option<(u64, bool)> {
|
||||
self.with_product_target(app, |w, app| app.session.active()
|
||||
.filter(|state| w.loaded_draft == Some(state.doc.id.0))
|
||||
.map(|state| (state.doc.id.0, w.draft_changed || w.creation_dirty
|
||||
|| w.persisted_revisions.get(&state.doc.id.0) != Some(&state.revision))))
|
||||
}
|
||||
|
||||
fn begin_project_exit(
|
||||
&mut self, app: &mut PhotocraftApp, deadline: Instant, draft: Option<(u64, bool)>,
|
||||
daemon: Option<super::super::ExitReceipt>, composers: Option<super::super::ExitReceipt>,
|
||||
) {
|
||||
self.cancel_deferred_image_recovery();
|
||||
let delivering = self.product_production.as_ref().is_some_and(|run| run.phase == Phase::DeliveringBundle);
|
||||
let ending = self.busy.as_deref() == Some("product-end-checkpoint");
|
||||
let run = if delivering { None } else { self.product_production.take() };
|
||||
if !delivering {
|
||||
self.with_product_target(app, |w, _| {
|
||||
w.pi_ui_cancel("客户端正在退出");
|
||||
w.handover();
|
||||
});
|
||||
}
|
||||
self.pending_slot_apply = None;
|
||||
self.pi_write_blocked = true;
|
||||
self.agent_effects_paused = true;
|
||||
|
||||
let input = run.as_ref().map(|run| {
|
||||
if ending {
|
||||
json!({"doc":run.doc,"checkpoint":{"active":false,"phase":"ended","project":run.project.rsplit('|').next()}})
|
||||
} else {
|
||||
Self::production_checkpoint_request(run, true)
|
||||
}
|
||||
}).or_else(|| {
|
||||
if delivering { return None; }
|
||||
let (doc, _) = draft?;
|
||||
let identity = self.open_projects.get(&doc)?;
|
||||
let project = identity.strip_prefix(&self.local_identity(""))?;
|
||||
Some(json!({"doc":doc,"checkpoint":{"project":project}}))
|
||||
});
|
||||
self.production_exit_state = Some(ExitState { run, checkpoint: std::mem::take(&mut self.product_checkpoint) });
|
||||
let checkpoint = if let Some(mut input) = input {
|
||||
input["checkpoint"]["status"] = json!("paused_on_exit");
|
||||
self.send_exit_checkpoint(input)
|
||||
} else { Some(Ok(())) };
|
||||
self.production_exit = Some(PendingExit {
|
||||
draft: draft.map(|(id, _)| id),
|
||||
deadline,
|
||||
daemon,
|
||||
composers,
|
||||
checkpoint,
|
||||
save_error: None,
|
||||
save_requested: false,
|
||||
});
|
||||
}
|
||||
|
||||
// The host writes these checkpoints serially and returns untagged acknowledgements.
|
||||
pub(super) fn send_exit_checkpoint(&mut self, input: Value) -> Option<Result<(), String>> {
|
||||
let owner = self.in_background_project.then_some(self.observed_doc).flatten();
|
||||
if self.tx.send(Request::Action("product-exit-checkpoint".into(), input)).is_err() {
|
||||
return Some(Err("本机制作记录保存服务已断开".into()));
|
||||
}
|
||||
self.exit_checkpoint_owners.push_back(owner);
|
||||
None
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn restore_cancelled_exit(&mut self) {
|
||||
self.production_exit = None;
|
||||
let Some(snapshot) = self.production_exit_state.take() else { return; };
|
||||
self.product_checkpoint = snapshot.checkpoint;
|
||||
if let Some(mut run) = snapshot.run {
|
||||
if !matches!(run.phase, Phase::Paused(_) | Phase::WaitingOriginals { .. }) {
|
||||
run.await_canvas_save();
|
||||
run.opening = None;
|
||||
run.finish = None;
|
||||
}
|
||||
self.write_production_checkpoint(&run, true);
|
||||
self.product_production = Some(run);
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn advance_production_exit(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
let Some(exit) = &self.production_exit else { return };
|
||||
let remaining = exit.deadline.saturating_duration_since(Instant::now());
|
||||
let result = if remaining.is_zero() {
|
||||
Err("退出等待超时,保存结果未确认".to_owned())
|
||||
} else {
|
||||
ctx.request_repaint_after(remaining);
|
||||
let mut pending = false;
|
||||
let mut error = None;
|
||||
for doc in self.parked_project_docs(app) {
|
||||
match self.with_parked_project(app, doc, Workspace::poll_project_exit).flatten() {
|
||||
None => pending = true,
|
||||
Some(Err(reason)) => { error.get_or_insert(reason); }
|
||||
Some(Ok(())) => {}
|
||||
}
|
||||
}
|
||||
if pending { return; }
|
||||
let Some(result) = self.poll_project_exit(app) else { return; };
|
||||
error.map_or(result, Err)
|
||||
};
|
||||
self.production_exit = None;
|
||||
if let Err(error) = result {
|
||||
log::warn!("小壹退出前保存未确认:{error}");
|
||||
app.ui.status = format!("小壹退出前保存未确认。{error}");
|
||||
app.ui.status_error = true;
|
||||
}
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
|
||||
}
|
||||
|
||||
fn poll_project_exit(&mut self, app: &mut PhotocraftApp) -> Option<Result<(), String>> {
|
||||
if self.product_production.as_ref().is_some_and(|run| run.phase == Phase::DeliveringBundle) {
|
||||
return None;
|
||||
}
|
||||
let view = self.flush_exit_view(app);
|
||||
self.with_product_target(app, Workspace::flush_exit_draft).map(|draft| draft.and(view))
|
||||
}
|
||||
|
||||
fn flush_exit_draft(&mut self, app: &mut PhotocraftApp) -> Option<Result<(), String>> {
|
||||
if self.saving.is_some() || self.metadata_saving.is_some() || self.product_view_save_pending() || app.saving() { return None; }
|
||||
let exit = self.production_exit.as_mut()?;
|
||||
if let Some(id) = exit.draft
|
||||
&& exit.save_error.is_none()
|
||||
{
|
||||
let Some(state) = app.session.active().filter(|state| state.doc.id.0 == id) else {
|
||||
return Some(Err("制作工程已切换,请核对原工程的草稿".into()));
|
||||
};
|
||||
if self.persisted_revisions.get(&id) != Some(&state.revision) || self.draft_changed
|
||||
|| (self.creation_dirty && !exit.save_requested)
|
||||
{
|
||||
if exit.save_requested {
|
||||
exit.save_error = Some("仍有编辑未落盘,请检查保存状态".into());
|
||||
} else {
|
||||
exit.save_requested = true;
|
||||
if self.enqueue_project_draft(state, true) { return None; }
|
||||
if let Some(exit) = &mut self.production_exit {
|
||||
exit.save_error = Some("本机草稿保存服务已断开".into());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !self.in_background_project && self.production_exit.as_ref()?.save_error.is_none() {
|
||||
let draft = app.session.documents().iter().find(|state| {
|
||||
let id = state.doc.id.0;
|
||||
state.is_dirty() && self.persisted_revisions.get(&id) != Some(&state.revision)
|
||||
&& self.open_projects.contains_key(&id)
|
||||
});
|
||||
if let Some(state) = draft {
|
||||
let doc = state.doc.id.0;
|
||||
let revision = state.revision;
|
||||
if self.tx.send(Request::Save(state.doc.clone(), revision, json!({"syncDirty":true}))).is_err() {
|
||||
return Some(Err("本机草稿保存服务已断开".into()));
|
||||
}
|
||||
self.saving = Some((doc, revision));
|
||||
return None;
|
||||
}
|
||||
// Save receipts mark the active canvas. Apply the same confirmed
|
||||
// revisions to other tabs before the general discard dialog runs.
|
||||
let active = app.session.active_index();
|
||||
let saved: Vec<_> = app.session.documents().iter().enumerate().filter_map(|(index, state)|
|
||||
(state.is_dirty() && self.persisted_revisions.get(&state.doc.id.0) == Some(&state.revision))
|
||||
.then_some((index, state.revision))).collect();
|
||||
for (index, revision) in saved {
|
||||
app.session.set_active(index);
|
||||
app.session.active_mut().unwrap().saved_revision = revision;
|
||||
}
|
||||
if let Some(active) = active { app.session.set_active(active); }
|
||||
}
|
||||
if self.busy.as_deref() == Some("slot-product-export") || app.exporting()
|
||||
|| self.product_production.as_ref().is_some_and(|run| run.phase == Phase::DeliveringBundle)
|
||||
{ return None; }
|
||||
self.production_exit.as_mut()?.poll_receipts()
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,843 @@
|
||||
use super::{Phase, Run, Stage, delivery_dir, original_ids, production_time};
|
||||
use crate::jiansun::{PhotocraftApp, Request, Value, Workspace, canvas_workspace, json};
|
||||
use std::collections::HashSet;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
impl Workspace {
|
||||
pub(in crate::jiansun) fn single_project_run_owner(&self) -> Option<u64> {
|
||||
if super::super::multi_project_state::MULTI_PROJECT_CONCURRENCY_ENABLED { return None; }
|
||||
self.product_production.as_ref()
|
||||
.filter(|run| run.is_active() || self.production_stop["state"] == "stopping")
|
||||
.map(|run| run.doc)
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn accepts_production_epoch(&self, epoch: &Value) -> bool {
|
||||
epoch.is_null() || epoch.as_u64() == Some(self.write_epoch)
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn revoke_production_epoch(&mut self) {
|
||||
if self.pi_request_scope["writeEpoch"].as_u64() != Some(self.write_epoch) { return; }
|
||||
self.cancel_deferred_image_recovery();
|
||||
self.write_epoch += 1;
|
||||
self.pi_write_blocked = true;
|
||||
self.allow_apply = false;
|
||||
self.agent_native.cancel();
|
||||
self.pi_run = None;
|
||||
self.stream_reply.clear();
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn resume_saved_production(&mut self, app: &PhotocraftApp) -> bool {
|
||||
let Some(canvas) = app.session.active() else { return false };
|
||||
let doc = canvas.doc.id.0;
|
||||
if self.single_project_run_owner().is_some_and(|owner| owner != doc) { return false; }
|
||||
let Some(project) = self.open_projects.get(&doc).cloned() else { return false };
|
||||
let Some(stages) = self.template_workflow["productionStages"].as_array()
|
||||
.and_then(|rows| rows.iter().map(Stage::read).collect::<Option<Vec<_>>>()) else { return false };
|
||||
let Some(stage) = Stage::read(&self.template_workflow) else { return false };
|
||||
let workspace = self.template_workflow["workspaceId"].clone();
|
||||
if stages.is_empty() || self.loaded_draft != Some(doc) || self.product_view_detached() || self.saving.is_some()
|
||||
|| self.persisted_revisions.get(&doc) != Some(&canvas.revision)
|
||||
|| !project.starts_with(&self.local_identity(""))
|
||||
|| !canvas_workspace::document_scope_matches(&canvas.doc, &self.template_workflow, &stage.output, &stage.variant)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let fresh = self.production_stop["state"] == "ended";
|
||||
let text = if fresh { "一键生成" } else { "继续整套制作" };
|
||||
self.messages.push(json!({"role":"user","text":text}));
|
||||
self.note(if fresh { "正在从当前画布开始新一轮制作。" } else { "已接续制作,正在核对当前画布和原请求。" });
|
||||
self.agent_effects_paused = false;
|
||||
let mut run = Run::new(doc, project, workspace, stages, Some(text.into()), Phase::AwaitingSave);
|
||||
run.delivery_dir = self.creation_delivery_dir.clone();
|
||||
run.bound = run.stages.contains(&stage).then_some(stage);
|
||||
self.begin_prepared_production(run, &self.template_workflow["productionBlocks"].clone());
|
||||
self.production_tick(app);
|
||||
true
|
||||
}
|
||||
|
||||
pub(super) fn begin_prepared_production(&mut self, mut run: Run, blocked: &Value) {
|
||||
run.reset_goal = self.production_stop["state"] == "ended";
|
||||
self.production_stop = json!({"mode":null,"state":"idle","reason":null,"error":null});
|
||||
for draft in blocked.as_array().into_iter().flatten() {
|
||||
let (Some(stage), Some(reason)) = (Stage::read(draft), draft["reason"].as_str()) else { continue; };
|
||||
self.note(format!("{}暂无法制作。{reason}。请核对所选模板的原稿与字段映射。", stage.label()));
|
||||
if !run.requested_outputs.contains(&stage) { run.requested_outputs.push(stage); }
|
||||
run.drafts.push(draft.clone());
|
||||
}
|
||||
run.total += run.drafts.len();
|
||||
self.product_views.clear_editor_basis();
|
||||
self.last_production_summary = None;
|
||||
self.product_production = Some(run);
|
||||
self.checkpoint_production();
|
||||
}
|
||||
|
||||
pub(super) fn production_checkpoint_request(run: &Run, active: bool) -> Value {
|
||||
let project = run.project.rsplit('|').next().unwrap_or_default();
|
||||
let mut checkpoint = json!({
|
||||
"deliveryDir":run.delivery_dir,"deliveryId":run.delivery_id,"published":run.published,
|
||||
"allOutputsCompleted":run.all_outputs_completed,
|
||||
"productionDelivery":run.delivery_receipt,"knownIssues":run.finish_receipt["knownIssues"],
|
||||
"deliveryReason":run.finish_receipt["deliveryReason"],
|
||||
"active":active,"project":project,"workspaceId":run.workspace,"startedAt":run.started_at,
|
||||
"pausedSeconds":run.paused_seconds,"clockSavedAt":run.paused_at.unwrap_or_else(production_time),
|
||||
"resetGoal":run.reset_goal,
|
||||
"boundOutput":run.working_output(),"outputSelected":run.bound.is_some(),
|
||||
"requestedOutputs":run.requested_outputs(),
|
||||
"total":run.total,"drafts":run.drafts,
|
||||
"stages":run.stages.iter().map(Stage::value).collect::<Vec<_>>(),
|
||||
"deferredImages":run.stages.iter().filter_map(|stage| run.deferred_images.get(stage)
|
||||
.map(|ids| json!({"stage":stage.value(),"candidateIds":ids}))).collect::<Vec<_>>()
|
||||
});
|
||||
if let Phase::Paused(pause) = &run.phase {
|
||||
checkpoint["phase"] = json!("paused");
|
||||
checkpoint["reason"] = pause["reason"].clone();
|
||||
checkpoint["requiredAction"] = pause["requiredAction"].clone();
|
||||
checkpoint["partialDelivered"] = pause["partialDelivered"].clone();
|
||||
}
|
||||
let waiting = Self::production_waiting_originals(&run.phase);
|
||||
if waiting.is_object() {
|
||||
checkpoint["waitingOriginals"] = waiting;
|
||||
}
|
||||
json!({"doc":run.doc,"checkpoint":checkpoint})
|
||||
}
|
||||
|
||||
fn production_waiting_originals(phase: &Phase) -> Value {
|
||||
match phase {
|
||||
Phase::WaitingOriginals { models, images, goal } => json!({"models":models,"images":images,"goal":goal}),
|
||||
Phase::Paused(pause) => pause["waitingOriginals"].clone(),
|
||||
_ => Value::Null,
|
||||
}
|
||||
}
|
||||
|
||||
fn production_resume_phase(waiting: &Value) -> Phase {
|
||||
if !waiting.is_object() { return Phase::AwaitingSave; }
|
||||
Phase::WaitingOriginals {
|
||||
models: original_ids(waiting, "models"),
|
||||
images: original_ids(waiting, "images"),
|
||||
goal: waiting["goal"].as_str().map(str::to_owned),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn write_production_checkpoint(&self, run: &Run, active: bool) {
|
||||
let _ = self.tx.send(Request::Action("product-run-checkpoint".into(), Self::production_checkpoint_request(run, active)));
|
||||
}
|
||||
|
||||
pub(super) fn checkpoint_production(&self) {
|
||||
if let Some(run) = self.product_production.as_ref() {
|
||||
self.write_production_checkpoint(run, true);
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn stop_production(&mut self) {
|
||||
if self.product_production.is_some() {
|
||||
let _ = self.request_production_stop("pause", "用户手动暂停");
|
||||
} else {
|
||||
self.handover();
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn request_production_stop(&mut self, mode: &str, reason: &str) -> Result<(), String> {
|
||||
if self.production_stop["state"] == "stopping" {
|
||||
if self.production_stop["mode"] == "pause" && mode != "pause" {
|
||||
self.production_stop["mode"] = json!(mode);
|
||||
self.production_stop["reason"] = json!(reason);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let mut run = self.product_production.take().ok_or("当前没有制作任务")?;
|
||||
if run.phase == Phase::DeliveringBundle {
|
||||
self.product_production = Some(run);
|
||||
return Err("当前交付正在进行".into());
|
||||
}
|
||||
if let Some(pause) = self.pause_production_agent {
|
||||
pause(run.doc, &run.project, run.session_epoch);
|
||||
}
|
||||
self.handover();
|
||||
run.pause(json!({"reason":"用户已停止制作"}));
|
||||
run.opening = None;
|
||||
run.finish = None;
|
||||
run.finish_receipt = Value::Null;
|
||||
self.product_production = Some(run);
|
||||
self.production_stop = json!({"mode":mode,"state":"stopping","reason":reason,"error":null});
|
||||
self.checkpoint_production();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn production_budget_state(&self) -> Value {
|
||||
json!({"startedAt":self.product_production.as_ref().map(|run| run.started_at),
|
||||
"budgetMinutes":self.production_budget_minutes,
|
||||
"elapsedMinutes":self.product_production.as_ref().map_or(0.0, |run| run.elapsed().as_secs_f64() / 60.0)})
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn production_budget_delay(&self) -> Option<Duration> {
|
||||
let run = self.product_production.as_ref()?;
|
||||
if matches!(run.phase, Phase::Paused(_) | Phase::DeliveringBundle) || run.paused_at.is_some() {
|
||||
return None;
|
||||
}
|
||||
Some(Duration::from_secs(self.production_budget_minutes.saturating_add(10).saturating_mul(60).saturating_add(1))
|
||||
.saturating_sub(run.elapsed()))
|
||||
}
|
||||
|
||||
fn settle_production_stop(&mut self, app: &PhotocraftApp) {
|
||||
if self.busy.is_some() || self.pi_run.is_some() || self.saving.is_some() || self.metadata_saving.is_some()
|
||||
|| self.product_view_save_pending() || self.production_write_pending() { return; }
|
||||
self.agent_presence.finish_run(Instant::now());
|
||||
if self.pi_context_usage.is_object() { self.pi_context_usage["phase"] = json!("ready"); }
|
||||
if self.production_stop["mode"] == "pause" {
|
||||
self.production_stop["state"] = json!("paused");
|
||||
return;
|
||||
}
|
||||
if self.production_stop["mode"] == "end" {
|
||||
let Some(canvas) = app.session.active() else { return; };
|
||||
let doc = canvas.doc.id.0;
|
||||
if self.persisted_revisions.get(&doc) != Some(&canvas.revision) || self.draft_changed {
|
||||
if !self.enqueue_project_draft(canvas, true) {
|
||||
self.production_end_received(Err("本机草稿保存服务已断开".into()));
|
||||
}
|
||||
return;
|
||||
}
|
||||
let Some(run) = self.product_production.as_ref() else { return; };
|
||||
let project = run.project.rsplit('|').next();
|
||||
if self.tx.send(Request::Action("product-end-checkpoint".into(),
|
||||
json!({"doc":run.doc,"checkpoint":{"active":false,"phase":"ended","project":project}}))).is_err() {
|
||||
self.production_end_received(Err("本机制作记录保存服务已断开".into()));
|
||||
} else {
|
||||
self.busy = Some("product-end-checkpoint".into());
|
||||
}
|
||||
return;
|
||||
}
|
||||
let Some(run) = self.product_production.as_mut() else { return; };
|
||||
run.phase = Phase::Agent;
|
||||
let mut input = run.bound.as_ref().map(Stage::value).unwrap_or_else(|| json!({}));
|
||||
input["operationId"] = json!(uuid::Uuid::new_v4().to_string());
|
||||
input["scope"] = json!("all");
|
||||
input["deliveryReason"] = self.production_stop["reason"].clone();
|
||||
if let Some(stage) = run.bound.as_ref()
|
||||
&& let Some(canvas) = app.session.active()
|
||||
&& canvas_workspace::document_scope_matches(&canvas.doc, &self.template_workflow, &stage.output, &stage.variant)
|
||||
{
|
||||
input["complete"] = json!(true);
|
||||
input["canvasRevision"] = json!(app.session.active().map(|state| state.revision));
|
||||
}
|
||||
self.production_stop["state"] = json!("delivering");
|
||||
if let Err(error) = self.finish_production(app, &input) {
|
||||
self.production_stop["state"] = json!("failed");
|
||||
self.production_stop["error"] = json!(error);
|
||||
if let Some(run) = self.product_production.as_mut() {
|
||||
run.pause(json!({"reason":error}));
|
||||
}
|
||||
self.checkpoint_production();
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn production_end_received(&mut self, result: Result<Value, String>) {
|
||||
match result {
|
||||
Ok(_) => {
|
||||
self.product_production = None;
|
||||
self.product_checkpoint = Value::Null;
|
||||
self.production_stop["state"] = json!("ended");
|
||||
}
|
||||
Err(error) => {
|
||||
self.production_stop["state"] = json!("failed");
|
||||
self.production_stop["error"] = json!(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn pause_for_authorization(&mut self, category: &Value) {
|
||||
const REAUTHORIZE: &str = "请重新授权后继续制作";
|
||||
let mut run = self.product_production.take();
|
||||
if let Some(run) = run.as_mut() {
|
||||
run.paused_at.get_or_insert_with(production_time);
|
||||
let waiting = Self::production_waiting_originals(&run.phase);
|
||||
run.cancel_deferred_image_recovery();
|
||||
if let Some(cancellation) = run.delivery_cancellation.take() {
|
||||
cancellation.store(true, Ordering::Release);
|
||||
}
|
||||
run.phase = Phase::Paused(json!({"reason":category,"requiredAction":REAUTHORIZE,"waitingOriginals":waiting}));
|
||||
self.write_production_checkpoint(run, true);
|
||||
} else if self.product_checkpoint["active"] == true || self.product_checkpoint["phase"] == "paused" {
|
||||
self.product_checkpoint["active"] = json!(true);
|
||||
self.product_checkpoint["phase"] = json!("paused");
|
||||
self.product_checkpoint["reason"] = category.clone();
|
||||
self.product_checkpoint["requiredAction"] = json!(REAUTHORIZE);
|
||||
if let Some(doc) = self.loaded_draft
|
||||
&& self.open_projects.get(&doc) == Some(&self.local_identity(self.product_checkpoint["project"].as_str().unwrap_or(""))) {
|
||||
let _ = self.tx.send(Request::Action("product-run-checkpoint".into(),
|
||||
json!({"doc":doc,"checkpoint":self.product_checkpoint})));
|
||||
}
|
||||
}
|
||||
self.handover();
|
||||
self.product_production = run;
|
||||
if self.has_paused_production() {
|
||||
self.production_stop = json!({"mode":"pause","state":"paused","reason":category,"error":null});
|
||||
}
|
||||
self.pi_write_blocked = true;
|
||||
self.agent_effects_paused = true;
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn production_settings(&self) -> Value {
|
||||
self.template_workflow.get("productionSettings").cloned()
|
||||
.unwrap_or_else(|| json!({"refinement":false,"timeBudgetMinutes":45}))
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn can_set_production_settings(&self) -> bool {
|
||||
self.busy.is_none() && (self.has_paused_production()
|
||||
|| self.product_production.is_none()
|
||||
&& (self.product_checkpoint["active"] != true || self.product_checkpoint["status"] == "paused_on_exit"))
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn set_production_settings(&mut self, app: &PhotocraftApp, input: &Value) -> Result<Value, String> {
|
||||
if !self.can_set_production_settings() { return Err("请在开工前或暂停后选择精修模式".into()); }
|
||||
let refinement = input["refinement"].as_bool().ok_or("请选择是否精修")?;
|
||||
let doc = app.session.active().map(|state| state.doc.id.0).ok_or("请先打开工程")?;
|
||||
if !self.open_projects.contains_key(&doc) {
|
||||
return Err("请先保存工程".into());
|
||||
}
|
||||
self.tx.send(Request::Action("production-settings".into(), json!({"doc":doc,"refinement":refinement})))
|
||||
.map_err(|_| "本机制作服务已关闭")?;
|
||||
self.busy = Some("production-settings".into());
|
||||
Ok(json!({"pending":true}))
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn has_paused_production(&self) -> bool {
|
||||
self.product_production.as_ref().is_some_and(|run| matches!(run.phase, Phase::Paused(_)))
|
||||
|| self.product_checkpoint["phase"] == "paused"
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn resume_paused_production(&mut self, app: &PhotocraftApp, text: String) {
|
||||
if !self.model_ready || !self.image_ready { return; }
|
||||
if self.product_production.is_none() {
|
||||
self.restore_production_checkpoint(app);
|
||||
}
|
||||
if let Some(run) = self.product_production.as_mut() {
|
||||
run.resume_clock();
|
||||
run.goal_user_entry = Some(text.clone());
|
||||
if self.production_stop["state"] == "interrupted" { self.error.clear(); }
|
||||
self.production_stop = json!({"mode":null,"state":"idle","reason":null,"error":null});
|
||||
run.phase = match &run.phase {
|
||||
Phase::Paused(pause) => Self::production_resume_phase(&pause["waitingOriginals"]),
|
||||
_ => Phase::AwaitingSave,
|
||||
};
|
||||
self.pi_write_blocked = false;
|
||||
self.agent_effects_paused = false;
|
||||
self.messages.push(json!({"role":"user","text":text}));
|
||||
self.checkpoint_production();
|
||||
self.production_tick(app);
|
||||
} else {
|
||||
self.error = "请保存当前项目后继续制作".into();
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn restore_production_checkpoint(&mut self, app: &PhotocraftApp) {
|
||||
let paused = self.product_checkpoint["phase"] == "paused";
|
||||
if (!paused && self.product_checkpoint["active"] != true) || self.busy.is_some() || self.saving.is_some() { return; }
|
||||
let Some(canvas) = app.session.active() else { return; };
|
||||
let doc = canvas.doc.id.0;
|
||||
let Some(project) = self.open_projects.get(&doc).cloned() else { return; };
|
||||
let workspace = self.template_workflow["workspaceId"].clone();
|
||||
if project != self.local_identity(self.product_checkpoint["project"].as_str().unwrap_or(""))
|
||||
|| workspace.is_null() || workspace != self.product_checkpoint["workspaceId"]
|
||||
|| !paused
|
||||
&& self.persisted_revisions.get(&doc) != Some(&canvas.revision)
|
||||
{ return; }
|
||||
const WAITING_MODELS: &str = "上次制作已中断,连接对话和生图模型后可继续";
|
||||
if self.product_checkpoint["deliveryId"].is_null() && (!self.model_ready || !self.image_ready) {
|
||||
self.production_stop = json!({"mode":null,"state":"interrupted","reason":"waiting_for_models","error":WAITING_MODELS});
|
||||
self.error = WAITING_MODELS.into();
|
||||
if !paused { return; }
|
||||
} else if self.production_stop["state"] == "interrupted" {
|
||||
self.production_stop = json!({"mode":null,"state":"idle","reason":null,"error":null});
|
||||
if self.error == WAITING_MODELS { self.error.clear(); }
|
||||
}
|
||||
let remaining: HashSet<_> = self.template_workflow["productionStages"].as_array()
|
||||
.into_iter().flatten().filter_map(Stage::read).collect();
|
||||
let checkpoint = std::mem::take(&mut self.product_checkpoint);
|
||||
let mut stages: Vec<_> = checkpoint["stages"].as_array().into_iter().flatten()
|
||||
.filter_map(Stage::read)
|
||||
.filter(|stage| checkpoint["partialDelivered"] == true || remaining.contains(stage)).collect();
|
||||
if checkpoint["status"] == "paused_on_exit" {
|
||||
for stage in self.template_workflow["productionStages"].as_array().into_iter().flatten().filter_map(Stage::read) {
|
||||
if !stages.contains(&stage) && checkpoint["published"].as_array().into_iter().flatten().any(|row|
|
||||
Stage::read(row).as_ref() == Some(&stage)
|
||||
&& row["issues"].as_array().is_some_and(|issues| !issues.is_empty())) {
|
||||
stages.push(stage);
|
||||
}
|
||||
}
|
||||
}
|
||||
let output_selected = checkpoint["outputSelected"].as_bool().unwrap_or_else(||
|
||||
checkpoint["selectFirstOutput"] != true && checkpoint["firstCanvasOpening"] != true);
|
||||
let bound = Stage::read(&checkpoint["boundOutput"])
|
||||
.or_else(|| output_selected.then(|| Stage::read(&self.template_workflow)).flatten())
|
||||
.filter(|stage| canvas_workspace::document_scope_matches(
|
||||
&canvas.doc, &self.template_workflow, &stage.output, &stage.variant));
|
||||
let phase = if paused {
|
||||
Phase::Paused(json!({"reason":checkpoint["reason"],"requiredAction":checkpoint["requiredAction"],
|
||||
"waitingOriginals":checkpoint["waitingOriginals"],"partialDelivered":checkpoint["partialDelivered"]}))
|
||||
} else { Self::production_resume_phase(&checkpoint["waitingOriginals"]) };
|
||||
let mut run = Run::new(doc, project, workspace, stages, None, phase);
|
||||
run.bound = bound;
|
||||
run.reset_goal = checkpoint["resetGoal"] == true;
|
||||
run.started_at = checkpoint["startedAt"].as_u64().or_else(|| {
|
||||
// Checkpoints before startedAt recorded a deadline and used 45 minutes by default.
|
||||
let deadline = checkpoint["deadline"].as_u64()?;
|
||||
let minutes = checkpoint["productionBudgetMinutes"].as_u64()
|
||||
.filter(|minutes| *minutes > 0).unwrap_or(45);
|
||||
Some(deadline.saturating_sub(minutes.saturating_mul(60)))
|
||||
}).unwrap_or(run.started_at);
|
||||
run.paused_seconds = checkpoint["pausedSeconds"].as_u64().unwrap_or_default();
|
||||
if let Some(saved_at) = checkpoint["clockSavedAt"].as_u64() {
|
||||
run.paused_at = Some(saved_at);
|
||||
if !paused { run.resume_clock(); }
|
||||
} else if paused {
|
||||
run.paused_at = Some(production_time());
|
||||
}
|
||||
run.delivery_dir = delivery_dir(&checkpoint);
|
||||
run.delivery_id = checkpoint["deliveryId"].as_str().map(str::to_owned);
|
||||
run.delivery_receipt = checkpoint["productionDelivery"].clone();
|
||||
run.all_outputs_completed = checkpoint["allOutputsCompleted"] == true;
|
||||
run.finish_receipt["knownIssues"] = checkpoint["knownIssues"].clone();
|
||||
run.finish_receipt["deliveryReason"] = checkpoint["deliveryReason"].clone();
|
||||
run.published = checkpoint["published"].as_array().cloned().unwrap_or_default();
|
||||
if let Some(requested) = checkpoint["requestedOutputs"].as_array() {
|
||||
run.requested_outputs = requested.iter().filter_map(Stage::read).collect();
|
||||
}
|
||||
run.drafts = checkpoint["drafts"].as_array().cloned().unwrap_or_default();
|
||||
run.total = checkpoint["total"].as_u64().unwrap_or(run.total as u64) as usize;
|
||||
run.restore_deferred_images(&checkpoint);
|
||||
Self::seed_deferred_images(&mut run, &self.template_workflow);
|
||||
if !paused && run.stages.is_empty() && run.delivery_id.is_none() {
|
||||
run.await_canvas_save();
|
||||
self.write_production_checkpoint(&run, false);
|
||||
self.production_stop = json!({"mode":null,"state":"idle","reason":null,"error":null});
|
||||
if self.error == WAITING_MODELS { self.error.clear(); }
|
||||
} else if !paused && (run.stages.is_empty() || run.finish_receipt["deliveryReason"].is_string()) && run.delivery_id.is_some() {
|
||||
if run.finish_receipt["deliveryReason"].is_string() {
|
||||
self.production_stop = json!({"mode":"deliver","state":"delivering","reason":run.finish_receipt["deliveryReason"],"error":null});
|
||||
}
|
||||
self.finish_production_outputs(run);
|
||||
} else {
|
||||
self.product_production = Some(run);
|
||||
if !paused { self.note("已从上次的制作进度接续"); }
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn production_saved(&self, app: &mut PhotocraftApp, id: u64, revision: u64, meta: &Value, owned: bool) {
|
||||
// Mark only the confirmed project snapshot as saved. Crash recovery
|
||||
// should still collect edits made after this revision.
|
||||
if owned
|
||||
&& let Some(path) = meta["savedPath"].as_str()
|
||||
&& let Some(state) = app.session.active_mut().filter(|state| state.doc.id.0 == id && state.revision == revision)
|
||||
&& state.path.as_deref().is_none_or(|source| std::path::Path::new(source) == std::path::Path::new(path))
|
||||
&& (self.production_exit.is_some() || self.template_workflow["productionStages"].is_array()
|
||||
&& super::super::canvas_workspace::document_mapping(&state.doc)
|
||||
.is_some_and(|map| map["workspaceId"] == self.template_workflow["workspaceId"]))
|
||||
{
|
||||
state.saved_revision = revision;
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn production_prepared(&mut self, app: &PhotocraftApp, meta: &Value) {
|
||||
if meta["productionPreparation"] == true {
|
||||
let Some(doc) = meta["doc"].as_u64() else { return };
|
||||
if self.single_project_run_owner().is_some_and(|owner| owner != doc) {
|
||||
self.error = super::super::SINGLE_PROJECT_IN_PROGRESS.into();
|
||||
return;
|
||||
}
|
||||
let Some(project) = self.owned_project_key(doc).map(str::to_owned) else {
|
||||
self.error = "项目尚未完成首次保存".into();
|
||||
return;
|
||||
};
|
||||
let Some(stages) = meta["workflow"]["productionStages"].as_array().and_then(|rows|
|
||||
rows.iter().map(Stage::read).collect::<Option<Vec<_>>>()) else {
|
||||
self.error = "未取得本轮输出的可用画布".into();
|
||||
return;
|
||||
};
|
||||
if stages.is_empty() {
|
||||
self.error = "请先在产品资料选择要制作的款式".into();
|
||||
return;
|
||||
}
|
||||
let goal_user_entry = self.messages.iter().rev().find(|message| message["role"] == "user")
|
||||
.and_then(|message| message["text"].as_str())
|
||||
.filter(|text| matches!(*text, "制作详情、主图和 SKU" | "继续整套制作")).map(str::to_owned);
|
||||
let mut run = Run::new(doc, project, meta["workflow"]["workspaceId"].clone(), stages, goal_user_entry, Phase::AwaitingSave);
|
||||
run.delivery_dir = delivery_dir(&meta["creation"]);
|
||||
self.begin_prepared_production(run, &meta["workflow"]["productionBlocks"]);
|
||||
self.production_tick(app);
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn production_opened(&mut self, app: &PhotocraftApp, meta: &Value) {
|
||||
if self.product_production.as_ref().is_none_or(|run| !run.current(self, app) || !run.accepts_canvas(meta)) {
|
||||
self.product_production = None;
|
||||
return;
|
||||
}
|
||||
if self.busy.as_deref() == Some("slot-skeleton") {
|
||||
self.busy = None;
|
||||
}
|
||||
if let Some(run) = self.product_production.as_mut() {
|
||||
run.await_canvas_save();
|
||||
}
|
||||
self.production_tick(app);
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn production_canvas_unbound(&self, app: &PhotocraftApp) -> bool {
|
||||
self.product_production.as_ref().is_some_and(|run| run.current(self, app)
|
||||
&& (run.bound.is_none() || run.opening.is_some()))
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn production_canvas_opening(&self, app: &PhotocraftApp) -> bool {
|
||||
self.product_production.as_ref().is_some_and(|run| run.current(self, app) && run.opening.is_some())
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn production_canvas_receipt(&self, app: &PhotocraftApp) -> Value {
|
||||
let Some(run) = self.product_production.as_ref().filter(|run| run.opening.is_none() && run.current(self, app))
|
||||
else { return Value::Null; };
|
||||
let Some(stage) = &run.bound else { return Value::Null; };
|
||||
if self.pi_request_scope["outputId"] != stage.output || self.pi_request_scope["variantId"] != stage.variant {
|
||||
return Value::Null;
|
||||
}
|
||||
json!({"outputId":stage.output,"variantId":stage.variant,"documentId":run.doc,"revision":self.expected_revision,
|
||||
"documentKey":self.pi_request_scope["documentKey"],"writeEpoch":self.write_epoch,
|
||||
"previousSave":run.previous_save,"pendingOutputs":run.pending_outputs()})
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn production_boundary_pending(&self) -> bool {
|
||||
self.product_production.as_ref().is_some_and(|run|
|
||||
run.opening.is_some() || run.finish.is_some() || run.finish_receipt["finalized"] == true)
|
||||
}
|
||||
|
||||
pub(super) fn production_write_pending(&self) -> bool {
|
||||
self.workflow.any_operation_in_flight() || !self.queue.is_empty()
|
||||
|| self.canvas_workspace.pending_adoption.is_some() || self.canvas_workspace.adoption_preparing()
|
||||
|| self.pi_run.as_deref().is_some_and(|run| self.agent_native.pending_job(run).is_some())
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn open_production_canvas(&mut self, app: &PhotocraftApp, requested: &Value) -> Result<Value, String> {
|
||||
let run = self.product_production.as_ref().filter(|run| run.current(self, app))
|
||||
.ok_or("原制作项目已切换")?;
|
||||
let stage = Stage::read(requested).ok_or("请指定输出和花色")?;
|
||||
if !run.requested_outputs.contains(&stage) || !self.template_workflow["productionBlocks"]
|
||||
.as_array().into_iter().flatten().all(|row| Stage::read(row).as_ref() != Some(&stage)) {
|
||||
return Err("请选择本轮可制作的输出和花色".into());
|
||||
}
|
||||
if let Some(opening) = &run.opening {
|
||||
return Ok(json!({"accepted":*opening == stage,"reason":"canvas_switch_pending",
|
||||
"openingOutput":opening.value()}));
|
||||
}
|
||||
if self.pi_write_blocked { return Err("画布已由用户接手".into()); }
|
||||
if run.phase != Phase::Agent || run.finish_receipt["finalized"] == true || self.busy.as_deref() != Some("pi-agent") {
|
||||
return Ok(json!({"accepted":false,"reason":"production_busy"}));
|
||||
}
|
||||
if let Some(knowledge) = requested.get("knowledge").filter(|value| !value.is_null()) {
|
||||
self.pi_request_scope["productionKnowledge"] = knowledge.clone();
|
||||
}
|
||||
let knowledge = &self.pi_request_scope["productionKnowledge"];
|
||||
let same_knowledge = knowledge.is_null()
|
||||
|| knowledge["knowledgeVersion"] == self.template_workflow["template"]["knowledgeVersion"];
|
||||
if same_knowledge && run.bound.as_ref() == Some(&stage) { return Ok(json!({"accepted":true})); }
|
||||
self.error.clear();
|
||||
let images = original_ids(requested, "previousImageRequests");
|
||||
let handoff = !images.is_empty() && run.bound.is_some();
|
||||
if let Some(run) = self.product_production.as_mut() {
|
||||
if let Some(previous) = run.bound.clone() {
|
||||
run.defer_images(previous, images);
|
||||
}
|
||||
run.opening = Some(stage);
|
||||
run.previous_save = Value::Null;
|
||||
}
|
||||
if handoff { self.checkpoint_production(); }
|
||||
self.production_tick(app);
|
||||
Ok(json!({"accepted":true}))
|
||||
}
|
||||
|
||||
fn dispatch_production_open(&mut self, app: &PhotocraftApp, stage: &Stage) {
|
||||
let knowledge = &self.pi_request_scope["productionKnowledge"];
|
||||
let same_knowledge = knowledge.is_null() || knowledge["knowledgeVersion"] == self.template_workflow["template"]["knowledgeVersion"];
|
||||
if same_knowledge && app.session.active().is_some_and(|canvas|
|
||||
self.persisted_revisions.get(&canvas.doc.id.0) == Some(&canvas.revision)
|
||||
&& canvas_workspace::document_scope_matches(&canvas.doc, &self.template_workflow, &stage.output, &stage.variant)) {
|
||||
self.bind_production_canvas(app);
|
||||
} else if let Err(error) = self.slot_action(app, "slot-skeleton", json!({
|
||||
"outputId":stage.output,"variantId":stage.variant,"continueProduct":true,
|
||||
"workspaceId":self.template_workflow["workspaceId"],
|
||||
"knowledge":self.pi_request_scope["productionKnowledge"]
|
||||
})) {
|
||||
self.production_canvas_open_failed(app, "slot-skeleton", &error);
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn production_switch_saved(&mut self, app: &PhotocraftApp, revision: u64) {
|
||||
let Some(run) = self.product_production.as_mut().filter(|run| run.opening.is_some()) else { return; };
|
||||
let Some(active) = app.session.active() else { return; };
|
||||
run.previous_save = json!({"saved":true,"revision":revision,
|
||||
"documentKey":super::super::product_document_key(&active.doc),"path":active.path});
|
||||
}
|
||||
|
||||
fn bind_production_canvas(&mut self, app: &PhotocraftApp) {
|
||||
let Some(canvas) = app.session.active() else { return; };
|
||||
let Some(run) = self.product_production.as_mut() else { return; };
|
||||
let Some(stage) = run.opening.take() else { return; };
|
||||
self.write_epoch += 1;
|
||||
self.pi_request_scope["writeEpoch"] = json!(self.write_epoch);
|
||||
self.pi_request_scope["outputId"] = json!(stage.output);
|
||||
self.pi_request_scope["variantId"] = json!(stage.variant);
|
||||
self.pi_request_scope["documentKey"] = super::super::product_document_key(&canvas.doc);
|
||||
self.pi_request_scope["template"] = json!({"id":self.template_workflow["templateId"],
|
||||
"version":self.template_workflow["templateVersion"],"hash":self.template_workflow["templateHash"]});
|
||||
self.expected_revision = canvas.revision;
|
||||
if !self.product_target_hidden {
|
||||
self.user_canvas_changes.bind(&canvas.doc, canvas.revision);
|
||||
self.product_views.bind_editor_basis(&stage, &canvas.doc);
|
||||
}
|
||||
self.pi_canvas_basis = Some(canvas.doc.clone());
|
||||
self.pi_manual_edit = false;
|
||||
self.allow_apply = false;
|
||||
if run.bound.as_ref() != Some(&stage) {
|
||||
self.workflow.clear_production_progress();
|
||||
}
|
||||
run.bound = Some(stage);
|
||||
run.phase = Phase::Agent;
|
||||
self.checkpoint_production();
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn production_canvas_open_failed(&mut self, app: &PhotocraftApp, method: &str, reason: &str) -> bool {
|
||||
if !self.production_canvas_opening(app) || !matches!(method, "slot-skeleton" | "save") {
|
||||
return false;
|
||||
}
|
||||
if let Some(run) = self.product_production.as_mut() {
|
||||
if run.awaiting_canvas_save() {
|
||||
run.bound = None;
|
||||
self.pi_request_scope["documentKey"] = Value::Null;
|
||||
self.pi_request_scope["outputId"] = Value::Null;
|
||||
self.pi_request_scope["variantId"] = Value::Null;
|
||||
self.pi_canvas_basis = app.session.active().map(|canvas| canvas.doc.clone());
|
||||
}
|
||||
run.opening = None;
|
||||
run.phase = Phase::Agent;
|
||||
}
|
||||
self.pending_slot_apply = None;
|
||||
self.finish_template_preparation();
|
||||
self.busy = Some("pi-agent".into());
|
||||
self.canvas_workspace.scope_switch_in_flight = false;
|
||||
self.error = reason.into();
|
||||
true
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn production_can_use_scoped_pending(&self) -> bool {
|
||||
self.product_production.is_some() && self.scoped_production_pending()
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn scoped_production_pending(&self) -> bool {
|
||||
!self.legacy_unknown && !self.unknown_image && self.template_workflow["scopedProductionPending"] == true
|
||||
}
|
||||
|
||||
fn production_start_session(&mut self, app: &PhotocraftApp) {
|
||||
if !self.can_start_production_turn() {
|
||||
return;
|
||||
}
|
||||
if !(self.model_ready && self.image_ready) || self.production_model_problem().is_some() {
|
||||
let reason = self.production_model_problem().unwrap_or_else(||
|
||||
"请配置可用的对话与生图模型".into());
|
||||
let Some(mut run) = self.product_production.take() else { return; };
|
||||
for stage in &run.stages {
|
||||
run.drafts.push(json!({"outputId":stage.output,"variantId":stage.variant,"reason":reason}));
|
||||
}
|
||||
self.note_production_summary(run);
|
||||
return;
|
||||
}
|
||||
let Some(run) = self.product_production.as_mut() else { return };
|
||||
run.resume_clock();
|
||||
run.phase = Phase::Agent;
|
||||
self.agent_effects_paused = false;
|
||||
self.submit_turn(app, "继续本轮制作".into(), true);
|
||||
if self.busy.as_deref() != Some("agent")
|
||||
&& let Some(run) = self.product_production.as_mut()
|
||||
{
|
||||
run.phase = Phase::AgentRetryAt(Instant::now() + Duration::from_secs(3));
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn production_agent_received(&mut self, app: &PhotocraftApp, value: &Value) {
|
||||
let Some(run) = self.product_production.as_ref().filter(|run|
|
||||
run.phase == Phase::Agent && run.current(self, app)) else { return };
|
||||
if value["doc"].as_u64() != Some(run.doc) || value["accountId"] != self.account["id"]
|
||||
|| value["origin"] != self.origin || value["projectLocalId"].as_str().is_none_or(|id| self.local_identity(id) != run.project) {
|
||||
return;
|
||||
}
|
||||
if value["production"]["stageStatus"] == "paused" {
|
||||
let pause = &value["production"]["pause"];
|
||||
let reason = pause["reason"].as_str().unwrap_or_default();
|
||||
if let Some(run) = self.product_production.as_mut() {
|
||||
if let Some(bound) = run.bound.clone() {
|
||||
run.defer_images(bound, original_ids(&value["production"]["originals"], "images"));
|
||||
}
|
||||
run.pause(pause.clone());
|
||||
}
|
||||
self.checkpoint_production();
|
||||
self.pi_write_blocked = true;
|
||||
self.agent_effects_paused = true;
|
||||
let mut message = format!("制作已暂停。{reason}");
|
||||
if let Some(action) = pause["requiredAction"].as_str() {
|
||||
message.push('\n');
|
||||
message.push_str(action);
|
||||
}
|
||||
self.note(message);
|
||||
return;
|
||||
}
|
||||
if value["failure"]["category"] == "transport_interrupted" && value["failure"]["retryable"] == true
|
||||
&& self.defer_production_agent(app) {
|
||||
return;
|
||||
}
|
||||
let originals = &value["production"]["originals"];
|
||||
let models = original_ids(originals, "models");
|
||||
let images = original_ids(originals, "images");
|
||||
if !models.is_empty() || !images.is_empty() {
|
||||
let goal = originals["goal"].as_str().map(str::to_owned);
|
||||
if let Some(run) = self.product_production.as_mut() {
|
||||
if let Some(stage) = run.bound.clone() {
|
||||
let dispatched = self.template_workflow["slots"].as_array().into_iter().flatten()
|
||||
.flat_map(|slot| slot["generationRequestIds"].as_array().into_iter().flatten())
|
||||
.filter_map(Value::as_str).collect::<HashSet<_>>();
|
||||
let native = images.iter().filter(|id| dispatched.contains(id.as_str()))
|
||||
.cloned().collect();
|
||||
run.defer_images(stage, native);
|
||||
}
|
||||
run.phase = Phase::WaitingOriginals { models, images, goal };
|
||||
}
|
||||
self.checkpoint_production();
|
||||
return;
|
||||
}
|
||||
let Some(mut run) = self.product_production.take() else { return; };
|
||||
let reason = value["error"].as_str().unwrap_or("本轮会话已结束,已保留现有进度");
|
||||
for stage in &run.stages {
|
||||
run.drafts.push(json!({"outputId":stage.output,"variantId":stage.variant,"reason":reason}));
|
||||
}
|
||||
self.note_production_summary(run);
|
||||
}
|
||||
|
||||
fn defer_production_agent(&mut self, app: &PhotocraftApp) -> bool {
|
||||
let Some(run) = self.product_production.as_mut() else { return false; };
|
||||
if run.phase != Phase::Agent || run.restarted
|
||||
|| app.session.active().is_none_or(|state| state.doc.id.0 != run.doc)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
run.restarted = true;
|
||||
run.phase = Phase::AgentRetryAt(Instant::now() + Duration::from_secs(3));
|
||||
if matches!(self.busy.as_deref(), Some("agent" | "pi-agent")) {
|
||||
self.busy = None;
|
||||
}
|
||||
self.pi_run = None;
|
||||
self.pi_request_scope = Value::Null;
|
||||
self.allow_apply = false;
|
||||
self.error.clear();
|
||||
true
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn production_operation_failed(&mut self, app: &PhotocraftApp, method: &str, reason: &str) -> bool {
|
||||
let Some(run) = self.product_production.as_ref().filter(|run| run.current(self, app)) else { return false; };
|
||||
if run.phase == Phase::Export && run.finish.is_some()
|
||||
&& (method == "slot-product-export" || method == "save" && self.pending_slot_apply.is_some()) {
|
||||
self.pending_slot_apply = None;
|
||||
self.complete_production_export(json!({"error":reason,"files":[]}));
|
||||
return true;
|
||||
}
|
||||
if method == "agent" && run.phase == Phase::Agent {
|
||||
if self.defer_production_agent(app) { return true; }
|
||||
if let Some(run) = self.product_production.take() {
|
||||
self.write_production_checkpoint(&run, true);
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn production_retry_delay(&self, now: Instant) -> Option<Duration> {
|
||||
match self.product_production.as_ref()?.phase {
|
||||
Phase::AgentRetryAt(at) if at > now => Some(at - now),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn production_start_waiting(&self) -> bool {
|
||||
self.product_production.as_ref().is_some_and(|run|
|
||||
run.awaiting_canvas_save() || matches!(run.phase, Phase::AgentRetryAt(at) if Instant::now() >= at))
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn production_canvas_save_delay(&self, now: Instant) -> Option<Duration> {
|
||||
self.product_production.as_ref().filter(|run| run.awaiting_canvas_save())
|
||||
.map(|run| run.canvas_save_deadline.saturating_duration_since(now))
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn production_tick(&mut self, app: &PhotocraftApp) {
|
||||
if self.product_production.is_none() {
|
||||
self.restore_production_checkpoint(app);
|
||||
}
|
||||
let current = self.product_production.as_ref().is_some_and(|run| run.current(self, app));
|
||||
if !current {
|
||||
if self.product_production.as_ref().is_some_and(|run|
|
||||
!run.awaiting_canvas_save() && app.session.documents().iter().any(|state| state.doc.id.0 == run.doc))
|
||||
{
|
||||
return;
|
||||
}
|
||||
if self.product_production.as_ref().is_some_and(Run::awaiting_canvas_save) {
|
||||
self.slot_apply_save_failed(app, "原制作项目已切换,请重新打开项目后继续");
|
||||
}
|
||||
self.product_production = None;
|
||||
self.product_export = None;
|
||||
if matches!(self.production_stop["state"].as_str(), Some("stopping" | "delivering")) {
|
||||
self.production_stop["state"] = json!("failed");
|
||||
self.production_stop["error"] = json!("原制作项目或授权已切换");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if self.product_production.as_ref().is_none_or(|run|
|
||||
app.session.active().is_none_or(|state| state.doc.id.0 != run.doc)) { return; }
|
||||
if self.production_stop["state"] == "stopping" {
|
||||
self.settle_production_stop(app);
|
||||
return;
|
||||
}
|
||||
if self.production_stop["state"] != "delivering" && self.production_budget_delay() == Some(Duration::ZERO) {
|
||||
let _ = self.request_production_stop("deliver", "到达时间上限自动交付");
|
||||
return;
|
||||
}
|
||||
let Some(run) = self.product_production.as_ref() else { return; };
|
||||
if run.phase == Phase::DeliveringBundle { return; }
|
||||
if self.production_canvas_save_delay(Instant::now()) == Some(Duration::ZERO) {
|
||||
self.slot_apply_save_failed(app, "等待制作画布保存超时,请重试");
|
||||
return;
|
||||
}
|
||||
if self.production_start_waiting() {
|
||||
let Some(canvas) = app.session.active() else { return; };
|
||||
let saved = self.persisted_revisions.get(&run.doc) == Some(&canvas.revision);
|
||||
if let Some(stage) = &run.opening {
|
||||
// A live handoff owns the checkpoint for the newly mounted output.
|
||||
if !saved && !(run.bound.is_some() && self.pi_run.is_some()
|
||||
&& self.saving.is_none() && !self.product_view_save_pending()) { return; }
|
||||
if !canvas_workspace::document_scope_matches(&canvas.doc, &self.template_workflow, &stage.output, &stage.variant) {
|
||||
self.production_canvas_open_failed(app, "save", "当前画布与所选输出或花色不一致,请重新打开");
|
||||
} else if saved {
|
||||
self.bind_production_canvas(app);
|
||||
} else if !self.enqueue_project_draft(canvas, !self.draft_changed) {
|
||||
self.production_canvas_open_failed(app, "save", "本机保存服务已断开,未绑定所选工作画布");
|
||||
}
|
||||
} else if saved && self.saving.is_none() && self.busy.is_none() && self.pending_slot_apply.is_none() {
|
||||
self.production_start_session(app);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if run.phase == Phase::Agent && self.busy.as_deref() == Some("pi-agent")
|
||||
&& self.saving.is_none() && !self.product_view_save_pending() && !self.production_write_pending()
|
||||
&& let Some(stage) = run.opening.clone() {
|
||||
self.dispatch_production_open(app, &stage);
|
||||
return;
|
||||
}
|
||||
if (self.busy.as_deref() == Some("pi-agent") || self.production_stop["state"] == "delivering" && self.busy.is_none())
|
||||
&& self.saving.is_none() && !self.product_view_save_pending()
|
||||
&& let Some(input) = self.product_export.take()
|
||||
&& let Err(error) = self.slot_action(app, "slot-product-export", input) {
|
||||
self.complete_production_export(json!({"error":error,"files":[]}));
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,758 @@
|
||||
use super::{Phase, Stage};
|
||||
use crate::jiansun::{Document, PhotocraftApp, Request, Value, Workspace, canvas_workspace, json};
|
||||
use photocraft_doc::LayerId;
|
||||
use photocraft_engine::DocState;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
// A production canvas has the same project identity as its viewer, but its
|
||||
// document, undo stack and working template belong to a single output.
|
||||
pub(super) struct Canvas {
|
||||
pub(super) document: DocState,
|
||||
pub(super) workflow: Value,
|
||||
pub(super) workspace: canvas_workspace::State,
|
||||
pub(super) camera: Option<crate::state::View>,
|
||||
}
|
||||
|
||||
enum ViewTarget {
|
||||
WorkingCanvas,
|
||||
CachedCanvas,
|
||||
Loading,
|
||||
Loaded(Box<Document>, Value),
|
||||
}
|
||||
|
||||
pub(super) struct ViewSwitch {
|
||||
id: u64,
|
||||
stage: Stage,
|
||||
target: ViewTarget,
|
||||
progress: Value,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(in crate::jiansun) struct Views {
|
||||
pub(super) worker: Option<Canvas>,
|
||||
pub(super) cached: HashMap<Stage, Canvas>,
|
||||
prepared: HashMap<Stage, (Box<Document>, Value)>,
|
||||
preloading: HashMap<Stage, ViewSwitch>,
|
||||
preload_attempts: HashSet<Stage>,
|
||||
preload_scope: Option<(u64, Value, Value)>,
|
||||
pub(super) switching: Option<ViewSwitch>,
|
||||
serial: u64,
|
||||
pub(super) saving: Option<u64>,
|
||||
failed_revision: Option<u64>,
|
||||
pub(in crate::jiansun) view_error: Option<String>,
|
||||
can_reuse_saved_view: bool,
|
||||
pub(super) editor_basis: Option<(Stage, Arc<Document>)>,
|
||||
pub(super) user_layers: HashMap<Stage, HashMap<LayerId, LayerRejection>>,
|
||||
waiting_stage: Option<Value>,
|
||||
}
|
||||
|
||||
impl Views {
|
||||
pub(super) fn clear(&mut self) {
|
||||
*self = Self { serial: self.serial, ..Self::default() };
|
||||
}
|
||||
|
||||
pub(super) fn clear_editor_basis(&mut self) {
|
||||
self.user_layers.clear();
|
||||
self.editor_basis = None;
|
||||
}
|
||||
|
||||
pub(super) fn bind_editor_basis(&mut self, stage: &Stage, doc: &Arc<Document>) {
|
||||
if self.editor_basis.as_ref().is_none_or(|(owner, _)| owner != stage) {
|
||||
self.editor_basis = Some((stage.clone(), doc.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn remember(&mut self, canvas: Canvas, active: Option<Stage>) {
|
||||
let Some(stage) = Stage::read(&canvas.workflow) else { return; };
|
||||
let Some(active) = active.filter(|active| *active != stage && active.variant == stage.variant) else { return; };
|
||||
if !canvas.matches_stage(&stage) {
|
||||
return;
|
||||
}
|
||||
self.cached.retain(|key, _| key.variant == active.variant && *key != active);
|
||||
if canvas.document.revision == canvas.document.saved_revision {
|
||||
self.cached.insert(stage, canvas);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn workflow_doc_matches_stage(doc: &Document, workflow: &Value, scope_blocked: bool, stage: &Stage) -> bool {
|
||||
if scope_blocked {
|
||||
return false;
|
||||
}
|
||||
if workflow["canvasFirst"] != true {
|
||||
return true;
|
||||
}
|
||||
canvas_workspace::document_scope_matches(doc, workflow, &stage.output, &stage.variant)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(in crate::jiansun) enum LayerRejection {
|
||||
UserEdit,
|
||||
UserLock,
|
||||
Precondition,
|
||||
}
|
||||
|
||||
impl LayerRejection {
|
||||
pub(in crate::jiansun) fn code(self) -> &'static str {
|
||||
match self {
|
||||
Self::UserEdit => "layer_manually_edited",
|
||||
Self::UserLock => "layer_newly_locked",
|
||||
Self::Precondition => "layer_precondition_failed",
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn message(self) -> &'static str {
|
||||
match self {
|
||||
Self::UserEdit => "当前图层已有手动修改",
|
||||
Self::UserLock => "当前图层或其父组有制作期间新增的锁",
|
||||
Self::Precondition => "当前图层的写入前置条件已变化",
|
||||
}
|
||||
}
|
||||
|
||||
fn check(basis: &Document, doc: &Document, id: LayerId) -> Option<Self> {
|
||||
if basis.id != doc.id { return Some(Self::Precondition); }
|
||||
let Some(path) = doc.path_of(id) else { return Some(Self::Precondition); };
|
||||
let Some(before) = basis.layer(id) else { return Some(Self::Precondition); };
|
||||
let now = doc.layer_at(&path).unwrap();
|
||||
// Check each ancestor as well as the target, even if a template
|
||||
// ancestor already contributes the same effective lock.
|
||||
if (1..=path.len()).filter_map(|n| doc.layer_at(&path[..n])).any(|layer| {
|
||||
let old = basis.layer(layer.id).map_or_else(Default::default, |layer| layer.locks);
|
||||
let new = layer.locks;
|
||||
new.all && !old.all || new.pixels && !old.pixels || new.position && !old.position
|
||||
|| new.transparency && !old.transparency || new.artboard && !old.artboard
|
||||
}) {
|
||||
return Some(Self::UserLock);
|
||||
}
|
||||
if basis.size != doc.size || before != now { return Some(Self::UserEdit); }
|
||||
if basis.mode != doc.mode || basis.depth != doc.depth
|
||||
|| basis.icc_profile != doc.icc_profile || basis.global_light != doc.global_light {
|
||||
return Some(Self::Precondition);
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl Workspace {
|
||||
pub(in crate::jiansun) fn product_view_pending(&self) -> bool {
|
||||
self.product_views.switching.is_some()
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn product_view_save_pending(&self) -> bool {
|
||||
self.product_views.saving.is_some()
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn product_view_detached(&self) -> bool {
|
||||
self.product_views.worker.is_some()
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn release_settled_product_view(&mut self) {
|
||||
if self.product_production.is_some() || self.pi_run.is_some() || self.busy.is_some()
|
||||
|| self.saving.is_some() || self.product_view_save_pending() {
|
||||
return;
|
||||
}
|
||||
if self.product_views.worker.as_ref().is_some_and(|worker|
|
||||
worker.document.revision == worker.document.saved_revision)
|
||||
&& let Some(worker) = self.product_views.worker.take()
|
||||
{
|
||||
self.product_views.remember(worker, Stage::read(&self.template_workflow));
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn product_stage_waiting_for_view(&self) -> bool {
|
||||
self.product_views.waiting_stage.is_some()
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn cancel_product_view_switch(&mut self) {
|
||||
self.product_views.cached.clear();
|
||||
self.product_views.prepared.clear();
|
||||
self.product_views.preloading.clear();
|
||||
self.product_views.preload_attempts.clear();
|
||||
self.product_views.preload_scope = None;
|
||||
self.product_views.switching = None;
|
||||
self.product_views.waiting_stage = None;
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn product_view_state(&self) -> Value {
|
||||
let working = self.product_production.as_ref().and_then(|run| run.bound.as_ref())
|
||||
.map(|stage| json!({"outputId":stage.output,"variantId":stage.variant}));
|
||||
let viewing = Stage::read(&self.template_workflow)
|
||||
.map(|stage| json!({"outputId":stage.output,"variantId":stage.variant}));
|
||||
json!({"viewing":viewing,"working":working,"switching":self.product_view_pending(),
|
||||
"prepared":self.product_views.prepared.keys().map(|stage| stage.output.as_str()).collect::<Vec<_>>(),
|
||||
"preparing":self.product_views.preloading.keys().map(|stage| stage.output.as_str()).min(),
|
||||
"progress":self.product_view_progress(),
|
||||
"detached":self.product_view_detached()})
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn product_view_progress(&self) -> Option<Value> {
|
||||
let request = self.product_views.switching.as_ref()?;
|
||||
let mut progress = request.progress.clone();
|
||||
if self.product_views.saving.is_some() {
|
||||
progress = json!({"phase":"view-save"});
|
||||
} else if !matches!(request.target, ViewTarget::Loading) {
|
||||
progress = json!({"phase":"view-ready"});
|
||||
}
|
||||
progress["viewLabel"] = json!(request.stage.label());
|
||||
Some(progress)
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn product_render_progress(&self, app: &PhotocraftApp) -> Option<Value> {
|
||||
if !self.template_workflow["productionStages"].is_array() { return None; }
|
||||
let stage = Stage::read(&self.template_workflow)?;
|
||||
let doc = app.session.active()?.doc.id;
|
||||
let fraction = app.redraws.get(&doc)?.fraction();
|
||||
(fraction < 1.0).then(|| json!({"phase":"view-render","viewLabel":stage.label(),"fraction":fraction}))
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn keep_current_product_view(&mut self) {
|
||||
let Some(request) = self.product_views.switching.take() else { return; };
|
||||
if let ViewTarget::Loaded(doc, meta) = request.target {
|
||||
self.product_views.prepared.insert(request.stage, (doc, meta));
|
||||
return;
|
||||
}
|
||||
if matches!(request.target, ViewTarget::Loading) {
|
||||
self.product_views.preload_attempts.insert(request.stage.clone());
|
||||
self.product_views.preloading.insert(request.stage.clone(), request);
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn production_canvas<'a>(&'a self, app: &'a PhotocraftApp) -> Option<(&'a DocState, &'a Value)> {
|
||||
if let Some(worker) = &self.product_views.worker {
|
||||
return Some((&worker.document, &worker.workflow));
|
||||
}
|
||||
app.session.active().map(|state| (state, &self.template_workflow))
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn production_revision(&self, app: &PhotocraftApp) -> Option<(u64, u64)> {
|
||||
self.production_canvas(app).map(|(state, _)| (state.doc.id.0, state.revision))
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn production_layer_rejection(&self, doc: &Document, layer: LayerId) -> Option<LayerRejection> {
|
||||
let key = &self.pi_request_scope["documentKey"];
|
||||
if key.is_object() && *key != super::super::product_document_key(doc) {
|
||||
return Some(LayerRejection::Precondition);
|
||||
}
|
||||
let variant = self.template_workflow["variantId"].as_str().unwrap_or(&self.canvas_workspace.variant);
|
||||
let marked = doc.layer(layer).is_some_and(|layer| {
|
||||
match &layer.content {
|
||||
photocraft_doc::LayerContent::Text(text) => {
|
||||
use sha2::{Digest, Sha256};
|
||||
let digest = format!("{:x}", Sha256::digest(text.text.as_bytes()));
|
||||
let key = format!("jiansun.manual-text.{}", layer.id.0);
|
||||
doc.metadata.text.iter().any(|(name, value)| *name == key
|
||||
&& serde_json::from_str::<Value>(value).is_ok_and(|value| value["sha256"] == digest))
|
||||
}
|
||||
photocraft_doc::LayerContent::Smart(_) => super::super::agent_canvas_read::template_field(doc, layer)["slotId"].as_str()
|
||||
.is_some_and(|slot| canvas_workspace::manual_image(doc, slot, variant).is_some()),
|
||||
_ => false,
|
||||
}
|
||||
});
|
||||
if marked { return Some(LayerRejection::UserEdit); }
|
||||
let live = self.pi_canvas_basis.as_ref().map_or(Some(LayerRejection::Precondition), |basis| {
|
||||
LayerRejection::check(basis, doc, layer)
|
||||
});
|
||||
if live == Some(LayerRejection::UserLock) { return live; }
|
||||
let recorded = Stage::read(&self.template_workflow)
|
||||
.and_then(|stage| self.product_views.user_layers.get(&stage)?.get(&layer).copied());
|
||||
recorded.or(live)
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn with_product_target<T>(&mut self, app: &mut PhotocraftApp, action: impl FnOnce(&mut Self, &mut PhotocraftApp) -> T) -> T {
|
||||
let Some(worker) = self.product_views.worker.as_ref() else { return action(self, app); };
|
||||
let doc = worker.document.doc.id;
|
||||
let Some(project) = self.owned_project_key(doc.0) else { return action(self, app); };
|
||||
if app.session.active().is_none_or(|state| state.doc.id != doc)
|
||||
|| self.product_production.as_ref().is_some_and(|run| run.project_identity() != (doc.0, project))
|
||||
{
|
||||
return action(self, app);
|
||||
}
|
||||
let mut worker = self.product_views.worker.take().unwrap();
|
||||
// The native tab ID is shared, but its camera belongs to the mounted output.
|
||||
worker.swap(self, app);
|
||||
worker.swap_camera(app);
|
||||
self.product_target_hidden = true;
|
||||
let result = action(self, app);
|
||||
self.product_target_hidden = false;
|
||||
worker.swap_camera(app);
|
||||
worker.swap(self, app);
|
||||
self.product_views.worker = Some(worker);
|
||||
result
|
||||
}
|
||||
|
||||
pub(super) fn product_stage_for_view(&self, input: &Value) -> Result<Stage, String> {
|
||||
let output = input["outputId"].as_str().ok_or("输出类型缺失")?;
|
||||
let available = self.template_workflow["outputVariantIds"][output].as_array().filter(|ids| !ids.is_empty());
|
||||
let variant = input["variantId"].as_str().filter(|id| !id.is_empty())
|
||||
.or_else(|| self.template_workflow["variantId"].as_str().filter(|shown| {
|
||||
!shown.is_empty() && available.is_none_or(|ids| ids.iter().any(|id| id == *shown))
|
||||
}))
|
||||
.or_else(|| {
|
||||
if let Some(ids) = available {
|
||||
ids.first()?.as_str()
|
||||
} else {
|
||||
self.template_workflow["variants"][0]["id"].as_str()
|
||||
.or_else(|| self.creation_brief["variants"][0]["id"].as_str())
|
||||
}
|
||||
}).ok_or("当前输出没有已选款式")?;
|
||||
Stage::read(&json!({"outputId":output,"variantId":variant})).ok_or_else(|| "产品画布类型无效".into())
|
||||
}
|
||||
|
||||
fn load_product_view(&mut self, active: &DocState, id: u64, stage: &Stage) -> Result<(), String> {
|
||||
self.tx.send(Request::Action("slot-product-view".into(), json!({
|
||||
"doc":active.doc.id.0,"baseRevision":active.revision,"workspaceId":self.template_workflow["workspaceId"],
|
||||
"productViewId":id,"outputId":stage.output,"variantId":stage.variant,
|
||||
}))).map_err(|_| "当前产品画布未能打开".into())
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn request_product_view(&mut self, app: &PhotocraftApp, input: &Value) -> Result<Value, String> {
|
||||
self.begin_product_view(app, input).inspect_err(|error| {
|
||||
self.product_views.view_error = Some(error.clone());
|
||||
self.error = error.clone();
|
||||
})
|
||||
}
|
||||
|
||||
fn begin_product_view(&mut self, app: &PhotocraftApp, input: &Value) -> Result<Value, String> {
|
||||
let active = app.session.active().ok_or("请先打开产品画布")?;
|
||||
if self.open_projects.get(&active.doc.id.0).is_none_or(|project| !project.starts_with(&self.local_identity(""))) {
|
||||
return Err("当前产品画布归属已变化".into());
|
||||
}
|
||||
let stage = self.product_stage_for_view(input)?;
|
||||
if Stage::read(&self.template_workflow).as_ref() == Some(&stage)
|
||||
&& workflow_doc_matches_stage(&active.doc, &self.template_workflow, self.canvas_workspace.scope_blocked, &stage)
|
||||
{
|
||||
self.keep_current_product_view();
|
||||
return Ok(json!({"viewing":true}));
|
||||
}
|
||||
if self.product_views.switching.as_ref().is_some_and(|pending| pending.stage == stage) {
|
||||
return Ok(json!({"viewing":true}));
|
||||
}
|
||||
self.keep_current_product_view();
|
||||
if let Some(request) = self.product_views.preloading.remove(&stage) {
|
||||
self.product_views.switching = Some(request);
|
||||
return Ok(json!({"viewing":true}));
|
||||
}
|
||||
self.product_views.serial += 1;
|
||||
self.product_views.failed_revision = None;
|
||||
self.product_views.view_error = None;
|
||||
let id = self.product_views.serial;
|
||||
let target = if self.product_views.worker.as_ref().is_some_and(|canvas| canvas.matches_stage(&stage)) {
|
||||
ViewTarget::WorkingCanvas
|
||||
} else if self.product_views.cached.get(&stage).is_some_and(|canvas|
|
||||
canvas.document.doc.id == active.doc.id && canvas.workflow["workspaceId"] == self.template_workflow["workspaceId"]
|
||||
&& canvas.matches_stage(&stage))
|
||||
{
|
||||
ViewTarget::CachedCanvas
|
||||
} else if let Some((doc, value)) = self.product_views.prepared.remove(&stage)
|
||||
&& doc.id == active.doc.id && value["workspaceId"] == self.template_workflow["workspaceId"]
|
||||
{
|
||||
ViewTarget::Loaded(doc, value)
|
||||
} else {
|
||||
self.load_product_view(active, id, &stage)?;
|
||||
ViewTarget::Loading
|
||||
};
|
||||
self.product_views.switching = Some(ViewSwitch { id, stage, target, progress: json!({"phase":"metadata"}) });
|
||||
Ok(json!({"viewing":true}))
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn product_view_received(&mut self, app: &PhotocraftApp, doc: Box<Document>, value: Value) {
|
||||
if !self.product_view_receipt_is_current(app, &value)
|
||||
|| !app.session.active().is_some_and(|active| active.doc.id == doc.id) { return; }
|
||||
if let Some(request) = self.product_views.switching.as_mut()
|
||||
&& value["productViewId"].as_u64() == Some(request.id) && Stage::read(&value).as_ref() == Some(&request.stage)
|
||||
{
|
||||
request.target = ViewTarget::Loaded(doc, value);
|
||||
} else if let Some(stage) = Stage::read(&value)
|
||||
&& self.product_views.preloading.get(&stage).is_some_and(|request| value["productViewId"].as_u64() == Some(request.id))
|
||||
{
|
||||
self.product_views.preloading.remove(&stage);
|
||||
self.product_views.prepared.insert(stage, (doc, value));
|
||||
}
|
||||
}
|
||||
|
||||
fn product_view_receipt_is_current(&self, app: &PhotocraftApp, value: &Value) -> bool {
|
||||
value["accountId"] == self.account["id"] && value["origin"] == self.origin
|
||||
&& value["workspaceId"] == self.template_workflow["workspaceId"]
|
||||
&& app.session.active().is_some_and(|active| value["doc"].as_u64() == Some(active.doc.id.0))
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn product_view_progressed(&mut self, app: &PhotocraftApp, value: &Value) {
|
||||
if !self.product_view_receipt_is_current(app, value) { return; }
|
||||
for pending in self.product_views.switching.iter_mut().chain(self.product_views.preloading.values_mut()) {
|
||||
if value["productViewId"].as_u64() == Some(pending.id) {
|
||||
pending.progress = value.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn product_view_failed(&mut self, value: &Value) {
|
||||
let (Some(id), Some(error)) = (value["productViewId"].as_u64(), value["error"].as_str()) else { return; };
|
||||
self.product_views.preloading.retain(|_, request| request.id != id);
|
||||
if self.product_views.switching.as_ref().is_some_and(|req| req.id == id) {
|
||||
self.product_views.switching = None;
|
||||
self.error = error.into();
|
||||
self.product_views.view_error = Some(error.into());
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn product_view_save_failed(&mut self, app: &PhotocraftApp, value: &Value) {
|
||||
if app.session.active().is_some_and(|state| Some(state.doc.id.0) == value["doc"].as_u64())
|
||||
&& self.product_views.saving.is_some() && self.product_views.saving == value["revision"].as_u64()
|
||||
{
|
||||
self.product_views.failed_revision = self.product_views.saving.take();
|
||||
self.product_views.switching = None;
|
||||
let error = value["error"].as_str().unwrap_or("当前产品画布保存失败");
|
||||
self.error = error.into();
|
||||
self.product_views.view_error = Some(error.into());
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn product_view_saved(&mut self, app: &mut PhotocraftApp, id: u64, revision: u64, meta: &Value) -> bool {
|
||||
if meta["productViewOnly"] != true && !meta["activeProductViewRevision"].is_u64() { return false; }
|
||||
if self.product_views.saving == Some(revision) { self.record_product_view_edits(app); }
|
||||
if self.product_views.saving == Some(revision)
|
||||
&& let Some(state) = app.session.active_mut().filter(|state| state.doc.id.0 == id)
|
||||
{
|
||||
self.product_views.saving = None;
|
||||
if meta["documentKey"].is_object() && meta["documentKey"] != super::super::product_document_key(&state.doc) {
|
||||
return true;
|
||||
}
|
||||
state.saved_revision = revision;
|
||||
if meta["activeProductViewRevision"].is_u64() {
|
||||
state.path = meta["savedPath"].as_str().map(str::to_owned);
|
||||
self.template_workflow["revision"] = meta["activeProductViewRevision"].clone();
|
||||
self.persisted_revisions.insert(id, revision);
|
||||
if let Some(previous) = self.product_views.worker.take() {
|
||||
self.product_views.remember(previous, Stage::read(&self.template_workflow));
|
||||
}
|
||||
self.product_views.failed_revision = None;
|
||||
self.product_views.can_reuse_saved_view = false;
|
||||
self.product_views.waiting_stage = None;
|
||||
self.draft_changed = true;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn sync_product_editor_basis_layers(&mut self, doc: &Document, layers: &[LayerId]) {
|
||||
if self.product_target_hidden { return; }
|
||||
let Some(stage) = Stage::read(&self.template_workflow) else { return; };
|
||||
let Some((_, basis)) = self.product_views.editor_basis.as_mut()
|
||||
.filter(|(owner, basis)| *owner == stage && basis.id == doc.id && basis.size == doc.size) else { return; };
|
||||
let user_layers = self.product_views.user_layers.get(&stage);
|
||||
let basis = Arc::make_mut(basis);
|
||||
for &id in layers {
|
||||
if user_layers.is_some_and(|layers| layers.contains_key(&id)) { continue; }
|
||||
if let Some((before, after)) = basis.layer_mut(id).zip(doc.layer(id)) {
|
||||
*before = after.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn record_product_view_edits(&mut self, app: &PhotocraftApp) {
|
||||
if self.product_target_hidden { return; }
|
||||
let Some((stage, basis)) = self.product_views.editor_basis.as_ref() else { return; };
|
||||
let Some(state) = app.session.active() else { return; };
|
||||
if basis.id != state.doc.id || Stage::read(&self.template_workflow).as_ref() != Some(stage) { return; }
|
||||
let Some(mapping) = canvas_workspace::document_mapping(&state.doc) else { return; };
|
||||
let changed = self.product_views.user_layers.entry(stage.clone()).or_default();
|
||||
for id in mapping["outputs"].as_array().into_iter().flatten()
|
||||
.flat_map(|page| page["mapping"]["fields"].as_array().into_iter().flatten())
|
||||
.filter_map(|field| field["nativeLayerId"].as_u64()).map(LayerId)
|
||||
{
|
||||
match LayerRejection::check(basis, &state.doc, id) {
|
||||
Some(LayerRejection::UserLock) => { changed.insert(id, LayerRejection::UserLock); }
|
||||
Some(LayerRejection::UserEdit) => { changed.insert(id, LayerRejection::UserEdit); }
|
||||
_ => { changed.remove(&id); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Bind to the already open editor if production catches up with the
|
||||
/// user's selection. The just-loaded disk draft cannot replace live edits.
|
||||
pub(in crate::jiansun) fn join_product_view(&mut self, app: &mut PhotocraftApp, meta: &Value) -> bool {
|
||||
if self.product_views.worker.is_none() || meta["continueProduct"] != true
|
||||
|| self.product_production.as_ref().is_none_or(|run| !run.accepts_canvas(meta))
|
||||
|| meta["accountId"] != self.account["id"] || meta["origin"] != self.origin
|
||||
|| !app.session.active().is_some_and(|state| canvas_workspace::document_mapping(&state.doc)
|
||||
.is_some_and(|mapping| mapping["workspaceId"] == meta["workspaceId"]
|
||||
&& mapping["templateHash"] == meta["workflow"]["templateHash"]))
|
||||
|| Stage::read(meta) != Stage::read(&self.template_workflow) { return false; }
|
||||
if self.product_views.saving.is_some() || app.saving() {
|
||||
self.product_views.waiting_stage = Some(meta.clone());
|
||||
return true;
|
||||
}
|
||||
self.record_product_view_edits(app);
|
||||
if let Some(worker) = self.product_views.worker.take()
|
||||
&& let Some(active) = app.session.active_mut() {
|
||||
active.path = worker.document.path;
|
||||
active.revision = active.revision.max(worker.document.revision) + 1;
|
||||
active.last_damage = None;
|
||||
}
|
||||
self.product_views.editor_basis = None;
|
||||
self.template_workflow = meta["workflow"].clone();
|
||||
self.canvas_workspace.scope_switch_in_flight = false;
|
||||
self.production_opened(app, meta);
|
||||
true
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn continue_product_canvas(&mut self, app: &mut PhotocraftApp, doc: Box<Document>, meta: Value) {
|
||||
if !self.accepts_production_epoch(&meta["writeEpoch"]) { return; }
|
||||
let Some(stage) = Stage::read(&meta) else { return; };
|
||||
let Some(run) = self.product_production.as_ref() else { return; };
|
||||
if !run.current(self, app) || !run.accepts_canvas(&meta)
|
||||
|| meta["accountId"] != self.account["id"] || meta["origin"] != self.origin { return; }
|
||||
let opening_first = run.bound.is_none();
|
||||
if !canvas_workspace::document_scope_matches(&doc, &meta["workflow"], &stage.output, &stage.variant) {
|
||||
self.production_canvas_open_failed(app, "slot-skeleton", "已打开的模板画布与所选输出或花色不一致,请重新打开");
|
||||
return;
|
||||
}
|
||||
self.park_user_canvas_changes(app);
|
||||
self.product_views.cached.remove(&stage);
|
||||
self.product_views.prepared.remove(&stage);
|
||||
self.product_views.preloading.remove(&stage);
|
||||
if self.join_product_view(app, &meta) { return; }
|
||||
if self.product_views.worker.is_some() {
|
||||
self.with_product_target(app, |w, app| w.receive_slot_canvas(app, doc, meta));
|
||||
return;
|
||||
}
|
||||
let Some(active) = app.session.active().filter(|state| state.doc.id == doc.id) else { return; };
|
||||
let visible = Stage::read(&self.template_workflow);
|
||||
if visible.as_ref() == Some(&stage)
|
||||
&& canvas_workspace::document_scope_matches(&active.doc, &meta["workflow"], &stage.output, &stage.variant) {
|
||||
self.template_workflow = meta["workflow"].clone();
|
||||
self.canvas_workspace.scope_switch_in_flight = false;
|
||||
self.production_opened(app, &meta);
|
||||
return;
|
||||
}
|
||||
// A preparation placeholder has no product view to keep alongside the worker.
|
||||
if visible.as_ref() == Some(&stage) || opening_first && visible.as_ref().is_none_or(|shown|
|
||||
!canvas_workspace::document_scope_matches(&active.doc, &self.template_workflow, &shown.output, &shown.variant)) {
|
||||
self.receive_slot_canvas(app, doc, meta);
|
||||
return;
|
||||
}
|
||||
let Some(active) = app.session.active_mut() else { return; };
|
||||
let mut worker = DocState::new(*doc, active.path.clone());
|
||||
worker.revision = active.revision + 1;
|
||||
// The replacement shares the native tab ID. The previous output's
|
||||
// saved revision cannot acknowledge this new working canvas.
|
||||
self.persisted_revisions.remove(&worker.doc.id.0);
|
||||
active.path = meta["previousViewPath"].as_str().map(str::to_owned);
|
||||
self.canvas_workspace.scope_switch_in_flight = false;
|
||||
self.product_views.editor_basis = visible.map(|stage| (stage, active.doc.clone()));
|
||||
self.product_views.worker = Some(Canvas { document: worker, workflow: meta["workflow"].clone(),
|
||||
workspace: canvas_workspace::State::default(), camera: None });
|
||||
self.with_product_target(app, |w, app| {
|
||||
w.canvas_opened(&meta);
|
||||
w.production_opened(app, &meta);
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn preload_product_outputs(&mut self, app: &PhotocraftApp) {
|
||||
let Some(active) = app.session.active() else { return; };
|
||||
if self.library || self.material || self.creation_open
|
||||
|| !self.template_workflow["productionStages"].is_array()
|
||||
|| self.open_projects.get(&active.doc.id.0).is_none_or(|project| !project.starts_with(&self.local_identity("")))
|
||||
{ return; }
|
||||
let scope = (active.doc.id.0, self.template_workflow["workspaceId"].clone(), self.creation["revision"].clone());
|
||||
if self.product_views.preload_scope.as_ref() != Some(&scope) {
|
||||
self.product_views.prepared.clear();
|
||||
self.product_views.preloading.clear();
|
||||
self.product_views.preload_attempts.clear();
|
||||
self.product_views.preload_scope = Some(scope);
|
||||
}
|
||||
if !self.product_views.preloading.is_empty() || self.product_views.switching.is_some() { return; }
|
||||
let viewing = Stage::read(&self.template_workflow);
|
||||
let working = self.product_views.worker.as_ref().and_then(|worker| Stage::read(&worker.workflow));
|
||||
let mut seen = HashSet::new();
|
||||
let alternatives: Vec<_> = self.template_workflow["outputs"].as_array().into_iter().flatten()
|
||||
.filter_map(|row| row["outputId"].as_str()).filter(|output| seen.insert(*output))
|
||||
.filter_map(|output| self.product_stage_for_view(&json!({"outputId":output})).ok()).collect();
|
||||
self.product_views.prepared.retain(|stage, _| alternatives.contains(stage));
|
||||
let next = alternatives.into_iter()
|
||||
.find(|stage| Some(stage) != viewing.as_ref() && Some(stage) != working.as_ref()
|
||||
&& !self.product_views.preload_attempts.contains(stage) && !self.product_views.cached.contains_key(stage)
|
||||
&& !self.product_views.prepared.contains_key(stage));
|
||||
if let Some(stage) = next {
|
||||
self.product_views.preload_attempts.insert(stage.clone());
|
||||
self.product_views.serial += 1;
|
||||
let id = self.product_views.serial;
|
||||
if self.load_product_view(active, id, &stage).is_ok() {
|
||||
self.product_views.preloading.insert(stage.clone(), ViewSwitch { id, stage, target: ViewTarget::Loading,
|
||||
progress: json!({"phase":"metadata"}) });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::jiansun) fn product_view_tick(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
let _timing = crate::operation_timer::OperationTimer::new(
|
||||
"product.switch_view", app.session.active().map(|state| state.doc.as_ref()), true,
|
||||
);
|
||||
if !self.in_background_project { self.preload_product_outputs(app); }
|
||||
if self.product_views.saving.is_some() || app.saving() { return; }
|
||||
if let Some(meta) = self.product_views.waiting_stage.take() {
|
||||
if self.join_product_view(app, &meta) { return; }
|
||||
}
|
||||
let Some(active) = app.session.active() else { self.product_views.clear(); return; };
|
||||
if self.product_views.worker.as_ref().is_some_and(|worker| worker.document.doc.id != active.doc.id) {
|
||||
return;
|
||||
}
|
||||
if (self.product_view_detached() || self.product_view_pending())
|
||||
&& self.open_projects.get(&active.doc.id.0).is_none_or(|project| !project.starts_with(&self.local_identity("")))
|
||||
{
|
||||
self.product_views.clear();
|
||||
return;
|
||||
}
|
||||
let ready = self.product_views.switching.as_ref().is_some_and(|request| !matches!(request.target, ViewTarget::Loading));
|
||||
let detached = self.product_views.worker.is_some();
|
||||
let viewing_worker = !detached && self.product_production.as_ref().is_some_and(|run|
|
||||
run.phase == Phase::Agent && Stage::read(&self.template_workflow).as_ref() == run.bound.as_ref());
|
||||
let activate = detached && self.product_production.is_none() && self.pi_run.is_none()
|
||||
&& self.busy.is_none() && self.saving.is_none() && self.product_views.switching.is_none();
|
||||
let dirty = active.revision != active.saved_revision;
|
||||
if app.ui.transform.is_some() || app.ui.text_edit.is_some()
|
||||
|| ctx.input(|input| input.raw.focused && input.pointer.any_down()) { return; }
|
||||
// A running stage keeps its own DocState after the viewer swaps away, so its
|
||||
// edits can finish saving on the Agent's lane while the other output opens.
|
||||
if (dirty && (ready && !viewing_worker || detached && self.touched.elapsed() > Duration::from_secs(2))) || activate {
|
||||
if self.product_views.failed_revision == Some(active.revision) { return; }
|
||||
self.record_product_view_edits(app);
|
||||
let meta = if activate {
|
||||
let reuse_saved = self.product_views.can_reuse_saved_view && !dirty;
|
||||
json!({"activateProductView":true,"reuseSavedProductView":reuse_saved,"composer":self.composer,
|
||||
"messages":self.messages,"project":self.project_context,"syncDirty":!reuse_saved&&self.sync_dirty,
|
||||
"creationDraft":self.creation_draft()})
|
||||
} else { json!({"productViewOnly":true}) };
|
||||
self.queue_product_view_save(active, meta);
|
||||
return;
|
||||
}
|
||||
if !ready { return; }
|
||||
let Some(request) = self.product_views.switching.take() else { return; };
|
||||
let doc_id = active.doc.id;
|
||||
match request.target {
|
||||
ViewTarget::WorkingCanvas => {
|
||||
if !self.product_views.worker.as_ref().is_some_and(|worker| worker.matches_stage(&request.stage)) {
|
||||
let input = json!({"outputId":request.stage.output,"variantId":request.stage.variant});
|
||||
let _ = self.request_product_view(app, &input);
|
||||
return;
|
||||
}
|
||||
let Some(mut worker) = self.product_views.worker.take() else { return; };
|
||||
worker.swap_view(self, app);
|
||||
self.product_views.remember(worker, Stage::read(&self.template_workflow));
|
||||
self.product_views.editor_basis = None;
|
||||
}
|
||||
ViewTarget::CachedCanvas => {
|
||||
let Some(mut view) = self.product_views.cached.remove(&request.stage)
|
||||
.filter(|canvas| canvas.matches_stage(&request.stage))
|
||||
else {
|
||||
let input = json!({"outputId":request.stage.output,"variantId":request.stage.variant});
|
||||
let _ = self.request_product_view(app, &input);
|
||||
return;
|
||||
};
|
||||
view.swap_view(self, app);
|
||||
if detached {
|
||||
self.product_views.remember(view, Stage::read(&self.template_workflow));
|
||||
} else {
|
||||
self.product_views.worker = Some(view);
|
||||
}
|
||||
self.product_views.editor_basis = app.session.active().map(|state| (request.stage, state.doc.clone()));
|
||||
self.product_views.can_reuse_saved_view = true;
|
||||
}
|
||||
ViewTarget::Loaded(doc, value) => {
|
||||
// A result can finish loading as its production stage starts.
|
||||
// In that case the already open worker is the live editor.
|
||||
if self.product_views.worker.as_ref().is_some_and(|worker| worker.matches_stage(&request.stage)) {
|
||||
let Some(mut worker) = self.product_views.worker.take() else { return; };
|
||||
worker.swap_view(self, app);
|
||||
self.product_views.remember(worker, Stage::read(&self.template_workflow));
|
||||
self.product_views.editor_basis = None;
|
||||
} else {
|
||||
let mut view = Canvas { document: DocState::new(*doc, value["viewPath"].as_str().map(str::to_owned)),
|
||||
workflow: value["workflow"].clone(), workspace: canvas_workspace::State::default(), camera: None };
|
||||
view.swap_view(self, app);
|
||||
if detached {
|
||||
self.product_views.remember(view, Stage::read(&self.template_workflow));
|
||||
} else {
|
||||
self.product_views.worker = Some(view);
|
||||
}
|
||||
self.product_views.editor_basis = app.session.active().map(|state| (request.stage, state.doc.clone()));
|
||||
self.product_views.can_reuse_saved_view = value["canReuseSavedView"] == true;
|
||||
self.canvas_opened(&value);
|
||||
}
|
||||
}
|
||||
ViewTarget::Loading => return,
|
||||
}
|
||||
self.product_views.view_error = None;
|
||||
app.canvases.retain(|(id, _), _| *id != doc_id);
|
||||
app.channel_views.remove(&doc_id.0);
|
||||
crate::background_redraw::cancel(app, doc_id);
|
||||
if let Some(pending) = &mut app.product_cpu_texture {
|
||||
pending.key = None;
|
||||
}
|
||||
app.product_view_redraw = Some(doc_id);
|
||||
app.sync_views();
|
||||
ctx.request_repaint();
|
||||
}
|
||||
|
||||
fn queue_product_view_save(&mut self, state: &DocState, meta: Value) -> bool {
|
||||
if self.tx.send(Request::Save(state.doc.clone(), state.revision, meta)).is_err() {
|
||||
return false;
|
||||
}
|
||||
self.product_views.saving = Some(state.revision);
|
||||
true
|
||||
}
|
||||
|
||||
pub(super) fn flush_exit_view(&mut self, app: &PhotocraftApp) -> Result<(), String> {
|
||||
// The editable view may be on another output of the same project.
|
||||
// Preserve its own draft before briefly swapping in the working canvas.
|
||||
if !self.product_view_save_pending() && !app.saving()
|
||||
&& let Some(view) = app.session.active().filter(|state| state.is_dirty())
|
||||
&& self.product_views.worker.as_ref().is_some_and(|worker| worker.document.doc.id == view.doc.id)
|
||||
{
|
||||
if self.product_views.failed_revision == Some(view.revision) {
|
||||
return Err(self.error.clone());
|
||||
}
|
||||
if !self.queue_product_view_save(view, json!({"productViewOnly":true})) {
|
||||
return Err("当前产品画布保存服务已断开".into());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Canvas {
|
||||
fn matches_stage(&self, stage: &Stage) -> bool {
|
||||
Stage::read(&self.workflow).as_ref() == Some(stage)
|
||||
&& workflow_doc_matches_stage(&self.document.doc, &self.workflow, self.workspace.scope_blocked, stage)
|
||||
}
|
||||
|
||||
fn swap(&mut self, w: &mut Workspace, app: &mut PhotocraftApp) {
|
||||
if let Some(active) = app.session.active_mut() {
|
||||
std::mem::swap(active, &mut self.document);
|
||||
std::mem::swap(&mut w.template_workflow, &mut self.workflow);
|
||||
std::mem::swap(&mut w.canvas_workspace, &mut self.workspace);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn swap_view(&mut self, w: &mut Workspace, app: &mut PhotocraftApp) {
|
||||
w.record_product_view_edits(app);
|
||||
w.park_user_canvas_changes(app);
|
||||
w.canvas_workspace.finish_reference_intro();
|
||||
self.swap(w, app);
|
||||
if w.product_production.is_some() && let Some(active) = app.session.active() {
|
||||
w.user_canvas_changes.bind(&active.doc, active.revision);
|
||||
}
|
||||
self.swap_camera(app);
|
||||
}
|
||||
|
||||
fn swap_camera(&mut self, app: &mut PhotocraftApp) {
|
||||
if let Some(index) = app.session.active_index()
|
||||
&& let Some(view) = app.ui.views.get_mut(index)
|
||||
{
|
||||
let target = self.camera.take().unwrap_or_default();
|
||||
self.camera = Some(std::mem::replace(view, target));
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user