让小壹后台成品先制作和复核候选

This commit is contained in:
WuYongJie 2026-11-28 22:08:41 +08:00
parent 2fc959e741
commit dac0658448
6 changed files with 180 additions and 68 deletions

View File

@ -161,7 +161,7 @@ export async function callProductionTool(host, name, args, signal) {
?{includeProductReferences:false,includeTemplateReference:false}:null)};
return imageResult({...target,...await host.canvas.detailImages(input.slotId,input.candidateId,options)});
}
if(!working&&!['plan_production','review_image_slots','await_image_slots','reconcile_image_slots','check_image_slots'].includes(name))
if(!working&&!['plan_production','review_image_slots','await_image_slots','reconcile_image_slots','check_image_slots','use_product_image','transform_slot_image'].includes(name))
return {...target,accepted:false,reason:'canvas_inactive',workingOutput:goal.outputId?{
outputId:goal.outputId,variantId:goal.variantId}:null};
if (name==='finish_production' && args.revision===undefined) {

View File

@ -89,7 +89,7 @@ export const productionOperationTools = [
['read_slot_images','查看指定成品图位的同款实拍、模板构图和候选。adopted=true 读取当前可写画布上的实际回填。候选只返回候选画面;需要同时查看或重新查看参考时传 includeReferences=true。',obj({
...outputScope,slotId:slotRef,candidateId:optional(Type.String()),adopted:optional(Type.Boolean()),includeReferences:optional(Type.Boolean()),
})],
['use_product_image','用本款原片或裁切区域创建候选。通过 adopt_production_image 回填时,放置回执会列出覆盖图位的模板叠层。',obj({slotId:slotRef,...productImageArgs})],
['use_product_image','用本款原片或裁切区域创建候选。通过 adopt_production_image 回填时,放置回执会列出覆盖图位的模板叠层。',obj({...outputScope,slotId:slotRef,...productImageArgs})],
['transform_slot_image','在本机裁切、镜像、旋转、缩放或位移本款实拍及任一成品的同花色候选,返回新候选和像素清晰度指标。',obj({...outputScope,slotId:slotRef,...transformImageArgs})],
['prepare_image_request','保存完整生图请求,返回正式文本、参考顺序、模型参数与请求编号。'+imagePromptGuidance,obj({...outputScope,slotId:slotRef,...preparationArgs})],
['dispatch_image_request','审阅准备回执后填写 requestId 确认派发。宿主从该编号绑定的请求读取版本和哈希。使用 await_image_slots 或 review_image_slots 查看实际结果。',obj({...outputScope,...dispatchArgs})],
@ -161,6 +161,11 @@ function productionInputs(plan,variantId){
plan.productEvidence.sellingPoints?.selected]);
}
export function preparedCandidateId(intent,values,operation){
const adopting=intent==='adopt_candidate';
return adopting?values.candidateId:values.useProductReference!==true?operation.operationId:null;
}
function changedProductionFields(previous,current,variantId){
const inputs=value=>{
const {variants,...brief}=value.productEvidence?.brief??{};
@ -457,27 +462,23 @@ export async function openProductionOperations(host,{target=host.productionGoal,
? AbortSignal.any([host.productionSignal,stageController.signal]):stageController.signal;
const onCanvas=async(signal,task,permit,row)=>{
while(canvasReady&&!stageSignal.aborted){
const step=row?.step;
if(permit){
if(row){
waitingCanvas.set(row.slotId,row.label);
publishWaitingCanvas();
}
if(permit){
permit.release();
permit.release=null;
}
try {
await awaitCanvas(canvasReady.promise,signal);
} finally {
if(permit){
if(row){
waitingCanvas.delete(row.slotId);
publishWaitingCanvas();
}
}
if(permit){
row.step='排队中';
notice('图位已排队');
permit.release=await pool.acquire(signal);
row.step=step;
}
if(permit)permit.release=await pool.acquire(signal);
}
stageSignal.throwIfAborted();
signal?.throwIfAborted();
@ -699,7 +700,7 @@ export async function openProductionOperations(host,{target=host.productionGoal,
const args={version:(await current()).version,intent,outputId,slotId:slot.id,productVariantId:variantId,...values};
let prepared;
const archive=async operation=>{
const candidateId=adopting?values.candidateId:null;
const candidateId=preparedCandidateId(intent,values,operation);
prepared={...operation,intent,candidateId};
dispatchingImages.set(operation.operationId,undefined);
await save(slot,{[pendingKey]:prepared,...(!adopting?{state:'dispatching'}:null)});
@ -749,22 +750,28 @@ export async function openProductionOperations(host,{target=host.productionGoal,
tailWatcher.refresh();
}
}
const transformImage=async(slot,{sourceCandidateId,referenceIndex,...transform},signal)=>{
const localCandidate=async(slot,action,values,signal,source)=>{
signal?.throwIfAborted();
await current();
const receipt=await canvas.imageRequest('transform',{slotId:slot.id,sourceCandidateId,referenceIndex,transform});
if(receipt?.status!=='complete'||!receipt.id)throw Error('原生画布未返回已保存的变换候选');
signal?.throwIfAborted();
const request={slotId:slot.id,...values};
const receipt=canvasReady||action==='product_reference'
? await canvas.imageRequest(action,request,undefined,imageScope)
: await trackCanvas(canvas.imageRequest(action,request));
if(receipt?.status!=='complete'||!receipt.id)throw Error('原生宿主未返回已保存的本地候选');
const result={...receipt,candidateId:receipt.id,phase:'complete'};
await update(journal=>{
const item=journal.items[slot.id]??={};
if(item.state!=='applied'&&!item.pendingOperation&&!item.pendingAdoption){
Object.assign(item,{state:'candidate',candidateId:receipt.id,source:'transform'});
Object.assign(item,{state:'candidate',candidateId:receipt.id,source});
}
},{evidence:[slot.id,receipt.id,'candidate',receipt]});
candidates.set(receipt.id,{slotId:slot.id,status:'complete'});
notice('画布调整已有候选');
if(action==='transform')notice('画布调整已有候选');
return result;
};
const transformImage=(slot,{sourceCandidateId,referenceIndex,...transform},signal)=>
serialize(()=>localCandidate(slot,'transform',{sourceCandidateId,referenceIndex,transform},signal,'transform'));
const prepareImageRequest=async(slot,{prompt,retryOf,useTemplateReference,prefer2k,geometryReferenceIndex,
referenceIndexes,useSceneComposite,reworkCandidateId,reworkChange},signal)=>{
signal?.throwIfAborted();
@ -842,7 +849,9 @@ export async function openProductionOperations(host,{target=host.productionGoal,
return {slotId:slot.id,phase:'accepted',candidateId:id,operationId:id};
};
const useProductImage=async(slot,options,signal)=>({
...await operate(slot,'generate_candidate',{useProductReference:true,...options},signal,{source:'product'}),
...(canvasReady
? await localCandidate(slot,'product_reference',options,signal,'product')
: await trackCanvas(operate(slot,'generate_candidate',{useProductReference:true,...options},signal,{source:'product'}))),
requestedSource:'product',sourceNote:'仅使用或裁切原片,保留原片的背景和光线。',
});
const launchProductImage=(slot,options,signal)=>{
@ -851,7 +860,7 @@ export async function openProductionOperations(host,{target=host.productionGoal,
const receipt={slotId:key,phase:'accepted'};
const row={number:nextWorkerNumber(),slotId:key,label:slot.label,step:'生成',active:true};
generation.set(key,receipt);
const run=onCanvas(signal,()=>useProductImage(slot,options,signal))
const run=useProductImage(slot,options,signal)
.catch(error=>({phase:'failed',reason:error.message}))
.then(result=>{
const receipt={slotId:key,...result};
@ -1176,7 +1185,7 @@ export async function openProductionOperations(host,{target=host.productionGoal,
return launchProductImage(slot,options,signal?AbortSignal.any([signal,stageSignal]):stageSignal);
},
transform_slot_image({slotId,...options},signal){
return serialize(()=>transformImage(matches(slotId),options,signal));
return transformImage(matches(slotId),options,signal);
},
prepare_image_request({slotId,...args},signal){
return prepareImageRequest(matches(slotId),args,signal);
@ -1221,11 +1230,11 @@ export async function openProductionOperations(host,{target=host.productionGoal,
},
};
};
const makeTools=permit=>[
const workerTools=[
workerTool('use_product_image','用本款实拍创建图位候选',productImageArgs,
(args,activeSignal)=>onCanvas(activeSignal,()=>useProductImage(slot,args,activeSignal),permit,row),true),
(args,activeSignal)=>useProductImage(slot,args,activeSignal),true),
workerTool('transform_slot_image','用本款实拍或本项目候选裁切、镜像、旋转、缩放或位移',transformImageArgs,
(args,activeSignal)=>onCanvas(activeSignal,()=>serialize(()=>transformImage(slot,args,activeSignal)),permit,row)),
(args,activeSignal)=>transformImage(slot,args,activeSignal)),
workerTool('prepare_image_request','准备并持久保存完整生图请求。',preparationArgs,
(args,activeSignal)=>prepareImageRequest(slot,{...args,reworkCandidateId:rework?.candidateId},activeSignal)),
workerTool('dispatch_image_request','审阅准备回执后填写 requestId 确认派发',dispatchArgs,
@ -1254,7 +1263,7 @@ export async function openProductionOperations(host,{target=host.productionGoal,
delegateSignal.throwIfAborted();
return imageResult(await readImages(slot.id));
}};
const run=scheduleDelegate(delegateSignal,async permit=>{
const run=scheduleDelegate(delegateSignal,async()=>{
row.step='正在准备';
notice('子代理正在制作');
const prior=journal.items[slot.id];
@ -1288,7 +1297,7 @@ export async function openProductionOperations(host,{target=host.productionGoal,
const screenCopy=await liveSlotCopy(slot);
delegateSignal.throwIfAborted();
await runDetailAgent(slot.id,instructions,
JSON.stringify({rework,goal,screenCopy,...status,field:slot.fieldId,label:slot.label,rule:slot.productionRule,requirements:slot.requirements}),[readTool,...makeTools(permit)],
JSON.stringify({rework,goal,screenCopy,...status,field:slot.fieldId,label:slot.label,rule:slot.productionRule,requirements:slot.requirements}),[readTool,...workerTools],
rejectedImage?[rejectedImage]:[],productRequestScope('slot',slot.id),undefined,delegateSignal);
if(!produced)generation.set(workerId,{slotId:slot.id,phase:'no_candidate'});
}).catch(async error=>{
@ -1427,7 +1436,7 @@ export async function openProductionOperations(host,{target=host.productionGoal,
},
async adopt_production_image({slotId,candidateId,fit},signal){
const slot=matches(slotId);
const result=await serialize(async()=>{
const result=await onCanvas(signal,()=>serialize(async()=>{
const adopted=await operate(slot,'adopt_candidate',{candidateId,fit},signal);
if(adopted.phase!=='complete')return adopted;
const entry=journal.items[slot.id]?.reviewHistory?.findLast(row=>row.candidateId===candidateId&&row.screenReview);
@ -1438,7 +1447,7 @@ export async function openProductionOperations(host,{target=host.productionGoal,
} catch(error) {
return {...adopted,screenReviewError:error.message};
}
});
}),undefined,{slotId:slot.id,label:slot.label});
if(result.phase==='complete'&&candidates.has(candidateId))candidates.get(candidateId).status='adopted';
notice('画布回填回执');
return result;
@ -1562,10 +1571,10 @@ export async function openProductionOperations(host,{target=host.productionGoal,
const existing=screenChecks.get(page);
if(existing?.run)return existing;
const job={receipt:{page,state:'queued'}};
job.run=scheduleDelegate(activeSignal,async()=>{
job.run=scheduleDelegate(activeSignal,async permit=>{
job.receipt={page,state:'checking'};
notice('正在按屏复核');
const screen=await onCanvas(activeSignal,()=>operations.read_output_screen({page:page-1},activeSignal));
const screen=await onCanvas(activeSignal,()=>operations.read_output_screen({page:page-1},activeSignal),permit);
const previous=new Map(journal.screenReviews??[]).get(page-1);
if(previous?.candidateReview && !screen.details.screenChanged &&
previous.screenFingerprint===screen.details.screenFingerprint &&
@ -1581,7 +1590,7 @@ export async function openProductionOperations(host,{target=host.productionGoal,
await onCanvas(activeSignal,()=>operations.record_screen_check({
page:page-1,screenFingerprint:receipt.screenFingerprint,
issues:[...receipt.imageIssues,...receipt.overlayFixes,...receipt.copyFixes],
},activeSignal,inputSignature));
},activeSignal,inputSignature),permit);
job.receipt=receipt;
}).catch(error=>{
job.receipt={page,error:error.message};

View File

@ -5,7 +5,7 @@ import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { openProductionOperations as openOperations } from '../src/production-operations.mjs';
import { openProductionOperations as openOperations, preparedCandidateId } from '../src/production-operations.mjs';
import { callProductionTool, closeProductionTurn, currentProductionOperations } from '../src/production-goal.mjs';
import { cleanup } from './cleanup.mjs';
import { bindRecovery } from '../src/desktop-host.mjs';
@ -13,6 +13,13 @@ import { openEnterpriseSkills } from '../src/enterprise-skill-resources.mjs';
import { productionStore } from './production-store-fixture.mjs';
import { completeCanvas } from './fake-canvas.mjs';
test('a prepared generation keeps the original operation number as its candidate',()=>{
const operation={operationId:randomUUID()};
assert.equal(preparedCandidateId('generate_candidate',{},operation),operation.operationId);
assert.equal(preparedCandidateId('generate_candidate',{useProductReference:true},operation),null);
assert.equal(preparedCandidateId('adopt_candidate',{candidateId:'selected'},operation),'selected');
});
const imageBridges=new WeakSet();
// The fixture models the host journal. Each Pi operations instance reads it anew.
@ -658,7 +665,7 @@ test('a switched-away worker prepares and dispatches under its original output a
assert.deepEqual(await queuedCopy.promise,['榫接结构']);
});
test('one six-worker pool spans all outputs and admits another worker when a canvas write waits', {timeout:5000}, async t=>{
test('one six-worker pool spans all outputs and completes transforms on a switched-away output', {timeout:5000}, async t=>{
const {host}=await tailFixture(t,[]);
const outputs=['detail','main_images','sku_images'].map(outputId=>({outputId,variantId:'oak'}));
host.productionGoal.requestedOutputs=outputs;
@ -675,15 +682,12 @@ test('one six-worker pool spans all outputs and admits another worker when a can
template:{contentHash:outputId},totalSlots:drafts.get(outputId).length,slots:drafts.get(outputId)});
host.canvas.workflowRead=async()=>view(host.productionGoal.outputId);
host.canvas.detailHistory=async({targetOutput})=>view(targetOutput.outputId);
const waitShown=Promise.withResolvers(), waitCleared=Promise.withResolvers(), transform=Promise.withResolvers();
host.canvas.delta=async(_text,_thinking,progress)=>{
if(progress.outputId==='detail'&&progress.waitingCanvas===1)waitShown.resolve();
if(progress.outputId==='detail'&&progress.waitingCanvas===0)waitCleared.resolve();
};
host.canvas.imageRequest=async(action,args)=>{
const transform=Promise.withResolvers();
host.canvas.imageRequest=async(action,args,_execution,target)=>{
if(action==='pending')return [];
assert.equal(action,'transform');
assert.equal(host.productionGoal.outputId,'detail');
assert.equal(host.productionGoal.outputId,'sku_images');
assert.deepEqual(target,{...outputs[0],templateHash:'detail'});
transform.resolve(args.slotId);
return {id:'transformed',status:'complete'};
};
@ -702,21 +706,86 @@ test('one six-worker pool spans all outputs and admits another worker when a can
await enter.get('main_images-1').promise;
assert.deepEqual(started,['detail-0','detail-1','detail-2','detail-3','main_images-0','main_images-1']);
release.get('detail-0').resolve();
await waitShown.promise;
assert.equal(await transform.promise,'detail-0');
await enter.get('main_images-2').promise;
const waiting={slotId:'detail-0',phase:'waiting_canvas'};
assert.equal((await callProductionTool(host,'review_image_slots',{...outputs[0],slotIds:['detail-0']})).pictures[0].state,waiting.phase);
assert.deepEqual((await callProductionTool(host,'await_image_slots',{...outputs[0],slotIds:['detail-0']})).generation,[waiting]);
const switched=await callProductionTool(host,'open_production_output',outputs[1]);
assert.deepEqual(switched.work.find(row=>row.outputId==='detail').waitingCanvas,[{fieldId:'detail-0',label:'detail-0'}]);
await callProductionTool(host,'open_production_output',outputs[0]);
await waitCleared.promise;
const state=await callProductionTool(host,'review_image_slots',{...outputs[0],slotIds:['detail-0']});
assert.equal(state.pictures[0].generation.candidateId,'transformed');
for(let n=0;n<3;n++){
release.get('detail-'+(n+1)).resolve();
await enter.get('sku_images-'+n).promise;
}
release.get('sku_images-0').resolve();
assert.equal(await transform.promise,'detail-0');
});
test('an inactive output stages and reviews a product photo before waiting for adoption', {timeout:5000}, async t=>{
const {host}=await tailFixture(t,[]);
const main={outputId:'main_images',variantId:'oak'};
const detail={outputId:'detail',variantId:'oak'};
const slotId='cover';
const candidateId='product-photo';
const slot={id:slotId,fieldId:slotId,label:'主图'};
const pixels={type:'image',mimeType:'image/png',data:'fixture'};
const view=outputId=>({available:true,canvasFirst:true,version:1,outputId,productVariantId:'oak',
template:{contentHash:outputId},totalSlots:outputId===main.outputId?1:0,
slots:outputId===main.outputId?[slot]:[]});
let writes=0;
host.productionGoal.requestedOutputs=[detail,main];
host.bindGoalRequestScope=()=>{};
Object.assign(host.canvas,{
workflowRead:async()=>view(host.productionGoal.outputId),
detailHistory:async({targetOutput})=>view(targetOutput.outputId),
openProductionOutput:async target=>target,
imageRequest:async(action,request,_execution,target)=>{
if(action==='pending')return [];
assert.equal(action,'product_reference');
assert.equal(host.productionGoal.outputId,detail.outputId);
assert.deepEqual(target,{...main,templateHash:main.outputId});
assert.deepEqual(request,{slotId,referenceCrop:[100,200,800,900]});
return {id:candidateId,status:'complete'};
},
detailCandidateScreen:async(request,_signal,target)=>{
assert.deepEqual(target,main);
return {...request,page:0,screenFingerprint:'fixture',imageSlots:[slotId],overlayLayers:[],
copyFields:[],images:[pixels]};
},
detailImages:async(_slot,id,{targetOutput})=>{
assert.deepEqual(targetOutput,main);
return {candidateId:id,referenceCount:1,images:[pixels,pixels]};
},
read:async()=>({revision:1}),
requestWrite:async revision=>({allowed:true,revision}),
workflowExecute:async input=>{
assert.equal(host.productionGoal.outputId,main.outputId);
assert.equal(input.intent,'adopt_candidate');
writes++;
return {phase:'submitted',operationId:input.operationId,candidateId};
},
workflowPoll:async operationId=>({phase:'complete',operationId,candidateId}),
});
host.runDetailAgent=async(_slot,_system,_prompt,[review])=>{
await review.execute('',{candidateId,screenReview:passedScreen,verdict:'pass',
checks:{structure:true,color:true,composition:true,evidence:true},reason:'颜色与实拍相符'});
};
t.after(()=>closeProductionTurn(host));
const operations=await openOperations(host,{target:main,maxActiveDelegates:1});
host.productionWork=new Map([[JSON.stringify([main.outputId,main.variantId]),Promise.resolve(operations)]]);
const generated=await callProductionTool(host,'use_product_image',{...main,slotId,referenceCrop:[100,200,800,900]});
assert.equal(generated.phase,'accepted');
for(let attempt=0;operations.active&&attempt<100;attempt++){
await new Promise(resolve=>setTimeout(resolve,10));
}
assert.equal(operations.active,0);
const completed=await operations.await_image_slots({slotIds:[slotId]});
assert.equal(completed.generation[0].candidateId,candidateId);
const [review]=await callProductionTool(host,'check_image_slots',{...main,candidates:[{slotId,candidateId}],wait:true});
assert.equal(review.verdict,'pass',review.error);
assert.equal(writes,0);
const adoption=operations.adopt_production_image({slotId,candidateId});
assert.equal((await operations.await_image_slots({slotIds:[slotId]})).generation[0].phase,'waiting_canvas');
const [reviewWhileWaiting]=await callProductionTool(host,'check_image_slots',{...main,candidates:[{slotId,candidateId}],wait:true});
assert.equal(reviewWhileWaiting.verdict,'pass',reviewWhileWaiting.error);
await callProductionTool(host,'open_production_output',main);
assert.equal((await adoption).phase,'complete');
assert.equal(writes,1);
});
test('project image discovery can stage a completed image on another output without generation',async t=>{
@ -1421,6 +1490,7 @@ test('a lost native acknowledgement can be recovered with the saved generation o
const host={canvas,store,productionGoal:{outputId:'detail',variantId:'ink'}};
imageBridge(host,async(_args,operationId)=>{
submissions.push(operationId);
assert.equal((await host.canvas.imageRequest('read',{requestId:operationId})).requestId,operationId);
assert.equal(journal(),null);
throw new BridgeError('画布连接中断,原操作不会重发','transport_interrupted',{dispatched:true});
});

View File

@ -870,7 +870,7 @@ fn pending_production_images(dir: &Path, state: &Value) -> R<Value> {
fn reserve(dir: &Path, state: Value, record: &Value) -> R<()> {
reserve_candidate(dir, state, record, false)
}
fn reserve_candidate(dir: &Path, mut state: Value, record: &Value, admitted_dispatch: bool) -> R<()> {
fn reserve_candidate(dir: &Path, mut state: Value, record: &Value, project_scoped: bool) -> R<()> {
let _guard = sync::context_guard();
let original = load(dir)?;
let binding = &record["binding"];
@ -882,7 +882,7 @@ fn reserve_candidate(dir: &Path, mut state: Value, record: &Value, admitted_disp
} else {
check_image_context(dir, None, batch)?;
}
if admitted_dispatch {
if project_scoped {
let scoped = image_output_state(original.clone(), binding)?;
if !candidate_uses_current_inputs(dir, &scoped, record, binding["variantId"].as_str().ok_or("花色缺失")?)? {
return Err("商品资料或制作依据已变化,请重新准备请求".into());
@ -1054,7 +1054,7 @@ fn crop_product_photo(bytes: &[u8], region: &Value, frame: &Value, inside: bool)
photocraft_codecs::encode(&crop, photocraft_codecs::Format::Png, &Default::default()).map_err(|_| "局部图无法编码".into())
}
fn original_product_candidate(dir: &Path, state: Value, binding: Value, products: &Value, index: usize, frame: &Value) -> R<Value> {
fn original_product_candidate(dir: &Path, state: Value, binding: Value, products: &Value, index: usize, frame: &Value, project_scoped: bool) -> R<Value> {
let image = products.as_array().into_iter().flatten().filter(|row| row["purpose"] == "product")
.nth(index).ok_or("当前花色没有所选产品原图")?;
let id = uuid(&binding["candidateId"], "原图候选")?;
@ -1076,7 +1076,7 @@ fn original_product_candidate(dir: &Path, state: Value, binding: Value, products
let record = json!({"version":2,"id":id,"sequence":sequence,"binding":binding,"phase":"complete",
"sourceType":"product-reference","modelId":null,"inputHash":input_hash(dir,&state,variant_id)?,
"prompt":"产品原图","instructions":"产品原图","references":[image],"requestId":null,"artifact":artifact,"createdAt":now()});
reserve(dir, state, &record)?;
reserve_candidate(dir, state, &record, project_scoped)?;
Ok(record)
}
@ -3650,15 +3650,23 @@ impl Backend {
scoped_binding["imageFrame"] = json!({"width":frame["width"],"height":frame["height"]});
&scoped_binding
} else { binding };
if matches!(phase, "prepare" | "transform") {
if matches!(phase, "prepare" | "transform" | "product_reference") {
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["projectScopedPrepare"] = binding["projectScope"].clone();
let action = if phase == "transform" { "slot-transform-image" } else { "slot-prepare-image" };
input["projectScopedImage"] = binding["projectScope"].clone();
let action = match phase {
"transform" => "slot-transform-image",
"product_reference" => {
input["useProductReference"] = json!(true);
input["instructions"] = json!("产品原图");
"slot-append"
}
_ => "slot-prepare-image",
};
return self.canvas_workspace_action(action, &input, events, ctx).map_err(BridgeFailure::from);
}
if phase != "dispatch" { return Err("生图请求动作无效".into()); }
@ -3923,7 +3931,8 @@ impl Backend {
}
let batch = input["detailBatch"] == true && matches!(method, "slot-prepare-image" | "slot-append" | "slot-adopt-prep" | "slot-transform-image");
let mut state = if batch { load_detail_workspace(&dir)? } else { load(&dir)? };
if batch && method == "slot-prepare-image" && input["projectScopedPrepare"] == true {
let project_scoped_image = batch && input["projectScopedImage"] == true;
if project_scoped_image {
state = production_image_target(state, &input["detailWorkspace"])?;
}
if batch && input["detailWorkspace"] != json!({"id":state["id"],"templateHash":state["template"]["contentHash"],
@ -4117,6 +4126,9 @@ impl Backend {
if let Some(receipt) = view_receipt { return Ok(receipt); }
} else if method == "slot-transform-image" {
let record = jiansun_image_transform::stage_candidate(&dir, state, input)?;
if project_scoped_image {
return Ok(candidate_receipt(&record));
}
if let Ok((mut reference, preview)) = self.agent_image_preview(&json!({"doc":doc,"taskId":record["id"]})) {
reference["purpose"] = json!("template-candidate");
let _ = events.send(Event::Preview(reference, preview));
@ -4190,7 +4202,10 @@ impl Backend {
binding["referenceCropMode"] = json!(mode);
}
}
let record = original_product_candidate(&dir, state, binding, &images, index as usize, &field["frame"])?;
let record = original_product_candidate(&dir, state, binding, &images, index as usize, &field["frame"], project_scoped_image)?;
if project_scoped_image {
return Ok(candidate_receipt(&record));
}
if let Ok((mut reference, preview)) = self.agent_image_preview(&json!({"doc":doc,"taskId":candidate})) {
reference["purpose"] = json!("template-candidate");
let _ = events.send(Event::Preview(reference, preview));
@ -5822,8 +5837,27 @@ mod tests {
main["contentHash"] = json!(template_slots::pack_hash(&main).unwrap());
let detail = state["template"].clone();
state["productTemplates"] = json!({"detail":detail,"main_images":main});
let detail_mapping = mapping_key(&variant, "detail", None);
state["mappings"][&detail_mapping] = json!({"variantId":variant,
"fields":[{"slotId":slot,"nativeLayerId":17}]});
let dir_revision = revision(&state);
let state = persist(dir, production_output_state(state, "main_images", &variant).unwrap(), dir_revision).unwrap();
let target = json!({"id":state["id"],"templateHash":detail["contentHash"],"outputId":"detail","variantId":variant});
let original = json!({"action":"product_reference","projectScope":true,"scope":target,
"request":{"slotId":slot,"referenceIndex":0}});
let original = backend.production_image_request(doc, &original, &events, &ctx, None).unwrap();
let original_record = read_candidate(dir, original["id"].as_str().unwrap()).unwrap();
assert_eq!(candidate_pixels(dir, &original_record["artifact"]).unwrap(), pixels);
assert_eq!(original_record["binding"]["templateHash"], detail["contentHash"]);
let transformed = json!({"action":"transform","projectScope":true,"scope":target,
"request":{"slotId":slot,"sourceCandidateId":original["id"],"transform":{"flipX":true}}});
let transformed = backend.production_image_request(doc, &transformed, &events, &ctx, None).unwrap();
assert_eq!(transformed["status"], "complete");
let saved = load(dir).unwrap();
assert_eq!(saved["activeOutput"], "main_images");
assert_eq!(saved["activeMapping"], state["activeMapping"]);
assert_eq!(saved["template"], state["template"]);
assert!(saved["candidates"].as_array().unwrap().contains(&transformed["id"]));
write_json(&dir.join("template-outputs").join("canvas-adoption-fixture.json"), &json!({
"phase":"acknowledged","meta":{"workspaceId":state["id"],"candidateId":source_id}
})).unwrap();
@ -6908,7 +6942,7 @@ mod tests {
let references = generation_references(&project, &state, &variant).unwrap();
let target = json!({"variantId":variant,"templateHash":state["template"]["contentHash"],"slotId":slot,
"outputId":"detail","candidateId":id});
let record = original_product_candidate(&project, state, binding, &references, 0, &Value::Null).unwrap();
let record = original_product_candidate(&project, state, binding, &references, 0, &Value::Null, false).unwrap();
let job = project.join("image-jobs").join(&id);
assert_eq!(fs::read(job.join("generated.png")).unwrap(), pixels);
assert_eq!(candidate_receipt(&record)["sourceType"], "product-reference");

View File

@ -3,7 +3,7 @@
use super::{
Digest, Path, R, Sha256, Uuid, Value, candidate_available, candidate_pixels, candidate_uses_current_inputs, crop_product_image, definition,
generation_references, hash, image_output_component, input_hash, json, local_product_photo, mapped_slot, material_task_id, new_binding, now, output_uses_variant,
product_slot_binding, read_candidate, reserve, slot_frame, template_slots, uuid, write_json,
product_slot_binding, read_candidate, reserve_candidate, slot_frame, template_slots, uuid, write_json,
};
use image::{Rgba, Rgba32FImage, imageops};
use photocraft_codecs::{ChannelLayout, Image, SampleType};
@ -105,7 +105,7 @@ pub(super) fn stage_candidate(dir: &Path, state: Value, input: &Value) -> R<Valu
"references":references,"requestId":null,"artifact":artifact,"createdAt":now(),
"parentCandidateId":edit["sourceCandidateId"],"canvasTransform":edit,
"materialTaskId":original_task,"sourceRequestId":original_request,"reusedFrom":ancestry});
reserve(dir, state, &record)?;
reserve_candidate(dir, state, &record, input["projectScopedImage"] == true)?;
Ok(record)
}

View File

@ -350,7 +350,7 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
&& input["candidatePreview"].is_object() && input["candidatePreview"]["adopted"] != true);
let scoped_image = private && method == "pi-image-request"
&& (input["action"] == "pending" || input["targetOutput"].is_object()
&& matches!(input["action"].as_str(), Some("read" | "prepare" | "dispatch")));
&& matches!(input["action"].as_str(), Some("read" | "prepare" | "dispatch" | "transform" | "product_reference")));
if w.production_boundary_pending() && !scoped_read && !(opening && scoped_image) && !matches!(method,
"pi-state" | "pi-activity" | "pi-delta" | "pi-context-usage" | "pi-production-open"
| "pi-production-finish" | "pi-production-finish-status" | "pi-workflow-poll" | "pi-native-poll" | "pi-end") {
@ -617,7 +617,7 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
"templateHash":w.template_workflow["templateHash"],"canvasLayerId":canvas_layer}))
}
"pi-image-request" => {
let action = input["action"].as_str().filter(|action| matches!(*action,"prepare"|"dispatch"|"transform"|"read"|"pending"))
let action = input["action"].as_str().filter(|action| matches!(*action,"prepare"|"dispatch"|"transform"|"product_reference"|"read"|"pending"))
.ok_or("生图请求动作无效")?;
if action == "pending" || action == "read" && !scoped_image {
if w.pi_request_scope["productProduction"] != true {
@ -641,6 +641,7 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
"prepare" => &["slotId","instructions","geometryReferenceIndex","prefer2k","retryOf","reworkOf","reworkChange",
"referenceIndexes","useTemplateReference","useSceneComposite"],
"transform" => &["slotId","sourceCandidateId","referenceIndex","transform"],
"product_reference" => &["slotId","referenceIndex","referenceCrop"],
"read" => &["requestId"],
_ => &["requestId","expectedRevision","expectedHash","slotId","workerNumber"],
};
@ -1048,11 +1049,13 @@ mod tests {
"variantId":"oak","templateHash":"main-pack","slots":[]});
let ctx = egui::Context::default();
input["targetOutput"] = detail.clone();
for action in ["prepare", "dispatch", "read"] {
for action in ["prepare", "dispatch", "read", "transform", "product_reference"] {
input["action"] = json!(action);
input["request"] = match action {
"prepare" => json!({"slotId":"detail-slot","instructions":"准备首屏"}),
"dispatch" => json!({"slotId":"detail-slot","requestId":"saved-request"}),
"transform" => json!({"slotId":"detail-slot","referenceIndex":0,"transform":{}}),
"product_reference" => json!({"slotId":"detail-slot","referenceIndex":0}),
_ => json!({"requestId":"saved-request"}),
};
let reply = private_action_in_ui(&mut w, &mut app, &ctx, "pi-image-request", &input).unwrap();
@ -1062,10 +1065,6 @@ mod tests {
}
input["targetOutput"]["variantId"] = json!("other");
assert!(private_action_in_ui(&mut w, &mut app, &ctx, "pi-image-request", &input).is_err());
input["action"] = json!("transform");
input["targetOutput"] = detail;
input["request"] = json!({"slotId":"detail-slot","referenceIndex":0,"transform":{}});
assert!(private_action_in_ui(&mut w, &mut app, &ctx, "pi-image-request", &input).is_err());
input["text"] = json!("");
input["production"] = json!({"outputId":"detail","variantId":"oak","waitingCanvas":2});
private_action_in_ui(&mut w, &mut app, &ctx, "pi-delta", &input).unwrap();