From 4fd6544c4c5eeced2772e8c3c19d26fdee2bc3e0 Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Thu, 3 Dec 2026 18:13:08 +0800 Subject: [PATCH] =?UTF-8?q?=E6=81=A2=E5=A4=8D=E5=8E=86=E5=8F=B2=E5=80=99?= =?UTF-8?q?=E9=80=89=E5=B9=B6=E9=9A=8F=E4=BA=A4=E4=BB=98=E4=BF=9D=E5=AD=98?= =?UTF-8?q?=E6=9C=AA=E9=87=87=E7=BA=B3=E5=9B=BE=E7=89=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/jiansun_canvas_workspace.rs | 375 +++++++++++++++--- .../apps/photocraft/src/jiansun_delivery.rs | 113 +++++- .../photocraft/src/jiansun_project_file.rs | 16 +- .../ui-egui/src/jiansun/canvas_workspace.rs | 42 +- .../ui-egui/src/jiansun/project_file.rs | 6 +- 5 files changed, 477 insertions(+), 75 deletions(-) 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 c60beb51..7d020ab1 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_canvas_workspace.rs @@ -855,11 +855,14 @@ fn input_hash(dir: &Path, state: &Value, variant_id: &str) -> R { } fn candidate_uses_current_inputs(dir: &Path, state: &Value, record: &Value, variant_id: &str) -> R { + candidate_matches_inputs(state, record, variant_id, state["activeOutput"].as_str().unwrap_or("detail"), &creation::load(dir)?) +} + +fn candidate_matches_inputs(state: &Value, record: &Value, variant_id: &str, component: &str, creation: &Value) -> R { let saved = &record["inputHash"]; if saved.as_str().is_some_and(|value| value.starts_with(VARIANT_INPUT_HASH)) { - return Ok(*saved == input_hash(dir, state, variant_id)?); + return Ok(*saved == variant_input_hash(state, creation, variant_id, component, &state["template"]["contentHash"], &state["structureHash"])?); } - let creation = creation::load(dir)?; let old = json!({"brief":state["brief"],"liveBrief":creation["brief"],"variant":variant(state,variant_id)?, "templateHash":state["template"]["contentHash"],"structureHash":state["structureHash"],"rules":creation["designSnapshot"]}); Ok(*saved == hash(&old.to_string())) @@ -937,7 +940,27 @@ fn recover_candidate_without_task(dir: &Path, record: &Value) -> R { } } +fn unindexed_candidate_ids(dir: &Path, seen: &std::collections::HashSet) -> R> { + let jobs = dir.join("image-jobs"); + let mut ids = Vec::new(); + if jobs.exists() { + for entry in fs::read_dir(jobs).map_err(|_| "候选归档目录不可读取")? { + let entry = entry.map_err(|_| "候选归档目录读取中断")?; + let id = entry.file_name().to_string_lossy().into_owned(); + if entry.path().join(CANDIDATE).exists() && !seen.contains(&id) { + ids.push(id); + } + } + } + ids.sort_unstable(); + Ok(ids) +} + fn records(dir: &Path, state: &Value) -> R> { + read_records(dir, state, false) +} + +fn read_records(dir: &Path, state: &Value, include_completed_orphans: bool) -> R> { let mut out = Vec::new(); let mut seen = std::collections::HashSet::new(); for id in state["candidates"].as_array().ok_or("候选索引无效")? { @@ -945,20 +968,60 @@ fn records(dir: &Path, state: &Value) -> R> { if !seen.insert(id.clone()) { return Err("候选索引重复,原历史保留".into()); } - out.push(read_candidate(dir, &id)?); + let record = read_candidate(dir, &id)?; + if record["binding"]["workspaceId"] != state["id"] { + return Err("候选不属于当前项目,原记录保留".into()); + } + out.push(record); } - let jobs = dir.join("image-jobs"); - if jobs.exists() { - for entry in fs::read_dir(jobs).map_err(|_| "候选归档目录不可读取")? { - let entry = entry.map_err(|_| "候选归档目录读取中断")?; - if entry.path().join(CANDIDATE).exists() && !seen.contains(&entry.file_name().to_string_lossy().to_string()) { - return Err("发现未完成写入的候选预留,原记录保留;未开始新请求".into()); - } + for id in unindexed_candidate_ids(dir, &seen)? { + if include_completed_orphans + && let Ok(record) = read_candidate(dir, &id) + && let Some((mut record, _)) = completed_candidate(dir, state, record, false) + { + record["unindexed"] = json!(true); + out.push(record); + } else { + return Err("发现未完成写入的候选预留,原记录保留;未开始新请求".into()); } } + if include_completed_orphans { out.sort_by_key(|record| record["sequence"].as_u64()); } Ok(out) } +// An unindexed record is only evidence of a result when the independent +// task journal agrees. Indexed terminal records retain their own pixel digest. +fn completed_candidate(dir: &Path, state: &Value, mut record: Value, indexed: bool) -> Option<(Value, Vec)> { + let binding = &record["binding"]; + let variant_id = uuid(&binding["variantId"], "花色").ok()?; + if !binding_is_canvas(binding) || binding["workspaceId"] != state["id"] + || variant(state, &variant_id).is_err() || record["retirement"].is_object() + { + return None; + } + let id = uuid(&record["id"], "候选").ok()?; + if !indexed || matches!(record["phase"].as_str(), Some("prepared" | "dispatched" | "running" | "unknown")) { + let task = read_json(&candidate_path(dir, &id).ok()?.with_file_name("task.json")).ok()?; + if task["id"] != id || task["slotBinding"] != *binding + || !matches!(task["phase"].as_str(), Some("complete" | "applied")) + { + return None; + } + if record["phase"] == "complete" { + if record["artifact"] != template_slots::artifact(dir, &id, &task).ok()? { + return None; + } + } else { + record = project_candidate(dir, &record, &task).ok()?; + } + } + if !candidate_available(&record) || record["artifact"]["taskId"] != id { + return None; + } + let pixels = candidate_pixels(dir, &record["artifact"]).ok()?; + Some((record, pixels)) +} + fn pending_production_image(record: &Value, task: &Value) -> R> { let binding = &record["binding"]; if binding["detailBatch"] != true || !task["outputScope"].is_string() || !record["sourceType"].is_null() @@ -1081,7 +1144,7 @@ fn publish_prepared(events: &mpsc::Sender, snapshot: Value) -> R<()> { fn new_binding(state: &Value, output: &Value, field: &Value, slot: &str, variant: &str, id: &str, prompt: &str) -> Value { json!({"schemaVersion":2,"canvasFirst":true,"workspaceId":state["id"],"templateId":state["template"]["id"], "templateVersion":state["template"]["version"],"templateHash":state["template"]["contentHash"], - "structureHash":state["structureHash"],"slotId":slot,"fieldId":field["fieldId"],"outputId":output["id"], + "structureHash":state["structureHash"],"slotId":slot,"fieldId":field["fieldId"],"outputId":output["id"],"component":output["component"], "variantId":variant,"candidateId":id,"taskId":id,"promptHash":hash(prompt)}) } @@ -3557,6 +3620,49 @@ fn save_delivery_canvas(native: &Document, export_dir: &Path, name: &str, compon Ok(count) } +pub(super) fn export_candidates( + dir: &Path, + workspace: Option<&Value>, + mut save: impl FnMut(&Value, &Path, &[u8], (u32, u32)) -> R<()>, +) -> R<()> { + if !exists(dir) { return Ok(()); } + let state = load(dir)?; + if workspace.is_some_and(|id| *id != state["id"]) { + return Err("交付候选所属画布已变化".into()); + } + let indexed: std::collections::HashSet<_> = state["candidates"].as_array().into_iter() + .flatten().filter_map(Value::as_str).map(str::to_owned).collect(); + let orphans = unindexed_candidate_ids(dir, &indexed)?; + let mut ids: Vec<_> = indexed.iter().chain(&orphans).collect(); + ids.sort_unstable(); + for id in ids { + let Ok(record) = read_candidate(dir, id) else { continue; }; + let Some((record, pixels)) = completed_candidate(dir, &state, record, indexed.contains(id)) else { continue; }; + let Ok(size) = creation::png_size(&pixels) else { continue; }; + let binding = &record["binding"]; + let variant_id = uuid(&binding["variantId"], "花色")?; + let name = variant(&state, &variant_id).ok().and_then(|row| row["name"].as_str()) + .filter(|name| !name.trim().is_empty()).unwrap_or("花色"); + let component = binding["component"].as_str().or_else(|| image_output_component(&state, binding)) + .or_else(|| state["template"]["outputs"].as_array()?.iter() + .find(|output| output["id"] == binding["outputId"])?.get("component")?.as_str()); + let label = match component { + Some("detail") => "详情页", + Some("main_images") => "主图", + Some("sku_images") => "SKU", + _ => "历史输出", + }; + let page = super::delivery::name_component(binding["outputId"].as_str().unwrap_or(label), 9); + let field = super::delivery::name_component(binding["fieldId"].as_str().unwrap_or("图位"), 9); + let sequence = record["sequence"].as_u64().unwrap_or_default(); + let name = super::delivery::name_component(name, 11); + let relative = PathBuf::from(format!("{name}-{}", &variant_id[..8])) + .join(label).join(format!("{page}-{field}-{sequence:03}-{id}.png")); + save(&record, &relative, &pixels, size)?; + } + Ok(()) +} + pub(super) fn save_delivery_artifacts(dir: &Path, active: &Document, export_dir: &Path, choices: &Value) -> R { let state = exists(dir).then(|| load(dir)).transpose()?; let mut count = 0; @@ -3573,7 +3679,7 @@ pub(super) fn save_delivery_artifacts(dir: &Path, active: &Document, export_dir: _ => continue, }; let variant_id = uuid(&meta["variantId"], "花色")?; - if mapping_key(&variant_id, component, meta["documentId"].as_str()) != *key { + if document_mapping_key(meta)? != *key { return Err("项目画布映射不一致".into()); } let file = dir.join("template-outputs").join(format!("canvas-{key}-edited.pcraft")); @@ -3581,7 +3687,7 @@ pub(super) fn save_delivery_artifacts(dir: &Path, active: &Document, export_dir: let owned; let native = if active_mapping.as_ref().is_some_and(|active| { active["component"] == meta["component"] && active["variantId"] == meta["variantId"] - && active["documentId"] == meta["documentId"] + && active["outputId"] == meta["outputId"] }) { active } else { owned = super::load_draft(dir, &file).map_err(|_| format!("{label}编辑稿无法打开"))?; &owned @@ -3591,7 +3697,7 @@ pub(super) fn save_delivery_artifacts(dir: &Path, active: &Document, export_dir: if ch.is_control() || "\"<>:/\\|?*".contains(ch) { '_' } else { ch } }).collect(); let mut target = export_dir.join(format!("{} ({})", variant_name.trim(), &variant_id[..8])).join(label); - if meta["documentId"].is_string() { target.push(&key[..8]); } + if meta["outputId"].is_string() { target.push(&key[..8]); } fs::create_dir_all(&target).map_err(|_| "成品目录无法创建")?; count += save_delivery_canvas(native, &target, label, component, choices)?; } @@ -3599,17 +3705,13 @@ pub(super) fn save_delivery_artifacts(dir: &Path, active: &Document, export_dir: if count == 0 { count += save_delivery_canvas(active, export_dir, "当前画布", "", choices)?; } } if choices["candidates"] == true { - let target = export_dir.join("候选区图片"); - fs::create_dir_all(&target).map_err(|_| "候选目录无法创建")?; - if let Some(state) = &state { - for candidate in records(dir, state)?.into_iter().filter(candidate_available) { - let id = uuid(&candidate["id"], "候选")?; - let seq = candidate["sequence"].as_u64().ok_or("候选序号无效")?; - let bytes = candidate_pixels(dir, &candidate["artifact"])?; - fs::write(target.join(format!("{seq:03}-{id}.png")), bytes).map_err(|_| "一张候选图无法保存")?; - count += 1; - } - } + export_candidates(dir, None, |_, relative, pixels, _| { + let target = export_dir.join("候选区图片").join(relative); + fs::create_dir_all(target.parent().ok_or("候选目录无效")?).map_err(|_| "候选目录无法创建")?; + fs::write(target, pixels).map_err(|_| "一张候选图无法保存")?; + count += 1; + Ok(()) + })?; } Ok(count) } @@ -4652,12 +4754,36 @@ fn candidate_reviews(dir: &Path, pack: &Value, output: &str, variant: &str) -> V Value::Object(reviews) } +fn candidate_matches_slot(record: &Value, state: &Value, pack: &Value, output: &Value, field: &Value, variant: &str) -> bool { + let binding = &record["binding"]; + let (Some(field_id), Some(old_hash)) = (field["fieldId"].as_str(), binding["templateHash"].as_str()) else { return false; }; + if binding["workspaceId"] != state["id"] || binding["variantId"] != variant + || binding["outputId"] != output["id"] || binding["fieldId"] != field_id + || binding["slotId"] != slot_id(&binding["templateHash"], variant, field_id) + || binding["component"].is_string() && binding["component"] != output["component"] + { + return false; + } + if pack["contentHash"] == old_hash { + return true; + } + if !candidate_available(record) || !binding["templateId"].is_string() || binding["templateId"] != pack["id"] { + return false; + } + // Older bindings did not store component. Do not infer it if the page + // and field are also described by another output in this workspace. + binding["component"].is_string() || !state["productTemplates"].as_object().into_iter().flatten() + .filter(|(component, _)| output["component"] != component.as_str()) + .any(|(_, other)| other["outputs"].as_array().into_iter().flatten().any(|page| + page["id"] == output["id"] && page["slots"].as_array().into_iter().flatten().any(|slot| slot["fieldId"] == field_id))) +} + fn snapshot_for_view(dir: &Path, view: Option, read_only: bool) -> R { let project_plan = read_only && view.is_some(); let (state, mut history) = { let _guard = sync::context_guard(); let state = load(dir)?; - let history = records(dir, &state)?; + let history = read_records(dir, &state, true)?; let state = if let Some(mut view) = view { view["revision"] = state["revision"].clone(); view @@ -4669,6 +4795,7 @@ fn snapshot_for_view(dir: &Path, view: Option, read_only: bool) -> R, read_only: bool) -> R, read_only: bool) -> R, read_only: bool) -> R = in_slot().filter(|record| record["retirement"].is_object()) .map(|record| &record["id"]).collect(); let generation_request_ids: Vec<_> = in_slot().filter(|record| - record["id"].as_str().is_some_and(|id| dispatched_generations.contains(id))) + record["binding"]["slotId"] == id && record["id"].as_str().is_some_and(|id| dispatched_generations.contains(id))) .map(|record| &record["id"]).collect(); let candidates: Vec<_> = in_slot().filter(|record| record["retirement"].is_null()).map(|record| { let candidate_id = record["id"].as_str().unwrap_or(""); + let archive_preview = candidate_available(record) && !dir.join("image-jobs").join(candidate_id).join("task.json").is_file(); + let historical = candidate_available(record) && (archive_preview || record["unindexed"] == true + || record["binding"]["slotId"] != id || record["binding"]["structureHash"] != state["structureHash"] + || !candidate_matches_inputs(&state, record, active, component, ¤t).unwrap_or(false)); let review = &reviews[candidate_id]; - let decision = (review["slotId"] == id).then(|| &review["decision"]); + let decision = (!historical && review["slotId"] == id).then(|| &review["decision"]); let mut row = json!({"id":record["id"],"taskId":record["id"],"variant":record["id"],"sequence":record["sequence"],"status":record["phase"],"requestId":record["requestId"], + "historical":historical,"archivePreview":archive_preview, "materialTaskId":material_task_id(record),"sourceRequestId":record["sourceRequestId"],"instructions":record["instructions"],"parentCandidateId":record["parentCandidateId"],"reworkOf":record["reworkOf"],"sourceType":record["sourceType"],"reusedFrom":record["reusedFrom"],"previewUri":format!("bytes://template-candidate-{candidate_id}"),"error":record["message"],"generationEvidence":record["generationEvidence"],"reviewDecision":decision,"retryableFailure":record["retryableFailure"],"retryAfterSeconds":record["retryAfterSeconds"]}); if record["phase"] == "expired" { row["retryable"] = json!(false); @@ -4777,7 +4916,7 @@ fn snapshot_for_view(dir: &Path, view: Option, read_only: bool) -> R>()); @@ -4791,20 +4930,34 @@ fn snapshot_for_view(dir: &Path, view: Option, read_only: bool) -> R R { + fn opened_workspace_state(&self, doc: u64, state: Value) -> R<(Value, bool)> { let meta = self.access.opened_doc_scopes.lock().unwrap().get(&doc).cloned(); - let Some(meta) = meta else { return snapshot(dir); }; - let state = load(dir)?; + let Some(meta) = meta else { return Ok((state, false)); }; let component = meta["component"].as_str().ok_or("编辑稿输出类型缺失")?; - let variant = meta["variantId"].as_str().ok_or("编辑稿花色缺失")?; - let mut scoped = output_state_inner(state, component, variant, false)?; + let variant_id = meta["variantId"].as_str().ok_or("编辑稿花色缺失")?; + let mut scoped = if state["productTemplates"].is_object() { + output_state_inner(state, component, variant_id, false)? + } else { + variant(&state, variant_id)?; + if !state["template"]["outputs"].as_array().into_iter().flatten().any(|output| output["component"] == component) { + return Err("编辑稿输出不属于当前模板".into()); + } + let mut state = state; + state["activeOutput"] = json!(component); + state["activeVariantId"] = json!(variant_id); + state + }; if meta["workspaceId"] != scoped["id"] || meta["templateHash"] != scoped["template"]["contentHash"] { return Err("当前画布与项目模板版本不一致,请重新选择输出".into()); } let key = document_mapping_key(&meta)?; scoped["activeMapping"] = json!(key); scoped["mappings"][&key] = meta; - snapshot_for_view(dir, Some(scoped), true) + Ok((scoped, true)) + } + pub(super) fn opened_workspace_snapshot(&self, doc: u64, dir: &Path) -> R { + let (scoped, opened) = self.opened_workspace_state(doc, load(dir)?)?; + snapshot_for_view(dir, opened.then_some(scoped), opened) } pub(super) fn canvas_workspace_result(&self, doc: u64, dir: &Path) -> R { self.canvas_result_with_workflow(doc, dir, snapshot(dir)?) @@ -5228,6 +5381,30 @@ impl Backend { if !matches!(method, "slot-read" | "slot-templates") && input["baseRevision"].as_u64().is_none() { return Err("当前原生画布修订缺失,未修改项目".into()); } + if method == "slot-read" && !input["previewCandidateId"].is_null() { + let id = uuid(&input["previewCandidateId"], "候选")?; + let (scoped, view) = scope_state_for_view(load(&dir)?, input)?; + let state = if view { scoped } else { self.opened_workspace_state(doc, scoped)?.0 }; + let record = read_candidate(&dir, &id)?; + let pack = &state["template"]; + let variant = state["activeVariantId"].as_str().ok_or("当前花色缺失")?; + let mapping = &state["mappings"][state["activeMapping"].as_str().unwrap_or_default()]; + let matches = pack["outputs"].as_array().into_iter().flatten() + .filter(|output| output["component"] == state["activeOutput"] + && (mapping["outputId"].is_null() || mapping["outputId"] == output["id"])) + .any(|output| output["slots"].as_array().into_iter().flatten().any(|field| + field["kind"] == "image" && candidate_matches_slot(&record, &state, pack, output, field, variant))); + if !matches { + return Err("候选预览不属于当前画布".into()); + } + let indexed = state["candidates"].as_array().is_some_and(|ids| ids.contains(&json!(id))); + let (_, pixels) = completed_candidate(&dir, &state, record, indexed).ok_or("候选预览不可读取")?; + let preview = super::images::decode_agent_image(&pixels)?; + let reference = json!({"purpose":"template-candidate","doc":doc,"taskId":id, + "accountId":self.auth["account"]["id"],"origin":self.origin}); + events.send(Event::Preview(reference, preview)).map_err(|_| "画布已关闭")?; + return Ok(json!({"doc":doc,"accountId":self.auth["account"]["id"],"origin":self.origin})); + } if method == "slot-read" { let workflow = self.opened_workspace_snapshot(doc, &dir)?; return self.canvas_result_with_workflow(doc, &dir, workflow); @@ -5823,8 +6000,15 @@ impl Backend { let candidate = uuid(&input["candidateId"], "候选")?; let record = read_candidate(&dir, &candidate)?; if !candidate_available(&record) + || !state["candidates"].as_array().is_some_and(|ids| ids.contains(&json!(candidate))) + || record["binding"]["workspaceId"] != state["id"] || record["binding"]["slotId"] != id || record["binding"]["variantId"] != variant_id + || record["binding"]["templateHash"] != state["template"]["contentHash"] + || record["binding"]["structureHash"] != state["structureHash"] + || record["binding"]["outputId"] != output["id"] + || record["binding"]["fieldId"] != field["fieldId"] + || record["binding"]["component"].is_string() && record["binding"]["component"] != output["component"] { return Err("候选未完成或不属于当前产品花色与图片目标,未采纳".into()); } @@ -7930,21 +8114,120 @@ mod tests { let mut completed = candidate(dir, "complete"); let pending = candidate(dir, "unknown"); let id = completed["id"].as_str().unwrap().to_owned(); - let bytes = b"completed candidate"; + let image = photocraft_codecs::Image::from_u8(1, 1, photocraft_codecs::ChannelLayout::Rgb, vec![10, 20, 30]).unwrap(); + let bytes = photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap(); let file = candidate_path(dir, &id).unwrap(); let image = file.with_file_name("generated.png"); completed["artifact"] = json!({"taskId":id,"path":format!("image-jobs/{id}/generated.png"), - "sha256":format!("{:x}",Sha256::digest(bytes))}); + "sha256":format!("{:x}",Sha256::digest(&bytes))}); write_json(&file, &completed).unwrap(); - fs::write(image, bytes).unwrap(); + fs::write(image, &bytes).unwrap(); write_json(&candidate_path(dir, pending["id"].as_str().unwrap()).unwrap(), &pending).unwrap(); - state["candidates"] = json!([id,pending["id"]]); + let second = Uuid::new_v4().to_string(); + let second_color = Uuid::new_v4().to_string(); + state["variants"].as_array_mut().unwrap().push(json!({"id":second_color,"name":"暖白色"})); + let mut other = completed; + other["id"] = json!(second); + other["sequence"] = json!(3); + other["binding"]["candidateId"] = json!(second); + other["binding"]["taskId"] = json!(second); + other["binding"]["variantId"] = json!(second_color); + other["binding"]["component"] = json!("sku_images"); + other["binding"]["outputId"] = json!("SKU01"); + other["binding"]["fieldId"] = json!("SKU01-I01"); + other["binding"]["slotId"] = json!(slot_id(&state["template"]["contentHash"], &second_color, "SKU01-I01")); + other["artifact"]["taskId"] = json!(second); + other["artifact"]["path"] = json!(format!("image-jobs/{second}/generated.png")); + let file = candidate_path(dir, &second).unwrap(); + write_json(&file, &other).unwrap(); + fs::write(file.with_file_name("generated.png"), &bytes).unwrap(); + state["candidates"] = json!([id,pending["id"],second]); persist(dir, state, 1).unwrap(); let output = tempfile::tempdir().unwrap(); let doc = Document::new("candidate checkpoint", photocraft_doc::Size::new(60, 60), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8); - assert_eq!(save_delivery_artifacts(dir, &doc, output.path(), &json!({"candidates":true})).unwrap(), 1); - assert_eq!(fs::read(output.path().join("候选区图片").join(format!("001-{id}.png"))).unwrap(), bytes); + assert_eq!(save_delivery_artifacts(dir, &doc, output.path(), &json!({"candidates":true})).unwrap(), 2); + let variant = load(dir).unwrap()["activeVariantId"].as_str().unwrap().to_owned(); + let file = output.path().join("候选区图片").join(format!("原色-{}", &variant[..8])) + .join("详情页").join(format!("S01-S01-I01-001-{id}.png")); + assert_eq!(fs::read(file).unwrap(), bytes); + let file = output.path().join("候选区图片").join(format!("暖白色-{}", &second_color[..8])) + .join("SKU").join(format!("SKU01-SKU01-I01-003-{second}.png")); + assert_eq!(fs::read(file).unwrap(), bytes); + } + + #[test] + fn template_and_brief_changes_keep_verified_candidates_visible_in_their_original_scope() { + let project = fixture(); + let dir = &project.dir; + let mut state = load(dir).unwrap(); + let mut record = candidate(dir, "complete"); + record["binding"]["templateId"] = state["template"]["id"].clone(); + let id = record["id"].as_str().unwrap().to_owned(); + let variant = state["activeVariantId"].as_str().unwrap().to_owned(); + let path = candidate_path(dir, &id).unwrap(); + let png = encode_template_rgba(1, 1, vec![10, 20, 30, 255]).unwrap(); + let digest = format!("{:x}", Sha256::digest(&png)); + record["artifact"] = json!({"taskId":id,"path":format!("image-jobs/{id}/generated.png"),"sha256":digest}); + write_json(&path, &record).unwrap(); + fs::write(path.with_file_name("generated.png"), &png).unwrap(); + state["candidates"] = json!([id]); + state = persist(dir, state, 1).unwrap(); + + let history = |snapshot: &Value| snapshot["slots"][0]["candidates"][0].clone(); + let journal = json!({"id":id,"slotBinding":record["binding"],"phase":"complete","sha256":digest}); + write_json(&path.with_file_name("task.json"), &journal).unwrap(); + assert_eq!(history(&snapshot(dir).unwrap())["historical"], false); + let mut live = creation::load(dir).unwrap(); + live["brief"]["name"] = json!("新商品描述"); + write_json(&dir.join("creation.json"), &live).unwrap(); + assert_eq!(history(&snapshot(dir).unwrap())["historical"], true); + fs::remove_file(path.with_file_name("task.json")).unwrap(); + assert_eq!(history(&snapshot(dir).unwrap())["archivePreview"], true); + + state["template"]["version"] = json!("2"); + state["template"]["contentHash"] = json!(template_slots::pack_hash(&state["template"]).unwrap()); + state["structureHash"] = json!(hash(&json!([state["template"]["contentHash"],750]).to_string())); + state = persist(dir, state, 2).unwrap(); + let refreshed = snapshot(dir).unwrap(); + assert_ne!(refreshed["slots"][0]["id"], record["binding"]["slotId"]); + assert_eq!(history(&refreshed)["id"], id); + assert_eq!(history(&refreshed)["historical"], true); + let output = &state["template"]["outputs"][0]; + let field = &output["slots"][0]; + let mut other = record.clone(); + for (key, value) in [("workspaceId", json!(Uuid::new_v4())), ("variantId", json!(Uuid::new_v4())), + ("outputId", json!("S02")), ("component", json!("main_images"))] + { + other["binding"][key] = value; + assert!(!candidate_matches_slot(&other, &state, &state["template"], output, field, &variant)); + other["binding"][key] = record["binding"][key].clone(); + } + + let mut backend = Backend::new(dir.join("profile")).unwrap(); + let doc = 1; + backend.bind_new(doc); + let reopened_dir = backend.project_dir(doc).unwrap(); + write_json(&reopened_dir.join("context.json"), &json!({"doc":doc})).unwrap(); + write_json(&reopened_dir.join(FILE), &state).unwrap(); + let restored = candidate_path(&reopened_dir, &id).unwrap(); + write_json(&restored, &record).unwrap(); + fs::write(restored.with_file_name("generated.png"), &png).unwrap(); + let (events, receive) = mpsc::channel(); + backend.slot_action("slot-read", &json!({"doc":doc,"previewCandidateId":id}), + &events, &egui::Context::default()).unwrap(); + let Event::Preview(meta, image) = receive.try_recv().unwrap() else { panic!("expected archival preview"); }; + assert_eq!(meta["taskId"], id); + assert_eq!(image.size, [1, 1]); + + write_json(&path.with_file_name("task.json"), &journal).unwrap(); + state["candidates"] = json!([]); + persist(dir, state, 3).unwrap(); + let reopened = snapshot(dir).unwrap(); + assert_eq!(history(&reopened)["id"], id); + assert_eq!(history(&reopened)["historical"], true); + assert_eq!(reopened["capabilities"]["imageDispatchAllowed"], false); + assert!(pending_summary(dir).is_err()); } #[test] diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs index e54a2ced..c1bd6ea7 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_delivery.rs @@ -20,8 +20,13 @@ fn clean_name(name: &str) -> String { cleaned.trim_matches(|ch: char| ch == '.' || ch.is_whitespace()).to_owned() } -fn name_component(name: &str) -> String { - safe_name(&clean_name(&name.chars().take(24).collect::())) +pub(super) fn name_component(name: &str, limit: usize) -> String { + let mut units = 0; + let prefix: String = name.chars().take_while(|ch| { + units += ch.len_utf16(); + units <= limit + }).collect(); + safe_name(&clean_name(&prefix)) } fn safe_name(name: &str) -> String { @@ -116,7 +121,7 @@ pub(super) fn variant_name(brief: &Value, variant: &str) -> Option { let (source, field) = row.map_or((brief, "variant"), |row| (row, "name")); [field, "colorName"].into_iter().filter_map(|key| source[key].as_str()) .find(|name| !name.trim_matches(|ch: char| ch == '.' || ch.is_whitespace()).is_empty()) - .map(name_component) + .map(|name| name_component(name, 24)) } pub(super) fn copy_generation(root: &Path, project: &Path, input: &Value, output: &Value, folder: &Path, color: Option<&str>, files: &mut Vec) -> R { @@ -298,6 +303,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"], + "candidateCount":saved["candidateCount"],"unadoptedCandidateCount":saved["unadoptedCandidateCount"], "slotCoverage":saved["slotCoverage"],"missingSlots":saved["missingSlots"].as_array().map_or(&[][..], Vec::as_slice), "unreviewedScreens":saved["unreviewedScreens"].as_array().map_or(&[][..], Vec::as_slice), "deliveryStatus":if saved["allOutputsCompleted"] == true { "completed" } else { "partial_delivered" },"deliveryReason":saved["deliveryReason"],"missingOutputs":saved["missingOutputs"],"missing":saved["missing"],"knownIssues":saved["knownIssues"],"unverifiedCopy":saved["unverifiedCopy"]})) @@ -352,8 +358,6 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu let project_file = package_root.join(format!("{entry_name}.xiaoyi")); let mut package = json!({"version":2,"localId":policy.project,"scope":policy.scope, "snapshot":Uuid::new_v4().to_string(),"sourceRoot":project,"resources":"资源"}); - project_file::write_project(project, &project_file, &mut package, policy, true)?; - let snapshot = project_file::resource_checkpoint(&project_file, &package)?; let mut files = Vec::new(); let variants: HashSet<_> = outputs.iter().filter_map(|output| output["variantId"].as_str()).collect(); @@ -397,6 +401,41 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu } output_evidence.push(evidence); } + let adopted_ids: HashSet<_> = output_evidence.iter().flat_map(|output| output["adoptedImages"].as_array().into_iter().flatten()) + .filter_map(|row| row["candidateId"].as_str()).collect(); + let mut candidate_images = Vec::new(); + let mut candidate_files: BTreeMap<_, _> = files.iter() + .filter(|file| file["category"] == "采用图") + .filter_map(|file| Some((file["sha256"].as_str()?.to_owned(), file["relativePath"].clone()))) + .collect(); + canvas_workspace::export_candidates(project, Some(&input["workspaceId"]), |record, relative, pixels, size| { + admitted()?; + let id = record["id"].as_str().ok_or("候选编号缺失")?; + let adopted = adopted_ids.contains(id); + let digest = record["artifact"]["sha256"].as_str().ok_or("候选图片校验信息缺失")?; + let relative_path = if let Some(path) = candidate_files.get(digest) { + path.clone() + } else { + let path = root.join("候选区图片").join(if adopted { "已采纳" } else { "未采纳" }).join(relative); + fs::create_dir_all(path.parent().ok_or("候选目录无效")?).map_err(disk)?; + fs::write(&path, pixels).map_err(disk)?; + let file = file_record(root, &path, "候选区图片", Some(size))?; + let relative_path = file["relativePath"].clone(); + candidate_files.insert(digest.to_owned(), relative_path.clone()); + files.push(file); + relative_path + }; + let binding = &record["binding"]; + candidate_images.push(json!({"candidateId":id,"variantId":binding["variantId"], + "outputId":binding["outputId"],"fieldId":binding["fieldId"],"slotId":binding["slotId"], + "adoptedInDelivery":adopted,"sequence":record["sequence"],"relativePath":relative_path})); + Ok(()) + })?; + let candidate_count = candidate_images.len(); + let unadopted_candidate_count = candidate_images.iter().filter(|row| row["adoptedInDelivery"] == false).count(); + let saved_candidates = candidate_images.iter().filter_map(|row| row["candidateId"].as_str()).collect(); + project_file::write_project(project, &project_file, &mut package, policy, Some(&saved_candidates))?; + let snapshot = project_file::resource_checkpoint(&project_file, &package)?; compact_resources(root, &snapshot, &mut package, &mut files)?; let canvas = files.iter().find(|record| record["relativePath"] == package["resourcePaths"]["canvas.pcraft"]) .ok_or("工程画布未列入成品清单")?; @@ -438,7 +477,8 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu let delivery_status = if all_outputs_completed { "completed" } else { "partial_delivered" }; 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, + "counts":counts,"files":files,"candidateImages":candidate_images,"candidateCount":candidate_count, + "unadoptedCandidateCount":unadopted_candidate_count,"deliveryReason":input["deliveryReason"],"knownIssues":known_issues,"unverifiedCopy":unverified_copy, "slotCoverage":coverage,"outputEvidence":output_evidence,"deliveryStatus":delivery_status, "missingSlots":missing_slots,"unreviewedScreens":unreviewed_screens}); if let Some(version) = input["knowledgeVersion"].as_str() { @@ -461,7 +501,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,"slotCoverage":coverage,"deliveryStatus":delivery_status, + "counts":counts,"candidateCount":candidate_count,"unadoptedCandidateCount":unadopted_candidate_count,"slotCoverage":coverage,"deliveryStatus":delivery_status, "missingSlots":missing_slots,"unreviewedScreens":unreviewed_screens,"missingOutputs":missing_outputs,"missing":missing, "deliveryReason":input["deliveryReason"],"knownIssues":known_issues,"unverifiedCopy":unverified_copy,"durabilityWarning":flush})); } @@ -506,6 +546,7 @@ impl Backend { Ok(receipt) => { let status = if receipt["durabilityWarning"].is_string() { "unconfirmed" } else { "completed" }; (status, json!({"counts":receipt["counts"],"allOutputsCompleted":receipt["allOutputsCompleted"], + "candidateCount":receipt["candidateCount"],"unadoptedCandidateCount":receipt["unadoptedCandidateCount"], "deliveryStatus":receipt["deliveryStatus"],"missingSlots":receipt["missingSlots"], "unreviewedScreens":receipt["unreviewedScreens"]})) } @@ -577,6 +618,62 @@ mod tests { (root, project, local, input) } + #[test] + fn production_delivery_lists_unadopted_images_and_restores_their_jobs_offline() { + let (root, project, local, input) = fixture(); + let variant = input["published"][0]["variantId"].as_str().unwrap(); + let mut pack = json!({"schemaVersion":1,"id":"FIXTURE","version":"1","name":"本机模板", + "brandId":"00000000-0000-4000-8000-000000000001","categoryId":"00000000-0000-4000-8000-000000000002", + "outputs":[{"id":"S01","name":"首屏","component":"detail","width":750,"height":300,"top":0, + "slots":[{"fieldId":"I01","kind":"image","crop":"cover","frame":{"x":0,"y":0,"width":750,"height":300}}]}]}); + pack["contentHash"] = json!(super::super::template_slots::pack_hash(&pack).unwrap()); + let complete = Uuid::new_v4().to_string(); + let missing = Uuid::new_v4().to_string(); + let brief = creation::load(&project).unwrap()["brief"].clone(); + write_json(&project.join("canvas-workspace.json"), &json!({"version":1,"canvasFirst":true, + "id":input["workspaceId"],"revision":1,"brief":brief,"mappings":{},"template":pack, + "variants":brief["variants"],"activeVariantId":variant,"activeOutput":"detail","candidates":[complete,missing]})).unwrap(); + let png = photocraft_codecs::encode( + &photocraft_codecs::Image::from_u8(1, 1, photocraft_codecs::ChannelLayout::Rgb, vec![10, 20, 30]).unwrap(), + photocraft_codecs::Format::Png, &Default::default()).unwrap(); + let image = format!("image-jobs/{complete}/generated.png"); + let group = project.join(&image); + fs::create_dir_all(group.parent().unwrap()).unwrap(); + fs::write(&group, &png).unwrap(); + let digest = canvas_workspace::file_digest(&group).unwrap(); + for id in [&complete, &missing] { + let binding = json!({"schemaVersion":2,"canvasFirst":true,"workspaceId":input["workspaceId"], + "variantId":variant,"templateHash":pack["contentHash"],"outputId":"S01","fieldId":"I01","component":"detail", + "slotId":canvas_workspace::slot_id(&pack["contentHash"], variant, "I01"),"candidateId":id,"taskId":id}); + write_json(&project.join(format!("image-jobs/{id}/canvas-candidate.json")), &json!({"version":2,"id":id, + "binding":binding,"phase":"complete","sequence":7, + "artifact":{"taskId":id,"path":format!("image-jobs/{id}/generated.png"),"sha256":digest}})).unwrap(); + } + + let policy = transfer::Policy { chat: false, scope: "owner", project: &local }; + let result = deliver_production_bundle(&project, &policy, &input, || Ok(())).unwrap(); + assert_eq!(result["candidateCount"], 1); + assert_eq!(result["unadoptedCandidateCount"], 1); + assert_eq!(result["counts"]["候选区图片"], 1); + let bundle = Path::new(result["path"].as_str().unwrap()); + let manifest = read_json(&bundle.join("交付清单.json")).unwrap(); + let row = &manifest["candidateImages"][0]; + assert_eq!(row["candidateId"], complete); + assert_eq!(row["adoptedInDelivery"], false); + let relative = row["relativePath"].as_str().unwrap(); + assert!(relative.starts_with("候选区图片/未采纳/")); + assert_eq!(fs::read(bundle.join(relative)).unwrap(), png); + assert!(manifest["files"].as_array().unwrap().iter().any(|file| + file["relativePath"] == relative && file["sha256"] == digest && file["verified"] == true)); + let entry = bundle.join("工程文件/天青椅.xiaoyi"); + assert_eq!(read_json(&entry).unwrap()["resourcePaths"][&image], relative); + fs::rename(&project, root.path().join("offline-source")).unwrap(); + let reopened = root.path().join("reopened"); + assert_eq!(project_file::open(&entry, &reopened, "owner").unwrap(), local); + assert_eq!(fs::read(reopened.join(&local).join(&image)).unwrap(), png); + assert_eq!(read_json(&reopened.join(&local).join("canvas-workspace.json")).unwrap()["candidates"], json!([complete])); + } + #[test] #[ignore = "requires a copied production project"] fn offline_delivery_reopens_copied_production_project() { @@ -816,7 +913,7 @@ mod tests { let baseline_file = root.path().join("baseline.xiaoyi"); let mut baseline = json!({"version":2,"localId":local,"scope":"owner","snapshot":Uuid::new_v4().to_string(), "sourceRoot":project,"resources":"baseline 资源"}); - project_file::write_project(&project, &baseline_file, &mut baseline, &policy, false).unwrap(); + project_file::write_project(&project, &baseline_file, &mut baseline, &policy, None).unwrap(); let baseline_root = project_file::resource_checkpoint(&baseline_file, &baseline).unwrap(); let baseline_bytes: u64 = baseline["projectManifest"]["included"].as_array().unwrap().iter() .map(|entry| fs::metadata(baseline_root.join(entry.as_str().unwrap())).unwrap().len()).sum(); 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 6b435080..61e57532 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_project_file.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_project_file.rs @@ -216,7 +216,7 @@ fn copy_project( Ok(()) } -fn trim_candidate_history(stage: &Path, selection: &mut Selection) -> R<()> { +fn trim_candidate_history(stage: &Path, selection: &mut Selection, saved: &HashSet<&str>) -> R<()> { let workspace_path = stage.join("canvas-workspace.json"); if !workspace_path.is_file() { return Ok(()); @@ -229,8 +229,8 @@ fn trim_candidate_history(stage: &Path, selection: &mut Selection) -> R<()> { let jobs: HashSet<_> = selection.included.iter().filter_map(|path| { path.strip_prefix("image-jobs/")?.split_once('/').map(|(id, _)| id.to_owned()) }).collect(); - let mut kept = HashSet::new(); - let mut pending = Vec::new(); + let mut kept: HashSet<_> = jobs.iter().filter(|id| saved.contains(id.as_str())).cloned().collect(); + let mut pending: Vec<_> = kept.iter().cloned().collect(); let collect = |text: &str, kept: &mut HashSet, pending: &mut Vec| { for id in text.split(|c: char| !c.is_ascii_alphanumeric() && c != '-') { if jobs.contains(id) && kept.insert(id.to_owned()) { @@ -276,7 +276,7 @@ fn trim_candidate_history(stage: &Path, selection: &mut Selection) -> R<()> { Ok(()) } -pub(super) fn write_project(dir: &Path, file: &Path, manifest: &mut Value, policy: &Policy<'_>, delivery: bool) -> R<()> { +pub(super) fn write_project(dir: &Path, file: &Path, manifest: &mut Value, policy: &Policy<'_>, delivery_candidates: Option<&HashSet<&str>>) -> R<()> { let checkpoint = resource_checkpoint(file, manifest)?; let resource_dir = checkpoint.parent().ok_or("工程资源目录无效")?; fs::create_dir_all(resource_dir).map_err(disk)?; @@ -286,9 +286,9 @@ pub(super) fn write_project(dir: &Path, file: &Path, manifest: &mut Value, polic .filter(|previous| previous.is_dir()); let stage = tempfile::tempdir_in(resource_dir).map_err(disk)?; let mut selection = Selection::default(); - let mode = if delivery { CheckpointCopy::Deliver } else { CheckpointCopy::Save }; + let mode = if delivery_candidates.is_some() { CheckpointCopy::Deliver } else { CheckpointCopy::Save }; copy_project(dir, dir, stage.path(), previous.as_deref(), mode, policy, &mut selection)?; - if delivery { trim_candidate_history(stage.path(), &mut selection)?; } + if let Some(saved) = delivery_candidates { trim_candidate_history(stage.path(), &mut selection, saved)?; } if !["canvas.pcraft", CONTEXT].into_iter().all(|required| selection.included.iter().any(|path| path == required)) { return Err("工程缺少必要的编辑数据,未写入工程包".into()); } @@ -339,7 +339,7 @@ pub(super) fn save( let policy = Policy { chat, scope, project: local }; let mut manifest = json!({"version":2,"localId":local,"scope":scope,"snapshot":snapshot, "sourceRoot":dir,"resources":format!("{name} 资源")}); - write_project(dir, &file, &mut manifest, &policy, false)?; + write_project(dir, &file, &mut manifest, &policy, None)?; context["projectFile"] = json!({"path":file,"snapshot":snapshot,"syncChatHistory":chat}); result["path"] = json!(file); result["localSave"] = json!({"state":"saved","path":file,"manifest":manifest["projectManifest"]}); @@ -651,7 +651,7 @@ mod tests { 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(); + trim_candidate_history(stage, &mut selection, &HashSet::new()).unwrap(); assert_eq!(read_json(&workspace).unwrap()["candidates"], json!([applied,parent,manual])); assert_eq!(selection.included.len(), 4); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/canvas_workspace.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/canvas_workspace.rs index 3b963c69..76bec8ce 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/canvas_workspace.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/canvas_workspace.rs @@ -426,7 +426,8 @@ fn candidates(slot: &Value) -> &[Value] { fn first_generated_preview(slot: &Value) -> Option<&Value> { candidates(slot).iter() - .find(|candidate| candidate["status"] == "complete" && !candidate["sourceType"].is_string()) + .find(|candidate| candidate["status"] == "complete" && candidate["historical"] != true + && candidate["archivePreview"] != true && !candidate["sourceType"].is_string()) } fn preview_rejected(candidate: &Value, slot_id: &str, progress: &Value) -> bool { @@ -2243,7 +2244,7 @@ impl Workspace { if super::stitch_ui::menu_item( ui, "采纳", - c["status"] == "complete" && !adopted && self.canvas_workspace.pending_adoption.is_none() && self.saving.is_none(), + c["status"] == "complete" && c["historical"] != true && !adopted && self.canvas_workspace.pending_adoption.is_none() && self.saving.is_none(), ) .clicked() { @@ -2257,7 +2258,7 @@ impl Workspace { action = Some(("slot-recover", json!({"slotId":slot_id,"candidateId":id,"candidate":c["variant"],"variantId":variant}))); ui.close(); } - if workflow["canvasFirst"] == true && c["status"] == "complete" { + if workflow["canvasFirst"] == true && c["status"] == "complete" && c["historical"] != true { let regenerate = super::stitch_ui::menu_item(ui, "重新生成", true); let rect = regenerate.rect; self.canvas_workspace.geometry.insert("candidate-menu-regenerate".into(), @@ -2271,7 +2272,8 @@ impl Workspace { ui.close(); } } - if c["status"] == "complete" && super::stitch_ui::menu_item(ui, "引用到小壹", true).clicked() + if c["status"] == "complete" && c["archivePreview"] != true + && super::stitch_ui::menu_item(ui, "引用到小壹", true).clicked() && let Some(slot) = workflow["slots"].as_array().into_iter().flatten().find(|slot| slot["id"] == slot_id) { let mut target = scope(slot, Some(c), variant, ""); @@ -2285,7 +2287,7 @@ impl Workspace { ui.data_mut(|data| data.insert_temp(egui::Id::unique("jiansun-image-expanded"), task_id.to_owned())); ui.close(); } - if super::stitch_ui::menu_item(ui, "专业编辑图片", c["status"] == "complete" && mapping_layer.is_some()) + if super::stitch_ui::menu_item(ui, "专业编辑图片", c["status"] == "complete" && c["historical"] != true && mapping_layer.is_some()) .on_hover_text("用原始图片打开独立原生画布,编辑后明确回填到此图位") .clicked() { @@ -2481,15 +2483,20 @@ impl Workspace { let (kind,label)=if pending {(BadgeKind::Running,"正在采纳")} else if status == "unknown" {(BadgeKind::Warning,"待核查")} else if status == "failed" {(BadgeKind::Warning,"生成失败")} + else if candidate["historical"] == true {(BadgeKind::Neutral,"历史候选")} else if self.agent_effects_paused && matches!(status,"prepared"|"dispatched"|"running") {(BadgeKind::Neutral,"已停止")} else {return;}; - let badge=Rect::from_min_size(rect.right_top()+vec2(-92.0,8.0),vec2(84.0,24.0)); + let badge = if candidate["historical"] == true { + Rect::from_min_size(rect.left_top() + vec2(8.0, 8.0), vec2(68.0, 24.0)) + } else { + Rect::from_min_size(rect.right_top() + vec2(-92.0, 8.0), vec2(84.0, 24.0)) + }; kit::paint_badge(ui,id.with("badge"),badge,kind,label,self.reduce_motion); } fn mark_workspace_candidate_visible(&mut self, task_id: &str, candidate: Option<&Value>) { if !task_id.is_empty() { - if candidate.is_some_and(|candidate| candidate["status"] == "complete") { self.agent_images.mark_visible(task_id); } + if candidate.is_some_and(|candidate| candidate["status"] == "complete" && candidate["archivePreview"] != true) { self.agent_images.mark_visible(task_id); } else { self.agent_images.mark_visible_existing(task_id); } } } @@ -2528,6 +2535,8 @@ impl Workspace { let field = row.slot["label"].as_str().unwrap_or("图片"); let label = if candidate.is_some_and(|row| row["sourceType"] == "product-reference") { format!("{field},产品原图") + } else if candidate.is_some_and(|row| row["historical"] == true) { + format!("{field},历史候选 {}", index + 1) } else if candidate.is_some() { format!("{field},候选 {}", index + 1) } else { @@ -2556,7 +2565,15 @@ impl Workspace { painter.add(candidate_image_shape(ui.ctx(), texture.id(), image_world, xf, ease)); has_image = true; } else if c["status"] == "complete" && !task_id.is_empty() && self.agent_images.can_insert(task_id) && self.requested_previews.insert(task_id.to_owned()) { - let _ = self.tx.send(Request::Action("agent-image-preview".into(), json!({"doc":doc_id,"taskId":task_id}))); + let request = if c["archivePreview"] == true { + Request::Action("slot-read".into(), json!({"doc":doc_id,"previewCandidateId":task_id, + "viewOutputId":output,"viewVariantId":variant,"viewTemplateHash":workflow["templateHash"]})) + } else { + Request::Action("agent-image-preview".into(), json!({"doc":doc_id,"taskId":task_id})) + }; + if self.tx.send(request).is_err() { + self.requested_previews.remove(task_id); + } } let processing = !has_image && matches!(c["status"].as_str(), Some("prepared" | "dispatched" | "running")) && candidate_is_running(self, doc_id, slot_id, c); @@ -2622,7 +2639,7 @@ impl Workspace { } if !processing && footer_height > 0.0 && (result.pointer_on_image || selected) { let button_rect = Rect::from_min_size(rect.right_bottom() + vec2(-72.0, -40.0), vec2(64.0, 34.0)); - if c["status"] == "complete" && !adopted { + if c["status"] == "complete" && c["historical"] != true && !adopted { let mut controls = ui.new_child(egui::UiBuilder::new() .id_salt(("candidate-adopt", &key)).max_rect(button_rect) .layout(egui::Layout::top_down(egui::Align::Min))); @@ -2919,7 +2936,7 @@ impl Workspace { let popover_layer = reference_dock_layer("popover"); let reveal_id = popover_layer.with("reveal"); let shown = !(self.professional_mode || self.library || self.material || (self.creation_open && self.creation_step != 3) - || self.professional_child_active(app) || self.production_canvas_unbound(app) || !self.canvas_scope_valid(app)) + || self.professional_child_active(app) || !self.canvas_scope_valid(app)) && bound_project(self, doc).is_some(); let images = if shown && self.template_workflow["canvasFirst"] == true { self.product_reference_images(doc) } else { Vec::new() }; let resources = if shown { self.production_assets().count() } else { 0 }; @@ -5456,6 +5473,11 @@ pub(super) mod tests { h.run_steps(4); h.render().unwrap().save(std::path::Path::new(&directory).join(format!("candidate-primary-{width}.png"))).unwrap(); assert!(h.state().0.canvas_workspace.geometry.contains_key("adopt:image-slot/new-candidate")); + h.state_mut().0.template_workflow["slots"][0]["candidates"][0]["historical"] = json!(true); + h.run_steps(4); + assert!(h.state().0.canvas_workspace.geometry.contains_key("image-slot/new-candidate")); + assert!(!h.state().0.canvas_workspace.geometry.contains_key("adopt:image-slot/new-candidate")); + h.render().unwrap().save(std::path::Path::new(&directory).join(format!("candidate-history-{width}.png"))).unwrap(); let target=json!({"kind":"slot","slotId":"image-slot","productVariantId":"wood","outputId":"detail","nativeLayerId":layer}); let workspace=&mut h.state_mut().0; workspace.template_workflow["slots"][0]["candidates"]=json!([{"id":"in-flight","status":"running"}]); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/project_file.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/project_file.rs index 7f60b50b..f13b044b 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/project_file.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/project_file.rs @@ -60,7 +60,7 @@ impl PhotocraftApp { let name: String = name.chars().map(|ch| if ch.is_control() || "\"<>:/\\|?*".contains(ch) { '_' } else { ch }).collect(); let suggested = previous.clone().unwrap_or_else(|| format!("{name}.xiaoyi")); let dialog = SaveDialog { doc, account:w.account["id"].clone(), origin:w.origin.clone(), - project:true, psd:false, jpg:false, candidates:false, chat_history:(choose || previous.is_none()).then_some(false), suggested }; + project:true, psd:false, jpg:false, candidates:true, chat_history:(choose || previous.is_none()).then_some(false), suggested }; if let Some(file) = previous.filter(|_| !choose) { Some(w.submit_project_save(self, ctx, &dialog, file)) } else { @@ -182,7 +182,7 @@ mod tests { let initial = read(&harness.ctx); assert!(initial.project); assert_eq!(initial.chat_history, Some(false)); - assert!(!initial.psd && !initial.jpg && !initial.candidates); + assert!(!initial.psd && !initial.jpg && initial.candidates); for label in ["随工程保存项目对话", "PSD 分层文件", "JPG 图片", "候选区图片"] { let pos = harness.get_by_label(label).rect().center(); harness.hover_at(pos); @@ -193,7 +193,7 @@ mod tests { } } let selected = read(&harness.ctx); - assert!(selected.project && selected.psd && selected.jpg && selected.candidates); + assert!(selected.project && selected.psd && selected.jpg && !selected.candidates); assert_eq!(selected.options("test.xiaoyi".into())["syncChatHistory"], true); if let Some(path) = std::env::var_os("PHOTOCRAFT_PROJECT_SAVE_SCREENSHOT") { let path = std::path::PathBuf::from(path);