fix: 自动保存候选采纳并拦截缺图导出

This commit is contained in:
WuYongJie 2026-12-04 11:30:55 +08:00
parent 47d6c4ce6e
commit c665fbd2ab
8 changed files with 764 additions and 69 deletions

View File

@ -1678,7 +1678,8 @@ impl Backend {
if !canvas_workspace::save_edited_output(dir, doc, &bytes)? {
return Err("当前输出缺少原稿映射,未覆盖编辑稿".into());
}
Ok(json!({"outputCheckpointOnly":true,"documentKey":photocraft_ui_egui::jiansun::product_document_key(doc)}))
Ok(json!({"outputCheckpointOnly":true,"documentKey":photocraft_ui_egui::jiansun::product_document_key(doc),
"outputCheckpointSha256":format!("{:x}",Sha256::digest(&bytes))}))
}
fn save(&mut self, doc: Arc<Document>, revision: u64, meta: Value) -> R<Value> {
@ -1801,7 +1802,12 @@ impl Backend {
let dir = self.project_dir(doc.id.0)?;
let path = dir.join("context.json");
let mut state = read_json(&path)?;
if state["revision"] != revision { return Err("项目已变化,请重新保存".into()); }
if receipt["outputCheckpointOnly"] == true {
let digest = receipt["outputCheckpointSha256"].as_str().ok_or("当前输出尚未保存")?;
canvas_workspace::verify_saved_output(&dir, doc, digest)?;
} else if state["revision"] != revision {
return Err("项目已变化,请重新保存".into());
}
let local = self.locations.get(&doc.id.0).ok_or("项目身份尚未绑定")?;
let scope = self.owners.get(&doc.id.0).ok_or("项目账户尚未绑定")?;
let delivery = project_file::save(&dir, doc, options, scope, local, &mut state)?;

View File

@ -16,6 +16,7 @@ const CANDIDATE: &str = "canvas-candidate.json";
const MAPPING: &str = "jiansun.slot-mapping.v1";
const SUPPORTED_PRODUCTION_OUTPUTS: [&str; 3] = ["detail", "main_images", "sku_images"];
const DELIVERY_REOPEN_MISMATCH: &str = "成品工程重开后与本轮画布的图层或图片不一致,未交付成品";
pub(super) fn exists(dir: &Path) -> bool {
@ -1067,7 +1068,8 @@ fn reserve_candidate(dir: &Path, mut state: Value, record: &Value, project_scope
if record["phase"] == "complete" && (record["sourceType"] == "archived-candidate"
|| record["origin"] == "human" && local_candidate(record))
{
if creation::load(dir)?["brief"] != original["brief"] {
let operator_reuse = record["origin"] == "human" && record["sourceType"] == "archived-candidate";
if !operator_reuse && creation::load(dir)?["brief"] != original["brief"] {
return Err("产品资料已变化,未添加候选".into());
}
} else {
@ -1846,24 +1848,89 @@ fn reuse_archived_candidate_scoped(dir: &Path, state: Value, input: &Value, pref
let id = Uuid::new_v4().to_string();
let mut binding = new_binding(&state,output,field,slot,&variant_id,&id,"历史同款候选");
if input["detailBatch"] == true { binding["detailBatch"] = json!(true); }
let job = dir.join("image-jobs").join(&id);
let material_task = material_task_id(&source_record);
let source_request = source_task.get("requestId").filter(|id| id.is_string())
.unwrap_or(&source_record["sourceRequestId"]);
let journal = json!({"id":id,"version":1,"slotBinding":binding,"phase":"complete","requestId":null,
"sourceType":"archived-candidate","reusedFrom":origin,"materialTaskId":material_task,
"sourceRequestId":source_request,"sha256":artwork["sha256"]});
write_json(&job.join("task.json"), &journal)?;
photocraft_format::atomic_write(&job.join("generated.png"), &pixels).map_err(|_| "历史候选无法保存")?;
let artifact = template_slots::artifact(dir,&id,&journal)?;
let record = json!({"version":2,"id":id,"binding":binding,"phase":"complete","sourceType":"archived-candidate",
"reusedFrom":origin,"materialTaskId":material_task,"sourceRequestId":source_request,"requestId":null,
let record = json!({"version":2,"id":id,"binding":binding,"phase":"complete",
"reusedFrom":origin,"materialTaskId":material_task_id(&source_record),"sourceRequestId":source_request,"requestId":null,
"inputHash":target_input,"references":original_refs,
"prompt":source_record.get("prompt").filter(|prompt| prompt.is_string()).unwrap_or(&source_task["prompt"]),
"instructions":"历史候选,等待当前图位验收","artifact":artifact,"createdAt":now()});
"instructions":"历史候选,等待当前图位验收","createdAt":now()});
mount_archived_candidate(dir, state, record, artwork["sha256"].clone(), &pixels, project_scoped)
}
fn mount_archived_candidate(dir: &Path, state: Value, mut record: Value, digest: Value, pixels: &[u8], project_scoped: bool) -> R<Value> {
let id = uuid(&record["id"], "候选")?;
let job = dir.join("image-jobs").join(&id);
record["sourceType"] = json!("archived-candidate");
let journal = json!({"id":id,"version":1,"slotBinding":record["binding"],"phase":"complete","requestId":null,
"sourceType":record["sourceType"],"reusedFrom":record["reusedFrom"],"materialTaskId":record["materialTaskId"],
"sourceRequestId":record["sourceRequestId"],"sha256":digest});
write_json(&job.join("task.json"), &journal)?;
photocraft_format::atomic_write(&job.join("generated.png"), pixels).map_err(|_| "历史候选无法保存")?;
record["artifact"] = template_slots::artifact(dir, &id, &journal)?;
reserve_candidate(dir, state, &record, project_scoped)?;
Ok(record)
}
fn historical_candidate_pixels(dir: &Path, state: &Value, record: &Value) -> R<Vec<u8>> {
let id = &record["id"];
if record["artifact"]["taskId"] != *id || !binding_is_canvas(&record["binding"]) {
return Err("历史候选记录不一致,无法采纳".into());
}
if state["candidates"].as_array().is_some_and(|ids| ids.contains(id)) {
return candidate_pixels(dir, &record["artifact"])
.map_err(|error| format!("历史图片无法采纳:{error}"));
}
completed_candidate(dir, state, record.clone(), false).map(|(_, pixels)| pixels)
.ok_or_else(|| "历史图片已缺失或校验失败,无法采纳".into())
}
fn mount_historical_adoption(dir: &Path, state: &Value, input: &Value, record: &Value, project_scoped: bool) -> R<Value> {
let variant = uuid(&input["variantId"], "花色")?;
let slot = input["slotId"].as_str().ok_or("请选择图片目标")?;
let (output, field) = definition(state, slot, &variant)?;
if !candidate_available(record) || state["activeVariantId"] != variant || state["activeOutput"] != output["component"]
|| !candidate_matches_slot(record, state, &state["template"], output, field, &variant)
{
return Err("历史候选不属于当前画布的图位和花色,未采纳".into());
}
let layer = input["nativeLayerId"].as_u64().filter(|&id| id > 0).ok_or("原生图片图层身份缺失")?;
let mapped = mapped_slot(state, slot, &variant).filter(|row| row["nativeLayerId"] == layer)
.ok_or("原生图层不属于此花色和图片目标,未采纳")?;
slot_frame(field, Some(mapped)).ok_or("当前图片图层缺少已核对的范围,未采纳")?;
let source_id = uuid(&record["id"], "历史候选")?;
let _source = lock_candidate_dispatch(dir, &source_id)?.ok_or("历史候选正在处理,请稍后采纳")?;
let record = &read_candidate(dir, &source_id)?;
if !candidate_available(record) || !candidate_matches_slot(record, state, &state["template"], output, field, &variant) {
return Err("历史候选已不可用,未采纳".into());
}
let pixels = historical_candidate_pixels(dir, state, record)?;
let project = uuid(&json!(dir.file_name().and_then(|name| name.to_str())), "当前项目")?;
let origin = json!({"projectId":project,"candidateId":record["id"]});
let target_input = input_hash(dir, state, &variant)?;
let current = load(dir)?;
for prior in read_records(dir, &current, true)?.into_iter().filter(|prior|
candidate_available(prior) && prior["unindexed"].is_null()
&& prior["binding"]["slotId"] == slot && prior["inputHash"] == target_input
&& prior["reusedFrom"] == origin && prior["artifact"]["sha256"] == record["artifact"]["sha256"]
) {
let id = uuid(&prior["id"], "候选")?;
if read_json(&dir.join("image-jobs").join(&id).join("task.json")).is_ok_and(|task|
task["slotBinding"] == prior["binding"]
&& template_slots::artifact(dir, &id, &task).is_ok_and(|artifact| artifact == prior["artifact"]))
{
return Ok(prior);
}
}
let id = Uuid::new_v4().to_string();
let binding = new_binding(state, output, field, slot, &variant, &id, "历史候选");
let source_request = record.get("requestId").filter(|id| id.is_string()).unwrap_or(&record["sourceRequestId"]);
let mounted = json!({"version":2,"id":id,"binding":binding,"phase":"complete","origin":"human",
"reusedFrom":origin,"materialTaskId":material_task_id(record),"sourceRequestId":source_request,"requestId":null,
"inputHash":target_input,"references":record["references"],"prompt":record["prompt"],
"instructions":"历史候选","createdAt":now()});
mount_archived_candidate(dir, state.clone(), mounted, record["artifact"]["sha256"].clone(), &pixels, project_scoped)
}
fn operation_receipt(mut canonical: Value, candidate: Option<Value>, error: Option<String>) -> Value {
if let Some(candidate) = candidate {
canonical["candidateResult"] = candidate;
@ -2750,6 +2817,7 @@ fn acknowledge_adoption(dir: &Path, state: &Value, input: &Value) -> R<()> {
let mut audit = read_json(&file)?;
for key in [
"candidateId",
"sourceCandidateId",
"slotId",
"variantId",
"nativeLayerId",
@ -2839,6 +2907,16 @@ pub(super) fn save_edited_output(dir: &Path, doc: &Document, bytes: &[u8]) -> R<
Ok(true)
}
pub(super) fn verify_saved_output(dir: &Path, doc: &Document, digest: &str) -> R<()> {
let meta = mapping(doc).ok_or("编辑稿输出映射缺失")?;
let key = document_mapping_key(&meta)?;
let file = dir.join("template-outputs").join(format!("canvas-{key}-edited.pcraft"));
if !file_digest(&file).is_ok_and(|actual| actual == digest) {
return Err("当前输出的编辑稿已变化,请重新保存".into());
}
Ok(())
}
pub(super) fn activate_edited_output(dir: &Path, doc: &Document) -> R<Value> {
activate_edited_output_with_knowledge(dir, doc, &Value::Null, true)
}
@ -2909,6 +2987,9 @@ pub(super) fn manifest_path(generation: &str) -> PathBuf {
pub(super) fn published_receipt(path: &Path) -> R<Value> {
let pointer = read_json(path)?;
if pointer["reopenVerification"]["consistent"] == false {
return Err(DELIVERY_REOPEN_MISMATCH.into());
}
if pointer.get("publishedPointer").is_none() {
return Ok(pointer);
}
@ -2920,6 +3001,9 @@ pub(super) fn published_receipt(path: &Path) -> R<Value> {
return Err("交付指针无效".into());
}
let mut manifest = read_json(&path.parent().ok_or("交付目录缺失")?.join(manifest))?;
if manifest["reopenVerification"]["consistent"] == false {
return Err(DELIVERY_REOPEN_MISMATCH.into());
}
if ["generationId", "workspaceId", "outputId", "variantId"].iter()
.any(|field| manifest[*field] != pointer[*field])
{
@ -4306,6 +4390,7 @@ fn reusable_product_generation(receipt: &Path, result: &Value,
if !result["workingSha256"].is_string() || result["workingSha256"] != old["sourceDocument"]["workingSha256"]
|| !result["stageInputHash"].is_string()
|| old["validation"]["mode"] != "full"
|| old["reopenVerification"]["consistent"] != true
|| ["templateHash", "stageInputHash", "variantId", "outputId", "workspaceId", "imageSources"]
.iter().any(|key| old[*key] != result[*key])
|| !export_records_match(&old["files"], regions, Some(generation))
@ -4374,6 +4459,9 @@ pub(super) fn publish_product_generation(
&& verified.iter().all(|row| row["consistent"] == true));
reopen_verification["manualImages"] = json!(verified);
}
if reopen_verification["consistent"] != true {
return Err(DELIVERY_REOPEN_MISMATCH.into());
}
super::transfer::check_pcraft_file(&editable)?;
let layered = export_layered_document(generation.path(), component, id, &reopened)?;
let exported_mapping = mapping(&reopened);
@ -4893,6 +4981,9 @@ fn snapshot_for_view(dir: &Path, view: Option<Value>, read_only: bool) -> R<Valu
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 historical {
row["adoptionError"] = json!(historical_candidate_pixels(dir, &state, record).err());
}
if record["phase"] == "expired" {
row["retryable"] = json!(false);
row["resultExpiry"] = record["resultExpiry"].clone();
@ -5370,6 +5461,8 @@ impl Backend {
ctx: &egui::Context, source: Option<jiansun_image_transform::SlotSource>,
) -> R<Value> {
let import = method == "slot-import-local" || method == "slot-append" && input["localPath"].is_string();
let historical_adoption = method == "slot-adopt-prep" && input["historicalCandidate"] == true
&& input["detailBatch"] != true && input["workflowOperationId"].is_null();
let local = import || method == "slot-append" && input["useProductReference"] == true;
if !local && !matches!(method, "slot-read" | "slot-recover" | "slot-templates" | "slot-adopted") {
self.check_dispatch()?;
@ -5996,9 +6089,16 @@ impl Backend {
} else if matches!(method, "slot-adopt-prep" | "slot-edit-prep") {
let variant_id = uuid(&input["variantId"], "花色")?;
let id = input["slotId"].as_str().ok_or("请选择图片目标")?;
let source_id = uuid(&input["candidateId"], "候选")?;
let mut record = read_candidate(&dir, &source_id)?;
if historical_adoption {
record = mount_historical_adoption(&dir, &state, input, &record, view_scoped)?;
let current = load(&dir)?;
state["candidates"] = current["candidates"].clone();
state["revision"] = current["revision"].clone();
}
let (output, field) = definition(&state, id, &variant_id)?;
let candidate = uuid(&input["candidateId"], "候选")?;
let record = read_candidate(&dir, &candidate)?;
let candidate = uuid(&record["id"], "候选")?;
if !candidate_available(&record)
|| !state["candidates"].as_array().is_some_and(|ids| ids.contains(&json!(candidate)))
|| record["binding"]["workspaceId"] != state["id"]
@ -6028,6 +6128,8 @@ impl Backend {
let fit = production_placement_fit(&record, field, &input["fit"], input["detailBatch"] == true);
let meta = json!({"canvasFirst":true,"doc":doc,"accountId":self.auth["account"]["id"],"origin":self.origin,"baseRevision":input["baseRevision"],"workspaceRevision":state["revision"],"workspaceId":state["id"],"templateHash":state["template"]["contentHash"],"structureHash":state["structureHash"],"outputId":output["component"],"documentId":output["id"],"slotId":id,"variantId":variant_id,"candidateId":candidate,"taskId":candidate,"nativeLayerId":layer,"sha256":artifact["sha256"],"fit":fit,"frame":frame});
let mut meta = meta;
if historical_adoption { meta["sourceCandidateId"] = json!(source_id); }
if input["previewExport"] == true && !batch { meta["previewExport"] = json!(true); }
meta["fitRequested"] = json!(input["fit"].is_string());
if batch {
meta["detailBatch"] = json!(true);
@ -6115,6 +6217,29 @@ mod tests {
assert_ne!(changed["generationId"], repaired["generationId"]);
}
#[test]
fn product_generation_rejects_reopened_adoption_mismatch_without_replacing_previous_delivery() {
use photocraft_doc::{ColorMode, SampleType, Size};
let temp = tempfile::tempdir().unwrap();
let receipt = temp.path().join("detail.json");
let doc = Document::new("输出", Size::new(8, 8), ColorMode::Rgb, SampleType::U8);
let regions = [(0, 8, 8)];
let mut initial = json!({"outputId":"detail"});
publish_product_generation(&receipt, &doc, &json!(1), &mut initial, &regions, &[]).unwrap();
let previous = fs::read(&receipt).unwrap();
let mut mismatched = json!({"outputId":"detail","imageSources":[{
"slotId":"cover","variantId":"wood","nativeLayerId":1,"candidateId":"missing","embeddedSha256":"missing"
}]});
let error = publish_product_generation(&receipt, &doc, &json!(2), &mut mismatched, &regions, &[]).unwrap_err();
assert!(error.contains("成品工程重开后") && error.contains("未交付成品"));
assert_eq!(fs::read(&receipt).unwrap(), previous);
assert_eq!(fs::read_dir(temp.path().join("generations")).unwrap().count(), 1);
let mut legacy = read_json(&receipt).unwrap();
legacy["reopenVerification"]["consistent"] = json!(false);
write_json(&receipt, &legacy).unwrap();
assert_eq!(published_receipt(&receipt).unwrap_err(), DELIVERY_REOPEN_MISMATCH);
}
#[test]
fn pending_production_reads_legacy_tasks_on_their_original_output() {
let fixture = fixture();
@ -7846,6 +7971,109 @@ mod tests {
json!({"version":2,"id":id,"sequence":state["candidates"].as_array().unwrap().len()+1,"binding":{"schemaVersion":2,"canvasFirst":true,"workspaceId":state["id"],"templateHash":state["template"]["contentHash"],"structureHash":state["structureHash"],"slotId":slot,"variantId":variant,"fieldId":"S01-I01","outputId":"S01","taskId":id,"candidateId":id},"phase":phase,"modelId":"image-model","inputHash":input_hash(dir,&state,variant).unwrap(),"requestId":null,"prompt":"本地fixture不调用模型","instructions":"测试提示"})
}
#[test]
fn historical_candidate_adoption_uses_verified_archive_and_exports_saved_pixels() {
use photocraft_doc::{Affine, ColorMode, Layer, LayerContent, SampleType, Size, SmartObject, SmartSource};
use photocraft_engine::{Session, smart_cmds};
let fixture = fixture();
let mut backend = Backend::new(fixture.dir.join("profile")).unwrap();
let mut document = Document::new("历史项目", Size::new(8, 8), ColorMode::Rgb, SampleType::U8);
let doc = document.id.0;
backend.bind_new(doc);
let dir = backend.project_dir(doc).unwrap();
write_json(&dir.join("context.json"), &json!({"doc":doc})).unwrap();
fs::copy(fixture.dir.join("creation.json"), dir.join("creation.json")).unwrap();
let mut state = load(&fixture.dir).unwrap();
let variant = state["activeVariantId"].as_str().unwrap().to_owned();
let slot = slot_id(&state["template"]["contentHash"], &variant, "S01-I01");
let flat_png = |rgba: [u8; 4]| encode_template_rgba(8, 8, rgba.repeat(64)).unwrap();
let object = SmartObject::new(SmartSource::Embedded {
file_name:"template-empty.png".into(), bytes:Arc::new(flat_png([255, 255, 255, 255])),
}, Affine::IDENTITY, None);
let contents = object.contents_id;
let layer = Layer::new("产品图", LayerContent::Smart(object));
let layer_id = layer.id;
document.layers.push(layer);
let mapping = json!({"version":1,"canvasFirst":true,"workspaceId":state["id"],"templateId":state["template"]["id"],
"templateVersion":state["template"]["version"],"templateHash":state["template"]["contentHash"],
"variantId":variant,"component":"detail","outputId":null,"outputs":[{"documentId":"S01",
"mapping":{"fields":[{"kind":"image","fieldId":"S01-I01","slotId":slot,"nativeLayerId":layer_id.0,
"frame":{"x":0,"y":0,"width":8,"height":8}}]}}]});
document.metadata.text.push((MAPPING.into(), mapping.to_string()));
let key = mapping_key(&variant, "detail", None);
state["activeMapping"] = json!(key);
state["mappings"][&key] = mapping;
let id = Uuid::new_v4().to_string();
let mut binding = new_binding(&state, &state["template"]["outputs"][0],
&state["template"]["outputs"][0]["slots"][0], &slot, &variant, &id, "历史样图");
binding["structureHash"] = json!("old-structure");
let png = flat_png([220, 30, 20, 255]);
let file = candidate_path(&dir, &id).unwrap();
let record = json!({"version":2,"id":id,"binding":binding,"phase":"complete","sequence":1,
"inputHash":"old-input","artifact":{"taskId":id,"path":format!("image-jobs/{id}/generated.png"),
"sha256":format!("{:x}",Sha256::digest(&png))}});
write_json(&file, &record).unwrap();
state["candidates"] = json!([id]);
let state = persist(&dir, state, 0).unwrap();
let generated = file.with_file_name("generated.png");
let (events, receiver) = mpsc::channel();
let ctx = egui::Context::default();
let mut session = Session::new();
session.add_document(document, None);
let revision = session.active().unwrap().revision;
let input = json!({"doc":doc,"slotRevision":state["revision"],"baseRevision":revision,
"candidateId":id,"slotId":slot,"variantId":variant,"nativeLayerId":layer_id.0,"historicalCandidate":true});
for invalid in [None, Some(flat_png([1, 2, 3, 255]))] {
if let Some(bytes) = invalid { fs::write(&generated, bytes).unwrap(); }
assert!(snapshot(&dir).unwrap()["slots"][0]["candidates"][0]["adoptionError"].is_string());
assert!(backend.canvas_workspace_action("slot-adopt-prep", &input, &events, &ctx).is_err());
assert!(receiver.try_recv().is_err());
}
fs::write(&generated, &png).unwrap();
let row = &snapshot(&dir).unwrap()["slots"][0]["candidates"][0];
assert_eq!(row["historical"], true);
assert!(row["adoptionError"].is_null());
backend.canvas_workspace_action("slot-adopt-prep", &input, &events, &ctx).unwrap();
let Event::SlotAdopt { bytes, meta } = receiver.try_recv().unwrap() else { panic!("expected native adoption") };
assert_eq!(meta["sourceCandidateId"], id);
let mounted = meta["candidateId"].as_str().unwrap();
assert_ne!(mounted, id);
assert_eq!(read_candidate(&dir, mounted).unwrap()["reusedFrom"]["candidateId"], id);
assert_eq!(read_candidate(&dir, &id).unwrap(), record);
assert_eq!(bytes, png);
let mut retry = input.clone();
retry["slotRevision"] = load(&dir).unwrap()["revision"].clone();
backend.canvas_workspace_action("slot-adopt-prep", &retry, &events, &ctx).unwrap();
let Event::SlotAdopt { meta: retried, .. } = receiver.try_recv().unwrap() else { panic!("expected adoption retry") };
assert_eq!(retried["candidateId"], mounted);
let ticket = smart_cmds::freeze_source(&session, photocraft_doc::DocId(doc), revision, layer_id, contents).unwrap();
let updated = photocraft_ui_egui::jiansun::prepare_adoption_document(
&session.active().unwrap().doc, &meta, bytes, &ticket, false).unwrap();
session.edit("采纳图片", |doc, _| { *doc = updated.document; Ok(()) }).unwrap();
let active = session.active().unwrap();
let receipt = backend.save(active.doc.clone(), active.revision, json!({})).unwrap();
assert_eq!(receipt["localSave"]["state"], "saved");
let reopened = super::super::load_draft(&dir, Path::new(receipt["savedPath"].as_str().unwrap())).unwrap();
let marker = format!("jiansun.adopted.{variant}.{slot}");
assert!(reopened.metadata.text.iter().any(|(key, id)| key == &marker && id == mounted));
let mut checkpoint = backend.save_product_view(&reopened).unwrap();
let context_path = dir.join("context.json");
let mut context = read_json(&context_path).unwrap();
context["revision"] = json!(active.revision + 1);
write_json(&context_path, &context).unwrap();
let output = tempfile::tempdir().unwrap();
let options = json!({"jpg":true,"file":output.path().join("历史项目.xiaoyi")});
let mut stale = checkpoint.clone();
stale["outputCheckpointSha256"] = json!("stale");
assert!(backend.deliver_project(&reopened, active.revision, &options, &mut stale).is_err());
backend.deliver_project(&reopened, active.revision, &options, &mut checkpoint).unwrap();
let delivered = Path::new(checkpoint["delivered"]["outputs"].as_str().unwrap());
let jpg = photocraft_codecs::decode(&fs::read(delivered.join("当前画布.jpg")).unwrap()).unwrap();
let pixels = jpg.as_u8().unwrap();
assert!(pixels[0] > 180 && pixels[1] < 80 && pixels[2] < 80, "JPG contains the adopted red product image");
}
#[test]
fn completed_images_can_be_transformed_and_reused_across_product_outputs() {
let project = fixture();

View File

@ -561,7 +561,9 @@ impl Backend {
#[cfg(test)]
mod tests {
use super::*;
use photocraft_doc::{ColorMode, Document, SampleType, Size};
use photocraft_doc::{Affine, ColorMode, Document, Layer, LayerContent, SampleType, Size, SmartObject, SmartSource};
const OPAQUE_BLOCK: [u8; 4] = *b"tstD";
fn fixture() -> (tempfile::TempDir, PathBuf, String, Value) {
let root = tempfile::tempdir().unwrap();
@ -569,7 +571,7 @@ mod tests {
let project = root.path().join("drafts").join(&local);
fs::create_dir_all(&project).unwrap();
let mut canvas = Document::new("天青椅", Size::new(8, 10), ColorMode::Rgb, SampleType::U8);
canvas.metadata.psd_global_blocks.push((*b"8BIM", *b"lnk2", std::sync::Arc::new(vec![123; 1 << 20])));
canvas.metadata.psd_global_blocks.push((*b"8BIM", OPAQUE_BLOCK, std::sync::Arc::new(vec![123; 1 << 20])));
let draft = photocraft_format::PcraftWriter::new().save_draft_zip(&canvas, &super::super::draft_objects(&project)).unwrap();
fs::write(project.join("canvas.pcraft"), draft).unwrap();
write_json(&project.join("context.json"), &json!({"localId":local,"owner":"owner"})).unwrap();
@ -593,6 +595,7 @@ mod tests {
("main_images", vec![(0, 8, 4), (4, 8, 6)], vec![]),
("sku_images", vec![(0, 8, 10)], vec![]),
] {
let mut canvas = canvas.clone();
let pages = if component == "detail" { &screens } else { &regions };
let outputs = pages.iter().enumerate().map(|(index, (top, width, height))|
json!({"documentId":format!("{component}-{}",index+1),"top":top,"width":width,"height":height}))
@ -601,14 +604,26 @@ mod tests {
let receipt = canvas_workspace::receipt_path(&project, &variant, component);
let mut result = json!({"workspaceId":workspace,"variantId":variant,"outputId":component});
if component == "detail" {
let pixels = std::sync::Arc::new(png.clone());
let source = photocraft_engine::smart_cmds::prepare_bounded_source("candidate.png", pixels.clone()).unwrap();
let mut layer = Layer::new("已采纳图片", LayerContent::Smart(SmartObject::new(
SmartSource::Embedded { file_name:"candidate.png".into(), bytes:pixels },
Affine::IDENTITY, None,
)));
photocraft_engine::smart_cmds::refresh_layer_with_bounded_source(&canvas, &mut layer, &source).unwrap();
let layer_id = layer.id.0;
canvas.layers.push(layer);
canvas.metadata.text.push((format!("jiansun.adopted.{variant}.slot"), task.clone()));
result["unverifiedCopy"] = json!(["S01-T01"]);
result["unverifiedFacts"] = json!([{"fieldId":"S01-T01","pageId":"S01",
"label":"材质","productValues":[],"basis":"资料未注明"}]);
result["imageSources"] = json!([{"pageId":"S01","fieldId":"I01","slotId":"slot",
"variantId":variant,"nativeLayerId":layer_id,"embeddedSha256":adopted_sha,
"candidateId":task,"requestId":"request","prompt":"Adopted image prompt",
"candidateArtifact":{"taskId":task,"path":adopted,"sha256":adopted_sha}}]);
}
canvas_workspace::publish_product_generation(&receipt, &canvas, &json!(7), &mut result, &regions, &screens).unwrap();
assert_eq!(result["reopenVerification"]["consistent"], true);
assert_eq!(result["layeredDocument"]["format"], "psd");
assert_eq!(result["validation"]["filesVerified"], 2 + regions.len() + screens.len());
published.push(json!({"variantId":variant,"outputId":component,"generationId":result["generationId"]}));
@ -936,7 +951,7 @@ mod tests {
assert_eq!(canvas_workspace::layered_size(&filename, &bytes).unwrap(), (8, 10));
let layered = photocraft_io::import(&filename, &bytes).unwrap().document;
assert!(layered.metadata.psd_global_blocks.iter().any(|(_, key, bytes)|
key == b"lnk2" && bytes.len() == 1 << 20 && bytes.iter().all(|&byte| byte == 123)));
*key == OPAQUE_BLOCK && bytes.len() == 1 << 20 && bytes.iter().all(|&byte| byte == 123)));
}
for entry in manifest["files"].as_array().unwrap() {
let relative = entry["relativePath"].as_str().unwrap();

View File

@ -1307,7 +1307,9 @@ impl Workspace {
let batch_image = delegated && pi_slot_operation && input["detailBatch"] == true;
let scoped_export = method == "slot-product-export" && (self.production_can_use_scoped_pending()
|| self.production_stop["state"] == "delivering");
if !batch_image && !scoped_export && !slot_action_allowed(&self.template_workflow, self.unknown, method) {
let local_history = local_adoption && !delegated && input["historicalCandidate"] == true
&& self.template_workflow["canvasFirst"] == true;
if !batch_image && !scoped_export && !local_history && !slot_action_allowed(&self.template_workflow, self.unknown, method) {
return Err(if self.unknown {
"原请求待核查,此操作尚未获准;不会重发"
} else {
@ -2864,7 +2866,7 @@ impl Workspace {
"projectLocalId":self.pi_request_scope["project"]["localId"],"documentId":state.doc.id.0,
"beforeRevision":meta.get("commitBaseRevision").unwrap_or(&meta["baseRevision"]),"afterRevision":state.revision,"method":"workflow.execute","command":"slot-adopt",
"dispatched":true,"executed":true,"pending":false,"completed":true,
"actualResult":{"slotId":meta["slotId"],"candidateId":meta["candidateId"]},"subject":self.pi_request_scope["subject"]});
"actualResult":{"slotId":meta["slotId"],"candidateId":meta["candidateId"],"localSave":meta["localSave"]},"subject":self.pi_request_scope["subject"]});
if self.agent_native.record(receipt).is_err() {
self.handover();
return;
@ -2882,6 +2884,8 @@ impl Workspace {
*before = applied.clone();
}
}
#[cfg(not(target_arch = "wasm32"))]
self.preview_export_adopted(meta, adopted);
}
fn receive_json_slot(&mut self, app: &mut PhotocraftApp, name: &str, v: Value) {
@ -2908,7 +2912,7 @@ impl Workspace {
&& self.pi_request_scope["productProduction"] == true && v["candidateResult"]["id"].is_string();
if let Some(error) = v["error"].as_str().filter(|_| !settled_batch_candidate) {
if !self.show_library_action_error(error) { self.error = error.into(); }
} else if name != "slot-adopt-prep" && (name != "slot-skeleton" || self.canvas_scope_valid(app)) {
} else if !matches!(name, "slot-adopt-prep" | "slot-adopted") && (name != "slot-skeleton" || self.canvas_scope_valid(app)) {
// The canonical switch can finish after the native
// canvas rejected its stale revision. Preserve that
// local refusal until the visible scope is accepted.
@ -3223,6 +3227,17 @@ impl Workspace {
self.receive_creation_save(app, result);
return;
}
let adoption_save_failed = method == "save" && result.is_err()
&& self.saving.is_some_and(|(doc, rev)| self.has_pending_adoption_save(doc, rev));
#[cfg(not(target_arch = "wasm32"))]
let preview_adoption_failed = method == "slot-adopt-prep" && result.is_err();
if adoption_save_failed {
self.fail_adoption_save();
self.draft_changed = true;
if let Err(error) = &mut result {
*error = format!("图片已采纳,工程保存失败:{error}");
}
}
if method == "save" && let Err(error) = &result
&& self.template_progress["phase"] == "save"
{
@ -3479,6 +3494,10 @@ impl Workspace {
Err(e) => self.receive_json_error(&method, e),
Ok(v) => self.receive_json_success(app, ctx, &method, v, live_image_request),
}
#[cfg(not(target_arch = "wasm32"))]
if adoption_save_failed || preview_adoption_failed {
self.cancel_preview_export();
}
}
fn receive_json_error(&mut self, method: &str, e: String) {
@ -4173,6 +4192,11 @@ impl Workspace {
}
}
if self.authority_active() {
if self.product_view_detached()
&& let Some((meta, adopted)) = self.poll_canvas_adoption(app, ctx, painting)
{
self.finish_adoption_receipt(app, &meta, adopted);
}
self.with_product_target(app, |w, app| {
if let Some((meta, adopted)) = w.poll_canvas_adoption(app, ctx, painting) {
w.finish_adoption_receipt(app, &meta, adopted);
@ -4283,6 +4307,9 @@ impl Workspace {
if self.product_view_detached() && self.can_start_production_turn() && self.production_start_waiting() {
self.park_user_canvas_changes(app);
}
if self.product_view_detached() && self.canvas_workspace.adoption_save_pending.is_some() {
self.autosave_project(app, ctx);
}
self.with_product_target(app, |w, app| {
let now = Instant::now();
w.production_tick(app);
@ -4343,6 +4370,16 @@ impl Workspace {
Event::SlotCanvas(doc, meta) if meta["continueProduct"] == true =>
self.continue_product_canvas(app, doc, meta),
Event::Saved(id, revision, ref meta) if self.product_view_saved(app, id, revision, meta) => {}
Event::Saved(id, revision, meta) if self.product_view_detached() && meta["documentKey"].is_object()
&& (self.has_pending_adoption_save(id, revision) || self.saving == Some((id, revision)))
&& app.session.active().is_some_and(|state| state.doc.id.0 == id && product_document_key(&state.doc) == meta["documentKey"]) =>
self.receive_event(app, ctx, Event::Saved(id, revision, meta)),
Event::Json(method, result) if method == "slot-adopt-prep" && self.product_view_detached()
&& self.canvas_workspace.pending_adoption.as_ref().is_some_and(|pending| pending["detailBatch"] != true) =>
self.receive_event(app, ctx, Event::Json(method, result)),
Event::Json(method, result) if method == "save" && self.product_view_detached()
&& self.saving.is_some_and(|(doc, rev)| self.has_pending_adoption_save(doc, rev)) =>
self.receive_event(app, ctx, Event::Json(method, result)),
Event::Json(method, Ok(value)) if method == "slot-product-view" => self.product_view_failed(&value),
Event::Json(method, Ok(value)) if method == "slot-product-view-progress" =>
self.product_view_progressed(app, &value),
@ -4371,17 +4408,43 @@ impl Workspace {
}
}
fn has_pending_adoption_save(&self, id: u64, rev: u64) -> bool {
self.canvas_workspace.adoption_save_pending
.is_some_and(|(doc, revision)| doc == id && rev >= revision)
}
fn fail_adoption_save(&mut self) {
if let Some((doc, revision)) = self.canvas_workspace.adoption_save_pending.take() {
self.workflow.adoption_save_settled(doc, revision, false);
}
}
fn adoption_saved(&mut self, _app: &PhotocraftApp, _ctx: &egui::Context, id: u64, rev: u64) {
if !self.has_pending_adoption_save(id, rev) { return; }
let exact = self.canvas_workspace.adoption_save_pending.take() == Some((id, rev));
if exact {
self.workflow.adoption_save_settled(id, rev, true);
self.note("图片已采纳并保存到本机");
#[cfg(not(target_arch = "wasm32"))]
self.preview_export_saved(_app, _ctx, id, rev);
} else {
#[cfg(not(target_arch = "wasm32"))]
self.cancel_preview_export();
}
}
fn autosave_project(&mut self, app: &PhotocraftApp, ctx: &egui::Context) {
// A view activation writes the same project checkpoint as the worker.
// Wait for its receipt before the next autosave can select a snapshot.
if self.product_view_save_pending() || self.canvas_workspace.scope_blocked || self.professional_child_active(app) { return; }
if let Some(st) = app.session.active() {
let key = (st.doc.id.0, st.revision);
let saved = self.persisted_revisions.get(&key.0) == Some(&key.1);
let adopted = self.has_pending_adoption_save(key.0, key.1);
let saved = !adopted && self.persisted_revisions.get(&key.0) == Some(&key.1);
if (!saved || self.draft_changed) && self.saving.is_none() && self.canvas_workspace.pending_adoption.is_none() && !self.canvas_workspace.adoption_preparing()
&& self.loaded_draft == Some(key.0) {
if saved && self.metadata_saving.is_some() { return; }
let delay = if !saved && self.product_production.as_ref().is_some_and(product_production::Run::awaiting_canvas_save) {
let delay = if adopted || !saved && self.product_production.as_ref().is_some_and(product_production::Run::awaiting_canvas_save) {
Duration::ZERO
} else if self.product_production.is_some() && self.pi_run.is_some() {
Duration::from_secs(20)
@ -4396,8 +4459,11 @@ impl Workspace {
if saved {
let composer_saved = self.flush_document_draft(ctx, Some(key.0), false);
self.submit_project_draft(st, composer_saved, true);
} else {
self.save_project_draft(st, ctx);
} else if !self.save_project_draft(st, ctx) && adopted {
self.fail_adoption_save();
self.error = "图片已采纳,工程保存服务不可用".into();
#[cfg(not(target_arch = "wasm32"))]
self.cancel_preview_export();
}
}
}
@ -4429,6 +4495,22 @@ impl Workspace {
submitted
}
fn receive_project_delivery_receipt(&mut self, app: &mut PhotocraftApp, id: u64, rev: u64, meta: &Value) {
if let Some(path) = meta["projectFile"]["path"].as_str() {
self.project_files.insert(id, path.to_owned());
if let Some(state) = app.session.active_mut().filter(|state| state.doc.id.0 == id) {
state.path = Some(path.into());
state.saved_revision = rev;
}
}
if let Some(error) = meta["deliveryError"].as_str() {
self.error = error.into();
} else if meta["delivered"].is_object() {
let path = meta["delivered"]["path"].as_str().or(meta["delivered"]["outputs"].as_str()).unwrap_or("");
self.note(format!("已保存至 {path}"));
}
}
fn receive_event(&mut self, app: &mut PhotocraftApp, ctx: &egui::Context, event: Event) {
match event {
Event::PiAction(method, mut input, reply) => {
@ -4540,14 +4622,18 @@ impl Workspace {
self.saving = None;
}
self.persisted_revisions.insert(id, rev);
let save_owned_here =
self.open_projects.get(&id).map_or(self.loaded_draft == Some(id), |identity| identity.starts_with(&self.local_identity("")));
// An output checkpoint can satisfy the canvas save without
// advancing the main project's local metadata or file path.
// advancing the main project's local metadata.
if meta["outputCheckpointOnly"] == true {
if let Some(state) = app.session.active_mut().filter(|state| state.doc.id.0 == id && state.revision == rev) {
state.saved_revision = rev;
}
if save_owned_here { self.receive_project_delivery_receipt(app, id, rev, &meta); }
self.slot_apply_saved(app, id, rev);
self.project_open_saved(app, id, rev);
self.adoption_saved(app, ctx, id, rev);
return;
}
self.saved = Some((id, rev, meta["time"].as_str().unwrap_or("").into()));
@ -4562,33 +4648,17 @@ impl Workspace {
self.project_context = context;
self.sync_dirty = dirty;
}
let save_owned_here =
self.open_projects.get(&id).map_or(self.loaded_draft == Some(id), |identity| identity.starts_with(&self.local_identity("")));
if let Some(local) = meta["localId"].as_str().filter(|_| save_owned_here) {
self.open_projects.insert(id, self.local_identity(local));
}
if save_owned_here && let Some(path) = meta["projectFile"]["path"].as_str() {
self.project_files.insert(id, path.to_owned());
if let Some(state) = app.session.active_mut().filter(|state| state.doc.id.0 == id) {
state.path = Some(path.into());
state.saved_revision = rev;
}
}
if save_owned_here {
if let Some(error) = meta["deliveryError"].as_str() {
self.error = error.into();
} else if meta["delivered"].is_object() {
let path = meta["delivered"]["path"].as_str().or(meta["delivered"]["outputs"].as_str()).unwrap_or("");
self.note(format!("已保存至 {path}"));
}
}
if save_owned_here { self.receive_project_delivery_receipt(app, id, rev, &meta); }
self.production_saved(app, id, rev, &meta, save_owned_here);
if let Some(items) = meta["projects"].as_array() {
self.merge_project_receipt(app, items);
}
self.slot_apply_saved(app, id, rev);
self.project_open_saved(app, id, rev);
self.adoption_saved(app, ctx, id, rev);
}
Event::Preview(reference, image) => {
if matches!(reference["purpose"].as_str(), Some("creation-material" | "creation-platform-preview")) {

View File

@ -85,6 +85,9 @@ pub(super) struct State {
composer_edit_version: u64,
submitted_composer: Option<SubmittedComposer>,
pub(super) pending_adoption: Option<Value>,
pub(super) adoption_save_pending: Option<(u64, u64)>,
#[cfg(not(target_arch = "wasm32"))]
pub(super) preview_export: Option<super::project_file::PreviewExport>,
adoption_worker: Option<AdoptionWorker>,
pub(super) handed_over: bool,
pub(super) scope_blocked: bool,
@ -424,6 +427,18 @@ fn candidates(slot: &Value) -> &[Value] {
slot["candidates"].as_array().map(Vec::as_slice).unwrap_or(&[])
}
fn candidate_adoption_input(candidate: &Value, slot: &str, variant: &str, layer: Option<u64>) -> Value {
let mut input = json!({"slotId":slot,"candidateId":candidate["id"],"variantId":variant,"nativeLayerId":layer});
if candidate["historical"] == true {
input["historicalCandidate"] = json!(true);
}
input
}
fn candidate_can_adopt(candidate: &Value, layer: Option<u64>) -> bool {
candidate["status"] == "complete" && candidate["adoptionError"].is_null() && layer.is_some()
}
fn first_generated_preview(slot: &Value) -> Option<&Value> {
candidates(slot).iter()
.find(|candidate| candidate["status"] == "complete" && candidate["historical"] != true
@ -1537,6 +1552,8 @@ impl Workspace {
self.canvas_workspace.locate_highlight = None;
self.canvas_workspace.invalidate_regen();
self.canvas_workspace.pending_adoption = None;
#[cfg(not(target_arch = "wasm32"))]
self.cancel_preview_export();
self.canvas_workspace.submitted_composer = None;
self.canvas_workspace.submitted_regen = None;
self.canvas_workspace.clear_canvas_geometry();
@ -1673,6 +1690,7 @@ impl Workspace {
use std::sync::atomic::Ordering;
let pending = self.canvas_workspace.pending_adoption.clone()?;
let batch = meta["detailBatch"] == true;
let candidate = meta.get("sourceCandidateId").unwrap_or(&meta["candidateId"]);
let write_mode = adoption_write_mode(self, app);
if pending["workflowOperationId"] != meta["workflowOperationId"] || pending["workflowRun"] != meta["workflowRun"] {
return Some((meta, false));
@ -1683,11 +1701,13 @@ impl Workspace {
&& meta["doc"].as_u64() == Some(state.doc.id.0)
&& (if batch { valid_detail_adoption(self, &state.doc, &meta) } else { meta["baseRevision"].as_u64() == Some(state.revision) })
&& meta["templateHash"] == self.template_workflow["templateHash"]
&& pending["slotId"] == meta["slotId"] && pending["candidateId"] == meta["candidateId"] && pending["variantId"] == meta["variantId"]
&& pending["slotId"] == meta["slotId"] && pending["candidateId"] == *candidate && pending["variantId"] == meta["variantId"]
&& (pending["historicalCandidate"] == true) == meta["sourceCandidateId"].is_string()
&& pending["previewExport"] == meta["previewExport"]
&& meta["nativeLayerId"].as_u64().is_some_and(|layer| meta["slotId"].as_str().and_then(|slot| native_layer(&state.doc, slot)) == Some(layer))
});
if !valid {
if pending["slotId"] == meta["slotId"] && pending["candidateId"] == meta["candidateId"] && pending["variantId"] == meta["variantId"] {
if pending["slotId"] == meta["slotId"] && pending["candidateId"] == *candidate && pending["variantId"] == meta["variantId"] {
self.canvas_workspace.pending_adoption = None;
}
self.error = adoption_block_reason(self, app, &mut meta)
@ -1948,6 +1968,13 @@ impl Workspace {
Ok(())
}) { self.error = error.to_string(); return Some((meta, false)); }
if batch { meta["commitBaseRevision"] = json!(before_revision); }
if let Some(active) = app.session.active() {
let doc = active.doc.clone();
let revision = active.revision;
app.clear_slot_preview(&doc, layer);
self.canvas_workspace.adoption_save_pending = Some((doc.id.0, revision));
meta["localSave"] = json!({"state":"pending","revision":revision});
}
if agent_adoption {
if let Some(active) = app.session.active() {
self.sync_pi_canvas_basis_layers(&active.doc, &[layer]);
@ -1982,7 +2009,8 @@ impl Workspace {
}
if self.tx.send(Request::Action("slot-adopted".into(), ack)).is_err() {
self.error = "图片已在本机采纳;记录尚未保存,请保留工程".into();
} else { self.note("已采纳图片,可撤销"); }
}
self.autosave_project(app, ctx);
Some((meta, true))
}
pub(crate) fn canvas_adoption_valid(&self, app: &PhotocraftApp, lease: &Value, started: std::time::Instant) -> bool {
@ -2241,15 +2269,17 @@ impl Workspace {
}
constrain_candidate_menu_width(ui);
ui.spacing_mut().item_spacing.y = 2.0;
let adopt_enabled = candidate_can_adopt(c, mapping_layer) && !adopted
&& self.canvas_workspace.pending_adoption.is_none() && self.saving.is_none();
if super::stitch_ui::menu_item(
ui,
"采纳",
c["status"] == "complete" && c["historical"] != true && !adopted && self.canvas_workspace.pending_adoption.is_none() && self.saving.is_none(),
adopt_enabled,
)
.on_disabled_hover_text(c["adoptionError"].as_str().unwrap_or("当前无法采纳"))
.clicked()
{
action =
Some(("slot-adopt-prep", json!({"slotId":slot_id,"candidateId":id,"variantId":variant,"nativeLayerId":mapping_layer})));
action = Some(("slot-adopt-prep", candidate_adoption_input(c, slot_id, variant, mapping_layer)));
ui.close();
}
if matches!(c["status"].as_str(), Some("unknown" | "prepared" | "dispatched" | "running"))
@ -2302,7 +2332,8 @@ impl Workspace {
});
});
if let Some(shown) = shown {
let mut menu_rows = vec![("采纳", c["status"] == "complete" && !adopted && self.canvas_workspace.pending_adoption.is_none() && self.saving.is_none())];
let mut menu_rows = vec![("采纳", candidate_can_adopt(c, mapping_layer) && !adopted
&& self.canvas_workspace.pending_adoption.is_none() && self.saving.is_none())];
if matches!(c["status"].as_str(), Some("unknown" | "prepared" | "dispatched" | "running")) {
menu_rows.push(("核查原结果", true));
}
@ -2555,6 +2586,10 @@ impl Workspace {
}
let mut has_image = false;
if let Some(c) = candidate {
let adoption_error = c["adoptionError"].as_str();
if let Some(error) = adoption_error {
let _ = response.clone().on_hover_text(error);
}
if let Some(texture) = self.agent_images.get(task_id) {
let (ease, _) = self.canvas_workspace.appeared.get(task_id)
.map(|start| super::agent_motion::image_enter(now - *start, screen_scale, self.reduce_motion))
@ -2564,8 +2599,9 @@ 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 request = if c["archivePreview"] == true {
} else if c["status"] == "complete" && c["adoptionError"].is_null() && !task_id.is_empty()
&& self.agent_images.can_insert(task_id) && self.requested_previews.insert(task_id.to_owned()) {
let request = if c["historical"] == true || c["archivePreview"] == true {
Request::Action("slot-read".into(), json!({"doc":doc_id,"previewCandidateId":task_id,
"viewOutputId":output,"viewVariantId":variant,"viewTemplateHash":workflow["templateHash"]}))
} else {
@ -2600,7 +2636,9 @@ impl Workspace {
ui.data_mut(|data| data.remove::<f64>(waiting_id));
}
if !has_image && !processing {
let text = if self.agent_effects_paused && matches!(c["status"].as_str(), Some("prepared" | "dispatched" | "running")) {
let text = if adoption_error.is_some() {
"历史图片不可用"
} else if self.agent_effects_paused && matches!(c["status"].as_str(), Some("prepared" | "dispatched" | "running")) {
"已停止修改 · 原请求保留"
} else if c["status"] == "complete" {
"已生成 · 预览未载入"
@ -2614,7 +2652,7 @@ impl Workspace {
Align2::CENTER_CENTER,
text,
FontId::proportional(13.0),
if c["status"] == "unknown" { t.warning } else { t.text_dim },
if c["status"] == "unknown" || adoption_error.is_some() { t.warning } else { t.text_dim },
);
}
let can_expand = has_image && rect.width() >= 42.0 && rect.height() >= 42.0
@ -2639,15 +2677,17 @@ 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" && c["historical"] != true && !adopted {
if c["status"] == "complete" && !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)));
let pending = self.canvas_workspace.pending_adoption.as_ref().is_some_and(|pending| pending["candidateId"] == id);
let enabled = !reference_owns_pointer && self.canvas_workspace.pending_adoption.is_none() && self.saving.is_none()
let enabled = candidate_can_adopt(c, mapping_layer) && !reference_owns_pointer
&& self.canvas_workspace.pending_adoption.is_none() && self.saving.is_none()
&& app.ui.dialogs.is_empty() && !egui::Popup::is_any_open(ui.ctx())
&& ui.memory(|memory| memory.top_modal_layer().is_none());
let response = super::stitch_ui::action_button(&mut controls, if pending { "采纳中…" } else { "采纳" }, super::stitch_ui::ButtonRole::Primary, enabled);
let response = super::stitch_ui::action_button(&mut controls, if pending { "采纳中…" } else { "采纳" }, super::stitch_ui::ButtonRole::Primary, enabled)
.on_disabled_hover_text(c["adoptionError"].as_str().unwrap_or("当前无法采纳"));
self.canvas_workspace
.geometry
.insert(format!("adopt:{key}"), [response.rect.min.x, response.rect.min.y, response.rect.width(), response.rect.height()]);
@ -2668,8 +2708,7 @@ impl Workspace {
clicked
});
if response.clicked() || clicked {
result.action =
Some(("slot-adopt-prep", json!({"slotId":slot_id,"candidateId":id,"variantId":variant,"nativeLayerId":mapping_layer})));
result.action = Some(("slot-adopt-prep", candidate_adoption_input(c, slot_id, variant, mapping_layer)));
}
} else if c["status"] != "complete" {
painter.text(
@ -5476,7 +5515,7 @@ pub(super) mod tests {
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"));
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;
@ -5821,6 +5860,35 @@ pub(super) mod tests {
}
}
#[test]
fn historical_card_adopts_the_verified_mounted_candidate_into_the_native_layer() {
let (mut w, mut app, requests, layer, bytes) = native_fixture();
let mut candidate = json!({"id":"old-photo","status":"complete","historical":true});
candidate["adoptionError"] = json!("历史图片已缺失");
assert!(!candidate_can_adopt(&candidate, Some(layer)));
candidate["adoptionError"] = Value::Null;
assert!(candidate_can_adopt(&candidate, Some(layer)));
let input = candidate_adoption_input(&candidate, "image-slot", "wood", Some(layer));
w.slot_action(&app, "slot-adopt-prep", input).unwrap();
let Request::Action(method, mut meta) = requests.try_recv().unwrap() else { panic!("expected native adoption request") };
assert_eq!(method, "slot-adopt-prep");
assert_eq!(meta["historicalCandidate"], true);
meta["accountId"] = w.account["id"].clone();
meta["origin"] = json!(w.origin);
meta["templateHash"] = json!("fixed");
meta["fit"] = json!("contain");
meta["sourceCandidateId"] = json!("old-photo");
meta["candidateId"] = json!("mounted-photo");
adopt_and_wait(&mut w, &mut app, bytes, meta);
let doc = &app.session.active().unwrap().doc;
assert_eq!(adopted(doc, "image-slot", "wood"), Some("mounted-photo"));
let Request::Action(method, receipt) = requests.try_recv().unwrap() else { panic!("expected adoption receipt") };
assert_eq!(method, "slot-adopted");
assert_eq!(receipt["sourceCandidateId"], "old-photo");
assert_eq!(receipt["candidateId"], "mounted-photo");
assert_eq!(receipt["localSave"]["state"], "pending");
}
#[test]
fn adoption_checkpoint_survives_reopen_without_an_acknowledgment() {
use photocraft_doc::{DocId, LayerId, SmartSource};
@ -6003,7 +6071,7 @@ pub(super) mod tests {
#[test]
fn production_replaces_its_own_candidate_and_preserves_manual_layer_edits() {
use super::super::workflow_bridge;
let (mut w, mut app, _requests, layer, bytes) = native_fixture();
let (mut w, mut app, requests, layer, bytes) = native_fixture();
let state = app.session.active().unwrap();
let doc = state.doc.id.0;
let other = state.doc.layers.last().unwrap().id;
@ -6057,7 +6125,13 @@ pub(super) mod tests {
}
adopt_and_wait(&mut w, &mut app, bytes.clone(), meta.clone());
assert!(w.error.is_empty(), "{}", w.error);
assert!(w.workflow.adoption_receipt(&meta, true, None));
let Request::Action(method, receipt) = requests.try_recv().unwrap() else { panic!("expected adoption receipt") };
assert_eq!(method, "slot-adopted");
assert_eq!(receipt["localSave"]["state"], "pending");
assert!(w.workflow.adoption_receipt(&receipt, true, None));
let Request::Save(saved, revision, _) = requests.try_recv().unwrap() else { panic!("expected canvas checkpoint") };
w.receive_event(&mut app, &egui::Context::default(), super::super::Event::Saved(doc, revision,
json!({"outputCheckpointOnly":true,"documentKey":super::super::product_document_key(&saved)})));
let state = app.session.active().unwrap();
assert_eq!(adopted(&state.doc, "image-slot", "wood"), Some(candidate));
assert!(w.detail_layer_unchanged(&state.doc, target));

View File

@ -1,5 +1,6 @@
use super::{PhotocraftApp, RichText, Value, Workspace, json, stitch_ui};
use super::{PhotocraftApp, RichText, Value, Workspace, canvas_workspace, json, product_document_key, stitch_ui};
use crate::theme::Tokens;
use std::collections::VecDeque;
#[derive(Clone)]
struct SaveDialog {
@ -20,7 +21,113 @@ impl SaveDialog {
}
}
#[derive(Clone)]
pub(super) struct PreviewExport {
dialog: SaveDialog,
file: String,
document_key: Value,
revision: u64,
remaining: VecDeque<Value>,
}
fn unadopted_previews(app: &PhotocraftApp, doc: &super::Document) -> VecDeque<Value> {
let Some(mapping) = canvas_workspace::document_mapping(doc) else { return VecDeque::new(); };
let Some(variant) = mapping["variantId"].as_str() else { return VecDeque::new(); };
canvas_workspace::native_layers(doc).into_iter().filter_map(|(slot, layer)| {
let layer_id = photocraft_doc::LayerId(layer);
let candidate = app.slot_preview_candidate(doc, layer_id)?;
let path = doc.path_of(layer_id)?;
let visible = (1..=path.len()).all(|depth| doc.layer_at(&path[..depth]).is_some_and(|layer| layer.visible));
if !visible
|| canvas_workspace::adopted(doc, &slot, variant).is_some()
|| canvas_workspace::manual_image(doc, &slot, variant).is_some()
{
return None;
}
Some(json!({"slotId":slot,"candidateId":candidate,"variantId":variant,"nativeLayerId":layer}))
}).collect()
}
impl PreviewExport {
fn matches(&self, w: &Workspace, app: &PhotocraftApp) -> bool {
w.loaded_draft == Some(self.dialog.doc) && w.account["id"] == self.dialog.account
&& w.origin == self.dialog.origin && app.session.active().is_some_and(|state|
state.doc.id.0 == self.dialog.doc && state.revision == self.revision
&& product_document_key(&state.doc) == self.document_key)
}
}
impl Workspace {
fn confirm_project_save(&mut self, app: &PhotocraftApp, ctx: &egui::Context, dialog: &SaveDialog, file: String) -> Result<Value, String> {
if dialog.jpg {
let state = app.session.active().filter(|state| state.doc.id.0 == dialog.doc)
.ok_or("画布已切换,请在原项目中保存")?;
let remaining = unadopted_previews(app, &state.doc);
if !remaining.is_empty() {
let export = PreviewExport { dialog:dialog.clone(), file, document_key:product_document_key(&state.doc),
revision:state.revision, remaining };
ctx.data_mut(|data| data.insert_temp(egui::Id::unique("xiaoyi-jpg-preview-confirm"), export));
return Ok(json!({"confirmJpgPreviews":true}));
}
}
self.submit_project_save(app, ctx, dialog, file)
}
fn advance_preview_export(&mut self, app: &PhotocraftApp, ctx: &egui::Context, mut export: PreviewExport) -> Result<Value, String> {
if !export.matches(self, app) {
return Err("画布已变化,请核对当前图位后重新导出".into());
}
if let Some(mut target) = export.remaining.pop_front() {
let state = app.session.active().ok_or("请先打开项目")?;
if !unadopted_previews(app, &state.doc).contains(&target) {
return Err("候选预览已变化,请核对当前图位后重新导出".into());
}
if self.template_workflow["slots"].as_array().into_iter().flatten()
.find(|slot| slot["id"] == target["slotId"])
.and_then(|slot| slot["candidates"].as_array())
.is_some_and(|rows| rows.iter().any(|row| row["id"] == target["candidateId"] && row["historical"] == true))
{
target["historicalCandidate"] = json!(true);
}
target["previewExport"] = json!(true);
self.slot_action(app, "slot-adopt-prep", target)?;
self.canvas_workspace.preview_export = Some(export);
Ok(json!({"adoptingJpgPreviews":true}))
} else {
self.submit_project_save(app, ctx, &export.dialog, export.file)
}
}
pub(super) fn preview_export_adopted(&mut self, meta: &Value, adopted: bool) {
if meta["previewExport"] != true { return; }
if !adopted {
self.cancel_preview_export();
} else if let Some(export) = &mut self.canvas_workspace.preview_export
&& let Some(revision) = meta["localSave"]["revision"].as_u64()
{
export.revision = revision;
}
}
pub(super) fn preview_export_saved(&mut self, app: &PhotocraftApp, ctx: &egui::Context, doc: u64, revision: u64) {
if self.canvas_workspace.preview_export.as_ref().is_some_and(|export| export.dialog.doc == doc && export.revision == revision)
&& let Some(export) = self.canvas_workspace.preview_export.take()
&& let Err(error) = self.advance_preview_export(app, ctx, export)
{
self.error = format!("{error},未导出 JPG");
}
}
pub(super) fn cancel_preview_export(&mut self) {
if self.canvas_workspace.preview_export.take().is_some() {
self.error = if self.error.is_empty() {
"候选采纳或保存未完成,未导出 JPG".into()
} else {
format!("{},未导出 JPG", self.error)
};
}
}
fn submit_project_save(&mut self, app: &PhotocraftApp, ctx: &egui::Context, dialog: &SaveDialog, file: String) -> Result<Value, String> {
let st = app.session.active().filter(|st| st.doc.id.0 == dialog.doc)
.ok_or("画布已切换,请在原项目中保存")?;
@ -28,6 +135,9 @@ impl Workspace {
return Err("项目已切换,请在原项目中保存".into());
}
if self.saving.is_some() || self.product_view_save_pending() { return Err("项目正在保存,请稍后再试".into()); }
if self.canvas_workspace.pending_adoption.is_some() || self.canvas_workspace.preview_export.is_some() {
return Err("图片正在采纳,请稍后再试".into());
}
if !self.flush_document_draft(ctx, Some(dialog.doc), false) {
return Err("输入草稿还未写入,工程尚未保存".into());
}
@ -55,6 +165,10 @@ impl PhotocraftApp {
let doc = state.doc.id.0;
let mut w = self.jiansun.take()?;
let result = if w.loaded_draft == Some(doc) {
if ctx.data(|data| data.get_temp::<PreviewExport>(egui::Id::unique("xiaoyi-jpg-preview-confirm"))).is_some() {
self.jiansun = Some(w);
return Some(Ok(json!({"confirmJpgPreviews":true})));
}
let previous = w.project_files.get(&doc).cloned();
let name = state.doc.name.trim_end_matches(".pcraft");
let name: String = name.chars().map(|ch| if ch.is_control() || "\"<>:/\\|?*".contains(ch) { '_' } else { ch }).collect();
@ -75,6 +189,7 @@ impl PhotocraftApp {
#[cfg(not(target_arch = "wasm32"))]
pub(super) fn show_project_save(w: &mut Workspace, app: &mut PhotocraftApp, ctx: &egui::Context) {
show_preview_export(w, app, ctx);
let id = egui::Id::unique("xiaoyi-project-save");
let Some(mut dialog) = ctx.data(|data| data.get_temp::<SaveDialog>(id)) else { return };
if w.loaded_draft != Some(dialog.doc) || w.account["id"] != dialog.account || w.origin != dialog.origin {
@ -116,7 +231,7 @@ pub(super) fn show_project_save(w: &mut Workspace, app: &mut PhotocraftApp, ctx:
let ctx = ctx.clone();
let with_file = move |app: &mut PhotocraftApp, dialog: &SaveDialog, file: String| {
let mut w = app.jiansun.take().ok_or("项目窗口已关闭")?;
let result = w.submit_project_save(app, &ctx, dialog, file);
let result = w.confirm_project_save(app, &ctx, dialog, file);
app.jiansun = Some(w);
result
};
@ -139,12 +254,170 @@ pub(super) fn show_project_save(w: &mut Workspace, app: &mut PhotocraftApp, ctx:
}
}
fn show_preview_export(w: &mut Workspace, app: &PhotocraftApp, ctx: &egui::Context) {
let id = egui::Id::unique("xiaoyi-jpg-preview-confirm");
let Some(export) = ctx.data(|data| data.get_temp::<PreviewExport>(id)) else { return; };
if !export.matches(w, app) {
ctx.data_mut(|data| { data.remove::<PreviewExport>(id); });
w.error = "画布已切换,请在原项目中重新导出".into();
return;
}
let mut adopt = false;
let mut export_layers = false;
let mut cancel = false;
let visual = stitch_ui::overlay_transition(ctx, id.with("transition"), true, w.reduce_motion);
let response = stitch_ui::modal(ctx, id.with("modal"), visual, w.reduce_motion, |ui| {
use stitch_ui::ButtonRole;
let tokens = Tokens::get(ui.ctx()).agent();
ui.set_width(380.0_f32.min((ui.ctx().content_rect().width() - 64.0).max(220.0)));
ui.label(RichText::new("导出 JPG 前确认").size(20.0).strong().color(tokens.text));
ui.add_space(8.0);
ui.label(format!("当前画布有 {} 个图位只显示候选预览,图片尚未写入图层。直接导出时,这些图位会留空。", export.remaining.len()));
ui.add_space(12.0);
adopt = stitch_ui::action_button(ui, "一键采纳当前预览图并导出", ButtonRole::Primary, true).clicked();
export_layers = stitch_ui::action_button(ui, "仍按当前真实图层导出", ButtonRole::Secondary, true).clicked();
cancel = stitch_ui::action_button(ui, "取消", ButtonRole::Quiet, true).clicked();
});
if adopt || export_layers || cancel || response.is_some_and(|response| response.should_close()) {
ctx.data_mut(|data| { data.remove::<PreviewExport>(id); });
let result = if adopt {
w.advance_preview_export(app, ctx, export)
} else if export_layers {
w.submit_project_save(app, ctx, &export.dialog, export.file)
} else { return; };
if let Err(error) = result { w.error = error; }
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use super::*;
use crate::jiansun::{Event, Request, canvas_workspace::tests::{adopt_and_wait, native_fixture}};
use egui_kittest::{Harness, kittest::Queryable};
use photocraft_doc::{ColorMode, Document, SampleType, Size};
#[test]
fn jpg_confirmation_offers_real_layers_and_cancel_on_narrow_and_wide_windows() {
for (width, label) in [(420.0, "仍按当前真实图层导出"), (800.0, "取消")] {
let (mut workspace, app, requests, _, _) = native_fixture();
workspace.reduce_motion = true;
let state = app.session.active().unwrap();
let doc = state.doc.id.0;
workspace.loaded_draft = Some(doc);
let dialog = SaveDialog { doc, account:workspace.account["id"].clone(), origin:workspace.origin.clone(),
suggested:"test.xiaoyi".into(), project:false, psd:false, jpg:true, candidates:false, chat_history:None };
let mut confirmation = Some(PreviewExport { dialog, file:"test.xiaoyi".into(),
document_key:product_document_key(&state.doc), revision:state.revision, remaining:VecDeque::from([Value::Null]) });
let mut harness = Harness::builder().with_context_setup(crate::cjk_fonts::install_system_provider_for_tests)
.with_size(egui::vec2(width, 570.0)).build_ui_state(move |ui, (workspace, app)| {
if let Some(export) = confirmation.take() {
ui.ctx().data_mut(|data| data.insert_temp(egui::Id::unique("xiaoyi-jpg-preview-confirm"), export));
}
show_preview_export(workspace, app, ui.ctx());
}, (workspace, app));
harness.run_steps(4);
for action in ["一键采纳当前预览图并导出", "仍按当前真实图层导出", "取消"] {
let rect = harness.get_by_label(action).rect();
assert!(rect.left() >= 0.0 && rect.right() <= width && rect.bottom() <= 570.0);
}
let pos = harness.get_by_label(label).rect().center();
harness.hover_at(pos);
harness.run_steps(2);
for pressed in [true, false] {
harness.event(egui::Event::PointerButton { pos, button:egui::PointerButton::Primary, pressed, modifiers:egui::Modifiers::NONE });
harness.run_steps(1);
}
if label == "取消" {
assert!(requests.try_recv().is_err());
} else {
let Request::Save(document, _, meta) = requests.try_recv().unwrap() else { panic!("expected real layer export") };
assert_eq!(meta["deliverProject"]["jpg"], true);
assert_eq!(canvas_workspace::adopted(&document, "image-slot", "wood"), None);
}
}
}
#[test]
fn jpg_preview_confirmation_waits_for_adoption_and_its_disk_receipt() {
let (mut w, mut app, requests, layer, bytes) = native_fixture();
let ctx = egui::Context::default();
let second = app.session.active().unwrap().doc.layers.last().unwrap().id;
app.session.edit("添加图位", |doc, _| {
let (_, raw) = doc.metadata.text.iter_mut().find(|(key, _)| key == "jiansun.slot-mapping.v1").unwrap();
let mut mapping: Value = serde_json::from_str(raw).unwrap();
mapping["outputs"][0]["mapping"]["fields"].as_array_mut().unwrap().push(
json!({"kind":"image","slotId":"second-slot","nativeLayerId":second.0}));
*raw = mapping.to_string();
Ok(())
}).unwrap();
w.template_workflow["slots"].as_array_mut().unwrap().push(json!({
"id":"second-slot","outputId":"detail","documentId":"S01","variantId":"wood","kind":"image"
}));
let active = app.session.active().unwrap();
let (id, revision) = (active.doc.id.0, active.revision);
let layers = [photocraft_doc::LayerId(layer), second];
let nodes = layers.map(|layer| active.doc.layer(layer).unwrap().clone());
w.loaded_draft = Some(id);
w.persisted_revisions.insert(id, revision);
w.draft_flush = Some(std::sync::Arc::new(|_, _, _, _, _| Ok(())));
w.receive_composer_draft(&ctx, id, &json!({"localId":"local-project","composerDraftToken":"draft-token"}));
let targets = [("image-slot", "preview"), ("second-slot", "other-preview")];
for (node, (_, candidate)) in nodes.into_iter().zip(targets) {
let preview = json!({"doc":id,"nativeLayerId":node.id.0,"candidateId":candidate});
app.queue_slot_preview(&w.tx, node.id, preview.clone());
app.receive_slot_preview(&preview, Some(Box::new(node)));
assert!(matches!(requests.try_recv().unwrap(), Request::SlotPreview(..)));
}
let dialog = SaveDialog { doc:id, account:w.account["id"].clone(), origin:w.origin.clone(),
suggested:"test.xiaoyi".into(), project:false, psd:false, jpg:true, candidates:false, chat_history:None };
assert_eq!(w.confirm_project_save(&app, &ctx, &dialog, dialog.suggested.clone()).unwrap()["confirmJpgPreviews"], true);
let confirmation = egui::Id::unique("xiaoyi-jpg-preview-confirm");
let export = ctx.data_mut(|data| {
let export = data.get_temp::<PreviewExport>(confirmation).unwrap();
data.remove::<PreviewExport>(confirmation);
export
});
assert_eq!(export.remaining.len(), 2);
assert!(requests.try_recv().is_err());
w.advance_preview_export(&app, &ctx, export).unwrap();
let saved = tempfile::tempdir().unwrap();
let saved_path = saved.path().join("preview-export.pcraft");
for ((slot, candidate), layer) in targets.into_iter().zip(layers) {
let Request::Action(method, mut meta) = requests.try_recv().unwrap() else { panic!("expected adoption") };
assert_eq!(method, "slot-adopt-prep");
assert_eq!(meta["candidateId"], candidate);
meta["accountId"] = w.account["id"].clone();
meta["origin"] = json!(w.origin);
meta["templateHash"] = json!("fixed");
meta["fit"] = json!("contain");
adopt_and_wait(&mut w, &mut app, bytes.clone(), meta);
let Request::Action(method, ack) = requests.try_recv().unwrap() else { panic!("expected native adoption receipt") };
assert_eq!(method, "slot-adopted");
assert_eq!(ack["localSave"]["state"], "pending");
w.finish_adoption_receipt(&mut app, &ack, true);
let active = app.session.active().unwrap();
assert_eq!(canvas_workspace::adopted(&active.doc, slot, "wood"), Some(candidate));
assert!(!app.has_slot_preview(&active.doc, layer));
w.autosave_project(&app, &ctx);
let Request::Save(checkpoint, saved_revision, meta) = requests.try_recv().unwrap() else { panic!("expected checkpoint") };
assert!(meta["deliverProject"].is_null());
assert!(requests.try_recv().is_err(), "export must not queue before the disk receipt");
let serialized = photocraft_format::save_to_bytes(&checkpoint, &Default::default()).unwrap();
std::fs::write(&saved_path, serialized).unwrap();
let reopened = photocraft_format::load_path(&saved_path).unwrap();
assert_eq!(canvas_workspace::adopted(&reopened, slot, "wood"), Some(candidate));
w.receive_event(&mut app, &ctx, Event::Saved(id, saved_revision,
json!({"documentKey":product_document_key(&checkpoint),"localSave":{"state":"saved","revision":saved_revision}})));
}
let Request::Save(exported, revision, meta) = requests.try_recv().unwrap() else { panic!("expected JPG export") };
assert_eq!(meta["deliverProject"]["jpg"], true);
assert_eq!(canvas_workspace::adopted(&exported, "image-slot", "wood"), Some("preview"));
assert_eq!(canvas_workspace::adopted(&exported, "second-slot", "wood"), Some("other-preview"));
assert_eq!(w.persisted_revisions.get(&id), Some(&revision));
assert!(w.messages.iter().any(|message| message["text"] == "图片已采纳并保存到本机"));
}
#[test]
fn save_dialog_initializes_project_and_keeps_export_choices_independent() {
for width in [800.0, 420.0] {

View File

@ -450,8 +450,24 @@ impl crate::PhotocraftApp {
}
pub(crate) fn has_slot_preview(&self, draft: &Document, layer: LayerId) -> bool {
self.slot_previews.get(&draft.id).and_then(|slots| slots.get(&layer)).is_some_and(|preview|
slot_scope(draft).is_some_and(|scope| preview.picture(draft, &scope).is_some()))
self.slot_preview_candidate(draft, layer).is_some()
}
pub(crate) fn slot_preview_candidate(&self, draft: &Document, layer: LayerId) -> Option<&str> {
let preview = self.slot_previews.get(&draft.id)?.get(&layer)?;
preview.picture(draft, &slot_scope(draft)?)?;
Some(&preview.candidate)
}
pub(crate) fn clear_slot_preview(&mut self, doc: &Document, layer: LayerId) {
if let Some(scope) = slot_scope(doc)
&& let Some(slots) = self.slot_previews.get_mut(&doc.id)
&& slots.get(&layer).is_some_and(|preview| preview.scope == scope)
{
slots.remove(&layer);
self.slot_preview_epoch = self.slot_preview_epoch.wrapping_add(1);
self.display_memo.remove(&doc.id);
}
}
}

View File

@ -245,7 +245,7 @@ impl State {
op["phase"] = json!(if adopted { "complete" } else { "failed" });
if adopted {
op["persistence"] = json!("session");
for key in ["overlayLayers", "overlayNote", "afterRevision", "hiddenRetouchLayers"] {
for key in ["overlayLayers", "overlayNote", "afterRevision", "hiddenRetouchLayers", "localSave"] {
if let Some(value) = meta.get(key) { op[key] = value.clone(); }
}
} else {
@ -257,6 +257,17 @@ impl State {
false
}
pub(super) fn adoption_save_settled(&mut self, doc: u64, revision: u64, saved: bool) {
for operation in self.operations.iter_mut().filter(|op| op["intent"] == "adopt_candidate"
&& op["localSave"]["state"] == "pending" && op["documentId"] == doc && op["localSave"]["revision"] == revision)
{
if saved {
operation["persistence"] = json!("checkpoint");
}
operation["localSave"]["state"] = json!(if saved { "saved" } else { "failed" });
}
}
/// Reveal a new reviewed card once, after the durable Pi turn ends. Later
/// manual scrolling stays with the user instead of being reset each frame.
pub(super) fn take_card_reveal(&mut self) -> bool {
@ -458,6 +469,7 @@ pub(super) fn reconcile(w: &Workspace, app: &PhotocraftApp, input: &Value) -> Re
let mut receipt = json!({"run":run,"documentId":doc,"operationId":id,"phase":phase,"candidateId":op["candidateId"],
"message":op["message"],"retryableFailure":op["retryableFailure"],"retryAfterSeconds":op["retryAfterSeconds"],
"persistence":op["persistence"]});
if let Some(local_save) = op.get("localSave") { receipt["localSave"] = local_save.clone(); }
copy_expiry(op, &mut receipt);
copy_candidate_limit(op, &mut receipt);
Ok(receipt)
@ -984,6 +996,7 @@ pub(super) fn action(w: &mut Workspace, app: &mut PhotocraftApp, method: &str, i
copy_expiry(op, &mut receipt);
copy_candidate_limit(op, &mut receipt);
if let Some(persistence) = op.get("persistence") { receipt["persistence"] = persistence.clone(); }
if let Some(local_save) = op.get("localSave") { receipt["localSave"] = local_save.clone(); }
if let Some(reason) = op.get("writeBlockReason") { receipt["writeBlockReason"] = reason.clone(); }
Ok(receipt)
}