diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs index 4b03c700..0aa8a255 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs @@ -958,12 +958,15 @@ fn reserve_candidate(dir: &Path, mut state: Value, record: &Value, project_scope let original = load(dir)?; let binding = &record["binding"]; let batch = (binding["detailBatch"] == true).then_some(binding); - if record["sourceType"] == "archived-candidate" && record["phase"] == "complete" { + if record["phase"] == "complete" && (record["sourceType"] == "archived-candidate" + || record["origin"] == "human" && local_candidate(record)) + { if creation::load(dir)?["brief"] != original["brief"] { - return Err("产品资料已变化,未复用旧候选".into()); + return Err("产品资料已变化,未添加候选".into()); } } else { - check_image_context(dir, None, batch)?; + let manual = (binding["origin"] == "human").then_some(binding); + check_image_context(dir, None, batch.or(manual))?; } if project_scoped { let scoped = image_output_state(original.clone(), binding)?; @@ -972,7 +975,7 @@ fn reserve_candidate(dir: &Path, mut state: Value, record: &Value, project_scope } state = original; } else if revision(&state) != revision(&original) { - if batch.is_none() || ["structureHash", "id", "activeVariantId", "activeOutput", "mappings"].iter().any(|key| original[*key] != state[*key]) + if (batch.is_none() && record["origin"] != "human") || ["structureHash", "id", "activeVariantId", "activeOutput", "mappings"].iter().any(|key| original[*key] != state[*key]) || !candidate_uses_current_inputs(dir, &original, record, binding["variantId"].as_str().ok_or("花色身份无效")?)? { return Err("画布已有新版本,未预留候选".into()); @@ -1135,25 +1138,61 @@ fn crop_product_photo(bytes: &[u8], region: &Value, frame: &Value, inside: bool) fn original_product_candidate(dir: &Path, state: Value, binding: Value, products: &Value, index: usize, frame: &Value, project_scoped: bool) -> R { let image = products.as_array().into_iter().flatten().filter(|row| row["purpose"] == "product") .nth(index).ok_or("当前花色没有所选产品原图。用 read_slot_images 查看当前图位的 productReferences,从清单中选择 reference(如 P01)。")?; - let id = uuid(&binding["candidateId"], "原图候选")?; - let job = dir.join("image-jobs").join(&id); let mut bytes = local_product_photo(dir, image)?; if let Some(region) = binding.get("referenceCrop") { let inside = matches!(binding["referenceCropMode"].as_str(), Some("inside" | "cover")); bytes = crop_product_photo(&bytes, region, frame, inside)?; } + stage_local_image(dir, state, binding, "product-reference", json!([image]), &bytes, project_scoped) +} + +fn product_reference_index(value: &Value) -> R { + if value.is_null() { return Ok(0); } + value.as_u64().filter(|&index| index < 8).map(|index| index as usize) + .ok_or_else(|| "所选商品原图编号无效".into()) +} + +fn import_local_candidate(dir: &Path, state: Value, output: &Value, field: &Value, slot: &str, variant: &str, input: &Value) -> R { + use std::io::Read; + const MAX_IMPORT: u64 = 64 * 1024 * 1024; + let path = input["localPath"].as_str().map(Path::new).filter(|path| path.is_absolute() && path.is_file()) + .ok_or("请选择本机图片文件")?; + let file = fs::File::open(path).map_err(|_| "本机图片无法读取")?; + let mut bytes = Vec::new(); + file.take(MAX_IMPORT + 1).read_to_end(&mut bytes).map_err(|_| "本机图片无法读取")?; + if bytes.len() as u64 > MAX_IMPORT { return Err("本机图片超过 64 MB".into()); } + let image = photocraft_codecs::decode_with(&bytes, &photocraft_codecs::DecodeOptions { + limits: photocraft_codecs::Limits { max_width: 8192, max_height: 8192, max_pixels: 24_000_000, max_alloc: 192 * 1024 * 1024 }, + ..Default::default() + }).map_err(|_| "本机图片无法解码或尺寸超过限制")?; + let png = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()) + .map_err(|_| "本机图片无法保存为候选")?; + let id = Uuid::new_v4().to_string(); + let mut binding = new_binding(&state, output, field, slot, variant, &id, "本机导入"); + binding["origin"] = json!("human"); + stage_local_image(dir, state, binding, "local-import", json!([]), &png, false) +} + +fn stage_local_image(dir: &Path, state: Value, binding: Value, source: &str, references: Value, bytes: &[u8], project_scoped: bool) -> R { + if bytes.len() > 20 * 1024 * 1024 { + return Err("图片转为候选格式后超过 20 MB".into()); + } + let id = uuid(&binding["candidateId"], "候选")?; + let job = dir.join("image-jobs").join(&id); let journal = json!({"version":1,"id":id,"phase":"complete","slotBinding":binding,"requestId":null, - "sourceType":"product-reference","sha256":format!("{:x}", Sha256::digest(&bytes))}); + "sourceType":source,"sha256":format!("{:x}", Sha256::digest(bytes))}); // Stage a complete local artifact before publishing its candidate. This // branch never creates an upstream request or an unknown task. write_json(&job.join("task.json"), &journal)?; - photocraft_format::atomic_write(&job.join("generated.png"), &bytes).map_err(|_| "产品原图无法保存为候选")?; + photocraft_format::atomic_write(&job.join("generated.png"), bytes).map_err(|_| "本机图片无法保存为候选")?; let artifact = template_slots::artifact(dir, &id, &journal)?; let variant_id = binding["variantId"].as_str().ok_or("花色身份无效")?; let sequence = state["candidates"].as_array().ok_or("候选索引无效")?.len() + 1; - 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()}); + let label = if source == "local-import" { "本机导入" } else { "产品原图" }; + let mut record = json!({"version":2,"id":id,"sequence":sequence,"binding":binding,"phase":"complete", + "sourceType":source,"modelId":null,"inputHash":input_hash(dir,&state,variant_id)?, + "prompt":label,"instructions":label,"references":references,"requestId":null,"artifact":artifact,"createdAt":now()}); + if binding["origin"] == "human" { record["origin"] = json!("human"); } reserve_candidate(dir, state, &record, project_scoped)?; Ok(record) } @@ -1194,6 +1233,7 @@ fn candidate_receipt(record: &Value) -> Value { receipt["status"] = json!("retired"); receipt["message"] = record["retirement"]["reason"].clone(); } + if record["origin"] == "human" { receipt["origin"] = json!("human"); } if record["phase"] == "complete" { receipt["materialTaskId"] = material_task_id(record).clone(); } if record["generationEvidence"].is_object() { receipt["generationEvidence"] = record["generationEvidence"].clone(); } if record["phase"] == "expired" { @@ -1205,7 +1245,7 @@ fn candidate_receipt(record: &Value) -> Value { receipt["retryableFailure"] = json!(true); receipt["retryAfterSeconds"] = record["retryAfterSeconds"].clone(); } - if matches!(record["sourceType"].as_str(), Some("product-reference" | "archived-candidate")) { + if matches!(record["sourceType"].as_str(), Some("product-reference" | "archived-candidate" | "local-import")) { receipt["sourceType"] = record["sourceType"].clone(); } if record["sourceType"] == "archived-candidate" { @@ -1363,8 +1403,8 @@ fn slot_dispatch_usage(dir: &Path, state: &Value, slot: &Value, batch: &[String] } let task = candidate_projection_task(dir, &record)?; let dispatched = generation_was_dispatched(&record, task.as_ref()); - generations += u64::from(dispatched); - if dispatched || local_candidate(&record) { used += 1; } + generations += u64::from(dispatched && record["origin"] != "human"); + if automated_candidate(&record) && (dispatched || local_candidate(&record)) { used += 1; } if record["id"].as_str() != current && !batch.iter().any(|id| record["id"] == id.as_str()) && candidate_needs_recovery(dir, &record)? { pending = Some(record["id"].clone()); @@ -1373,6 +1413,10 @@ fn slot_dispatch_usage(dir: &Path, state: &Value, slot: &Value, batch: &[String] Ok((used, generations, pending)) } +fn automated_candidate(record: &Value) -> bool { + record["origin"] != "human" && record["retirement"].is_null() +} + fn local_candidate(record: &Value) -> bool { !record["sourceType"].is_null() || !record["reusedFrom"].is_null() } @@ -1806,10 +1850,16 @@ fn pending(dir: &Path, state: &Value, creation: &Value, except: Option<&Value>, } fn local_pending(dir: &Path, state: &Value, except: Option<&Value>, batch: Option<&Value>) -> R { - if !creation::pending_text_tasks(dir)?.is_empty() { + let manual = except.or(batch).filter(|binding| binding["origin"] == "human"); + if manual.is_none() && !creation::pending_text_tasks(dir)?.is_empty() { return Ok(true); } for record in records(dir, state)? { + if manual.is_some_and(|target| record["binding"]["slotId"] != target["slotId"] + || record["binding"]["variantId"] != target["variantId"]) + { + continue; + } if !except.is_some_and(|binding| record["binding"] == *binding && matches!(record["phase"].as_str(), Some("prepared" | "dispatched"))) && !batch.is_some_and(|binding| { let sibling = &record["binding"]; @@ -2927,6 +2977,54 @@ pub(super) fn delivery_inputs_match( current_export_inputs(state, Some(creation), &creation["revision"], variant, component, receipt) } +pub(super) const STALE_DELIVERY_EXPORT: &str = "画布在导出后已修改,请重新导出该组"; + +fn edited_delivery_canvas(dir: &Path, state: &Value, variant: &str, component: &str) -> R> { + let key = mapping_key(variant, component, None); + let edited = dir.join("template-outputs").join(format!("canvas-{key}-edited.pcraft")); + let active = dir.join("canvas.pcraft"); + let modified = |path: &Path| match fs::metadata(path) { + Ok(metadata) => metadata.modified().map(Some).map_err(|error| error.to_string()), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(error) => Err(error.to_string()), + }; + let edited_time = modified(&edited)?; + if state["activeOutput"] == component && state["activeVariantId"] == variant + && modified(&active)?.is_some_and(|time| Some(time) > edited_time) + { + let canvas = super::load_draft(dir, &active).map_err(|_| "当前画布无法读取,请保存后重新导出")?; + if mapping(&canvas).is_some_and(|meta| meta["workspaceId"] == state["id"] + && meta["variantId"] == variant && meta["component"] == component) + { + return Ok(Some(active)); + } + } + Ok(edited_time.map(|_| edited)) +} + +pub(super) fn check_delivery_source( + dir: &Path, state: &Value, variant: &str, component: &str, receipt: &Value, +) -> R<()> { + let source = &receipt["sourceDocument"]; + let Some(path) = edited_delivery_canvas(dir, state, variant, component)? else { + return if source["workingSha256"].is_string() { Err(STALE_DELIVERY_EXPORT.into()) } else { Ok(()) }; + }; + let expected = source["sha256"].as_str().ok_or(STALE_DELIVERY_EXPORT)?; + let actual = file_digest(&path).map_err(|_| STALE_DELIVERY_EXPORT)?; + if source["workingSha256"] == actual || actual == expected { + return Ok(()); + } + // Draft checkpoints can reference an object store, while the exported + // document is self-contained. Compare equivalent portable encodings. + let saved = super::load_draft(dir, &path).map_err(|_| STALE_DELIVERY_EXPORT)?; + let bytes = photocraft_format::save_to_bytes(&saved, &Default::default()) + .map_err(|_| STALE_DELIVERY_EXPORT)?; + if format!("{:x}", Sha256::digest(bytes)) != expected { + return Err(STALE_DELIVERY_EXPORT.into()); + } + Ok(()) +} + pub(super) fn check_delivery_export( dir: &Path, state: &Value, creation: &Value, variant: &str, component: &str, receipt: &Value, ) -> R<()> { @@ -2940,6 +3038,7 @@ pub(super) fn check_delivery_export( if !delivery_inputs_match(state, creation, variant, component, receipt) { return Err("商品资料或制作设置与上次导出不同,请重新导出该组".into()); } + check_delivery_source(dir, state, variant, component, receipt)?; if receipt_uses_retired_image(dir, receipt) { return Err("该组成品使用了已退回的图片,请核对画布后重新导出".into()); } @@ -2972,8 +3071,10 @@ fn current_export_inputs( } fn receipt_uses_retired_image(dir: &Path, receipt: &Value) -> bool { - receipt["imageSources"].as_array().into_iter().flatten().any(|source| - source["candidateId"].as_str().is_some_and(|id| retired_archive(dir, id))) + receipt["imageSources"].as_array().into_iter().flatten().any(|source| { + !(source["origin"] == "human" && source["candidateArtifact"].is_null()) + && source["candidateId"].as_str().is_some_and(|id| retired_archive(dir, id)) + }) } pub(super) fn remaining_stages(dir: &Path, state: &Value, brief_revision: &Value, verify_editable: bool) -> Vec { @@ -3054,6 +3155,9 @@ fn candidate_export_source(dir: &Path, record: &Value) -> Value { source["kind"] = json!("reused"); source["reusedFrom"] = record["reusedFrom"].clone(); source["requestId"] = record["sourceRequestId"].clone(); + } else if record["sourceType"] == "local-import" { + source["kind"] = json!("local-import"); + source["origin"] = json!("human"); } else if record["sourceType"] == "product-reference" { source["kind"] = json!("product-reference"); if let Some(crop) = record["binding"].get("referenceCrop") { @@ -3072,11 +3176,38 @@ fn candidate_export_source(dir: &Path, record: &Value) -> Value { source } -fn export_image_sources(dir: &Path, doc: &Document, state: &Value, meta: &Value, component: &str, variant: &str, aspects: &Value) -> (Vec, Vec, Vec) { +pub(super) fn manual_image_source(doc: &Document, layer: &photocraft_doc::Layer, variant: &str, slot: &str) -> Option { + use photocraft_doc::{LayerContent, SmartSource}; + let marker = format!("jiansun.manual-image.{variant}.{slot}"); + let (_, value) = doc.metadata.text.iter().find(|(key, _)| *key == marker)?; + let record: Value = serde_json::from_str(value).ok()?; + let source = record["source"].as_str().filter(|source| matches!(*source, "professional-edit" | "local-import"))?; + let sha = record["sha256"].as_str().filter(|sha| sha.len() == 64 && sha.bytes().all(|b| b.is_ascii_hexdigit()))?; + let embedded = match &layer.content { + LayerContent::Smart(smart) => { + let SmartSource::Embedded { bytes, .. } = &smart.source else { return None; }; + let actual = format!("{:x}", Sha256::digest(bytes.as_slice())); + if actual != sha { return None; } + Some(actual) + } + LayerContent::Raster(surface) if !surface.content_bounds().is_empty() => None, + _ => return None, + }; + Some(json!({"kind":source,"origin":"human","sha256":sha,"embeddedSha256":embedded, + "updatedAt":record["updatedAt"],"candidateId":record["candidateId"]})) +} + +pub(super) const COVERAGE_FIELDS: [&str; 6] = ["adopted", "manual", "unadoptedWithCandidates", "empty", "skipped", "total"]; + +fn export_image_sources(dir: &Path, doc: &Document, state: &Value, meta: &Value, component: &str, variant: &str, aspects: &Value) -> (Vec, Vec, Vec, Value) { use photocraft_doc::{LayerContent, LayerId, SmartSource}; let mut missing = Vec::new(); let mut invalid_sources = Vec::new(); let mut sources = Vec::new(); + let mut coverage = json!({"adopted":0,"manual":0,"unadoptedWithCandidates":0,"empty":0,"skipped":0,"total":0}); + let available_slots: std::collections::HashSet<_> = state["candidates"].as_array().into_iter().flatten() + .filter_map(Value::as_str).filter_map(|id| read_candidate(dir, id).ok()) + .filter(candidate_available).filter_map(|record| record["binding"]["slotId"].as_str().map(str::to_owned)).collect(); let template = &state["template"]; let current_input = input_hash(dir, state, variant).ok(); for page in production_export_pages(template, component, aspects) { @@ -3096,34 +3227,53 @@ fn export_image_sources(dir: &Path, doc: &Document, state: &Value, meta: &Value, !input.starts_with(VARIANT_INPUT_HASH) || current_input.as_deref() == Some(input))); let visible = layer_path.as_ref().is_some_and(|path| (1..=path.len()) .all(|len| doc.layer_at(&path[..len]).is_some_and(|layer| layer.visible && layer.opacity > 0.0))); - let found = layer_path.zip(record).and_then(|(path, record)| { - let layer = doc.layer_at(&path)?; - let LayerContent::Smart(smart) = &layer.content else { return None; }; - let SmartSource::Embedded { file_name, bytes } = &smart.source else { return None; }; - if file_name != "candidate.png" || !matches_placed_candidate(dir, &record["artifact"], bytes) { - return None; - } - let mut source = candidate_export_source(dir, &record); + let manual_key = format!("jiansun.manual-image.{variant}.{slot}"); + let found = layer_path.as_deref().and_then(|path| { + let layer = doc.layer_at(path)?; + let mut source = if let Some(manual) = manual_image_source(doc, layer, variant, &slot) { + manual + } else { + let record = record?; + let LayerContent::Smart(smart) = &layer.content else { return None; }; + let SmartSource::Embedded { file_name, bytes } = &smart.source else { return None; }; + if file_name != "candidate.png" || !matches_placed_candidate(dir, &record["artifact"], bytes) { + return None; + } + let mut source = candidate_export_source(dir, &record); + source["embeddedSha256"] = json!(fidelity::embedded_hash(layer)); + source["embeddedSize"] = json!(creation::png_size(bytes).ok()); + source + }; source["pageId"] = page["id"].clone(); source["fieldId"] = json!(id); source["slotId"] = json!(slot); source["nativeLayerId"] = json!(layer.id.0); source["variantId"] = json!(variant); - source["embeddedSha256"] = json!(fidelity::embedded_hash(layer)); - source["embeddedSize"] = json!(creation::png_size(bytes).ok()); Some(source) }); - if found.is_none() && adopted.is_some() { - invalid_sources.push(id.to_owned()); - } - if let Some(source) = found.filter(|_| visible) { - sources.push(source); + let skipped_key = format!("jiansun.skipped-image.{variant}.{slot}"); + let skipped = doc.metadata.text.iter().any(|(key, raw)| *key == skipped_key + && serde_json::from_str::(raw).is_ok_and(|status| status["status"] == "skipped")); + let status = if let Some(source) = found.as_ref().filter(|_| visible) { + let status = if matches!(source["kind"].as_str(), Some("professional-edit" | "local-import")) { + "manual" + } else { "adopted" }; + sources.push(source.clone()); + status + } else if skipped { + "skipped" } else { + if found.is_none() && (adopted.is_some() || doc.metadata.text.iter().any(|(key, _)| *key == manual_key)) { + invalid_sources.push(id.to_owned()); + } missing.push(id.to_owned()); - } + if available_slots.contains(&slot) { "unadoptedWithCandidates" } else { "empty" } + }; + coverage[status] = json!(coverage[status].as_u64().unwrap_or(0) + 1); + coverage["total"] = json!(coverage["total"].as_u64().unwrap_or(0) + 1); } } - (missing, invalid_sources, sources) + (missing, invalid_sources, sources, coverage) } fn unverified_export_copy( @@ -3139,6 +3289,12 @@ fn unverified_export_copy( .is_some_and(|node| node.visible && node.opacity > 0.0)) { return None; } let LayerContent::Text(text) = &doc.layer_at(&path)?.content else { return None; }; if text.text.trim().is_empty() { return None; } + let marker = format!("jiansun.manual-text.{layer}"); + if doc.metadata.text.iter().any(|(key, raw)| *key == marker + && serde_json::from_str::(raw).is_ok_and(|record| record["source"] == "human" && record["sha256"] == hash(&text.text))) + { + return None; + } let recorded = &journal["copyEvidence"][layer.to_string()]; let verified = recorded["field"] == field_id && recorded["text"] == text.text && recorded["sources"].as_array().is_some_and(|sources| !sources.is_empty()) @@ -3791,12 +3947,17 @@ pub(super) fn export_saved_production_output( .ok_or("制作输出缺失")?; let variant = uuid(&output["variantId"], "制作款式")?; let state = load(dir)?; - let key = mapping_key(&variant, component, None); - let native = super::load_draft(dir, &dir.join("template-outputs").join(format!("canvas-{key}-edited.pcraft"))) - .map_err(|_| "该输出没有已保存的可编辑画布")?; + let live = { + let _guard = sync::context_guard(); + let path = edited_delivery_canvas(dir, &state, &variant, component)? + .ok_or("该输出没有已保存的可编辑画布")?; + let native = super::load_draft(dir, &path).map_err(|_| "该输出的编辑稿无法读取")?; + let sha = file_digest(&path).map_err(|_| "无法核对编辑稿内容")?; + (native, sha) + }; let input = json!({"workspaceId":workspace,"outputId":component,"variantId":variant, "complete":true,"deliveryReason":reason}); - export_product_stage_snapshot(dir, doc, &state, &input, scope, Some(&native)) + export_product_stage_with_source(dir, doc, &state, &input, scope, Some(&live.0), Some(&live.1)) } fn export_product_stage(dir: &Path, doc: u64, state: &Value, input: &Value, scope: &str) -> R { @@ -3857,7 +4018,20 @@ pub(super) fn publish_product_generation( || reopened.layer_count() != native.layer_count() || reopened.metadata.text != native.metadata.text { return Err("成品工程重开后与本轮画布的身份、图层或页面信息不一致".into()); } - let reopen_verification = fidelity::reopen(native, &reopened, &result["imageSources"]); + let (manual, adopted): (Vec<_>, Vec<_>) = result["imageSources"].as_array().into_iter().flatten() + .cloned().partition(|source| source["origin"] == "human" && source["candidateArtifact"].is_null()); + let mut reopen_verification = fidelity::reopen(native, &reopened, &json!(adopted)); + if !manual.is_empty() { + let verified: Vec<_> = manual.iter().map(|source| { + let consistent = source["nativeLayerId"].as_u64().and_then(|id| reopened.layer(photocraft_doc::LayerId(id))) + .and_then(|layer| manual_image_source(&reopened, layer, source["variantId"].as_str()?, source["slotId"].as_str()?)) + .is_some_and(|saved| saved["sha256"] == source["sha256"]); + json!({"slotId":source["slotId"],"sha256":source["sha256"],"consistent":consistent}) + }).collect(); + reopen_verification["consistent"] = json!(reopen_verification["consistent"] == true + && verified.iter().all(|row| row["consistent"] == true)); + reopen_verification["manualImages"] = json!(verified); + } super::transfer::check_pcraft_file(&editable)?; let layered = export_layered_document(generation.path(), component, id, &reopened)?; let exported_mapping = mapping(&reopened); @@ -3919,6 +4093,9 @@ pub(super) fn publish_product_generation( result["sourceDocument"] = json!({"path":editable,"format":"pcraft","role":"editable","generationId":id, "revision":document_revision,"reopened":true,"width":reopened.size.width,"height":reopened.size.height, "sizeBytes":size,"sha256":sha}); + if let Some(working_sha) = result.as_object_mut().and_then(|row| row.remove("workingSha256")) { + result["sourceDocument"]["workingSha256"] = working_sha; + } result["layeredDocument"] = layered; result["files"] = json!(files); if !split.is_empty() { result["screenFiles"] = json!(split); } @@ -3940,6 +4117,13 @@ pub(super) fn publish_product_generation( } fn export_product_stage_snapshot(dir: &Path, doc: u64, state: &Value, input: &Value, scope: &str, snapshot: Option<&Document>) -> R { + export_product_stage_with_source(dir, doc, state, input, scope, snapshot, None) +} + +fn export_product_stage_with_source( + dir: &Path, doc: u64, state: &Value, input: &Value, scope: &str, + snapshot: Option<&Document>, working_sha: Option<&str>, +) -> R { let component = input["outputId"].as_str().filter(|kind| SUPPORTED_PRODUCTION_OUTPUTS.contains(kind)).ok_or("制作输出缺失")?; let variant_id = uuid(&input["variantId"], "制作款式")?; if !state["productTemplates"].is_object() || input["workspaceId"] != state["id"] @@ -3986,16 +4170,21 @@ fn export_product_stage_snapshot(dir: &Path, doc: u64, state: &Value, input: &Va result["productionDelivery"] = json!({"state":"blocked","outputId":component}); Ok(result) }; - let key = mapping_key(&variant_id, component, None); - let editable = dir.join("template-outputs").join(format!("canvas-{key}-edited.pcraft")); let loaded; let native = match snapshot { Some(canvas) => canvas, None => { - loaded = super::load_draft(dir, &editable).map_err(|_| "可编辑画布无法读取")?; + let _guard = sync::context_guard(); + let path = edited_delivery_canvas(dir, state, &variant_id, component)? + .ok_or("本组没有已保存的可编辑画布")?; + loaded = super::load_draft(dir, &path).map_err(|_| "可编辑画布无法读取")?; + result["workingSha256"] = json!(file_digest(&path).map_err(|_| "无法核对编辑稿内容")?); &loaded } }; + if let Some(sha) = working_sha { + result["workingSha256"] = json!(sha); + } let meta = mapping(native).ok_or("可编辑画布缺少图层映射")?; if snapshot.is_some() && input["canvasRevision"].is_u64() && (native.id.0 != doc || input["canvasRevision"] != input["baseRevision"]) @@ -4029,7 +4218,13 @@ fn export_product_stage_snapshot(dir: &Path, doc: u64, state: &Value, input: &Va } else { result["warnings"] = json!([production_profile::UNPUBLISHED_FIXED_TEXT]); } - let (missing, invalid_sources, image_sources) = export_image_sources(dir, native, state, &meta, component, &variant_id, &aspects); + let (missing, invalid_sources, image_sources, coverage) = export_image_sources(dir, native, state, &meta, component, &variant_id, &aspects); + result["slotCoverage"] = coverage; + let missing_issues: Vec<_> = missing.iter().map(|field| json!({ + "outputId":component,"variantId":variant_id,"field":field,"reason":"图位尚未采用图片" + })).collect(); + result["knownIssues"] = json!(missing_issues); + result["allOutputsCompleted"] = json!(false); if !missing.is_empty() { result["missingImages"] = json!(missing); } @@ -4100,6 +4295,15 @@ fn export_product_stage_snapshot(dir: &Path, doc: u64, state: &Value, input: &Va result["imageSources"] = json!(image_sources); result["unverifiedFacts"] = json!(input["unverifiedFacts"].as_array().map_or(&[][..], Vec::as_slice)); if !aspects.is_null() { result["mainImageAspects"] = aspects; } + let all_filled = missing.is_empty() && production_stages(state).iter().all(|stage| { + let variant = stage["variantId"].as_str().unwrap_or_default(); + let output = stage["outputId"].as_str().unwrap_or_default(); + (variant == variant_id && output == component) || + published_receipt(&receipt_path(dir, variant, output)).is_ok_and(|receipt| + receipt["missingImages"].as_array().is_none_or(Vec::is_empty)) + }); + result["allOutputsCompleted"] = json!(all_filled && remaining_stages(dir, state, &result["briefRevision"], false) + .iter().all(|stage| stage["variantId"] == variant_id && stage["outputId"] == component)); let blank_reasons: serde_json::Map = journal["copyEvidence"].as_object().into_iter().flatten() .filter(|(_, row)| row["text"].as_str().is_some_and(|text| text.trim().is_empty())) .filter_map(|(id, row)| { @@ -4114,13 +4318,14 @@ fn export_product_stage_snapshot(dir: &Path, doc: u64, state: &Value, input: &Va if remaining.is_empty() { remaining = remaining_stages(dir, state, &result["briefRevision"], true); } - if remaining.is_empty() + result["allOutputsCompleted"] = json!(remaining.is_empty() && all_filled); + if remaining.is_empty() && all_filled && let Some(goal) = input["piGoalId"].as_str() && let Err(error) = super::pi_runtime::record_product_export(dir, scope, goal) { result["goalSyncError"] = json!(error); } - result["productionDelivery"] = json!({"state":if remaining.is_empty() {"completed"} else {"in_progress"}, + result["productionDelivery"] = json!({"state":if remaining.is_empty() && all_filled {"completed"} else {"in_progress"}, "outputState":"exported","outputId":component,"generationId":result["generationId"]}); result["productionStages"] = json!(runnable_stages(state, remaining)); Ok(result) @@ -4217,11 +4422,11 @@ fn snapshot_for_view(dir: &Path, view: Option, read_only: bool) -> R "slot-transform-image", "product_reference" => { @@ -4434,7 +4639,8 @@ impl Backend { }; if used >= max { return Ok(candidate_limit_receipt(&source_slot, used, max)); } if action != "slot-prepare-image" { - return self.canvas_workspace_action(action, &input, events, ctx).map_err(BridgeFailure::from); + return self.canvas_workspace_action_with_source(action, &input, events, ctx, transform_source) + .map_err(BridgeFailure::from); } if generations >= generation_cap { return Ok(generation_limit_receipt(&source_slot, used, max, generations, generation_cap)); @@ -4562,7 +4768,7 @@ impl Backend { let slot = &task["slotBinding"]; let state = if slot["detailBatch"] == true { load_detail_workspace(dir)? } else { load(dir)? }; let record = &task["candidateRecord"]; - let _slot_dispatch = if production.is_none() && slot["detailBatch"] == true { + let _slot_dispatch = if production.is_none() && (slot["detailBatch"] == true || slot["origin"] == "human") { Some(lock_slot_dispatch(dir, slot)?.ok_or("本图位已有生图批次正在处理")?) } else { None }; let admitted = production.is_some() && slot["detailBatch"] == true; @@ -4705,7 +4911,15 @@ impl Backend { } pub(super) fn canvas_workspace_action(&mut self, method: &str, input: &Value, events: &mpsc::Sender, ctx: &egui::Context) -> R { - if !matches!(method, "slot-read" | "slot-recover" | "slot-templates" | "slot-adopted") { + self.canvas_workspace_action_with_source(method, input, events, ctx, None) + } + + fn canvas_workspace_action_with_source(&mut self, method: &str, input: &Value, events: &mpsc::Sender, + ctx: &egui::Context, source: Option, + ) -> R { + let import = method == "slot-import-local" || method == "slot-append" && input["localPath"].is_string(); + let local = import || method == "slot-append" && input["useProductReference"] == true; + if !local && !matches!(method, "slot-read" | "slot-recover" | "slot-templates" | "slot-adopted") { self.check_dispatch()?; } let doc = input["doc"].as_u64().ok_or("请先打开项目")?; @@ -5049,7 +5263,7 @@ impl Backend { events.send(Event::SlotCanvas(Box::new(native), result)).map_err(|_| "工作台已关闭,模板骨架记录保留")?; 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)?; + let record = jiansun_image_transform::stage_candidate(&dir, state, input, source)?; if project_scoped_image { return Ok(candidate_receipt(&record)); } @@ -5063,7 +5277,7 @@ impl Backend { } ctx.request_repaint(); return Ok(receipt); - } else if matches!(method, "slot-prepare-image" | "slot-append") { + } else if import || matches!(method, "slot-prepare-image" | "slot-append") { let variant_id = uuid(&input["variantId"], "花色")?; let id = input["slotId"].as_str().ok_or("请选择图片目标")?.to_owned(); let (output, field) = definition(&state, &id, &variant_id)?; @@ -5085,7 +5299,11 @@ impl Backend { .ok_or("请先打开对应模板画布,核对图片图层范围")?.clone(); let output = output.clone(); let preparing = method == "slot-prepare-image"; - let instructions = input["instructions"].as_str() + if import { + let record = import_local_candidate(&dir, state, &output, &field, &id, &variant_id, input)?; + return Ok(operation_receipt(self.canvas_workspace_result(doc, &dir)?, Some(candidate_receipt(&record)), None)); + } + let instructions = input["instructions"].as_str().or_else(|| local.then_some("产品原图")) .filter(|value| !value.chars().any(|c| c.is_control() && !matches!(c, '\n' | '\r' | '\t'))) .ok_or("图片要求须为文本且不能含控制字符")?; let parent = input.get("parentCandidateId").filter(|v| !v.is_null()).map(|value| uuid(value, "原候选")).transpose()?; @@ -5123,19 +5341,15 @@ impl Backend { } let candidate = Uuid::new_v4().to_string(); let mut binding = new_binding(&state, &output, &field, &id, &variant_id, &candidate, "产品原图"); - if input["detailBatch"] == true { binding["detailBatch"] = json!(true); } - let index = input["referenceIndex"].as_u64().unwrap_or(0); - if index >= 8 || input.get("referenceIndex").is_some() && (input["detailBatch"] != true || !state["productTemplates"].is_object()) { - return Err("当前任务不能使用所选商品原图".into()); - } - if let Some(crop) = input.get("referenceCrop") { - if input["detailBatch"] != true { return Err("局部取景仅用于整套制作的实物证据图".into()); } + if batch { binding["detailBatch"] = json!(true); } else { binding["origin"] = json!("human"); } + let index = product_reference_index(&input["referenceIndex"])?; + if let Some(crop) = input.get("referenceCrop").filter(|value| !value.is_null()) { binding["referenceCrop"] = crop.clone(); if let Some(mode @ ("inside" | "cover")) = product_crop_mode(&state, &output, &field)? { binding["referenceCropMode"] = json!(mode); } } - let record = original_product_candidate(&dir, state, binding, &images, index as usize, &field["frame"], project_scoped_image)?; + let record = original_product_candidate(&dir, state, binding, &images, index, &field["frame"], project_scoped_image)?; if project_scoped_image { return Ok(candidate_receipt(&record)); } @@ -5191,8 +5405,10 @@ impl Backend { let mut binding = new_binding(&state, &output, &field, &id, &variant_id, &candidate, instructions); if input["detailBatch"] == true { binding["detailBatch"] = json!(true); } if preparing { binding["frozenImageRequest"] = json!(true); } + if !batch && !preparing { binding["origin"] = json!("human"); } if !attachment_refs.as_array().is_none_or(Vec::is_empty) { binding["composerHash"] = json!(hash(&attachment_refs.to_string())); } let mut record = json!({"version":2,"id":candidate,"sequence":state["candidates"].as_array().ok_or("候选索引无效")?.len()+1,"binding":binding,"phase":"prepared","modelId":model,"inputHash":input_hash(&dir,&state,&variant_id)?,"prompt":instructions,"instructions":instructions,"parentCandidateId":parent,"references":images,"requestId":null,"createdAt":now()}); + if binding["origin"] == "human" { record["origin"] = json!("human"); } 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 let Some(operation) = input["workflowOperationId"].as_str() { record["workflowOperationId"] = json!(operation); } @@ -5235,7 +5451,7 @@ impl Backend { let candidate = uuid(input.get("candidateId").filter(|value| !value.is_null()).unwrap_or(&input["taskId"]), "原候选")?; let record = read_candidate(&dir, &candidate)?; checked_binding(&dir, &record["binding"], true)?; - if record["sourceType"] == "product-reference" || record["canvasTransform"].is_object() { + if matches!(record["sourceType"].as_str(), Some("product-reference" | "local-import")) || record["canvasTransform"].is_object() { return Ok(operation_receipt(self.canvas_workspace_result(doc, &dir)?, Some(candidate_receipt(&record)), None)); } let Some(_dispatch) = lock_candidate_dispatch(&dir, &candidate)? else { @@ -5303,7 +5519,7 @@ impl Backend { meta["variantBrief"] = json!({"row":variant_brief(&state["brief"], &variant_id), "shared":shared_variant_brief(&state["brief"])}); } - if method == "slot-adopt-prep" && batch && state["productTemplates"].is_object() + if method == "slot-adopt-prep" && state["productTemplates"].is_object() && let Some(component) = output["component"].as_str() && let Some(profile) = production_profile::select(&state["template"], component)? && let Some(field) = field["fieldId"].as_str() @@ -6691,10 +6907,22 @@ mod tests { save(&doc); let result = export_product_stage(&fixture.dir, 1, &state, &input, "test-account").unwrap(); assert_eq!(result["missingImages"], json!(["S01-I01"])); + assert_eq!(result["slotCoverage"], json!({"adopted":0,"manual":0,"unadoptedWithCandidates":0,"empty":1,"skipped":0,"total":1})); + assert_eq!(result["allOutputsCompleted"], false); + assert_eq!(result["knownIssues"][0]["field"], "S01-I01"); assert_eq!(result["productionDelivery"]["outputState"], "exported"); assert!(artifact_matches(&result["files"][0], true)); assert!(receipt_path(&fixture.dir,variant,"detail").exists()); + let slot = slot_id(&state["template"]["contentHash"], variant, "S01-I01"); + let mut skipped = doc.clone(); + skipped.metadata.text.push((format!("jiansun.skipped-image.{variant}.{slot}"), + json!({"status":"skipped","reason":"不需要这一张"}).to_string())); + let (missing, _, _, coverage) = export_image_sources( + &fixture.dir, &skipped, &state, &meta, "detail", variant, &Value::Null); + assert!(missing.is_empty()); + assert_eq!(coverage["skipped"], 1); + let mut agent_input = input.clone(); agent_input["writeEpoch"] = json!(1); agent_input["deliveryReason"] = json!("用户手动停止并交付"); @@ -6811,7 +7039,7 @@ mod tests { assert!(artifact_matches(&ready["sourceDocument"], true)); assert!(artifact_matches(&snapshot["sourceDocument"], true)); let reopened = photocraft_format::load_path(Path::new(snapshot["editable"].as_str().unwrap())).unwrap(); - let (missing, _, source_links) = export_image_sources(&fixture.dir, &reopened, &state, &meta, "detail", variant, &Value::Null); + let (missing, _, source_links, _) = export_image_sources(&fixture.dir, &reopened, &state, &meta, "detail", variant, &Value::Null); assert!(missing.is_empty()); assert_eq!(snapshot["imageSources"], json!(source_links)); assert_eq!(snapshot["imageSources"][0]["fieldId"], "S01-I01"); @@ -6820,6 +7048,24 @@ mod tests { assert_eq!(snapshot["imageSources"][0]["materialTaskId"], candidate["id"]); assert_eq!(snapshot["imageSources"][0]["embeddedSize"], json!([8,4])); assert_eq!(snapshot["reopenVerification"]["adoptions"][0]["consistent"], true); + let mut manual = doc.clone(); + manual.metadata.text.push((format!("jiansun.manual-image.{variant}.{slot}"), + json!({"source":"professional-edit","sha256":snapshot["imageSources"][0]["embeddedSha256"],"updatedAt":1}).to_string())); + manual.metadata.text.push((format!("jiansun.manual-text.{caption_id}"), + json!({"source":"human","sha256":hash("圆弧前缘")}).to_string())); + assert!(unverified_export_copy(&manual, &meta, &Value::Null).is_empty()); + let (missing, invalid, sources, coverage) = export_image_sources( + &fixture.dir, &manual, &state, &meta, "detail", variant, &Value::Null); + assert!(missing.is_empty() && invalid.is_empty()); + assert_eq!(coverage["manual"], 1); + assert_eq!(sources[0]["kind"], "professional-edit"); + let source = jiansun_image_transform::adopted_source( + &fixture.dir, &state, &json!({"sourceSlotId":slot}), variant, Some(&manual)).unwrap(); + assert!(matches!(source, jiansun_image_transform::SlotSource::Manual { evidence, .. } + if evidence["kind"] == "professional-edit")); + let mut facts = json!({"page":0}); + slot_image_facts::SlotImageReader::default().read(&fixture.dir, &Arc::new(manual.clone()), &mut facts); + assert_eq!(facts["slotImageFacts"][0]["source"]["kind"], "professional-edit"); assert_eq!(snapshot["unverifiedFacts"], bound["unverifiedFacts"]); let saved = published_receipt(&receipt_path(&fixture.dir, variant, "detail")).unwrap(); assert_eq!(saved["unverifiedFacts"], bound["unverifiedFacts"]); @@ -6836,6 +7082,9 @@ mod tests { .iter().any(|stage| stage["outputId"] == "detail" && stage["variantId"] == variant); assert!(!pending()); let creation = creation::load(&fixture.dir).unwrap(); + assert_eq!(check_delivery_export(&fixture.dir, &state, &creation, variant, "detail", &snapshot).unwrap_err(), + STALE_DELIVERY_EXPORT); + save(&doc); let mut moved = snapshot.clone(); moved["editable"] = json!("old-project/plate.pcraft"); moved["sourceDocument"]["path"] = moved["editable"].clone(); @@ -6886,6 +7135,20 @@ mod tests { assert_eq!(exported["unverifiedCopy"], json!(["S01-T01"])); assert_eq!(exported["productionDelivery"]["outputState"], "exported"); assert!(artifact_matches(&exported["files"][0], true)); + + let active = fixture.dir.join("canvas.pcraft"); + fs::write(&active, photocraft_format::save_to_bytes(&manual, &Default::default()).unwrap()).unwrap(); + fs::File::options().write(true).open(&active).unwrap().set_modified( + fs::metadata(&edited).unwrap().modified().unwrap() + std::time::Duration::from_secs(1)).unwrap(); + assert_eq!(check_delivery_export(&fixture.dir, &state, &creation, variant, "detail", &exported).unwrap_err(), + STALE_DELIVERY_EXPORT); + super::super::material_delivery::refresh_stale_exports(&fixture.dir, 1, "test-account").unwrap(); + let fresh = published_receipt(&receipt).unwrap(); + assert_ne!(fresh["generationId"], exported["generationId"]); + assert_eq!(fresh["sourceDocument"]["workingSha256"], file_digest(&active).unwrap()); + assert_eq!(fresh["slotCoverage"]["manual"], 1); + assert_eq!(fresh["reopenVerification"]["manualImages"][0]["consistent"], true); + check_delivery_export(&fixture.dir, &state, &creation, variant, "detail", &fresh).unwrap(); } #[test] @@ -7867,6 +8130,21 @@ mod tests { } } + #[test] + fn manual_pending_check_is_limited_to_the_target_slot() { + let fixture = fixture(); + let dir = &fixture.dir; + let original = candidate(dir, "unknown"); + reserve(dir, load(dir).unwrap(), &original).unwrap(); + let state = load(dir).unwrap(); + let mut target = original["binding"].clone(); + target["origin"] = json!("human"); + assert!(local_pending(dir, &state, None, Some(&target)).unwrap()); + target["slotId"] = json!("another-slot"); + assert!(!local_pending(dir, &state, None, Some(&target)).unwrap()); + assert!(local_pending(dir, &state, None, None).unwrap()); + } + #[test] fn unknown_reservation_blocks_new_candidates_and_existing_task_never_redispatches() { let fixture = fixture(); @@ -8467,7 +8745,12 @@ mod tests { let dir = project.join("creation-assets"); fs::create_dir_all(&dir).unwrap(); fs::write(dir.join(format!("{digest}.png")), &pixels).unwrap(); - state["brief"]["images"] = json!([{"name":"实物图","source":format!("local:{digest}"),"purpose":"product"}]); + let first = photocraft_codecs::Image::from_u8(1, 1, photocraft_codecs::ChannelLayout::Rgb, vec![40, 40, 40]).unwrap(); + let first = photocraft_codecs::encode(&first, photocraft_codecs::Format::Png, &Default::default()).unwrap(); + let first_digest = format!("{:x}", Sha256::digest(&first)); + fs::write(dir.join(format!("{first_digest}.png")), first).unwrap(); + state["brief"]["images"] = json!([{"name":"实物图","source":format!("local:{first_digest}"),"purpose":"product"}, + {"name":"第二张实物图","source":format!("local:{digest}"),"purpose":"product"}]); let mut current = creation::load(&project).unwrap(); current["brief"] = state["brief"].clone(); write_json(&project.join("creation.json"), ¤t).unwrap(); @@ -8477,12 +8760,23 @@ mod tests { let output = &state["template"]["outputs"][0]; let field = &output["slots"][0]; let slot = slot_id(&state["template"]["contentHash"], &variant, field["fieldId"].as_str().unwrap()); - let id = Uuid::new_v4().to_string(); - let binding = new_binding(&state, output, field, &slot, &variant, &id, "产品原图"); - let references = generation_references(&project, &state, &variant).unwrap(); + let (events, _receiver) = mpsc::channel(); + let ctx = egui::Context::default(); + let mut request = json!({"doc":doc,"baseRevision":1,"slotRevision":state["revision"], + "slotId":slot,"variantId":variant,"useProductReference":true,"referenceIndex":1}); + let result = backend.canvas_workspace_action("slot-append", &request, &events, &ctx).unwrap(); + let id = result["candidateResult"]["id"].as_str().unwrap().to_owned(); + let record = read_candidate(&project, &id).unwrap(); + assert_eq!(record["references"][0]["name"], "第二张实物图"); + assert_eq!(record["origin"], "human"); + request["slotRevision"] = load(&project).unwrap()["revision"].clone(); + request["localPath"] = json!(dir.join(format!("{digest}.png"))); + let result = backend.canvas_workspace_action("slot-import-local", &request, &events, &ctx).unwrap(); + assert_eq!(result["candidateResult"]["sourceType"], "local-import"); + assert_eq!(result["candidateResult"]["origin"], "human"); 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, false).unwrap(); + assert_eq!(slot_dispatch_usage(&project, &load(&project).unwrap(), &record["binding"], &[], None).unwrap(), (0, 0, None)); 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"); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs index dbd5951f..ab460a53 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs @@ -183,6 +183,10 @@ pub(super) fn copy_generation(root: &Path, project: &Path, input: &Value, output } let mut adopted = Vec::new(); for (index, source) in data["imageSources"].as_array().into_iter().flatten().enumerate() { + if source["origin"] == "human" && source["candidateArtifact"].is_null() { + adopted.push(source.clone()); + continue; + } let bytes = super::template_slots::candidate_pixels(project, &source["candidateArtifact"])?; let digest = &source["candidateArtifact"]["sha256"]; let existing = files.iter().find(|file| file["category"] == "采用图" && file["sha256"] == *digest); @@ -205,7 +209,7 @@ pub(super) fn copy_generation(root: &Path, project: &Path, input: &Value, output } Ok(json!({"variantId":variant,"outputId":component,"generationId":id, "unverifiedCopy":data["unverifiedCopy"],"unverifiedFacts":data["unverifiedFacts"].as_array().map_or(&[][..], Vec::as_slice), - "missingImages":data["missingImages"],"missingVisibleText":data["missingVisibleText"], + "slotCoverage":data["slotCoverage"],"missingImages":data["missingImages"],"missingVisibleText":data["missingVisibleText"], "visibleSampleLayer":data["visibleSampleLayer"],"unapprovedFixedTextLayer":data["unapprovedFixedTextLayer"], "adoptedImages":adopted,"fidelityReport":data["fidelityReport"],"reopenVerification":data["reopenVerification"]})) } @@ -290,7 +294,7 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu .ok() .filter(|saved| saved["deliveryId"] == delivery_id) .map(|saved| json!({"state":"bundle_saved","path":target,"allOutputsCompleted":saved["allOutputsCompleted"],"completedOutputs":saved["completedOutputs"],"counts":saved["counts"], - "deliveryReason":saved["deliveryReason"],"missingOutputs":saved["missingOutputs"],"missing":saved["missing"],"knownIssues":saved["knownIssues"],"unverifiedCopy":saved["unverifiedCopy"]})) + "slotCoverage":saved["slotCoverage"],"deliveryReason":saved["deliveryReason"],"missingOutputs":saved["missingOutputs"],"missing":saved["missing"],"knownIssues":saved["knownIssues"],"unverifiedCopy":saved["unverifiedCopy"]})) }; // Recover a committed directory if the client lost the completion event. for number in 1.. { @@ -352,6 +356,8 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu let mut unverified_copy = Vec::new(); let mut known_issues = input["knownIssues"].as_array().cloned().unwrap_or_default(); let mut output_evidence = Vec::new(); + let mut missing_images = false; + let mut coverage = std::collections::BTreeMap::from(canvas_workspace::COVERAGE_FIELDS.map(|key| (key, 0_u64))); for output in outputs { admitted()?; let variant = output["variantId"].as_str().ok_or("成品花色缺失")?; @@ -372,12 +378,15 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu unverified_copy.push(json!({"variantId":variant,"outputId":component, "generationId":evidence["generationId"],"fields":fields})); } - if input["deliveryReason"].is_string() { - for (key, reason) in [("missingImages", "图位尚未采用图片"), ("missingVisibleText", "文案格尚未填写")] { - for field in evidence[key].as_array().into_iter().flatten() { - let issue = json!({"outputId":component,"variantId":variant,"field":field,"reason":reason}); - if !known_issues.contains(&issue) { known_issues.push(issue); } - } + missing_images |= evidence["missingImages"].as_array().is_some_and(|fields| !fields.is_empty()); + for (key, count) in &mut coverage { + *count += evidence["slotCoverage"][*key].as_u64().unwrap_or(0); + } + for (key, reason) in [("missingImages", "图位尚未采用图片"), ("missingVisibleText", "文案格尚未填写")] { + if key == "missingVisibleText" && !input["deliveryReason"].is_string() { continue; } + for field in evidence[key].as_array().into_iter().flatten() { + let issue = json!({"outputId":component,"variantId":variant,"field":field,"reason":reason}); + if !known_issues.contains(&issue) { known_issues.push(issue); } } } output_evidence.push(evidence); @@ -392,9 +401,8 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu let total = input["total"].as_u64().ok_or("本轮计划输出数无效")?; let missing_outputs = total.checked_sub(outputs.len() as u64).ok_or("本轮已导出数量超过计划")?; - let all_outputs_completed = missing_outputs == 0 + let all_outputs_completed = missing_outputs == 0 && !missing_images && (!input["deliveryReason"].is_string() || known_issues.is_empty()); - let known_issues = if input["deliveryReason"].is_string() { json!(known_issues) } else { input["knownIssues"].clone() }; let mut missing = Vec::new(); if missing_outputs > 0 && let Ok(checkpoint) = read_json(&project.join("production-run.json")) @@ -418,7 +426,7 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu let mut manifest = json!({"version":1,"deliveryId":delivery_id,"allOutputsCompleted":all_outputs_completed, "completedOutputs":outputs.len(),"totalOutputs":total,"missingOutputs":missing_outputs,"missing":missing, "counts":counts,"files":files,"deliveryReason":input["deliveryReason"],"knownIssues":known_issues,"unverifiedCopy":unverified_copy, - "outputEvidence":output_evidence}); + "slotCoverage":coverage,"outputEvidence":output_evidence}); if let Some(version) = input["knowledgeVersion"].as_str() { manifest["knowledgeVersion"] = json!(version); } @@ -439,7 +447,7 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu Ok(()) => { let flush = RealFs.sync_dir(&dir).err().map(|error| disk(error)); return Ok(json!({"state":"bundle_saved","path":target,"allOutputsCompleted":all_outputs_completed,"completedOutputs":outputs.len(), - "counts":counts,"missingOutputs":missing_outputs,"missing":missing, + "counts":counts,"slotCoverage":coverage,"missingOutputs":missing_outputs,"missing":missing, "deliveryReason":input["deliveryReason"],"knownIssues":known_issues,"unverifiedCopy":unverified_copy,"durabilityWarning":flush})); } Err(_) if target.exists() => continue, @@ -692,6 +700,25 @@ mod tests { assert_eq!(manifest["allOutputsCompleted"], false); } + #[test] + fn complete_output_list_still_reports_missing_slots_without_a_delivery_reason() { + let (_root, project, local, input) = fixture(); + let output = &input["published"][0]; + let pointer = canvas_workspace::receipt_path(&project, output["variantId"].as_str().unwrap(), "detail"); + let generation = pointer.with_file_name(canvas_workspace::manifest_path(output["generationId"].as_str().unwrap())); + let mut receipt = read_json(&generation).unwrap(); + receipt["slotCoverage"] = json!({"adopted":0,"manual":1,"unadoptedWithCandidates":0,"empty":1,"skipped":1,"total":3}); + receipt["missingImages"] = json!(["I02"]); + receipt["imageSources"] = json!([{"origin":"human","kind":"local-import","slotId":"I01","sha256":"manual"}]); + write_json(&generation, &receipt).unwrap(); + let policy = transfer::Policy { scope:"owner", project:&local, chat:false }; + let done = deliver_production_bundle(&project, &policy, &input, || Ok(())).unwrap(); + assert_eq!(done["allOutputsCompleted"], false); + assert_eq!(done["slotCoverage"]["manual"], 1); + assert_eq!(done["slotCoverage"]["skipped"], 1); + assert_eq!(done["knownIssues"][0]["field"], "I02"); + } + #[test] fn locally_published_outputs_form_a_reopenable_verified_bundle_and_keep_older_deliveries() { let (root, project, local, mut input) = fixture(); diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_image_transform.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_image_transform.rs index 4123d556..9d6abf98 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_image_transform.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_image_transform.rs @@ -2,7 +2,7 @@ //! before editing, and offsets are pixels in the destination frame. 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, + generation_references, hash, image_output_component, input_hash, json, local_product_photo, manual_image_source, mapped_slot, material_task_id, new_binding, now, output_uses_variant, product_slot_binding, read_candidate, reserve_candidate, slot_frame, slot_id, template_slots, uuid, write_json, }; use image::{Rgba, Rgba32FImage, imageops}; @@ -81,6 +81,25 @@ fn adopted_candidate<'a>(canvas: Option<&'a super::Document>, variant: &str, slo canvas?.metadata.text.iter().find(|(key, _)| key == &marker).map(|(_, id)| id.as_str()) } +fn manual_slot<'a>(doc: &'a super::Document, variant: &str, slot: &str) -> Option<(Value, &'a photocraft_doc::Layer)> { + let meta = super::mapping(doc)?; + let field = super::page_fields(&meta).flat_map(|(_, fields)| fields) + .find(|field| field["kind"] == "image" && field["slotId"] == slot)?; + let path = doc.path_of(photocraft_doc::LayerId(field["nativeLayerId"].as_u64()?))?; + if !(1..=path.len()).all(|depth| doc.layer_at(&path[..depth]) + .is_some_and(|layer| layer.visible && layer.opacity > 0.0)) + { + return None; + } + let layer = doc.layer_at(&path)?; + Some((manual_image_source(doc, layer, variant, slot)?, layer)) +} + +pub(super) enum SlotSource { + Candidate(String), + Manual { bytes: Vec, evidence: Value }, +} + fn screen_slots(dir: &Path, state: &Value, source: &str, variant: &str, active: Option<&super::Document>) -> Vec { let packs = state["productTemplates"].as_object().into_iter().flat_map(|packs| packs.values()) .chain(std::iter::once(&state["template"])); @@ -100,7 +119,13 @@ fn screen_slots(dir: &Path, state: &Value, source: &str, variant: &str, active: source_canvas(dir, state, variant, component, template, active)); let mut row = json!({"fieldId":field_id,"slotId":slot}); match canvas { - Ok(canvas) => row["adoptedCandidateId"] = json!(adopted_candidate(canvas.as_deref(), variant, &slot)), + Ok(canvas) => { + if let Some((source, _)) = canvas.as_deref().and_then(|doc| manual_slot(doc, variant, &slot)) { + row["manualImage"] = source; + } else { + row["adoptedCandidateId"] = json!(adopted_candidate(canvas.as_deref(), variant, &slot)); + } + } Err(error) => row["adoptionReadError"] = json!(error), } rows.push(row); @@ -124,7 +149,7 @@ fn screen_slots(dir: &Path, state: &Value, source: &str, variant: &str, active: rows } -pub(super) fn adopted_source(dir: &Path, state: &Value, input: &Value, variant: &str, active: Option<&super::Document>) -> R { +pub(super) fn adopted_source(dir: &Path, state: &Value, input: &Value, variant: &str, active: Option<&super::Document>) -> R { if !input["sourceCandidateId"].is_null() || !input["referenceIndex"].is_null() { return Err("sourceSlotId、sourceCandidateId 和 referenceIndex 只能填写其中一项".into()); } @@ -144,11 +169,23 @@ pub(super) fn adopted_source(dir: &Path, state: &Value, input: &Value, variant: 1 => { let (slot, (component, template)) = slots.iter().next().unwrap(); let canvas = source_canvas(dir, state, variant, component, template, active)?; + if let Some((mut evidence, layer)) = canvas.as_deref().and_then(|doc| manual_slot(doc, variant, slot)) { + use photocraft_doc::{LayerContent, SmartSource}; + let LayerContent::Smart(smart) = &layer.content else { + return Err("此人工图位已填图,当前像素变换需要嵌入式源图".into()); + }; + let SmartSource::Embedded { bytes, .. } = &smart.source else { + return Err("此人工图位缺少嵌入式源图".into()); + }; + evidence["slotId"] = json!(slot); + evidence["outputId"] = json!(component); + return Ok(SlotSource::Manual { bytes: bytes.as_ref().clone(), evidence }); + } if let Some(id) = adopted_candidate(canvas.as_deref(), variant, slot) && read_candidate(dir, id).is_ok_and(|record| candidate_available(&record) && record["binding"]["slotId"] == slot.as_str() && record["binding"]["variantId"] == variant) { - return Ok(id.to_owned()); + return Ok(SlotSource::Candidate(id.to_owned())); } "该图位当前没有已采用的可用候选" } @@ -158,7 +195,7 @@ pub(super) fn adopted_source(dir: &Path, state: &Value, input: &Value, variant: Err(format!("来源图位「{source}」{reason}。匹配图位的已完成候选:{}。{hint}", json!(sources())).into()) } -pub(super) fn stage_candidate(dir: &Path, state: Value, input: &Value) -> R { +pub(super) fn stage_candidate(dir: &Path, state: Value, input: &Value, source: Option) -> R { let slot = input["slotId"].as_str().ok_or("缺少目标图位")?; let variant = uuid(&input["variantId"], "花色")?; let (output, field) = definition(&state, slot, &variant)?; @@ -169,8 +206,15 @@ pub(super) fn stage_candidate(dir: &Path, state: Value, input: &Value) -> R { + let (resolved, manual) = match source { + Some(SlotSource::Candidate(id)) => (Some(id), None), + Some(SlotSource::Manual { bytes, evidence }) => (None, Some((bytes, evidence))), + None => (None, None), + }; + let candidate = resolved.as_deref().or_else(|| input["sourceCandidateId"].as_str()); + let (bytes, source, reference_index, references, density, manual) = match (manual, candidate, input["referenceIndex"].as_u64()) { + (Some((bytes, evidence)), _, _) => (bytes, None, Value::Null, json!([]), 1.0, Some(evidence)), + (None, Some(candidate), None) if input["referenceIndex"].is_null() => { // 编号前缀至少 8 位且在本项目候选中唯一时,按完整编号处理。 let prefix = candidate.trim().to_ascii_lowercase(); let by_prefix = || { @@ -203,13 +247,13 @@ pub(super) fn stage_candidate(dir: &Path, state: Value, input: &Value) -> R { + (None, None, Some(index)) if index < 8 && input["sourceCandidateId"].is_null() => { let products = generation_references(dir, &state, &variant)?; let photo = products.as_array().into_iter().flatten().filter(|image| image["purpose"] == "product").nth(index as usize).ok_or("当前花色没有该同款原图。用 read_slot_images 查看当前图位的 productReferences,从清单中选择 reference(如 P01)。")?; - (local_product_photo(dir, photo)?, None, json!(index), json!([photo]), 1.0) + (local_product_photo(dir, photo)?, None, json!(index), json!([photo]), 1.0, None) } _ => return Err("用 read_slot_images 查看来源,再填写一个 sourceCandidateId 或一个 referenceIndex。".into()), }; @@ -230,13 +274,16 @@ pub(super) fn stage_candidate(dir: &Path, state: Value, input: &Value) -> R R<()> { + let state = canvas_workspace::load(project)?; + for output in canvas_workspace::production_stages(&state) { + let variant = output["variantId"].as_str().ok_or("成品花色身份无效")?; + let component = output["outputId"].as_str().ok_or("成品类型缺失")?; + let pointer = canvas_workspace::receipt_path(project, variant, component); + let existed = pointer.try_exists().map_err(|error| error.to_string())?; + let receipt = if existed { canvas_workspace::published_receipt(&pointer)? } else { Value::Null }; + match canvas_workspace::check_delivery_source(project, &state, variant, component, &receipt) { + Err(error) if error == canvas_workspace::STALE_DELIVERY_EXPORT => { + let exported = canvas_workspace::export_saved_production_output( + project, doc, scope, &state["id"], &output, &Value::Null, + )?; + if !exported["generationId"].is_string() { + return Err(format!("修改后的画布未通过导出核验,图位:{}", exported["invalidImageSources"])); + } + } + result => result?, + } + } + Ok(()) +} + pub(super) fn detail_artifacts(project: &Path) -> R> { let checkpoint = project.join("production-run.json"); let run = if checkpoint.try_exists().map_err(|error| error.to_string())? { read_json(&checkpoint)? } else { Value::Null }; @@ -264,6 +287,7 @@ pub(super) fn detail_artifacts(project: &Path) -> R> { } let pointer = canvas_workspace::receipt_path(project, variant, component); if !pointer.try_exists().map_err(|error| issue(error.to_string()))? { + canvas_workspace::check_delivery_source(project, &state, variant, component, &Value::Null).map_err(&issue)?; if bundle.is_none() { bundle = DeliveryBundle::open(project, &context, &creation, &state).map_err(&issue)?; } @@ -304,6 +328,9 @@ pub(super) fn detail_artifacts(project: &Path) -> R> { } canvas_workspace::check_delivery_export(project, &state, original_rules.as_ref().unwrap_or(&creation), variant, component, &manifest) .map_err(&issue)?; + if let Some(missing) = manifest["missingImages"].as_array().filter(|fields| !fields.is_empty()) { + return Err(issue(format!("以下图位尚未填图:{}", missing.iter().filter_map(Value::as_str).collect::>().join("、")))); + } let records = if component == "detail" { &manifest["screenFiles"] } else { &manifest["files"] }; let files = records.as_array().filter(|rows| !rows.is_empty()) .ok_or_else(|| issue("成品图片缺失,请重新导出该组".into()))?; @@ -535,6 +562,7 @@ impl Backend { let stored_identity = &state["identity"]; let same_delivery = *stored_identity == identity; let legacy_delivery = stored_identity["productModel"] == spu && stored_identity["identifier"].is_null() + && stored_identity["files"] == identity["files"] && ["projectId", "kind", "origin", "accountId"].iter().all(|key| stored_identity[*key] == identity[*key]); if let Some(request_id) = state["requestId"].as_str().map(str::to_owned) && (same_delivery || legacy_delivery) @@ -545,9 +573,6 @@ impl Backend { write_json(&state_file, &state)?; return Ok(json!({"materialId":material_id,"requestId":request_id,"kind":"detail"})); } - if let Some(id) = existing["materialId"].as_str().filter(|id| !id.is_empty()) { - return Err(format!("此项目已有完结交付,素材 ID:{id};已有素材已保留")); - } if !same_delivery { state = json!({"identity":identity,"requestId":Uuid::new_v4().to_string(),"uploads":{}}); write_json(&state_file, &state)?; @@ -638,7 +663,7 @@ impl Backend { if result["state"] == "removed" { return Err("原交付素材已被删除,素材 ID 已保留,请在素材库中处理".into()); } - if result["state"] != "completed" { return Err("素材库未确认成品已提交".into()); } + if result["state"] != "completed" || result["requestId"] != request_id { return Err("素材库未确认本次成品已提交".into()); } let material_id = result["materialId"].as_str().filter(|id| !id.is_empty()).ok_or("素材库未返回素材 ID")?; state["materialId"] = json!(material_id); write_json(&state_file, &state)?; diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_project_file.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_project_file.rs index 6c18f13d..72c403bc 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_project_file.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_project_file.rs @@ -238,6 +238,14 @@ fn trim_candidate_history(stage: &Path, selection: &mut Selection) -> R<()> { collect(&workspace.to_string(), &mut kept, &mut pending); let mut metadata: HashMap<&str, Vec<&str>> = HashMap::new(); for path in &selection.included { + if path == "canvas.pcraft" || path.starts_with("template-outputs/") && path.ends_with("-edited.pcraft") { + let canvas = photocraft_format::load_path(&stage.join(path)).map_err(disk)?; + for (key, value) in &canvas.metadata.text { + if key.starts_with("jiansun.adopted.") || key.starts_with("jiansun.manual-image.") { + collect(value, &mut kept, &mut pending); + } + } + } if !path.ends_with(".json") || path == "canvas-workspace.json" { continue; } if let Some((id, _)) = path.strip_prefix("image-jobs/").and_then(|path| path.split_once('/')) { metadata.entry(id).or_default().push(path); @@ -467,11 +475,13 @@ mod tests { let stage = root.path(); let applied = Uuid::new_v4().to_string(); let parent = Uuid::new_v4().to_string(); + let manual = Uuid::new_v4().to_string(); let unused = Uuid::new_v4().to_string(); let mut selection = Selection::default(); for (id, task) in [ (&applied, json!({"parentCandidateId":parent})), (&parent, json!({})), + (&manual, json!({})), (&unused, json!({})), ] { let dir = format!("image-jobs/{id}"); @@ -482,14 +492,19 @@ mod tests { } let workspace = stage.join("canvas-workspace.json"); write_json(&workspace, &json!({ - "candidates":[applied,parent,unused], - "mappings":{"detail":{"candidateArtifact":{"path":format!("image-jobs/{applied}/generated.png")}}} + "candidates":[applied,parent,manual,unused] })).unwrap(); + let mut canvas = Document::new("详情", Size::new(8, 8), ColorMode::Rgb, SampleType::U8); + canvas.metadata.text.push(("jiansun.adopted.variant.slot".into(), applied.clone())); + canvas.metadata.text.push(("jiansun.manual-image.variant.other".into(), + json!({"source":"local-import","candidateId":manual}).to_string())); + fs::write(stage.join("canvas.pcraft"), photocraft_format::save_to_bytes(&canvas, &Default::default()).unwrap()).unwrap(); + selection.included.push("canvas.pcraft".into()); trim_candidate_history(stage, &mut selection).unwrap(); - assert_eq!(read_json(&workspace).unwrap()["candidates"], json!([applied,parent])); - assert_eq!(selection.included.len(), 2); + assert_eq!(read_json(&workspace).unwrap()["candidates"], json!([applied,parent,manual])); + assert_eq!(selection.included.len(), 4); assert!(!stage.join("image-jobs").join(unused).exists()); } diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_slot_image_facts.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_slot_image_facts.rs index dad72902..e291afc0 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_slot_image_facts.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_slot_image_facts.rs @@ -117,12 +117,21 @@ fn lineage(record: &Value, parent: &Value) -> Value { "reused" } else if photo { "product-reference" + } else if record["sourceType"] == "local-import" { + "local-import" } else if record["requestId"].is_string() { "generation" } else { "unrecorded" }; let mut source = json!({"kind":kind,"candidateId":record["id"]}); + if kind == "local-import" { + source["origin"] = json!("human"); + source["sha256"] = record["artifact"]["sha256"].clone(); + } + if transform["manualSource"].is_object() { + source["manualSource"] = transform["manualSource"].clone(); + } for (key, value) in [ ("requestId", record.get("requestId").filter(|id| id.is_string()).unwrap_or(&record["sourceRequestId"])), ("sourceCandidateId", transform.get("sourceCandidateId").filter(|id| id.is_string()).unwrap_or(&reused["candidateId"])), @@ -167,7 +176,7 @@ struct Slot { hash: u64, near_white: f64, identity: Value, - candidate: String, + candidate: Option, layer_id: LayerId, } @@ -179,13 +188,14 @@ fn canvas_slots(doc: &Document, meta: &Value) -> Vec { for field in fields(page) { let Some(slot) = field["slotId"].as_str() else { continue }; let marker = format!("jiansun.adopted.{variant}.{slot}"); - let Some((_, candidate)) = doc.metadata.text.iter().find(|(key, _)| key == &marker) else { continue }; + let candidate = doc.metadata.text.iter().find(|(key, _)| key == &marker).map(|(_, id)| id.clone()); let Some(layer) = slot_layer(doc, field) else { continue }; + if candidate.is_none() && manual_image_source(doc, layer, variant, slot).is_none() { continue; } let Some(pixels) = slot_pixels(doc, area, field, layer) else { continue }; let (hash, near_white) = measure(&pixels); let identity = json!({"slotId":slot,"fieldId":field["fieldId"],"outputId":meta["component"], "variantId":variant,"documentId":meta["documentId"],"page":index}); - slots.push(Slot { hash, near_white, identity, candidate: candidate.clone(), layer_id: layer.id }); + slots.push(Slot { hash, near_white, identity, candidate, layer_id: layer.id }); } } slots @@ -222,9 +232,12 @@ impl SlotImageReader { .iter() .filter(|slot| slot.identity["page"] == page) .map(|slot| { - let source = doc - .layer(slot.layer_id) - .map_or_else(|| json!({"kind":"unrecorded"}), |layer| slot_source(dir, layer, &slot.candidate, &slot.identity["slotId"])); + let source = doc.layer(slot.layer_id).and_then(|layer| { + let variant = slot.identity["variantId"].as_str()?; + let id = slot.identity["slotId"].as_str()?; + manual_image_source(doc, layer, variant, id).or_else(|| + slot.candidate.as_deref().map(|candidate| slot_source(dir, layer, candidate, &slot.identity["slotId"]))) + }).unwrap_or_else(|| json!({"kind":"unrecorded"})); json!({"slotId":slot.identity["slotId"],"source":source,"nearWhiteFlatRatio":slot.near_white, "templateNearWhiteFlatRatio":null,"nearest":nearest(slot, &samples.slots)}) }) @@ -274,7 +287,7 @@ mod tests { #[test] fn jiansun_slot_nearest_lists_the_three_closest_slots_of_the_output() { let slot = |id, hash| Slot { hash, near_white: 0.0, identity: json!({"slotId":id,"fieldId":id,"page":1}), - candidate: String::new(), layer_id: LayerId(1) }; + candidate: None, layer_id: LayerId(1) }; let current = [slot("S05", 0), slot("S04", 1), slot("S06", 3), slot("S07", 7), slot("S08", 255)]; let rows = nearest(¤t[0], ¤t); assert_eq!( diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_sync.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_sync.rs index 6aaec261..6eabe4bf 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_sync.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_sync.rs @@ -360,7 +360,26 @@ fn context_identity(value: &Value, dir: &Path) -> R { // template inputs and the slot journal in the exact upload receipt identity. let template_slots = if dir.join("template-slots.json").exists() { file_digest(&dir.join("template-slots.json"))?.0 } else { String::new() }; let template_input = if dir.join("template-input.json").exists() { file_digest(&dir.join("template-input.json"))?.0 } else { String::new() }; - Ok(digest(serde_json::to_string(&json!({"revision":value["revision"],"name":value["name"],"composer":value["composer"],"messages":value["messages"],"creation":value["creation"],"creationDraft":value["creationDraft"],"creationFile":creation,"templateSlotsFile":template_slots,"templateInputFile":template_input})).map_err(|_|"项目身份无法读取")?.as_bytes())) + let mut working_canvases = std::collections::BTreeMap::new(); + for name in ["canvas.pcraft", "canvas-workspace.json"] { + let path = dir.join(name); + if path.try_exists().map_err(|error| error.to_string())? { + working_canvases.insert(name.to_owned(), file_digest(&path)?.0); + } + } + let outputs = dir.join("template-outputs"); + if outputs.try_exists().map_err(|error| error.to_string())? { + for entry in fs::read_dir(&outputs).map_err(|error| error.to_string())? { + let entry = entry.map_err(|error| error.to_string())?; + let name = entry.file_name(); + if let Some(name) = name.to_str() + && name.starts_with("canvas-") && name.ends_with("-edited.pcraft") + { + working_canvases.insert(format!("template-outputs/{name}"), file_digest(&entry.path())?.0); + } + } + } + Ok(digest(serde_json::to_string(&json!({"workingCanvases":working_canvases,"revision":value["revision"],"name":value["name"],"composer":value["composer"],"messages":value["messages"],"creation":value["creation"],"creationDraft":value["creationDraft"],"creationFile":creation,"templateSlotsFile":template_slots,"templateInputFile":template_input})).map_err(|_|"项目身份无法读取")?.as_bytes())) } fn finish_sync(dir: &Path, cloud_id: &str, cloud_revision: u64, revision: u64, state: &str, source_web: &Value, identity: &str) -> R { let _guard = context_guard(); @@ -665,7 +684,15 @@ impl Backend { self.ensure_owner(id)?; let dir = self.project_dir(id)?; super::projects::idle(&dir)?; - let artifacts = super::material_delivery::detail_artifacts(&dir)?; + super::material_delivery::refresh_stale_exports(&dir, id, &self.scope())?; + let (artifacts, identity) = { + let _guard = context_guard(); + let context = read_json(&dir.join("context.json"))?; + if context["revision"].as_u64() != Some(revision) { + return Err("本机版本已变化,请保存后重新完结".into()); + } + (super::material_delivery::detail_artifacts(&dir)?, context_identity(&context, &dir)?) + }; let creation_revision = creation::load(&dir)?["revision"].clone(); let (spu, delivery_files) = self.bind_sku_delivery(&dir, &artifacts)?; let cloud_id = self.delivery_project_id(&dir, revision, &artifacts)?; @@ -677,7 +704,7 @@ impl Backend { let mut context = read_json(&dir.join("context.json"))?; context["materialDelivery"] = receipt.clone(); context["syncDirty"] = json!(true); - if context["revision"].as_u64() == Some(revision) + if context_identity(&context, &dir).is_ok_and(|current| current == identity) && creation::load(&dir).is_ok_and(|current| current["revision"] == creation_revision) { context["status"] = json!("completed"); } else { @@ -1924,6 +1951,25 @@ mod tests { assert_eq!(file_digest(&dir.join("canvas.pcraft")).unwrap(), canvas); fs::remove_dir_all(&b.root).unwrap(); } + #[test] + fn non_active_edited_canvas_changes_sync_identity_without_a_revision_change() { + let root = tempfile::tempdir().unwrap(); + let dir = root.path(); + let context = json!({"revision":7}); + let baseline = context_identity(&context, dir).unwrap(); + write_json(&dir.join("canvas-workspace.json"), &json!({"revision":1})).unwrap(); + let workspace = context_identity(&context, dir).unwrap(); + assert_ne!(workspace, baseline); + let outputs = dir.join("template-outputs"); + fs::create_dir(&outputs).unwrap(); + let edited = outputs.join("canvas-inactive-edited.pcraft"); + fs::write(&edited, b"first document").unwrap(); + let original = context_identity(&context, dir).unwrap(); + assert_ne!(original, workspace); + fs::write(&edited, b"edited document").unwrap(); + assert_ne!(context_identity(&context, dir).unwrap(), original); + } + #[test] fn late_upload_receipt_keeps_template_changes_dirty_at_the_same_canvas_revision() { for file in ["template-slots.json", "template-input.json"] {