fix(xiaoyi): refresh unchanged copy fields and review same-product archives

This commit is contained in:
WuYongJie 2026-11-26 11:39:53 +08:00
parent af46f80f10
commit cbe66a920b
5 changed files with 131 additions and 62 deletions

View File

@ -46,7 +46,7 @@ export const productionOperationTools = [
})],
['await_image_slots','等待指定图位的任一子代理或验图返回。',obj({slotIds:optional(ids)})],
['review_image_slots','只读查看当前制作输出的候选、验图、原请求与覆盖统计。未指定图位时只回各图位一行状态。指定 slotIds 获取候选、原请求、验图详细结论与提示词。',obj({slotIds:optional(Type.Array(Type.String()))})],
['read_archived_images','只读查找其他本机项目同款、同模板图位的历史候选和原请求编号。可按 slotIds 缩小范围。',obj({
['read_archived_images','只读查找其他本机项目同款的历史候选。可选 slotIds 查看有对应图位的结果。不同模板或花色的已完成候选也可放入当前图位复核。',obj({
slotIds:optional(Type.Array(Type.String())),
})],
['stage_archived_image','把已完成的候选加入当前目标图位待验,沿用其原素材任务。来源是本项目已知候选时省略 projectId,来源是另一同款项目时使用 read_archived_images 返回的 projectId。请按目标图位复核再决定是否采用。',obj({
@ -126,6 +126,7 @@ export async function openProductionOperations(host) {
}
return {requested,matched,unmatched};
};
const copyReads=new Map();
const seenLayouts=new Set();
let seenProduct=false;
const jobs=new Map(), generation=new Map(), reviewWork=new Set(), candidates=new Map(), filled=new Set(slots.filter(s=>s.selectedCandidateId).map(s=>s.id));
@ -340,40 +341,70 @@ export async function openProductionOperations(host) {
async read_copy_fields({pageId,fieldId}){
pageId=pageId?.trim()||undefined;
fieldId=fieldId?.trim()||undefined;
const {revision}=await canvas.read();
const current=await canvas.detailCopyFields({includeFilled:true,pageId,fieldId});
return {...current,revision:(await canvas.read()).revision};
const end=await canvas.read();
if(end.revision===revision){
const snapshot=copyReads.get(revision)??new Map();
for(const field of current.fields??[])snapshot.set(field.layer,field.currentText);
copyReads.set(revision,snapshot);
}
return {...current,revision:end.revision};
},
write_copy_fields({revision,recordOnly,items=[]},signal){
return serialize(async()=>{
if(!items.length)return {appliedLayers:[],revision:(await canvas.read()).revision};
const inputPlan=await current();
if((await canvas.read()).revision!==revision)throw Error('画布修订已变化,请重新读取文字格');
const before=new Map((await fields()).map(field=>[field.layer,field]));
const targetFields=async()=>new Map((await fields()).map(field=>[field.layer,field]));
let result={appliedLayers:[]};
if(!recordOnly){
signal?.throwIfAborted();
const receipt=await canvas.requestWrite(revision);
if(receipt.retryWrite)return deferredCopyWrite(receipt,revision);
if(!receipt.allowed||receipt.revision!==revision)throw Error('画布修订已变化或用户已接手');
result=await canvas.detailApplyCopy(items.map(({layer,text})=>({layer,text,expectedText:before.get(layer)?.currentText})),revision);
if(result.retryWrite)return deferredCopyWrite(await canvas.read(),revision);
const submit=async(expected,before)=>{
signal?.throwIfAborted();
const receipt=await canvas.requestWrite(expected);
if(receipt.retryWrite)return deferredCopyWrite(receipt,expected);
if(!receipt.allowed||receipt.revision!==expected)throw Error('画布修订已变化或用户已接手');
const reply=await canvas.detailApplyCopy(items.map(({layer,text})=>({layer,text,expectedText:before.get(layer)?.currentText})),expected);
return reply.retryWrite?deferredCopyWrite(await canvas.read(),expected):reply;
};
let expected=(await canvas.read()).revision;
let before=await targetFields();
if(expected===revision){
result=await submit(expected,before);
if(!result.retryWrite)return await registerCopy(result);
expected=result.revision;
if(expected===revision)return result;
}
const sampled=copyReads.get(revision);
await current();
before=await targetFields();
const live=await canvas.read();
if(live.revision!==expected||live.writeBlocked||live.conversationActive===false||
!items.every(({layer})=>sampled?.has(layer)&&before.has(layer)&&sampled.get(layer)===before.get(layer).currentText)){
return deferredCopyWrite(live,revision);
}
result=await submit(expected,before);
if(result.retryWrite)return result;
}
return await registerCopy(result);
async function registerCopy(result){
const after=new Map((await fields()).map(field=>[field.layer,field]));
const applied=items.filter(row=>(recordOnly||result.appliedLayers?.includes(row.layer))&&after.get(row.layer)?.currentText===row.text);
await update(()=>{
syncCopyEvidence(inputPlan);
journal.copyEvidence??={};
for(const {layer,text,sources,pictures,reason} of applied){
journal.copyEvidence[layer]={field:after.get(layer).field,text,sources,pictures,
...(!text.trim()&&reason?.trim()?{blankReason:reason}:null)};
}
if(result.styleMappings?.length){
journal.copyStyleMappings??={};
for(const {layer,mapping} of result.styleMappings)journal.copyStyleMappings[layer]=mapping;
}
});
await notice('文字已更新');
return {...result,appliedLayers:applied.map(row=>row.layer),revision:(await canvas.read()).revision};
}
const after=new Map((await fields()).map(field=>[field.layer,field]));
const applied=items.filter(row=>(recordOnly||result.appliedLayers?.includes(row.layer))&&after.get(row.layer)?.currentText===row.text);
await update(()=>{
syncCopyEvidence(inputPlan);
journal.copyEvidence??={};
for(const {layer,text,sources,pictures,reason} of applied){
journal.copyEvidence[layer]={field:after.get(layer).field,text,sources,pictures,
...(!text.trim()&&reason?.trim()?{blankReason:reason}:null)};
}
if(result.styleMappings?.length){
journal.copyStyleMappings??={};
for(const {layer,mapping} of result.styleMappings)journal.copyStyleMappings[layer]=mapping;
}
});
await notice('文字已更新');
return {...result,appliedLayers:applied.map(row=>row.layer),revision:(await canvas.read()).revision};
});
},
async read_slot_images(args){
@ -516,7 +547,7 @@ export async function openProductionOperations(host) {
},
async read_archived_images({slotIds}){
const {requested,matched,unmatched}=readSelection(slotIds);
const history=await canvas.detailHistory();
const history=await canvas.detailHistory({sameProductOnly:true});
const candidates=history.filter(row=>!requested.size||matched.has(row.slotId))
.map(row=>({...row,fieldId:byId.get(row.slotId)?.fieldId}));
return {outputId,variantId,candidates,...(unmatched.length?{unmatched}:{})};

View File

@ -30,7 +30,7 @@ export class StdioCanvas {
detailCopyFields(options) { return this.#observe('pi-detail-copy-fields', options); }
detailApplyCopy(items,revision) { return this.action('pi-detail-copy-apply',{items,revision}); }
detailRetire(slotId,candidateId,reason) { return this.action('pi-detail-archive',{slotId,source:{candidateId,retireReason:reason}}); }
detailHistory() { return this.action('pi-detail-archive'); }
detailHistory(options) { return this.action('pi-detail-archive',options); }
detailArchive(slotId,{projectId,candidateId,forReview}) { return this.action('pi-detail-archive',{slotId,source:{projectId,candidateId,forReview}}); }
detailRecover(slotId,{projectId,candidateId}) { return this.action('pi-detail-archive',{slotId,source:{projectId,candidateId,recover:true}}); }
detailImages(slotId,candidateId,options) { return this.#observe('pi-detail-images', {slotId,candidateId,...options}); }

View File

@ -445,7 +445,16 @@ test('Pi chooses each image operation and keeps an unresolved paid request on it
assert.equal(fields[0].currentText,'');
}
waitingAt=undefined;
assert.deepEqual((await actions.write_copy_fields(proposal)).appliedLayers,[7]);
const beforeIndependentEdit=await actions.read_copy_fields({});
revision++;
assert.deepEqual((await actions.write_copy_fields({...proposal,revision:beforeIndependentEdit.revision})).appliedLayers,[7]);
const beforeUserEdit=await actions.read_copy_fields({});
fields[0].currentText='用户手改';
revision++;
const rejected=await actions.write_copy_fields({...proposal,revision:beforeUserEdit.revision});
assert.equal(rejected.retryWrite,true);
assert.deepEqual(rejected.appliedLayers,[]);
assert.equal(fields[0].currentText,'用户手改');
const first=await generateAndWait(actions,{slotId:'lamp',source:'generate',prompt:'场景桌面上的一盏灯',prefer2k:true});
assert.equal(first.phase,'unknown');
assert.equal(host.nativeUnresolved,originalNative);

View File

@ -1285,10 +1285,10 @@ fn retire_candidate(dir: &Path, target: &Value, reason: &str) -> R<Value> {
fn same_production_product(current: &Value, source: &Value) -> bool {
current["brief"]["identifier"].as_str().is_some_and(|id| !id.is_empty())
&& ["identifier","brandId","categoryId"].iter().all(|key| current["brief"][*key] == source["brief"][*key])
&& ["identifier","identifierType","brandId"].iter().all(|key| current["brief"][*key] == source["brief"][*key])
}
fn production_image_history(dir: &Path, state: &Value, variant_id: &str, scope: &str) -> R<Value> {
fn production_image_history(dir: &Path, state: &Value, variant_id: &str, scope: &str, same_product_only: bool) -> R<Value> {
let Some(account_projects) = dir.parent() else { return Err("当前项目目录无效".into()) };
let selected = variant(state, variant_id)?;
let references = generation_references(dir, state, variant_id)?;
@ -1312,18 +1312,21 @@ fn production_image_history(dir: &Path, state: &Value, variant_id: &str, scope:
let binding = &record["binding"];
let archived = record["sourceType"] == "archived-candidate";
let product_crop = record["sourceType"] == "product-reference" && binding["referenceCrop"].is_array();
if binding["templateHash"] != *template || !product_slot_binding(&previous, binding)
|| (!product_crop && (record["references"] != references || (record["sourceType"].is_string() && !archived)))
{ continue; }
if !product_slot_binding(&previous, binding) || !product_crop && record["sourceType"].is_string() && !archived {
continue;
}
let Some(old_variant) = binding["variantId"].as_str().and_then(|id| variant(&previous, id).ok()) else { continue };
if ["colorName","colorMaterialId","dimensions"].iter().any(|key| old_variant[*key] != selected[*key]) { continue; }
let Some(field) = binding["fieldId"].as_str() else { continue };
let slot = slot_id(template, variant_id, field);
let Ok((output, field)) = definition(state, &slot, variant_id) else { continue };
if output["component"] != state["activeOutput"] || output["id"] != binding["outputId"] { continue; }
let Some(source_field) = binding["fieldId"].as_str() else { continue };
let slot = slot_id(template, variant_id, source_field);
let exact = binding["templateHash"] == *template
&& ["colorName","colorMaterialId","dimensions"].iter().all(|key| old_variant[*key] == selected[*key])
&& (product_crop || record["references"] == references);
let target = exact.then(|| definition(state, &slot, variant_id).ok()).flatten()
.filter(|(output, _)| output["component"] == state["activeOutput"] && output["id"] == binding["outputId"]);
if target.is_none() && !same_product_only { continue; }
// The previous review only determines what to inspect first.
// Adoption always requires a fresh review against the current copy and frame.
let preferred = record["phase"] == "complete" && old_variant["id"].as_str().is_some_and(|previous_id| {
let preferred = target.is_some() && record["phase"] == "complete" && old_variant["id"].as_str().is_some_and(|previous_id| {
let journal = reviews.entry(previous_id).or_insert_with(|| {
let file = review_path.join(format!("production-{component}-{previous_id}.json"));
let receipt = read_json(&file).unwrap_or_default();
@ -1336,7 +1339,7 @@ fn production_image_history(dir: &Path, state: &Value, variant_id: &str, scope:
approval["candidateId"] == id && approval["decision"] == "pass")
});
if product_crop {
if !preferred { continue; }
let Some((output, field)) = target.filter(|_| preferred) else { continue };
let Ok(mode) = product_crop_mode(state, output, field) else { continue };
if binding["referenceCropMode"].as_str() != mode { continue; }
let Some(source) = record["references"][0]["source"].as_str() else { continue };
@ -1368,8 +1371,12 @@ fn production_image_history(dir: &Path, state: &Value, variant_id: &str, scope:
if phase == "complete" && preferred {
preferred_sources.insert((project.clone(), id.to_owned()));
}
result.push((project.clone(), id.to_owned(), json!({"slotId":slot,"projectId":project,"candidateId":id,"phase":phase,
"requestId":task["requestId"],"createdAt":record["createdAt"]})));
if target.is_none() && phase != "complete" { continue; }
result.push((project.clone(), id.to_owned(), json!({
"slotId":target.is_some().then_some(slot),"projectId":project,"candidateId":id,"phase":phase,
"requestId":task["requestId"],"createdAt":record["createdAt"],"originalFieldId":source_field,
"originalOutputId":binding["outputId"],"originalTemplateHash":binding["templateHash"],
"originalColor":old_variant["colorName"]})));
}
}
let mut result: Vec<_> = result.into_iter().map(|(project, id, row)| {
@ -1435,12 +1442,14 @@ fn reuse_archived_candidate(dir: &Path, state: Value, input: &Value, preflight:
current.iter().any(|image| image["source"] == reference["source"]))))
} else {
same_production_product(&state, &source_state)
&& archived_binding["templateHash"] == state["template"]["contentHash"]
&& archived_binding["fieldId"] == field["fieldId"] && archived_binding["outputId"] == output["id"]
&& source_record["references"] == original_refs && source_record["requestId"].is_string()
&& (input["forReview"] == true || (
archived_binding["templateHash"] == state["template"]["contentHash"]
&& archived_binding["fieldId"] == field["fieldId"] && archived_binding["outputId"] == output["id"]
&& source_record["references"] == original_refs))
&& source_record["requestId"].is_string()
};
if !scope_matches || !candidate_available(&source_record) {
return Err("原候选未完成或与当前商品原图和图位范围不一致,请查看已完成候选".into());
return Err("原候选未完成或不属于同款商品,请查看同款的已完成候选".into());
}
let source_task = read_json(&source.join("image-jobs").join(&candidate).join("task.json"))?;
if source_task["phase"] != "complete" || source_task["id"] != candidate
@ -1820,7 +1829,7 @@ impl Backend {
return Err("本轮原生候选范围已变化".into());
}
if target["source"].is_null() {
return production_image_history(&dir, &state, &variant_id, &self.scope());
return production_image_history(&dir, &state, &variant_id, &self.scope(), target["sameProductOnly"] == true);
}
if target["source"]["recover"] == true {
let candidate = uuid(&target["source"]["candidateId"], "原候选")?;
@ -1834,7 +1843,7 @@ impl Backend {
(dir.clone(), doc, Some(record))
} else {
let local = uuid(&target["source"]["projectId"], "历史原项目")?;
let history = production_image_history(&dir, &state, &variant_id, &self.scope())?;
let history = production_image_history(&dir, &state, &variant_id, &self.scope(), false)?;
if !history.as_array().into_iter().flatten().any(|item|
item["slotId"] == target["slotId"] && item["projectId"] == local && item["candidateId"] == candidate
&& matches!(item["phase"].as_str(), Some("unknown" | "complete" | "failed")))
@ -1893,7 +1902,8 @@ impl Backend {
}
let preflight = (target["source"]["forReview"] != true).then_some(&*self);
let record = reuse_archived_candidate(&dir, state, &json!({"slotId":target["slotId"],"variantId":variant_id,
"sourceProjectId":target["source"]["projectId"],"sourceCandidateId":target["source"]["candidateId"],"detailBatch":true}), preflight)?;
"sourceProjectId":target["source"]["projectId"],"sourceCandidateId":target["source"]["candidateId"],
"forReview":target["source"]["forReview"],"detailBatch":true}), preflight)?;
if record["status"] == "skipped" {
return Ok(record);
}
@ -3847,12 +3857,20 @@ mod tests {
let variant = state["activeVariantId"].as_str().unwrap();
let field = older["slotBinding"]["fieldId"].as_str().unwrap();
let slot = slot_id(&state["template"]["contentHash"], variant, field);
let history = production_image_history(&target,&state,variant,"isolated-fixture").unwrap();
let history = production_image_history(&target,&state,variant,"isolated-fixture",false).unwrap();
for row in [&older, &newer] {
assert!(history.as_array().unwrap().iter().any(|item|
item["slotId"] == slot && item["candidateId"] == row["id"] && item["requestId"] == row["requestId"]));
}
let mut another_color = state.clone();
another_color["variants"][0]["colorName"] = json!("另一个待复核花色");
let broader = production_image_history(&target, &another_color, variant, "isolated-fixture", true).unwrap();
assert!(broader.as_array().unwrap().iter().any(|item| item["candidateId"] == staged_from
&& item["phase"] == "complete" && item["slotId"].is_null()));
another_color["brief"]["identifier"] = json!("unrelated-fixture");
assert_eq!(production_image_history(&target, &another_color, variant, "isolated-fixture", true).unwrap(), json!([]));
let request = json!({"slotId":slot,"variantId":variant,"sourceProjectId":input["sourceProjectId"],
"sourceCandidateId":staged_from,"detailBatch":true});
let record = reuse_archived_candidate(&target, state.clone(), &request, None).unwrap();
@ -3876,6 +3894,13 @@ mod tests {
.find(|row| row["kind"] == "image" && row["fieldId"] != field).unwrap();
let second_field = second_field["fieldId"].as_str().unwrap();
let second_slot = slot_id(&state["template"]["contentHash"], variant, second_field);
let other_field = json!({"slotId":second_slot,"variantId":variant,"sourceProjectId":input["sourceProjectId"],
"sourceCandidateId":reworked,"detailBatch":true,"forReview":true});
let reindexed = reuse_archived_candidate(&target, state.clone(), &other_field, None).unwrap();
assert_eq!(reindexed["sourceRequestId"], newer["requestId"]);
assert_eq!(reindexed["binding"]["fieldId"], second_field);
assert_eq!(fs::read(target.join("image-jobs").join(reindexed["id"].as_str().unwrap()).join("generated.png")).unwrap(),
fs::read(reworked_file.with_file_name("generated.png")).unwrap());
let alias = reuse_archived_candidate(&target, state.clone(), &json!({"slotId":second_slot,"variantId":variant,
"sourceCandidateId":staged_id,"detailBatch":true}), None).unwrap();
assert_ne!(alias["id"], record["id"]);
@ -3904,7 +3929,7 @@ mod tests {
state["activeOutput"] = json!("main_images");
let variant = state["activeVariantId"].as_str().unwrap().to_owned();
let scope = dir.parent().and_then(Path::parent).and_then(Path::file_name).unwrap().to_string_lossy();
let rows = production_image_history(&dir, &state, &variant, &scope).unwrap();
let rows = production_image_history(&dir, &state, &variant, &scope, false).unwrap();
let slot = slot_id(&state["template"]["contentHash"], &variant, "M02-I01");
let archives = rows.as_array().unwrap().iter().filter(|row| row["slotId"] == slot && row["phase"] == "complete").collect::<Vec<_>>();
let held = rows.as_array().unwrap().iter().filter(|row| row["phase"] == "unknown").count();
@ -3916,7 +3941,7 @@ mod tests {
row["slotId"] == slot && row["phase"] == "complete").take(4).collect::<Vec<_>>();
println!("{}", json!({"target":"M03-I01","first":accepted_history}));
state["brief"]["identifier"] = json!("unrelated-product");
assert_eq!(production_image_history(&dir, &state, &variant, &scope).unwrap(), json!([]));
assert_eq!(production_image_history(&dir, &state, &variant, &scope, false).unwrap(), json!([]));
}
#[test]
@ -3930,7 +3955,7 @@ mod tests {
state["activeOutput"] = json!("detail");
let current_variant = state["activeVariantId"].as_str().unwrap();
let slot = slot_id(&state["template"]["contentHash"], current_variant, "S02-I04");
let history = production_image_history(&dir, &state, current_variant, &scope).unwrap();
let history = production_image_history(&dir, &state, current_variant, &scope, false).unwrap();
let candidates: Vec<_> = history.as_array().unwrap().iter().filter(|row|
row["slotId"] == slot && row["phase"] == "complete").collect();
let ranked = candidates.first().expect("completed same-product candidates");
@ -3963,7 +3988,7 @@ mod tests {
state["activeOutput"] = json!("detail");
let variant_id = state["activeVariantId"].as_str().unwrap().to_owned();
let slot = slot_id(&state["template"]["contentHash"], &variant_id, "S02-I06");
let history = production_image_history(&dir, &state, &variant_id, &scope).unwrap();
let history = production_image_history(&dir, &state, &variant_id, &scope, false).unwrap();
let crop = history.as_array().unwrap().iter().find(|row| row["slotId"] == slot && row["phase"] == "product-crop")
.expect("reviewed crop for this template and product");
let candidate_id = crop["candidateId"].as_str().unwrap();
@ -3977,7 +4002,7 @@ mod tests {
for variant in state["variants"].as_array_mut().unwrap() {
variant["images"].as_array_mut().unwrap().retain(|row| row["source"] != *source);
}
let without_source = production_image_history(&dir, &state, &variant_id, &scope).unwrap();
let without_source = production_image_history(&dir, &state, &variant_id, &scope, false).unwrap();
assert!(without_source.as_array().unwrap().iter().all(|row| row["candidateId"] != candidate_id));
println!("{}", json!({"field":"S02-I06","crop":crop,"source":source}));
}
@ -4920,7 +4945,7 @@ mod tests {
for copy in &used {
assert_eq!(candidate_pixels(&target,&copy["artifact"]).unwrap(), before[0].1);
}
let remaining = production_image_history(&target, &target_state, target_variant, "isolated-fixture").unwrap();
let remaining = production_image_history(&target, &target_state, target_variant, "isolated-fixture", false).unwrap();
assert!(remaining.as_array().unwrap().iter().all(|row|
row["projectId"] != source_id || row["candidateId"] != first && row["candidateId"] != second));
let proof = json!({"removedCandidate":unrelated,"retainedSharedMaterial":retained,"verifiedAliases":used.len(),

View File

@ -355,10 +355,13 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
if w.pi_request_scope["wholeDetail"] != true || w.pi_write_blocked || !w.allow_apply || !w.queue.is_empty() {
return Err("文案未取得当前画布写入许可,原内容保留".into());
}
let active = app.session.active().filter(|active| active.revision == w.expected_revision).ok_or("画布已变化")?;
if input["revision"].as_u64() != Some(active.revision) || super::canvas_workspace::detail_write_waiting(w, app) {
let active = app.session.active().ok_or("原项目未打开")?;
if active.revision != w.expected_revision || input["revision"].as_u64() != Some(active.revision)
|| super::canvas_workspace::detail_write_waiting(w, app)
{
let revision = active.revision;
w.allow_apply = false;
return Ok(json!({"retryWrite":true}));
return Ok(json!({"retryWrite":true,"revision":revision}));
}
let production = w.pi_request_scope["productProduction"] == true;
let fields = detail_copy_fields(&active.doc, production, None, None);
@ -375,10 +378,10 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
continue;
};
let current = field["currentText"].as_str().unwrap_or_default();
if w.product_layer_protected(id) { continue; }
if current.trim().is_empty() {
if !w.detail_layer_unchanged(&active.doc, id) { continue; }
} else if w.product_layer_protected(id)
|| item["expectedText"].as_str() != Some(current)
} else if item["expectedText"].as_str() != Some(current)
|| active.doc.path_of(id).is_none_or(|path| {
let locks = active.doc.locks_at(&path);
locks.all || locks.position || locks.pixels
@ -472,6 +475,7 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
.and_then(|slot| slot["nativeLayerId"].as_u64())
});
Ok(json!({"slotId":input["slotId"],"source":input["source"],"workspaceId":w.template_workflow["workspaceId"],
"sameProductOnly":input["sameProductOnly"] == true,
"outputId":w.pi_request_scope["outputId"],"variantId":w.pi_request_scope["variantId"],
"templateHash":w.template_workflow["templateHash"],"canvasLayerId":canvas_layer}))
}