feat(xiaoyi): persist and dispatch reviewed image requests by frozen id
This commit is contained in:
parent
b13ddba701
commit
f3fee2dc98
@ -11,7 +11,9 @@ const labels = Object.freeze({
|
||||
open_production_output: '打开制作画布',
|
||||
plan_production: '读取制作进度', start_production_strategy: '准备制作策划', read_production_knowledge: '读取制作规则',
|
||||
read_copy_fields: '查看待处理图文', delegate_image_slots: '分派图片图位', review_image_slots: '查看图位结果', retire_production_image: '清理已退回的候选图',
|
||||
read_slot_images: '查看图位图片', generate_slot_image: '生成候选图片',
|
||||
read_slot_images: '查看图位图片', use_product_image: '取用商品实拍',
|
||||
prepare_image_request: '准备生图请求', read_image_request: '核对生图请求',
|
||||
freeze_image_request: '冻结生图请求', dispatch_image_request: '生成候选图片',
|
||||
await_image_slots: '等待子代理回执', adopt_production_image: '回填候选图片', reconcile_image_slots: '核查图片原请求',
|
||||
read_archived_images: '查找同款历史候选', stage_archived_image: '加入待验历史候选',
|
||||
read_output_screen: '查看实际画布', record_screen_check: '记录本屏复核', check_page_copy: '发起文案复核',
|
||||
@ -44,8 +46,8 @@ export function activityScope(identity, canvas, begun) {
|
||||
|
||||
function details(event) {
|
||||
const toolName = Object.hasOwn(labels, event.toolName) ? event.toolName : 'other';
|
||||
const stopped = event.type === 'tool_execution_end' && event.isError && ['canvas_edit', 'canvas_preview', 'native_call', 'codemode'].includes(event.toolName)
|
||||
&& Array.isArray(event.result?.content) && event.result.content.some(c => c.type === 'text' && /接手|画布已修改/.test(c.text));
|
||||
const stopped = event.isError && ['write_revoked','revision_conflict','cancelled']
|
||||
.includes(event.result?.details?.failure?.category);
|
||||
const pending = typeof event.result?.details?.pendingOriginal === 'string';
|
||||
const status = event.type === 'tool_execution_start' ? 'started' : stopped ? 'stopped' :
|
||||
event.isError ? 'failed' : pending ? 'pending' : 'completed';
|
||||
|
||||
@ -75,8 +75,13 @@ function toolsFor(host) {
|
||||
if (host.compromised) throw Error('本地会话锁失效,已停止工具执行');
|
||||
if (name === 'memory_set' && !host.productionGoal && host.canvas?.workflowRead) await host.readWorkflow({section:'overview'});
|
||||
if (host.turnEpoch !== epoch) throw Error('原回合已结束,旧工具不会继续执行');
|
||||
const value = await execute(args, signal, ctx);
|
||||
return format(name==='canvas_read'&&args.revision!==undefined?{...value,changedSinceRevision:value.revision!==args.revision}:value);
|
||||
try {
|
||||
const value = await execute(args, signal, ctx);
|
||||
return format(name==='canvas_read'&&args.revision!==undefined?{...value,changedSinceRevision:value.revision!==args.revision}:value);
|
||||
} catch(error) {
|
||||
if (!(error instanceof BridgeError)) throw error;
|
||||
return {...plain({failure:error.wire()}),isError:true};
|
||||
}
|
||||
} });
|
||||
const string = maxLength => Type.String({ maxLength });
|
||||
const commands = nativeTools(host, make);
|
||||
|
||||
@ -19,21 +19,25 @@ const rev=Type.Integer({minimum:0});
|
||||
const optional=Type.Optional;
|
||||
const fit=Type.Union([Type.Literal('cover'),Type.Literal('contain')]);
|
||||
const nextOutput=optional(obj({outputId:text,variantId:text}));
|
||||
const imageSourceDescription='generate 使用生图模型,以同款实拍约束结构,默认参考模板场景和构图。product 直接使用或裁切已上传原片,保留原片场景。';
|
||||
const imageArgs=obj({
|
||||
source:Type.Union([Type.Literal('generate'),Type.Literal('product')],{description:imageSourceDescription}),
|
||||
prompt:optional(Type.String({description:'当 source=generate 时,描述新场景、构图或具体返工要求。'})),
|
||||
reworkChange:optional(Type.String({description:'返工时说明相对退回候选具体改了什么。其余情况可省略。'})),
|
||||
const productImageArgs={
|
||||
referenceIndex:optional(page),referenceCrop:optional(Type.Tuple(Array.from({length:4},()=>Type.Integer({minimum:0,maximum:1000})))),
|
||||
};
|
||||
const preparationArgs={
|
||||
prompt:text,
|
||||
reworkChange:optional(Type.String({description:'返工时记录这次改变了什么。'})),
|
||||
reworkCandidateId:optional(text),
|
||||
geometryReferenceIndex:optional(page),
|
||||
useTemplateReference:optional(Type.Boolean({description:'默认使用模板取景提示和构图参考。传 false 时只用同款原片与本次改写的要求。'})),
|
||||
prefer2k:optional(Type.Boolean({description:'当模板需大图或要二次裁切时,在当前线路支持的画幅中优先请求 2K。用候选原件的尺寸验收。'})),
|
||||
retryOf:optional(Type.String({minLength:1,description:'仅填写已明确可重试的生图失败候选 ID(retryableFailure=true)。验图退回时根据退回理由改写 prompt,创建新候选。'})),
|
||||
});
|
||||
useTemplateReference:optional(Type.Boolean({description:'传 false 可准备一版不使用模板参考和取景提示的请求。'})),
|
||||
prefer2k:optional(Type.Boolean()),
|
||||
retryOf:optional(Type.String({description:'仅限已确认可重试的失败候选。'})),
|
||||
};
|
||||
const requestIdArgs={requestId:text};
|
||||
const freezeArgs={...requestIdArgs,expectedRevision:rev,expectedHash:text};
|
||||
const dispatchArgs={frozenRequestId:text};
|
||||
|
||||
export const productionOperationTools = [
|
||||
['open_production_output','打开本轮待制作的工作画布,返回已保存画布的绑定回执。用 plan_production 获取输出和花色。',obj({outputId:text,variantId:text})],
|
||||
['plan_production','读取当前商品、模板、图位、资料和本轮其它待处理输出的索引。按 slotIds 读取指定图位的规则和要求。全局模板规则可用 workflow_read 读取。调用图位工具时优先使用 pictures 中的 fieldId。',obj({slotIds:optional(ids)})],
|
||||
['plan_production','读取当前商品、模板、图位、资料和本轮其它待处理输出的索引。按 slotIds 读取指定图位的规则和要求。模板规则从项目 Skill 及其引用读取。调用图位工具时优先使用 pictures 中的 fieldId。',obj({slotIds:optional(ids)})],
|
||||
['read_production_knowledge','读取已选模板的固定版本规则,按回执的 nextOffset 翻页。',obj({fileId:text,offset:optional(page)})],
|
||||
['read_copy_fields','读取画布文字格、当前文案和修订号。指定 pageId 或 fieldId 时一并读取该范围的模板样稿与发布要求,供撰写和复核。',obj({
|
||||
pageId:optional(Type.String()),fieldId:optional(Type.String()),
|
||||
@ -44,9 +48,11 @@ export const productionOperationTools = [
|
||||
['read_slot_images','查看当前图位的同款实拍和模板构图。候选只返回候选画面;需要同时查看或重新查看参考时传 includeReferences=true。',obj({
|
||||
slotId:slotRef,candidateId:optional(Type.String()),adopted:optional(Type.Boolean()),includeReferences:optional(Type.Boolean()),
|
||||
})],
|
||||
['generate_slot_image','开始制作一张候选,立即返回受理回执;可继续工作,用 review_image_slots 或 await_image_slots 取结果。'+imageSourceDescription+' 已有未知生图时核查原编号。',obj({slotId:slotRef,...imageArgs.properties,
|
||||
reworkCandidateId:optional(Type.String({description:'直接返工时,填写被替代的已退回候选号。'})),
|
||||
})],
|
||||
['use_product_image','用本款原片或裁切区域创建候选,返回后可继续处理其他图位。',obj({slotId:slotRef,...productImageArgs})],
|
||||
['prepare_image_request','按完整提示词、图位与参考设置准备并保存生图请求。回执含完整文本、实际参考顺序及模型参数。',obj({slotId:slotRef,...preparationArgs})],
|
||||
['read_image_request','从项目记录回读完整请求与实际参考,取得冻结所需版本和内容 hash。',obj(requestIdArgs)],
|
||||
['freeze_image_request','核对完整请求后,传入刚回读的版本和内容 hash 冻结。',obj(freezeArgs)],
|
||||
['dispatch_image_request','按冻结 ID 提交原请求并立即返回受理,使用 await_image_slots 或 review_image_slots 查看结果。',obj(dispatchArgs)],
|
||||
['delegate_image_slots','把图位和可执行要求交给 Pi 子代理并行制作。每个图位单独返回已接收或无法定位的结果。',obj({
|
||||
jobs:Type.Array(obj({slotId:slotRef,goal:text,reworkCandidateId:optional(Type.String({description:'返工时,指定之前被退回的候选号。'}))})),
|
||||
})],
|
||||
@ -280,23 +286,76 @@ export async function openProductionOperations(host) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
const generate=async(slot,args,signal,workerNumber)=>{
|
||||
const {source,prompt='',referenceIndex,referenceCrop,geometryReferenceIndex,prefer2k,retryOf,
|
||||
useTemplateReference,reworkCandidateId,reworkChange}=args;
|
||||
const isOriginal=source==='product';
|
||||
const templateRule=useTemplateReference===false?'':'模板只参考构图、景别、光线和品牌气质。';
|
||||
const sourceRules='商品外形、比例、接合和花色以同款实拍为准。'+templateRule+'标题、标注和尺寸由画布图层完成。';
|
||||
const attempt={source,prompt,...(reworkCandidateId?{reworkOf:reworkCandidateId}:null),
|
||||
...(reworkChange?{change:reworkChange}:null)};
|
||||
await notice('正在生成候选图片');
|
||||
const operation=await operate(slot,'generate_candidate',isOriginal
|
||||
? {useProductReference:true,referenceIndex,referenceCrop}
|
||||
: {instruction:sourceRules+'\n'+prompt,workerNumber,geometryReferenceIndex,prefer2k,retryOf,useTemplateReference},signal,attempt);
|
||||
await notice('候选图片回执');
|
||||
return {...operation,requestedSource:source,...(reworkCandidateId?{reworkOf:reworkCandidateId}:null),...(isOriginal?{
|
||||
sourceNote:'product 只使用或裁切原片,背景、光线和构图来自原片。场景提示词用于 generate。'
|
||||
}:null)};
|
||||
const pendingGeneration=slot=>{
|
||||
const item=journal.items[slot.id];
|
||||
const original=item?.pendingOperation;
|
||||
if (!original&&!item?.heldOriginalId&&item?.state!=='unknown') return null;
|
||||
const candidateId=originalCandidate(item);
|
||||
return {slotId:slot.id,phase:'unknown',operationId:original?.operationId,candidateId,
|
||||
pendingOriginal:candidateId??original?.operationId};
|
||||
};
|
||||
const readImageRequest=async(requestId,slot)=>{
|
||||
const data=await canvas.imageRequest('read',{requestId});
|
||||
if (data.requestId!==requestId || data.outputId!==outputId || data.variantId!==variantId ||
|
||||
slot && data.slotId!==slot.id) throw Error('生图请求不属于本轮工作画布或委托图位');
|
||||
return data;
|
||||
};
|
||||
const prepareImageRequest=async(slot,{prompt,retryOf,useTemplateReference,prefer2k,geometryReferenceIndex,reworkCandidateId,reworkChange},signal)=>{
|
||||
signal?.throwIfAborted();
|
||||
await current();
|
||||
return canvas.imageRequest('prepare',{slotId:slot.id,instructions:prompt,retryOf,useTemplateReference,
|
||||
prefer2k,geometryReferenceIndex,reworkOf:reworkCandidateId,reworkChange});
|
||||
};
|
||||
const dispatchImageRequest=async(slot,request,signal)=>{
|
||||
signal?.throwIfAborted();
|
||||
const prior=pendingGeneration(slot);
|
||||
if(prior)return prior;
|
||||
const candidateId=request.requestId;
|
||||
const original={candidateId,operationId:candidateId,kind:'frozen-image'};
|
||||
await save(slot,{pendingOperation:original,state:'dispatching'});
|
||||
let receipt;
|
||||
try { receipt=await canvas.imageRequest('dispatch',{frozenRequestId:candidateId}); }
|
||||
catch(error) {
|
||||
if (error.dispatched===false) {
|
||||
await save(slot,{pendingOperation:null,state:'failed',reason:error.message});
|
||||
return {phase:'failed',reason:error.message};
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
const phase=receipt.status??receipt.phase;
|
||||
const settled=['complete','failed'].includes(phase);
|
||||
await update(()=>{
|
||||
const item=journal.items[slot.id]??={};
|
||||
Object.assign(item,{pendingOperation:settled?null:original,candidateId,state:phase==='complete'?'candidate':phase,
|
||||
prompt:request.spec.prompt,source:'generate'});
|
||||
const attempts=item.attempts??=[];
|
||||
if(!attempts.some(row=>row.candidateId===candidateId))attempts.push({candidateId,source:'generate',
|
||||
prompt:request.spec.prompt,reworkOf:request.reworkOf,change:request.reworkChange});
|
||||
});
|
||||
return {candidateId,operationId:candidateId,phase:settled?phase:'unknown',reason:receipt.message,
|
||||
requestedSource:'generate',...(request.reworkOf?{reworkOf:request.reworkOf}:null),
|
||||
...(!settled?{pendingOriginal:candidateId}:null),
|
||||
...(receipt.retryableFailure===true?{retryableFailure:true,retryAfterSeconds:receipt.retryAfterSeconds}:null)};
|
||||
};
|
||||
const launchImage=(slot,operation)=>{
|
||||
if(jobs.has(slot.id))return {slotId:slot.id,phase:'already_running'};
|
||||
const pending=pendingGeneration(slot);
|
||||
if(pending)return pending;
|
||||
const receipt={slotId:slot.id,phase:'accepted'};
|
||||
const row={slotId:slot.id,label:slot.label,step:'生成',active:true};
|
||||
generation.set(slot.id,receipt);
|
||||
const run=Promise.resolve().then(operation)
|
||||
.catch(error=>({...pendingGeneration(slot)??{phase:'failed'},reason:error.message}))
|
||||
.then(result=>{generation.set(slot.id,{slotId:slot.id,...result});})
|
||||
.finally(()=>{jobs.delete(slot.id);return notice('候选图片回执');});
|
||||
jobs.set(slot.id,{row,run});
|
||||
return receipt;
|
||||
};
|
||||
const useProductImage=async(slot,options,signal)=>({
|
||||
...await operate(slot,'generate_candidate',{useProductReference:true,...options},signal,{source:'product'}),
|
||||
requestedSource:'product',sourceNote:'仅使用或裁切原片,保留原片的背景和光线。',
|
||||
});
|
||||
|
||||
const reconcile=async(slot,signal,adopting=false)=>{
|
||||
const item=journal.items[slot.id];
|
||||
const pendingKey=adopting?'pendingAdoption':'pendingOperation';
|
||||
@ -468,34 +527,25 @@ export async function openProductionOperations(host) {
|
||||
...(seenLayouts.has(slot.id)&&!includeLayout?{layoutReferenceEarlier:true}:null),
|
||||
images:[...product,...layout,...images.slice(referenceCount+layoutCount)]});
|
||||
},
|
||||
generate_slot_image({slotId,...args},signal){
|
||||
use_product_image({slotId,...options},signal){
|
||||
signal?.throwIfAborted();
|
||||
const slot=matches(slotId);
|
||||
if(jobs.has(slot.id))return {slotId:slot.id,phase:'already_running'};
|
||||
const item=journal.items[slot.id];
|
||||
const original=item?.pendingOperation;
|
||||
if(original||item?.heldOriginalId||item?.state==='unknown'){
|
||||
const candidateId=originalCandidate(item);
|
||||
return {slotId:slot.id,phase:'unknown',operationId:original?.operationId,candidateId,
|
||||
pendingOriginal:candidateId??original?.operationId};
|
||||
}
|
||||
|
||||
const receipt={slotId:slot.id,phase:'accepted'};
|
||||
const row={slotId:slot.id,label:slot.label,step:'生成',active:true};
|
||||
generation.set(slot.id,receipt);
|
||||
const run=Promise.resolve().then(()=>generate(slot,args,signal)).catch(error=>{
|
||||
const pending=journal.items[slot.id]?.pendingOperation;
|
||||
return pending?{phase:'unknown',operationId:pending.operationId,candidateId:pending.candidateId,
|
||||
pendingOriginal:pending.candidateId??pending.operationId,reason:error.message}:
|
||||
{phase:'failed',reason:error.message};
|
||||
}).then(result=>{
|
||||
generation.set(slot.id,{slotId:slot.id,...result});
|
||||
}).finally(()=>{
|
||||
jobs.delete(slot.id);
|
||||
return notice('候选图片回执');
|
||||
});
|
||||
jobs.set(slot.id,{row,run});
|
||||
return receipt;
|
||||
return launchImage(slot,()=>useProductImage(slot,options,signal));
|
||||
},
|
||||
prepare_image_request({slotId,...args},signal){
|
||||
return prepareImageRequest(matches(slotId),args,signal);
|
||||
},
|
||||
read_image_request({requestId}){
|
||||
return readImageRequest(requestId);
|
||||
},
|
||||
freeze_image_request(args){
|
||||
return canvas.imageRequest('freeze',args);
|
||||
},
|
||||
async dispatch_image_request({frozenRequestId},signal){
|
||||
const request=await readImageRequest(frozenRequestId);
|
||||
if(!request.frozen)throw Error('请先回读并冻结生图请求');
|
||||
const slot=matches(request.slotId);
|
||||
return launchImage(slot,()=>dispatchImageRequest(slot,request,signal));
|
||||
},
|
||||
async delegate_image_slots({jobs:requested},signal){
|
||||
const assigned=[],unmatched=[];
|
||||
@ -505,15 +555,33 @@ export async function openProductionOperations(host) {
|
||||
if(jobs.has(slot.id)){assigned.push({id:slot.id,state:'already_running'});continue;}
|
||||
const row={number:Math.max(0,...[...jobs.values()].map(job=>job.row.number??0))+1,slotId:slot.id,label:slot.label,step:'正在准备',active:true};
|
||||
let rework;
|
||||
const generateTool={name:'generate_slot_image',label:'制作候选',description:'制作一张候选。'+imageSourceDescription,
|
||||
parameters:imageArgs,execute:async(_id,args,workerSignal)=>{
|
||||
row.step='正在生图';
|
||||
const workerTool=(name,description,properties,execute,terminate=false)=>({
|
||||
name,label:description,description,parameters:obj(properties),
|
||||
execute:async(_id,args,workerSignal)=>{
|
||||
const signals=[workerSignal,signal].filter(Boolean);
|
||||
const details=await generate(slot,{...args,reworkCandidateId:rework?.candidateId},
|
||||
signals.length?AbortSignal.any(signals):undefined,row.number);
|
||||
generation.set(slot.id,{slotId:slot.id,...details});
|
||||
return {...imageResult(details),terminate:true};
|
||||
}};
|
||||
const activeSignal=signals.length?AbortSignal.any(signals):undefined;
|
||||
const result=await execute(args,activeSignal);
|
||||
if(terminate)generation.set(slot.id,{slotId:slot.id,...result});
|
||||
return {...imageResult(result),...(terminate?{terminate:true}:null)};
|
||||
},
|
||||
});
|
||||
const makeTools=()=>[
|
||||
workerTool('use_product_image','用本款实拍创建图位候选',productImageArgs,
|
||||
(args,activeSignal)=>useProductImage(slot,args,activeSignal),true),
|
||||
workerTool('prepare_image_request','准备并持久保存完整生图请求',preparationArgs,
|
||||
(args,activeSignal)=>prepareImageRequest(slot,{...args,reworkCandidateId:rework?.candidateId},activeSignal)),
|
||||
workerTool('read_image_request','回读请求文本、参考顺序和模型参数',requestIdArgs,
|
||||
({requestId})=>readImageRequest(requestId,slot)),
|
||||
workerTool('freeze_image_request','按回读的版本和内容 hash 冻结请求',freezeArgs,
|
||||
async args=>{await readImageRequest(args.requestId,slot);return canvas.imageRequest('freeze',args);}),
|
||||
workerTool('dispatch_image_request','仅按冻结 ID 提交请求',dispatchArgs,
|
||||
async ({frozenRequestId},activeSignal)=>{
|
||||
const request=await readImageRequest(frozenRequestId,slot);
|
||||
if(!request.frozen)throw Error('请先回读并冻结生图请求');
|
||||
row.step='正在生图';
|
||||
return dispatchImageRequest(slot,request,activeSignal);
|
||||
},true),
|
||||
];
|
||||
const readTool={name:'read_slot_images',label:'查看本图位实拍与构图',description:'读取本图位的原片与模板构图。',
|
||||
parameters:obj({}),execute:async()=>imageResult(await readImages(slot.id))};
|
||||
const run=Promise.resolve().then(async()=>{
|
||||
@ -540,13 +608,13 @@ export async function openProductionOperations(host) {
|
||||
};
|
||||
}
|
||||
}
|
||||
const instructions='完成主代理交付的单个图位。按需用工具看实拍和模板,再提交候选。'+
|
||||
const instructions='完成主代理委托的图位。按 Skill 选择直接用实拍,或准备生图请求、回读核对、冻结,再按冻结 ID 派发。'+
|
||||
(rework?'\n先看随消息附上的退回图,结合验图原话、建议和上一次实发提示词。提交新要求时用 reworkChange 写清这次具体改什么。缺少的证据如实说明。'+
|
||||
'同一原因第二次退回就换办法:模板提示或构图参考带偏时用 useTemplateReference=false;也可改用实拍裁切或合成、建议主代理用画布处理,或在符合验图标准时建议主代理直接采用。':'')+
|
||||
knowledgeReadInstruction;
|
||||
await host.runDetailAgent(slot.id,instructions,
|
||||
JSON.stringify({rework,goal,field:slot.fieldId,label:slot.label,rule:slot.productionRule,requirements:slot.requirements,
|
||||
knowledgeFiles:knowledge.files}),[readTool,generateTool,...knowledge.tools],
|
||||
knowledgeFiles:knowledge.files}),[readTool,...makeTools(),...knowledge.tools],
|
||||
rejectedImage?[rejectedImage]:[],productRequestScope('slot',slot.id));
|
||||
if(!generation.has(slot.id))generation.set(slot.id,{slotId:slot.id,phase:'no_candidate'});
|
||||
}).catch(async error=>{
|
||||
|
||||
@ -37,6 +37,7 @@ export class StdioCanvas {
|
||||
return binding;
|
||||
}
|
||||
readCanvas(input = {}) { return this.action('pi-canvas-read', input); }
|
||||
imageRequest(action,request) { return this.action('pi-image-request',{action,request}); }
|
||||
detailRender(options) { return this.#observe('pi-product-screen', options); }
|
||||
detailCopyFields(options) { return this.#observe('pi-detail-copy-fields', options); }
|
||||
detailApplyCopy(items,revision) { return this.action('pi-detail-copy-apply',{items,revision}); }
|
||||
|
||||
@ -51,7 +51,7 @@ test('Pi production and its worker read the same locked Skill and its relative r
|
||||
assert.match(system,/<name>lighting<\/name>/);
|
||||
assert.doesNotMatch(system,/PINNED_FINISH|Use the \[fixture notes\]/);
|
||||
const location=system.match(/<name>lighting<\/name>[\s\S]*?<location>([^<]*SKILL\.md)<\/location>/u)[1];
|
||||
const child=system.includes('主代理交付的单个图位');
|
||||
const child=system.includes('完成主代理委托的图位');
|
||||
const steps=child?[
|
||||
['read',{path:location}],
|
||||
['read',{path:path.join(path.dirname(location),'references','finish.md')}],
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
import { BridgeError } from '../src/bridge-error.mjs';
|
||||
import test from 'node:test';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
@ -8,8 +9,44 @@ import { openProductionOperations } from '../src/production-operations.mjs';
|
||||
import { cleanup } from './cleanup.mjs';
|
||||
import { bindRecovery } from '../src/desktop-host.mjs';
|
||||
|
||||
async function generateAndWait(actions, request) {
|
||||
const receipt=await actions.generate_slot_image(request);
|
||||
function imageBridge(host,dispatch,id=()=>randomUUID()) {
|
||||
const prepared=new Map();
|
||||
host.canvas.imageRequest=async(action,args)=>{
|
||||
if(action==='prepare'){
|
||||
const requestId=id();
|
||||
const receipt={requestId,revision:1,requestSpecHash:'fixture-digest',frozen:false,
|
||||
outputId:host.productionGoal.outputId,variantId:host.productionGoal.variantId,slotId:args.slotId,
|
||||
reworkOf:args.reworkOf,reworkChange:args.reworkChange,spec:{prompt:args.instructions}};
|
||||
prepared.set(requestId,{receipt,args});
|
||||
return structuredClone(receipt);
|
||||
}
|
||||
const request=prepared.get(args.requestId??args.frozenRequestId);
|
||||
assert.ok(request);
|
||||
if(action==='read')return structuredClone(request.receipt);
|
||||
if(action==='freeze'){
|
||||
assert.equal(args.expectedHash,request.receipt.requestSpecHash);
|
||||
assert.equal(args.expectedRevision,request.receipt.revision);
|
||||
request.receipt.frozen=true;
|
||||
return structuredClone(request.receipt);
|
||||
}
|
||||
assert.equal(action,'dispatch');
|
||||
assert.deepEqual(Object.keys(args),['frozenRequestId']);
|
||||
assert.equal(request.receipt.frozen,true);
|
||||
return dispatch(request.args,args.frozenRequestId);
|
||||
};
|
||||
}
|
||||
async function freezeForDispatch(actions,options) {
|
||||
const draft=await actions.prepare_image_request(options);
|
||||
const saved=await actions.read_image_request({requestId:draft.requestId});
|
||||
await actions.freeze_image_request({requestId:saved.requestId,expectedRevision:saved.revision,expectedHash:saved.requestSpecHash});
|
||||
return {frozenRequestId:saved.requestId};
|
||||
}
|
||||
async function generateAndWait(actions, {source,...request}) {
|
||||
let receipt;
|
||||
try {
|
||||
receipt=source==='product' ? await actions.use_product_image({slotId:request.slotId}) :
|
||||
await actions.dispatch_image_request(await freezeForDispatch(actions,request));
|
||||
} catch(error) { return {phase:'failed',reason:error.message}; }
|
||||
if(receipt.phase!=='accepted')return receipt;
|
||||
const {generation}=await actions.await_image_slots({slotIds:[request.slotId]});
|
||||
return generation[0];
|
||||
@ -103,10 +140,14 @@ test('a rework delegate sees the rejected image, exact previous prompt and revie
|
||||
assert.equal(context.rework.reason,'候选左下有多余支撑');
|
||||
assert.equal(context.rework.suggestions[0].suggestion,'保留原片的直杆');
|
||||
delegated=true;
|
||||
await tools.find(tool=>tool.name==='generate_slot_image').execute('fixture-call',
|
||||
{source:'generate',prompt:'以同款原片直杆为准,改为单张自然光近景',
|
||||
reworkChange:'去掉模板构图并以原片确认支撑形状',useTemplateReference:false});
|
||||
const call=(name,args)=>tools.find(tool=>tool.name===name).execute('fixture-call',args).then(row=>row.details);
|
||||
const draft=await call('prepare_image_request',{prompt:'以同款原片直杆为准,改为单张自然光近景',
|
||||
reworkChange:'去掉模板构图并以原片确认支撑形状',useTemplateReference:false});
|
||||
const saved=await call('read_image_request',{requestId:draft.requestId});
|
||||
await call('freeze_image_request',{requestId:saved.requestId,expectedRevision:saved.revision,expectedHash:saved.requestSpecHash});
|
||||
await call('dispatch_image_request',{frozenRequestId:saved.requestId});
|
||||
}};
|
||||
imageBridge(host,async args=>{requests.push(args);return {status:'complete'};},()=> 'replacement');
|
||||
const ops=await openProductionOperations(host);
|
||||
await ops.delegate_image_slots({jobs:[{slotId:'front',goal:'改掉多余支撑',reworkCandidateId:'old'}]});
|
||||
const {generation:[result]}=await ops.await_image_slots({slotIds:['front']});
|
||||
@ -117,8 +158,8 @@ test('a rework delegate sees the rejected image, exact previous prompt and revie
|
||||
options:{inspectCandidate:true,includeProductReferences:false,includeTemplateReference:false}}]);
|
||||
assert.equal(requests.length,1);
|
||||
assert.equal(requests[0].useTemplateReference,false);
|
||||
assert.match(requests[0].instruction,/改为单张自然光近景/u);
|
||||
assert.doesNotMatch(requests[0].instruction,/模板/u);
|
||||
assert.match(requests[0].instructions,/改为单张自然光近景/u);
|
||||
assert.doesNotMatch(requests[0].instructions,/模板/u);
|
||||
const reopened=await openProductionOperations({...host,store:{...host.store,
|
||||
get:filename=>fs.readFile(path.join(dir,filename),'utf8').then(JSON.parse)}});
|
||||
const {pictures:[exact]}=await reopened.review_image_slots({slotIds:['front']});
|
||||
@ -271,15 +312,23 @@ test('a sibling variant edit leaves the current plan usable, and a local edit ca
|
||||
},appendEvent:async()=>{}};
|
||||
const nextOutput={outputId:'sku_images',variantId:'white'};
|
||||
const host={canvas,store,productionGoal:{outputId,variantId,pendingOutputs:[nextOutput]}};
|
||||
imageBridge(host,async(_args,id)=>{submissions.push(id);prepared.resolve();await submit.promise;return {status:'complete'};});
|
||||
const actions=await openProductionOperations(host);
|
||||
assert.deepEqual((await actions.plan_production()).pendingOutputs,[nextOutput]);
|
||||
await actions.write_copy_fields({revision:3,recordOnly:true,items:[{layer:5,text:'木纹展示',sources:[],pictures:[]}]});
|
||||
const request={slotId,source:'generate',prompt:'给商品正面留出文字区域'};
|
||||
variants[1].colorName='暖白色';
|
||||
creation++;
|
||||
assert.equal((await actions.generate_slot_image(request)).phase,'accepted');
|
||||
const draft=await actions.prepare_image_request(request);
|
||||
assert.equal(draft.spec.prompt,request.prompt);
|
||||
await assert.rejects(actions.dispatch_image_request({frozenRequestId:draft.requestId}),/先回读并冻结/u);
|
||||
const saved=await actions.read_image_request({requestId:draft.requestId});
|
||||
await actions.freeze_image_request({requestId:saved.requestId,expectedRevision:saved.revision,expectedHash:saved.requestSpecHash});
|
||||
assert.equal(submissions.length,0);
|
||||
const frozen={frozenRequestId:saved.requestId};
|
||||
assert.equal((await actions.dispatch_image_request(frozen)).phase,'accepted');
|
||||
await prepared.promise;
|
||||
assert.equal((await actions.generate_slot_image(request)).phase,'already_running');
|
||||
assert.equal((await actions.dispatch_image_request(frozen)).phase,'already_running');
|
||||
assert.equal((await actions.review_image_slots({slotIds:[slotId]})).pictures[0].generation.phase,'accepted');
|
||||
assert.deepEqual((await actions.write_copy_fields({revision:3,recordOnly:true,
|
||||
items:[{layer:5,text:'木纹展示',sources:[],pictures:[]}]})).appliedLayers,[5]);
|
||||
@ -337,11 +386,18 @@ test('a lost native acknowledgement can be recovered with the saved generation o
|
||||
catch(error){if(error.code==='ENOENT')return null; throw error;}
|
||||
},appendEvent:async()=>{}};
|
||||
const host={canvas,store,productionGoal:{outputId:'detail',variantId:'ink'}};
|
||||
imageBridge(host,async(_args,operationId)=>{
|
||||
submissions.push(operationId);
|
||||
const pending=JSON.parse(await fs.readFile(file,'utf8')).items[slotId].pendingOperation;
|
||||
assert.equal(pending.operationId,operationId);
|
||||
assert.equal(pending.candidateId,operationId);
|
||||
throw new BridgeError('画布连接中断,原操作不会重发','transport_interrupted',{dispatched:true});
|
||||
});
|
||||
let actions=await openProductionOperations(host);
|
||||
const request={slotId,source:'generate',prompt:'保留商品比例'};
|
||||
const lost=await generateAndWait(actions,request);
|
||||
assert.equal(lost.phase,'unknown');
|
||||
assert.match(lost.reason,/原操作不存在/u);
|
||||
assert.match(lost.reason,/画布连接中断/u);
|
||||
canvas.run='restarted-run';
|
||||
canvas.documentId=42;
|
||||
actions=await openProductionOperations(host);
|
||||
@ -432,6 +488,7 @@ test('Pi chooses each image operation and keeps an unresolved paid request on it
|
||||
await review.execute('review-fixture',{candidateId,verdict:'pass',
|
||||
checks:{structure:true,color:true,composition:false,evidence:true},reason:'配色及结构与实拍一致,背景细节看不清'});
|
||||
}};
|
||||
imageBridge(host,async args=>{submissions.push({intent:'generate_candidate',...args});return {status:'unknown'};},()=> 'existing-candidate');
|
||||
const recovery=new Map();
|
||||
t.after(bindRecovery(host,recovery,identity));
|
||||
const originalNative={kind:'native',job:17,documentId:23,identity};
|
||||
@ -508,7 +565,7 @@ test('Pi chooses each image operation and keeps an unresolved paid request on it
|
||||
assert.equal(host.canvasOperations.original,originalNative);
|
||||
assert.deepEqual([...recovery.values()][0].pending,[originalNative,nextNative]);
|
||||
assert.equal(first.requestedSource,'generate');
|
||||
assert.match(submissions[0].instruction,/场景桌面上的一盏灯$/u);
|
||||
assert.match(submissions[0].instructions,/场景桌面上的一盏灯$/u);
|
||||
assert.equal(submissions[0].prefer2k,true);
|
||||
const overview=(await actions.review_image_slots({slotIds:[]})).pictures.find(row=>row.id==='lamp-photo');
|
||||
const exact=(await actions.review_image_slots({slotIds:['lamp']})).pictures[0].record;
|
||||
@ -561,7 +618,7 @@ test('Pi chooses each image operation and keeps an unresolved paid request on it
|
||||
const local=await generateAndWait(actions,{slotId:'switch',source:'product',prompt:'把开关放进夜景'});
|
||||
assert.equal(local.phase,'complete');
|
||||
assert.equal(local.requestedSource,'product');
|
||||
assert.match(local.sourceNote,/只使用或裁切原片/u);
|
||||
assert.match(local.sourceNote,/使用或裁切原片/u);
|
||||
assert.equal(submissions.at(-1).useProductReference,true);
|
||||
assert.equal(submissions.at(-1).instruction,undefined);
|
||||
const gate=Promise.withResolvers();
|
||||
|
||||
@ -3212,6 +3212,97 @@ impl Backend {
|
||||
json!({"doc":doc,"accountId":self.auth["account"]["id"],"origin":self.origin,"workflow":workflow,"creation":enrich_creation(dir,creation::load(dir)?)?,"pending":workflow["pending"],"canvasFirst":true}),
|
||||
)
|
||||
}
|
||||
pub(super) fn production_image_request(&mut self, doc: u64, binding: &Value, events: &mpsc::Sender<Event>, ctx: &egui::Context) -> R<Value> {
|
||||
self.ensure_owner(doc)?;
|
||||
let dir = self.project_dir(doc)?;
|
||||
original_project_present(&dir)?;
|
||||
let phase = binding["action"].as_str().ok_or("生图请求动作缺失")?;
|
||||
let request = &binding["request"];
|
||||
if phase == "prepare" {
|
||||
let mut input = request.clone();
|
||||
input["doc"] = json!(doc);
|
||||
input["baseRevision"] = binding["revision"].clone();
|
||||
input["variantId"] = binding["scope"]["variantId"].clone();
|
||||
input["detailBatch"] = json!(true);
|
||||
input["detailWorkspace"] = binding["scope"].clone();
|
||||
input["prepareRequest"] = json!(true);
|
||||
return self.canvas_workspace_action("slot-append", &input, events, ctx);
|
||||
}
|
||||
let id = uuid(if phase == "dispatch" { &request["frozenRequestId"] } else { &request["requestId"] }, "生图请求")?;
|
||||
let task = super::images::read_image_request(&dir, &id)?;
|
||||
let belongs = |task: &Value| {
|
||||
task["doc"] == doc && task["accountScope"] == self.scope()
|
||||
&& task["localProjectId"].as_str() == self.locations.get(&doc).map(String::as_str)
|
||||
&& task["origin"] == self.origin && task["outputScope"] == binding["scope"]["outputId"]
|
||||
&& ["workspaceId","templateHash","structureHash","variantId"].iter().all(|field|
|
||||
task["slotBinding"][*field] == binding["scope"][if *field=="workspaceId" {"id"}else{*field}])
|
||||
};
|
||||
if !belongs(&task) { return Err("生图请求不属于当前账户、项目或工作画布".into()); }
|
||||
match phase {
|
||||
"read" => Ok(super::images::image_request_receipt(&task)),
|
||||
"freeze" => super::images::freeze_image_request(&dir, &id, request),
|
||||
"dispatch" => {
|
||||
if !task["frozenAt"].is_number() { return Err("请先回读并冻结生图请求".into()); }
|
||||
let Some(_dispatch) = lock_candidate_dispatch(&dir, &id)? else {
|
||||
return Ok(json!({"phase":"running","candidateId":id}));
|
||||
};
|
||||
let task = super::images::read_image_request(&dir, &id)?;
|
||||
if task["phase"] != "prepared" {
|
||||
// Original outcome, including unknown, cannot enter the POST path again.
|
||||
let record = reconcile_candidate(&dir, &task)?;
|
||||
return Ok(candidate_receipt(&record));
|
||||
}
|
||||
super::images::validate_frozen_spec(&dir, &task)?;
|
||||
let slot = &task["slotBinding"];
|
||||
let state = load_detail_workspace(&dir)?;
|
||||
let record = &task["candidateRecord"];
|
||||
if !candidate_uses_current_inputs(&dir, &state, record, slot["variantId"].as_str().ok_or("花色缺失")?)? {
|
||||
return Err("商品资料或制作依据已变化,请重新准备请求".into());
|
||||
}
|
||||
if candidate_path(&dir, &id)?.exists() {
|
||||
let existing = read_candidate(&dir, &id)?;
|
||||
if existing["phase"] != "prepared" || existing["retirement"].is_object() {
|
||||
return Ok(candidate_receipt(&existing));
|
||||
}
|
||||
} else {
|
||||
reserve(&dir, state, record)?;
|
||||
}
|
||||
publish_prepared(events, self.canvas_workspace_result(doc, &dir)?)?;
|
||||
ctx.request_repaint();
|
||||
validate_image_context(&dir, Some(slot))?;
|
||||
let call = self.image_job(None, &json!({"doc":doc,"frozenRequestId":id}), false, events, ctx);
|
||||
let (receipt, failure) = self.settle_image_candidate(&dir, doc, &id, slot, call, events, ctx)?;
|
||||
let mut receipt = receipt;
|
||||
if receipt["status"] == "failed" && let Some(message) = failure {
|
||||
receipt["message"] = json!(message);
|
||||
}
|
||||
let snapshot = operation_receipt(self.canvas_workspace_result(doc, &dir)?, Some(receipt.clone()), None);
|
||||
let _ = events.send(Event::Json("slot-append".into(), Ok(snapshot)));
|
||||
ctx.request_repaint();
|
||||
Ok(receipt)
|
||||
}
|
||||
_ => Err("生图请求动作无效".into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn settle_image_candidate(&mut self, dir: &Path, doc: u64, id: &str, binding: &Value, mut call: R<Value>,
|
||||
events: &mpsc::Sender<Event>, ctx: &egui::Context) -> R<(Value, Option<String>)> {
|
||||
let file = dir.join("image-jobs").join(id).join("task.json");
|
||||
let mut journal = if file.try_exists().map_err(|_| "原生图记录无法核对,保留原候选")? {
|
||||
read_json(&file)?
|
||||
} else {
|
||||
json!({"id":id,"slotBinding":binding,"phase":"prepared","notDispatched":true,"message":call.as_ref().err()})
|
||||
};
|
||||
if matches!(journal["phase"].as_str(), Some("dispatched" | "running" | "unknown")) {
|
||||
call = self.recover_original_image(doc, id, events, ctx);
|
||||
journal = read_json(&file)?;
|
||||
} else if journal["phase"] == "prepared" && let Err(error) = &call {
|
||||
journal["notDispatched"] = json!(true);
|
||||
journal["message"] = json!(error);
|
||||
}
|
||||
Ok((candidate_receipt(&reconcile_candidate(dir, &journal)?),call.err()))
|
||||
}
|
||||
|
||||
pub(super) fn canvas_workspace_action(&mut self, method: &str, input: &Value, events: &mpsc::Sender<Event>, ctx: &egui::Context) -> R<Value> {
|
||||
let doc = input["doc"].as_u64().ok_or("请先打开项目")?;
|
||||
self.ensure_owner(doc)?;
|
||||
@ -3603,7 +3694,8 @@ impl Backend {
|
||||
let (references, layers) = creation::reference_canvas_with_attachments(&creation, &dir, doc, &attachments)?;
|
||||
let settings = self.settings()?;
|
||||
let model = settings["imageModel"].as_str().filter(|model| !model.is_empty()).ok_or("请先选择生图模型")?;
|
||||
let candidate = if input["workflowOperationId"].is_null() {
|
||||
let preparing = input["prepareRequest"] == true;
|
||||
let candidate = if input["workflowOperationId"].is_null() || preparing {
|
||||
Uuid::new_v4().to_string()
|
||||
} else {
|
||||
uuid(&input["workflowOperationId"], "原生图操作")?
|
||||
@ -3639,12 +3731,9 @@ impl Backend {
|
||||
if prefer_2k {
|
||||
prompt.push_str("\n局部证据请用稍宽的原始取景拍摄。保留目标部位与相邻的真实接合关系,将目标留在画面中心附近,并预留四周以便按最终图框裁切。");
|
||||
}
|
||||
if let Some(position) = layout_position {
|
||||
prompt.push_str(&format!(
|
||||
"{}第{position}张是本图位的取景底稿。保留参考的镜头角度、景别、主体占幅、布景与背景关系、光源方向、明暗和色调,以及人物位置、动作和排字留白。图位明确要求调整的构图和动作按本图位要求执行。将底稿中的旧商品换成本项目原片中的同款商品,其余保持原位,仅调整与新商品摆放、透视、接触和阴影有关的区域。旧商品轮廓、比例、部件、连接、空隙和表面一律以同款原片替换。清除模板文字、遮罩、虚线、尺寸和坐标。",
|
||||
super::images::TEMPLATE_LAYOUT_PROMPT_PREFIX
|
||||
let layout_note = layout_position.map(|position| format!(
|
||||
"\n【模板图位参考】第{position}张是本图位的取景底稿。保留参考的镜头角度、景别、主体占幅、布景与背景关系、光源方向、明暗和色调,以及人物位置、动作和排字留白。图位明确要求调整的构图和动作按本图位要求执行。将底稿中的旧商品换成本项目原片中的同款商品,其余保持原位,仅调整与新商品摆放、透视、接触和阴影有关的区域。旧商品轮廓、比例、部件、连接、空隙和表面一律以同款原片替换。清除模板文字、遮罩、虚线、尺寸和坐标。"
|
||||
));
|
||||
}
|
||||
let mut binding = new_binding(&state, &output, &field, &id, &variant_id, &candidate, &prompt);
|
||||
if input["detailBatch"] == true { binding["detailBatch"] = json!(true); }
|
||||
if !attachment_refs.as_array().is_none_or(Vec::is_empty) { binding["composerHash"] = json!(hash(&attachment_refs.to_string())); }
|
||||
@ -3652,6 +3741,27 @@ impl Backend {
|
||||
if let Some(previous) = retry_of { record["retryOf"] = json!(previous); }
|
||||
if !attachment_refs.as_array().is_none_or(Vec::is_empty) { record["composerAttachments"] = attachment_refs; }
|
||||
if !knowledge.is_null() { record["knowledge"] = knowledge.clone(); }
|
||||
if let Some(previous) = input["reworkOf"].as_str() {
|
||||
let old = read_candidate(&dir, previous)?;
|
||||
if old["binding"]["slotId"] != id || old["binding"]["variantId"] != variant_id {
|
||||
return Err("返工候选不属于当前图位".into());
|
||||
}
|
||||
record["reworkOf"] = json!(previous);
|
||||
record["reworkChange"] = input["reworkChange"].clone();
|
||||
}
|
||||
let request_frame = image_ratio.map_or_else(|| field["frame"].clone(), |(width,height)| json!({"width":width,"height":height}));
|
||||
let mut image_input = json!({"doc":doc,"revision":input["baseRevision"],"model":model,
|
||||
"mode":if parent.is_some(){"refine"}else{"generate"},"text":prompt,"references":layers,
|
||||
"templateLayoutNote":layout_note,"optionalLayoutReference":layout_position.is_some()&&!fixed_layout,
|
||||
"slotBinding":binding,"slotFrame":request_frame,"prefer2k":prefer_2k});
|
||||
if preparing {
|
||||
let mut origins = creation["brief"]["images"].as_array().cloned().unwrap_or_default();
|
||||
origins.extend(attachments.iter().map(|(asset,_)| json!({"source":asset["id"],"purpose":asset["purpose"]})));
|
||||
image_input["referenceOrigins"] = json!(origins);
|
||||
image_input["candidateRecord"] = record;
|
||||
image_input["outputScope"] = output["component"].clone();
|
||||
return self.image_job_with_scene(Some(Arc::new(references)), &image_input, false, events, ctx, scene);
|
||||
}
|
||||
let _dispatch = lock_candidate_dispatch(&dir, &candidate)?.ok_or("原生图操作正在处理,请核查原结果")?;
|
||||
reserve(&dir, state, &record)?;
|
||||
let mut snapshot = self.canvas_workspace_result(doc, &dir)?;
|
||||
@ -3661,23 +3771,10 @@ impl Backend {
|
||||
}
|
||||
publish_prepared(events, snapshot)?;
|
||||
ctx.request_repaint();
|
||||
let request_frame = image_ratio.map_or_else(|| field["frame"].clone(), |(width,height)| json!({"width":width,"height":height}));
|
||||
let call = self.image_job_with_scene(Some(Arc::new(references)), &json!({"doc":doc,"revision":input["baseRevision"],"model":model,"mode":if parent.is_some(){"refine"}else{"generate"},"text":prompt,"references":layers,"optionalLayoutReference":layout_position.is_some()&&!fixed_layout,"slotBinding":binding,"slotFrame":request_frame,"prefer2k":prefer_2k}), false, events, ctx, scene);
|
||||
let file = dir.join("image-jobs").join(&candidate).join("task.json");
|
||||
let mut journal =
|
||||
if file.try_exists().map_err(|_| "原生图记录无法核对,保留原候选")? {
|
||||
read_json(&file)?
|
||||
} else {
|
||||
json!({"id":candidate,"slotBinding":binding,"phase":"prepared","notDispatched":true,"message":call.as_ref().err()})
|
||||
};
|
||||
let mut call = call;
|
||||
// Keep the same worker and original candidate until read-only recovery settles.
|
||||
if matches!(journal["phase"].as_str(), Some("dispatched" | "running" | "unknown")) {
|
||||
call = self.recover_original_image(doc, &candidate, events, ctx);
|
||||
journal = read_json(&file)?;
|
||||
}
|
||||
candidate_result = Some(candidate_receipt(&reconcile_candidate(&dir, &journal)?));
|
||||
operation_error = call.err();
|
||||
let call = self.image_job_with_scene(Some(Arc::new(references)), &image_input, false, events, ctx, scene);
|
||||
let (receipt, failure) = self.settle_image_candidate(&dir, doc, &candidate, &binding, call, events, ctx)?;
|
||||
candidate_result = Some(receipt);
|
||||
operation_error = failure;
|
||||
} else if method == "slot-reuse" {
|
||||
let record = reuse_archived_candidate(&dir, state, input, None)?;
|
||||
if let Ok((mut reference, preview)) = self.agent_image_preview(&json!({"doc":doc,"taskId":record["id"]})) {
|
||||
|
||||
@ -57,13 +57,90 @@ pub(super) fn agent_color_preview(decoded: photocraft_codecs::Image) -> egui::Co
|
||||
egui::ColorImage::from_rgba_unmultiplied([w, h], &rgba)
|
||||
}
|
||||
|
||||
pub(super) const TEMPLATE_LAYOUT_PROMPT_PREFIX: &str = "\n【模板图位参考】";
|
||||
fn image_request_file(dir: &Path, id: &str) -> R<PathBuf> {
|
||||
Uuid::parse_str(id).map_err(|_| "图片请求编号无效")?;
|
||||
Ok(dir.join("image-jobs").join(id).join("task.json"))
|
||||
}
|
||||
|
||||
fn slot_transport_prompt(text: &str, omit_optional_layout: bool) -> &str {
|
||||
if omit_optional_layout {
|
||||
return text.rsplit_once(TEMPLATE_LAYOUT_PROMPT_PREFIX).map_or(text, |(instructions, _)| instructions);
|
||||
pub(super) fn read_image_request(dir: &Path, id: &str) -> R<Value> {
|
||||
let request = read_json(&image_request_file(dir, id)?)?;
|
||||
if request["id"] != id || !request["requestSpecHash"].is_string() {
|
||||
return Err("未找到此版本的生图请求".into());
|
||||
}
|
||||
text
|
||||
Ok(request)
|
||||
}
|
||||
|
||||
fn image_spec(task: &Value) -> Value {
|
||||
let references: Vec<_> = task["references"].as_array().into_iter().flatten().map(|reference|
|
||||
json!({"position":reference["position"],"source":reference["source"],"sourceSha256":reference["sourceSha256"],
|
||||
"role":reference["role"],"sha256":reference["sha256"],"size":reference["size"],"encoding":"image/png"})).collect();
|
||||
json!({"prompt":task["prompt"],"promptHash":hash(task["prompt"].as_str().unwrap_or("")),"modelId":task["modelId"],
|
||||
"route":task["protocol"]["route"],"protocolPath":task["protocol"]["path"],"parameters":task["protocol"]["parameters"],
|
||||
"encoding":if task["protocol"]["multipart"] == true {"multipart"}else{"json"},
|
||||
"referenceField":task["protocol"]["field"],"references":references,"inputVersion":task["candidateRecord"]["inputHash"],
|
||||
"templateHash":task["slotBinding"]["templateHash"],
|
||||
"sceneComposite":task["sceneComposite"],"localProductSha256":task["localProductSha256"]})
|
||||
}
|
||||
|
||||
pub(super) fn image_request_receipt(task: &Value) -> Value {
|
||||
json!({"requestId":task["id"],"revision":task["requestSpecRevision"],"requestSpecHash":task["requestSpecHash"],
|
||||
"frozen":task["frozenAt"].is_number(),"phase":task["phase"],"slotId":task["slotBinding"]["slotId"],
|
||||
"outputId":task["outputScope"],"variantId":task["slotBinding"]["variantId"],
|
||||
"templateHash":task["slotBinding"]["templateHash"],"retryOf":task["candidateRecord"]["retryOf"],
|
||||
"reworkOf":task["candidateRecord"]["reworkOf"],"reworkChange":task["candidateRecord"]["reworkChange"],"spec":image_spec(task)})
|
||||
}
|
||||
|
||||
fn verified_reference_bytes(task: &Value) -> R<Vec<Vec<u8>>> {
|
||||
task["references"].as_array().ok_or("参考图记录无效")?.iter().map(|reference| {
|
||||
let file = Path::new(reference["path"].as_str().ok_or("参考图记录无效")?);
|
||||
let bytes = fs::read(file).map_err(|_| "本机参考图不可读取")?;
|
||||
if bytes.len() > 10 * 1024 * 1024 || reference["sha256"] != format!("{:x}", Sha256::digest(&bytes)) {
|
||||
return Err("参考图已变化,未提交".into());
|
||||
}
|
||||
Ok(bytes)
|
||||
}).collect()
|
||||
}
|
||||
|
||||
fn image_payload(task: &Value, files: &[Vec<u8>]) -> R<Value> {
|
||||
let protocol = &task["protocol"];
|
||||
let mut payload = protocol["parameters"].clone();
|
||||
payload["model"] = task["modelId"].clone();
|
||||
payload["prompt"] = task["prompt"].clone();
|
||||
let field = protocol["field"].as_str().ok_or("参考图契约无效")?;
|
||||
payload[field] = json!(files.iter().map(|bytes| format!("data:image/png;base64,{}", STANDARD.encode(bytes))).collect::<Vec<_>>());
|
||||
if protocol["multipart"] != true && !protocol::accepts(&payload, &protocol["schema"], 0) {
|
||||
return Err("当前参数不满足98k公开契约,未提交".into());
|
||||
}
|
||||
Ok(payload)
|
||||
}
|
||||
|
||||
pub(super) fn validate_frozen_spec(dir: &Path, task: &Value) -> R<()> {
|
||||
if task["requestSpecHash"] != hash(&image_spec(task).to_string()) {
|
||||
return Err("生图请求内容已变化,请重新准备".into());
|
||||
}
|
||||
if task["localProductSha256"].is_string() {
|
||||
let file = image_request_file(dir, task["id"].as_str().ok_or("图片请求编号无效")?)?.with_file_name("scene-product.png");
|
||||
let product = fs::read(file).map_err(|_| "实拍抠图不可读取")?;
|
||||
if task["localProductSha256"] != format!("{:x}", Sha256::digest(&product)) {
|
||||
return Err("实拍抠图已变化,请重新准备".into());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn freeze_image_request(dir: &Path, id: &str, input: &Value) -> R<Value> {
|
||||
let _guard = sync::context_guard();
|
||||
let mut task = read_image_request(dir, id)?;
|
||||
if task["requestSpecRevision"] != input["expectedRevision"] || task["requestSpecHash"] != input["expectedHash"] {
|
||||
return Err("生图请求版本已变化,请重新读取".into());
|
||||
}
|
||||
validate_frozen_spec(dir, &task)?;
|
||||
if task["frozenAt"].is_null() {
|
||||
verified_reference_bytes(&task)?;
|
||||
task["frozenAt"] = json!(now());
|
||||
job_save_locked(dir, &task, false)?;
|
||||
}
|
||||
Ok(image_request_receipt(&task))
|
||||
}
|
||||
|
||||
pub(super) fn reference_preview_id(id: &str) -> bool {
|
||||
@ -597,6 +674,11 @@ impl Backend {
|
||||
decode_agent_raster(&bytes)?,
|
||||
))
|
||||
}
|
||||
pub(super) fn image_dispatch_may_have_started(&self, doc: u64, id: &str) -> bool {
|
||||
self.project_dir(doc).and_then(|dir| read_image_request(&dir, id))
|
||||
.map_or(true, |task| task["phase"] != "prepared")
|
||||
}
|
||||
|
||||
pub(super) fn recover_original_image(&mut self, doc: u64, task: &str, tx: &mpsc::Sender<Event>, ctx: &egui::Context) -> R<Value> {
|
||||
let started = Instant::now();
|
||||
retry_original_queries(
|
||||
@ -622,7 +704,17 @@ impl Backend {
|
||||
self.image_validate(deadline)?;
|
||||
let settings = self.settings()?;
|
||||
let key = settings["key"].as_str().ok_or("请在对话栏连接个人Key")?;
|
||||
let mut t = if recover {
|
||||
let preparing = input["candidateRecord"].is_object();
|
||||
let frozen = input["frozenRequestId"].as_str();
|
||||
let mut t = if let Some(id) = frozen {
|
||||
let task = read_image_request(&dir, id)?;
|
||||
if task["phase"] != "prepared" || !task["frozenAt"].is_number()
|
||||
|| settings["imageModel"] != task["modelKey"] {
|
||||
return Err("请求尚未冻结、已派发或模型选择已变化,请读取原请求".into());
|
||||
}
|
||||
validate_frozen_spec(&dir, &task)?;
|
||||
task
|
||||
} else if recover {
|
||||
if let Some(task) = input["taskId"].as_str() {
|
||||
Uuid::parse_str(task).map_err(|_| "原图片任务身份无效")?;
|
||||
let original = read_json(&dir.join("image-jobs").join(task).join("task.json"))?;
|
||||
@ -635,8 +727,10 @@ impl Backend {
|
||||
}
|
||||
} else {
|
||||
if input["slotBinding"].is_object() {
|
||||
super::template_slots::validate_dispatch(&dir, &input["slotBinding"])?;
|
||||
super::template_workflow::validate_image_context(&dir, Some(&input["slotBinding"]))?;
|
||||
if !preparing {
|
||||
super::template_slots::validate_dispatch(&dir, &input["slotBinding"])?;
|
||||
super::template_workflow::validate_image_context(&dir, Some(&input["slotBinding"]))?;
|
||||
}
|
||||
} else {
|
||||
if pending(&dir)?
|
||||
|| super::creation::unresolved(&dir)?
|
||||
@ -675,10 +769,10 @@ impl Backend {
|
||||
}
|
||||
let refs = input["references"].as_array().filter(|a| !a.is_empty()).ok_or("请选择参考图")?;
|
||||
let max_images = contract["maxImages"].as_u64().unwrap_or(1) as usize;
|
||||
let omit_layout = input["optionalLayoutReference"] == true && refs.len() == max_images.saturating_add(1);
|
||||
let omit_layout = !preparing && input["optionalLayoutReference"] == true && refs.len() == max_images.saturating_add(1);
|
||||
let refs = if omit_layout { &refs[..max_images] } else { refs.as_slice() };
|
||||
if refs.len() > max_images {
|
||||
return Err("参考图数量超出所选线路范围;请减少选中图片".into());
|
||||
return Err(format!("所选线路最多接收 {max_images} 张参考图,本次有 {} 张。请调整参考图后重新准备。", refs.len()));
|
||||
}
|
||||
let target = input["target"].as_u64();
|
||||
if input["mode"] == "regenerate" {
|
||||
@ -692,9 +786,7 @@ impl Backend {
|
||||
}
|
||||
}
|
||||
let text = input["text"].as_str().filter(|s| !s.trim().is_empty()).ok_or("请输入生图要求")?;
|
||||
let text = slot_transport_prompt(text, omit_layout);
|
||||
let job = if input["slotBinding"].is_object() {
|
||||
super::template_slots::validate_dispatch(&dir, &input["slotBinding"])?;
|
||||
input["slotBinding"]["taskId"].as_str().ok_or("图位候选身份无效")?.to_owned()
|
||||
} else {
|
||||
Uuid::new_v4().to_string()
|
||||
@ -708,6 +800,7 @@ impl Backend {
|
||||
if bytes.len() > IMAGE_BYTES as usize {
|
||||
return Err("参考图超过20MiB,请先缩小图片".into());
|
||||
}
|
||||
let source_hash = preparing.then(|| format!("{:x}", Sha256::digest(bytes.as_slice())));
|
||||
let bytes = reference_png(&name, &bytes)?;
|
||||
if scene.is_some() {
|
||||
let (width, height) = image::ImageReader::with_format(std::io::Cursor::new(&bytes), image::ImageFormat::Png)
|
||||
@ -720,14 +813,25 @@ impl Backend {
|
||||
}
|
||||
let path = files.join(format!("reference-{i}.png"));
|
||||
job_bytes(&dir, &path, &bytes).map_err(|_| "参考图保存失败,未提交")?;
|
||||
references.push(json!({"layer":layer.0,"name":name,"path":path.to_string_lossy(),"sha256":format!("{:x}",Sha256::digest(&bytes))}));
|
||||
let mut reference = json!({"layer":layer.0,"name":name,"path":path.to_string_lossy(),"sha256":format!("{:x}",Sha256::digest(&bytes))});
|
||||
if preparing {
|
||||
let [width,height] = image::ImageReader::with_format(std::io::Cursor::new(&bytes), image::ImageFormat::Png)
|
||||
.into_dimensions().map(|(w,h)| [w,h]).map_err(|_| "参考图尺寸无法读取")?;
|
||||
reference["position"] = json!(i + 1);
|
||||
reference["source"] = input["referenceOrigins"][i]["source"].clone();
|
||||
reference["role"] = input["referenceOrigins"][i]["purpose"].clone();
|
||||
reference["sourceSha256"] = json!(source_hash);
|
||||
reference["size"] = json!([width,height]);
|
||||
}
|
||||
references.push(reference);
|
||||
}
|
||||
if let Some((_,cutout)) = &scene {
|
||||
if references.len() != 1 { return Err("实拍合成只发送模板场景去除旧商品".into()); }
|
||||
job_bytes(&dir, &files.join("scene-product.png"), cutout).map_err(|_| "实拍抠图保存失败,未提交")?;
|
||||
}
|
||||
let prompt = if input["slotBinding"]["canvasFirst"] == true || scene.is_some() {
|
||||
text.to_owned()
|
||||
let note = (!omit_layout).then(|| input["templateLayoutNote"].as_str()).flatten().unwrap_or("");
|
||||
format!("{text}{note}")
|
||||
} else {
|
||||
let guidance = json!({"brand":input["brand"],"facts":input["facts"]});
|
||||
format!(
|
||||
@ -740,6 +844,21 @@ impl Backend {
|
||||
let prior = if dir.join("image-task.json").exists() { read_json(&dir.join("image-task.json"))?["id"].clone() } else { Value::Null };
|
||||
json!({"version":1,"id":job,"doc":id,"revision":input["revision"],"mode":input["mode"],"target":target,"modelId":model_id,"modelKey":choice,"protocol":contract,"prompt":prompt,"references":references,"omittedOptionalLayout":omit_layout,"keyFingerprint":hash(key),"phase":"prepared","requestId":null,"upstreamTaskId":null,"center":input["center"],"accountScope":self.scope(),"localProjectId":self.locations.get(&id),"origin":self.origin,"createdAt":now(),"replacesTaskId":prior,"creationBinding":input["creationBinding"],"slotBinding":input["slotBinding"],"sceneComposite":scene.as_ref().map(|(recipe,_)|recipe)})
|
||||
};
|
||||
if preparing {
|
||||
t["candidateRecord"] = input["candidateRecord"].clone();
|
||||
t["candidateRecord"]["prompt"] = t["prompt"].clone();
|
||||
t["slotBinding"]["promptHash"] = json!(hash(t["prompt"].as_str().ok_or("生图请求文本缺失")?));
|
||||
t["candidateRecord"]["binding"] = t["slotBinding"].clone();
|
||||
t["outputScope"] = input["outputScope"].clone();
|
||||
if let Some((_,cutout)) = &scene {
|
||||
t["localProductSha256"] = json!(format!("{:x}", Sha256::digest(cutout)));
|
||||
}
|
||||
t["requestSpecRevision"] = json!(1);
|
||||
t["requestSpecHash"] = json!(hash(&image_spec(&t).to_string()));
|
||||
image_payload(&t, &verified_reference_bytes(&t)?)?;
|
||||
job_save(&dir, &t)?;
|
||||
return read_image_request(&dir, t["id"].as_str().unwrap_or_default()).map(|task| image_request_receipt(&task));
|
||||
}
|
||||
if t["keyFingerprint"] != hash(key) {
|
||||
return Err("请切回原个人Key,只读核查原请求;不会重发".into());
|
||||
}
|
||||
@ -831,23 +950,9 @@ impl Backend {
|
||||
}
|
||||
} else {
|
||||
let p = t["protocol"].clone();
|
||||
let mut payload = p["parameters"].clone();
|
||||
payload["model"] = t["modelId"].clone();
|
||||
payload["prompt"] = t["prompt"].clone();
|
||||
let mut files = Vec::new();
|
||||
for r in t["references"].as_array().ok_or("参考图记录无效")? {
|
||||
let path = Path::new(r["path"].as_str().ok_or("参考图记录无效")?);
|
||||
let b = fs::read(path).map_err(|_| "本机参考图不可读取")?;
|
||||
if b.len() > 10 * 1024 * 1024 || r["sha256"] != format!("{:x}", Sha256::digest(&b)) {
|
||||
return Err("参考图已变化,未提交".into());
|
||||
}
|
||||
files.push(b);
|
||||
}
|
||||
let files = verified_reference_bytes(&t)?;
|
||||
let payload = image_payload(&t, &files)?;
|
||||
let field = p["field"].as_str().ok_or("参考图契约无效")?;
|
||||
payload[field] = json!(files.iter().map(|b| format!("data:image/png;base64,{}", STANDARD.encode(b))).collect::<Vec<_>>());
|
||||
if p["multipart"] != true && !protocol::accepts(&payload, &p["schema"], 0) {
|
||||
return Err("当前参数不满足98k公开契约,未提交".into());
|
||||
}
|
||||
let mut req = self
|
||||
.http
|
||||
.post(format!("{UPSTREAM}{}", p["path"].as_str().ok_or("模型路径无效")?))
|
||||
@ -1040,14 +1145,39 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn slot_dispatch_preserves_prompt_and_prepares_optional_reference_before_freeze() {
|
||||
let instructions = "同款实拍。品牌用侧光。用稍宽画面留出裁切空间。";
|
||||
let prompt = format!("{instructions}{TEMPLATE_LAYOUT_PROMPT_PREFIX}第 3 张仅作构图参考。");
|
||||
assert_eq!(slot_transport_prompt(&prompt, false).as_bytes(), prompt.as_bytes());
|
||||
assert_eq!(slot_transport_prompt(&prompt, true), instructions);
|
||||
assert_eq!(slot_transport_prompt(instructions, true), instructions);
|
||||
fn prepared_image_request_round_trips_and_freezes_exact_transport_inputs() {
|
||||
let fixture = canvas_post_fixture();
|
||||
let mut task = fixture.task.clone();
|
||||
let id = task["id"].as_str().unwrap().to_owned();
|
||||
let asset = image_request_file(&fixture.dir, &id).unwrap().with_file_name("reference-0.png");
|
||||
let pixels = b"fixture bytes";
|
||||
fs::write(&asset, pixels).unwrap();
|
||||
let prompt = "完整文本,保留换行。\n【模板图位参考】这也是用户正文。\n尾部说明。";
|
||||
task["phase"] = json!("prepared");
|
||||
task["prompt"] = json!(prompt);
|
||||
task["requestSpecRevision"] = json!(1);
|
||||
task["references"] = json!([{"position":1,"source":"P01","role":"product","path":asset,"sha256":format!("{:x}",Sha256::digest(pixels))}]);
|
||||
task["protocol"] = json!({"parameters":{"quality":"medium"},"field":"images","route":"fixture-route",
|
||||
"path":"/v1/images/edits","multipart":true});
|
||||
task["requestSpecHash"] = json!(hash(&image_spec(&task).to_string()));
|
||||
job_save(&fixture.dir, &task).unwrap();
|
||||
let read = image_request_receipt(&read_image_request(&fixture.dir, &id).unwrap());
|
||||
assert_eq!(read["spec"]["prompt"], prompt);
|
||||
assert_eq!(read["spec"]["references"][0]["sha256"], task["references"][0]["sha256"]);
|
||||
assert!(freeze_image_request(&fixture.dir, &id, &json!({"expectedRevision":2,"expectedHash":read["requestSpecHash"]})).is_err());
|
||||
let frozen = freeze_image_request(&fixture.dir,&id,&json!({"expectedRevision":1,"expectedHash":read["requestSpecHash"]})).unwrap();
|
||||
assert_eq!(frozen["frozen"], true);
|
||||
let saved = read_image_request(&fixture.dir, &id).unwrap();
|
||||
let payload = image_payload(&saved, &verified_reference_bytes(&saved).unwrap()).unwrap();
|
||||
assert_eq!(payload["prompt"], prompt);
|
||||
assert_eq!(payload["quality"], "medium");
|
||||
assert_eq!(payload["images"][0], format!("data:image/png;base64,{}", STANDARD.encode(pixels)));
|
||||
fs::write(&asset,b"modified").unwrap();
|
||||
assert!(verified_reference_bytes(&saved).is_err());
|
||||
let mut corrupt = saved;
|
||||
corrupt["prompt"] = json!("differs");
|
||||
assert!(validate_frozen_spec(&fixture.dir,&corrupt).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_thumbnail_is_pending_until_the_jpeg_is_published() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
@ -1168,20 +1298,29 @@ mod tests {
|
||||
header.extend(byte);
|
||||
}
|
||||
let text = String::from_utf8(header).unwrap();
|
||||
methods.push(text.lines().next().unwrap().to_owned());
|
||||
let method = text.lines().next().unwrap().to_owned();
|
||||
let length = text
|
||||
.lines()
|
||||
.find_map(|line| line.to_ascii_lowercase().strip_prefix("content-length:").and_then(|n| n.trim().parse::<usize>().ok()))
|
||||
.unwrap_or(0);
|
||||
let mut body = vec![0; length];
|
||||
socket.read_exact(&mut body).unwrap();
|
||||
methods.push((method, serde_json::from_slice::<Value>(&body).unwrap()));
|
||||
write!(socket, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{{}}").unwrap();
|
||||
}
|
||||
methods
|
||||
});
|
||||
let client = Client::builder().no_proxy().redirect(reqwest::redirect::Policy::none()).timeout(Duration::from_secs(2)).build().unwrap();
|
||||
let prompt = "保留正式文本及尾部\n按已审核的构图制作";
|
||||
let references = [vec![1,3,5],vec![2,4,6]];
|
||||
let mut task = fixture.task.clone();
|
||||
task["modelId"] = json!("fixture-image");
|
||||
task["prompt"] = json!(prompt);
|
||||
task["protocol"] = json!({"parameters":{"quality":"high","size":"1536x2048"},"field":"images",
|
||||
"multipart":true});
|
||||
let payload = image_payload(&task, &references).unwrap();
|
||||
let post = || -> R<Response> {
|
||||
client.post(format!("http://{address}/local-image-dispatch")).json(&json!({"fixture":true})).send().map_err(|error| error.to_string())
|
||||
client.post(format!("http://{address}/local-image-dispatch")).json(&payload).send().map_err(|error| error.to_string())
|
||||
};
|
||||
// This is the exact guard used around req.send() in image_job, not a
|
||||
// separate canvas-only validator or an actual upstream model call.
|
||||
@ -1196,7 +1335,10 @@ mod tests {
|
||||
assert!(slot_post(&fixture.dir, &wrong, post).is_err());
|
||||
}
|
||||
done.store(true, Ordering::SeqCst);
|
||||
assert_eq!(server.join().unwrap(), vec!["POST /local-image-dispatch HTTP/1.1"]);
|
||||
assert_eq!(server.join().unwrap(), vec![("POST /local-image-dispatch HTTP/1.1".into(),
|
||||
json!({"model":"fixture-image","prompt":prompt,"quality":"high","size":"1536x2048","images":[
|
||||
"data:image/png;base64,AQMF","data:image/png;base64,AgQG"
|
||||
]}))]);
|
||||
assert!(!fixture.dir.join("template-input.json").exists());
|
||||
assert_eq!(read_json(&fixture.dir.join("image-jobs").join(fixture.task["id"].as_str().unwrap()).join("task.json")).unwrap()["phase"], "unknown");
|
||||
}
|
||||
|
||||
@ -515,7 +515,7 @@ impl Drop for DaemonTurnGuard {
|
||||
}
|
||||
}
|
||||
fn allowed_canvas_action(action: &str) -> bool {
|
||||
matches!(action, "pi-begin" | "pi-state" | "pi-production-open" | "pi-ui-request" | "pi-ui-poll" | "pi-ui-cancel" | "pi-canvas-read" | "pi-template-image" | "pi-detail-images" | "pi-detail-archive" | "pi-detail-copy-fields" | "pi-detail-copy-apply" | "pi-product-screen" | "pi-preview" | "pi-copy-options" | "pi-copy-fields" | "pi-native-catalog" | "pi-native-call" | "pi-native-poll"
|
||||
matches!(action, "pi-begin" | "pi-state" | "pi-production-open" | "pi-ui-request" | "pi-ui-poll" | "pi-ui-cancel" | "pi-canvas-read" | "pi-template-image" | "pi-detail-images" | "pi-detail-archive" | "pi-detail-copy-fields" | "pi-detail-copy-apply" | "pi-product-screen" | "pi-image-request" | "pi-preview" | "pi-copy-options" | "pi-copy-fields" | "pi-native-catalog" | "pi-native-call" | "pi-native-poll"
|
||||
| "pi-delta" | "pi-reply" | "pi-activity" | "pi-context-usage" | "pi-write-request" | "pi-edit" | "pi-end" | "pi-workflow-read"
|
||||
| "pi-workflow-navigate" | "pi-workflow-propose" | "pi-workflow-execute" | "pi-workflow-poll"
|
||||
| "pi-native-reconcile" | "pi-edit-reconcile" | "pi-workflow-reconcile")
|
||||
@ -693,6 +693,27 @@ fn run_inner(b: &mut Backend, input: &Value, method: &str, events: &mpsc::Sender
|
||||
ctx.request_repaint();
|
||||
let reply = match rx.recv_timeout(Duration::from_secs(12)) {
|
||||
Ok(Ok((mut v, snapshot))) => {
|
||||
if action == "pi-image-request" {
|
||||
let mut worker = b.clone();
|
||||
let transport = daemon.clone();
|
||||
let run = daemon_run.clone();
|
||||
let id = value["id"].clone();
|
||||
let task_events = events.clone();
|
||||
let task_ctx = ctx.clone();
|
||||
workflow_children.workers.push(std::thread::spawn(move || {
|
||||
let result = worker.production_image_request(doc, &v, &task_events, &task_ctx);
|
||||
let reply = match result {
|
||||
Ok(value) => json!({"value":value}),
|
||||
Err(error) => {
|
||||
let dispatched = v["request"]["frozenRequestId"].as_str()
|
||||
.is_some_and(|id| worker.image_dispatch_may_have_started(doc, id));
|
||||
json!({"error":BridgeFailure::new("image_request_failed", false, dispatched, error).wire()})
|
||||
}
|
||||
};
|
||||
let _ = transport.reply(&run, &id, &reply);
|
||||
}));
|
||||
continue;
|
||||
}
|
||||
if matches!(action, "pi-detail-images" | "pi-detail-archive") {
|
||||
let archive = action == "pi-detail-archive";
|
||||
let queued = if archive && config["wholeDetail"] != true {
|
||||
|
||||
@ -55,7 +55,9 @@ fn tool_activity(w: &Workspace, event: &Value) -> Result<Value, String> {
|
||||
"open_production_output" => "打开制作画布",
|
||||
"plan_production" => "读取制作进度", "read_production_knowledge" => "读取制作规则",
|
||||
"read_copy_fields" => "读取画布文字格", "read_slot_images" => "查看图位图片",
|
||||
"generate_slot_image" => "生成候选图片", "delegate_image_slots" => "分派图片图位",
|
||||
"use_product_image" => "取用商品实拍", "prepare_image_request" => "准备生图请求",
|
||||
"read_image_request" => "核对生图请求", "freeze_image_request" => "冻结生图请求",
|
||||
"dispatch_image_request" => "生成候选图片", "delegate_image_slots" => "分派图片图位",
|
||||
"await_image_slots" => "等待子代理回执", "review_image_slots" => "查看图位结果",
|
||||
"adopt_production_image" => "回填候选图片", "retire_production_image" => "清理已退回的候选图",
|
||||
"reconcile_image_slots" => "核查图片原请求",
|
||||
@ -215,7 +217,7 @@ fn image_linked_copy(doc: &photocraft_doc::Document, slot_id: &Value) -> Vec<Val
|
||||
}
|
||||
|
||||
fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Context>, method: &str, input: &Value, private: bool) -> Result<Value, BridgeFailure> {
|
||||
if matches!(method, "pi-production-open" | "pi-workflow-execute" | "pi-detail-copy-fields" | "pi-detail-copy-apply" | "pi-product-screen") && !private { return Err("工作流执行仅允许当前本机Agent会话".into()); }
|
||||
if matches!(method, "pi-production-open" | "pi-image-request" | "pi-workflow-execute" | "pi-detail-copy-fields" | "pi-detail-copy-apply" | "pi-product-screen") && !private { return Err("工作流执行仅允许当前本机Agent会话".into()); }
|
||||
if method == "pi-begin" {
|
||||
if (input["accountId"].is_string() && input["accountId"] != w.account["id"]) || (input["origin"].is_string() && input["origin"] != w.origin) {
|
||||
return Err("画布与模型账户不一致".into());
|
||||
@ -485,6 +487,37 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
|
||||
"outputId":w.pi_request_scope["outputId"],"variantId":w.pi_request_scope["variantId"],
|
||||
"templateHash":w.template_workflow["templateHash"],"canvasLayerId":canvas_layer}))
|
||||
}
|
||||
"pi-image-request" => {
|
||||
let action = input["action"].as_str().filter(|action| matches!(*action,"prepare"|"read"|"freeze"|"dispatch"))
|
||||
.ok_or("生图请求动作无效")?;
|
||||
if w.pi_request_scope["productProduction"] != true || !w.canvas_scope_valid(app)
|
||||
|| w.pi_request_scope["outputId"] != w.template_workflow["outputId"]
|
||||
|| w.pi_request_scope["variantId"] != w.template_workflow["variantId"] {
|
||||
return Err(BridgeFailure::new("scope_changed", false, false, "生图请求未绑定本轮工作画布"));
|
||||
}
|
||||
if action != "read" && (w.pi_write_blocked || w.agent_effects_paused) {
|
||||
return Err(BridgeFailure::new("write_revoked", false, false, "本轮制作已暂停,原请求保留"));
|
||||
}
|
||||
let request = &input["request"];
|
||||
let allowed: &[&str] = match action {
|
||||
"prepare" => &["slotId","instructions","geometryReferenceIndex","prefer2k","retryOf","reworkOf","reworkChange","useTemplateReference"],
|
||||
"freeze" => &["requestId","expectedRevision","expectedHash"],
|
||||
"dispatch" => &["frozenRequestId"],
|
||||
_ => &["requestId"],
|
||||
};
|
||||
if request.as_object().is_none_or(|fields| fields.keys().any(|key| !allowed.contains(&key.as_str()))) {
|
||||
return Err("生图请求包含不适用于当前动作的字段".into());
|
||||
}
|
||||
if action == "prepare" && !w.template_workflow["slots"].as_array().into_iter().flatten().any(|slot|
|
||||
slot["id"] == request["slotId"] && slot["outputId"] == w.pi_request_scope["outputId"]
|
||||
&& slot["variantId"] == w.pi_request_scope["variantId"] && slot["nativeLayerId"].is_u64()) {
|
||||
return Err("图位不属于本轮制作画布".into());
|
||||
}
|
||||
Ok(json!({"action":action,"request":request,"revision":w.expected_revision,
|
||||
"scope":{"id":w.template_workflow["workspaceId"],"templateHash":w.template_workflow["templateHash"],
|
||||
"structureHash":w.template_workflow["structureHash"],"outputId":w.pi_request_scope["outputId"],
|
||||
"variantId":w.pi_request_scope["variantId"]}}))
|
||||
}
|
||||
"pi-detail-images" => {
|
||||
let inspect = private && input["inspectCandidate"] == true;
|
||||
if !inspect && (w.pi_request_scope["wholeDetail"] != true || w.pi_write_blocked || w.agent_effects_paused) {
|
||||
|
||||
@ -450,7 +450,9 @@ impl Workspace {
|
||||
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 alternatives: Vec<_> = ["main_images", "sku_images"].into_iter()
|
||||
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()
|
||||
@ -1684,7 +1686,8 @@ mod tests {
|
||||
let app = PhotocraftApp::new(session, crate::Services::default());
|
||||
let doc = app.session.active().unwrap().doc.id.0;
|
||||
w.open_projects.insert(doc, w.local_identity("project"));
|
||||
w.template_workflow = json!({"workspaceId":"workspace","outputId":"detail","variantId":"oak","productionStages":[]});
|
||||
w.template_workflow = json!({"workspaceId":"workspace","outputId":"detail","variantId":"oak",
|
||||
"outputs":[{"outputId":"detail"},{"outputId":"main_images"},{"outputId":"sku_images"}],"productionStages":[]});
|
||||
w.preload_product_outputs(&app);
|
||||
let Request::Action(method, input) = requests.try_recv().unwrap() else { panic!("expected a background view read"); };
|
||||
assert_eq!(method, "slot-product-view");
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user