fix(xiaoyi): land Item 90 opaque/reviewHints/projection and thin-harness canvas sync
This commit is contained in:
parent
45b3cfdca9
commit
a9bbf5494d
@ -125,9 +125,11 @@ function componentPack(manifest, revision, mappings, binding) {
|
||||
throw Error(`字段 ${field.field_id} 的样式角色无效`);
|
||||
}
|
||||
const embeddedTarget=field.embedded_target??field.ps_location?.embedded_target;
|
||||
const requireOpaque=field.requireOpaque===true||field.require_opaque===true||field.ps_style?.replacement==='opaque_white'||field.ps_style?.replacement?.requireOpaque===true||field.ps_style?.replacement?.require_opaque===true;
|
||||
return {fieldId:field.field_id,name:field.name,role:field.role,kind,
|
||||
...(kind==='text'&&field.style_roles?.length?{styleRoles:field.style_roles}:{}),
|
||||
...(kind==='text'&&field.textSafeFrame===true?{textSafeFrame:true}:{}),
|
||||
...(kind==='image'&&requireOpaque?{requireOpaque:true}:{}),
|
||||
...(embeddedTarget?{embeddedTarget}:{}),
|
||||
frame:{x:x-left,y:y-nativeTop,width:x2-x,height:y2-y},nativeFrame:[l,t,r,b],
|
||||
psLayer:field.ps_location,crop:'cover',...(field.nativeTextBounds?{nativeTextBounds:true}:{}),...(field.nativeBounds?{nativeBounds:field.nativeBounds}:{}),
|
||||
|
||||
@ -29,7 +29,7 @@ async function acquireWrite(host, scope, signal, checkTurn, onWait) {
|
||||
await onWait?.();
|
||||
return null;
|
||||
}
|
||||
if(receipt.revision!==state.revision || receipt.writeBlockReason === 'revision_conflict') {
|
||||
if(receipt.writeBlockReason === 'revision_conflict') {
|
||||
throw new BridgeError('准备期间画布有改动,本次未采纳,请确认图位后继续。','revision_conflict',
|
||||
{retryable:true,currentRevision:receipt.revision,changedLayers:receipt.changedLayers});
|
||||
}
|
||||
@ -120,8 +120,6 @@ export async function executeWorkflow(host, args, signal, { timeoutMs, pause = d
|
||||
checkTurn();
|
||||
if (state?.conversationActive === false) throw new BridgeError('当前画布已切换,尚未派发操作','scope_changed');
|
||||
if (state?.writeBlocked) throw new BridgeError('本轮写入许可已撤销,尚未派发操作','write_revoked');
|
||||
if (!detailBatch && state?.revision !== result.revision) throw new BridgeError('准备期间画布有改动,请确认图位后继续。','revision_conflict',
|
||||
{retryable:true,currentRevision:state?.revision});
|
||||
if (!detailBatch && state?.error) throw Error(state.error);
|
||||
if(adoption)await requestWrite();
|
||||
dispatched = true;
|
||||
|
||||
@ -149,12 +149,15 @@ test('an unsettled original holds only its own slot; another slot dispatches nor
|
||||
assert.equal(x.calls.filter(c=>c[0]==='execute').length,2);
|
||||
assert.equal(x.host.canvasOperations.original.slotId,'hero');
|
||||
});
|
||||
test('failed or stale adoption permission never dispatches',async()=>{
|
||||
for (const permission of [{allowed:false,revision:17},{allowed:true,revision:18},null]) {
|
||||
test('failed adoption permission never dispatches; changed revision with allowed=true dispatches normally',async()=>{
|
||||
for (const permission of [{allowed:false,revision:17},null]) {
|
||||
const x=setup(['complete']);x.host.canvas.read=async()=>({revision:17});x.host.canvas.requestWrite=async()=>permission;
|
||||
await assert.rejects(executeWorkflow(x.host,{...args,intent:'adopt_candidate',candidateId:'chosen'}));
|
||||
assert.equal(x.calls.length,0); assert.equal(x.host.canvasOperations.original,undefined);
|
||||
}
|
||||
const ok=setup(['complete']);ok.host.canvas.read=async()=>({revision:17});ok.host.canvas.requestWrite=async()=>({allowed:true,revision:18});
|
||||
const res=await executeWorkflow(ok.host,{...args,intent:'adopt_candidate',candidateId:'chosen'},undefined,{pause:async()=>{}});
|
||||
assert.equal(res.operation.phase,'complete');
|
||||
});
|
||||
test('generation never requests a write lease',async()=>{
|
||||
const x=setup(['complete']);x.host.canvas.read=async()=>{throw Error('unexpected canvas read')};x.host.canvas.requestWrite=async()=>{throw Error('unexpected permission')};
|
||||
|
||||
@ -3067,7 +3067,7 @@ pub(super) fn published_receipt(path: &Path) -> R<Value> {
|
||||
"productionProfile", "fidelityReport", "knownIssues", "issues", "slotCoverage", "missingImages",
|
||||
"missingSlots", "unreviewedScreens", "missingVisibleText", "visibleSampleLayer",
|
||||
"unapprovedFixedTextLayer", "unverifiedCopy", "unverifiedFacts", "blankCopyReasons",
|
||||
"warnings", "allOutputsCompleted", "deliveryStatus"] {
|
||||
"warnings", "missingFonts", "allOutputsCompleted", "deliveryStatus"] {
|
||||
if let Some(value) = pointer.get(field) {
|
||||
manifest[field] = value.clone();
|
||||
} else {
|
||||
@ -4732,6 +4732,10 @@ fn export_product_stage_with_source(
|
||||
}
|
||||
let profile = production_profile::select(&state["template"], component)?;
|
||||
result["fidelityReport"] = fidelity::report(native, &meta);
|
||||
let missing_fonts = photocraft_engine::type_extra_cmds::missing_fonts(native);
|
||||
if !missing_fonts.is_empty() {
|
||||
result["missingFonts"] = json!(missing_fonts);
|
||||
}
|
||||
if let Some(profile) = profile {
|
||||
result["productionProfile"] = production_profile::source(&state["template"], component);
|
||||
if let Some(layer) = production_profile::visible_sample_layer(native, profile, &meta) {
|
||||
@ -6275,6 +6279,11 @@ impl Backend {
|
||||
if mapped["embeddedTarget"].is_object() {
|
||||
meta["embeddedTarget"] = mapped["embeddedTarget"].clone();
|
||||
}
|
||||
if photocraft_ui_egui::jiansun::production_facts::slot_requires_opaque(field)
|
||||
|| photocraft_ui_egui::jiansun::production_facts::slot_requires_opaque(mapped)
|
||||
{
|
||||
meta["requireOpaque"] = json!(true);
|
||||
}
|
||||
if manual_adoption { meta["manualAdoption"] = json!(true); }
|
||||
if historical_adoption { meta["sourceCandidateId"] = json!(source_id); }
|
||||
if input["previewExport"] == true && !batch { meta["previewExport"] = json!(true); }
|
||||
|
||||
@ -371,6 +371,7 @@ pub(super) fn copy_generation(root: &Path, project: &Path, input: &Value, output
|
||||
"slotCoverage":data["slotCoverage"],"missingImages":data["missingImages"],"missingVisibleText":data["missingVisibleText"],
|
||||
"missingSlots":data.get("missingSlots").unwrap_or(&data["missingImages"]),"unreviewedScreens":data["unreviewedScreens"],
|
||||
"visibleSampleLayer":data["visibleSampleLayer"],"unapprovedFixedTextLayer":data["unapprovedFixedTextLayer"],
|
||||
"warnings":data["warnings"],"missingFonts":data["missingFonts"],
|
||||
"adoptedImages":adopted,"skuBarcodeWarning":sku_barcode_warning,"fidelityReport":data["fidelityReport"],"reopenVerification":data["reopenVerification"]}))
|
||||
}
|
||||
|
||||
@ -436,6 +437,81 @@ fn sync_tree(dir: &Path) -> R<()> {
|
||||
RealFs.sync_dir(dir).map_err(disk)
|
||||
}
|
||||
|
||||
fn push_unique_hint(hints: &mut Vec<String>, text: impl Into<String>) {
|
||||
let text = text.into();
|
||||
let trimmed = text.trim();
|
||||
if !trimmed.is_empty() && !hints.iter().any(|existing| existing == trimmed) {
|
||||
hints.push(trimmed.to_owned());
|
||||
}
|
||||
}
|
||||
|
||||
fn push_mapping_hints(hints: &mut Vec<String>, node: &Value, prefix: Option<&str>) {
|
||||
for key in ["review_hint", "manualReviewHint"] {
|
||||
if let Some(text) = node[key].as_str().map(str::trim).filter(|s| !s.is_empty()) {
|
||||
let entry = prefix.map_or_else(|| text.to_owned(), |p| format!("{p}:{text}"));
|
||||
push_unique_hint(hints, entry);
|
||||
}
|
||||
}
|
||||
if let Some(items) = node["reviewHints"].as_array() {
|
||||
for text in items.iter().filter_map(Value::as_str).map(str::trim).filter(|s| !s.is_empty()) {
|
||||
let entry = prefix.map_or_else(|| text.to_owned(), |p| format!("{p}:{text}"));
|
||||
push_unique_hint(hints, entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_review_hints(project: &Path, workspace_id: &Value, creation: &Value, output_evidence: &[Value]) -> Vec<String> {
|
||||
let mut hints = Vec::new();
|
||||
for output in output_evidence {
|
||||
let label = match output["outputId"].as_str() {
|
||||
Some("detail") => "详情页",
|
||||
Some("main_images") => "主图",
|
||||
Some("sku_images") => "SKU 图",
|
||||
_ => "成品",
|
||||
};
|
||||
if let Some(layer) = output["unapprovedFixedTextLayer"].as_str().map(str::trim).filter(|s| !s.is_empty()) {
|
||||
push_unique_hint(&mut hints, format!("{label}:固定图层「{layer}」保留了模板旧文字,请人工核对是否需要修改或隐藏。"));
|
||||
}
|
||||
if let Some(layer) = output["visibleSampleLayer"].as_str().map(str::trim).filter(|s| !s.is_empty()) {
|
||||
push_unique_hint(&mut hints, format!("{label}:模板示例图层「{layer}」仍处于显示状态,请人工核对是否应隐藏。"));
|
||||
}
|
||||
if let Some(fonts) = output["missingFonts"].as_array() {
|
||||
let names: Vec<_> = fonts.iter().filter_map(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).collect();
|
||||
if !names.is_empty() {
|
||||
push_unique_hint(&mut hints, format!("{label}:检测到缺失或回退字体({}),请人工核对文字样式与换行。", names.join("、")));
|
||||
}
|
||||
}
|
||||
if let Some(warnings) = output["warnings"].as_array() {
|
||||
for warning in warnings.iter().filter_map(Value::as_str).map(str::trim).filter(|s| !s.is_empty()) {
|
||||
push_unique_hint(&mut hints, format!("{label}:{warning}"));
|
||||
}
|
||||
}
|
||||
if output["skuBarcodeWarning"] == true {
|
||||
push_unique_hint(&mut hints, SKU_BARCODE_WARNING);
|
||||
}
|
||||
}
|
||||
if let Some(warnings) = creation["brief"]["templateSelection"]["compatibilityWarnings"].as_array() {
|
||||
for warning in warnings.iter().filter_map(Value::as_str).map(str::trim).filter(|s| !s.is_empty()) {
|
||||
push_unique_hint(&mut hints, warning);
|
||||
}
|
||||
}
|
||||
if let Some(ws_id) = workspace_id.as_str().filter(|id| !id.is_empty())
|
||||
&& let Ok(workspace) = read_json(&project.join("template-outputs").join(ws_id).join("workspace.json"))
|
||||
{
|
||||
let template = &workspace["template"];
|
||||
push_mapping_hints(&mut hints, template, None);
|
||||
for output in template["outputs"].as_array().into_iter().flatten() {
|
||||
let page_label = output["name"].as_str().or_else(|| output["id"].as_str());
|
||||
push_mapping_hints(&mut hints, output, page_label);
|
||||
for slot in output["slots"].as_array().into_iter().flatten() {
|
||||
let slot_label = slot["name"].as_str().or_else(|| slot["fieldId"].as_str());
|
||||
push_mapping_hints(&mut hints, slot, slot_label);
|
||||
}
|
||||
}
|
||||
}
|
||||
hints
|
||||
}
|
||||
|
||||
fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, input: &Value, admitted: impl Fn() -> R<()>) -> R<Value> {
|
||||
admitted()?;
|
||||
let dir = project_file::delivery_directory(project, &input["deliveryDir"])?.ok_or("未选择成品目录")?;
|
||||
@ -636,10 +712,11 @@ fn deliver_production_bundle(project: &Path, policy: &transfer::Policy<'_>, inpu
|
||||
*counts.entry(category.to_owned()).or_insert(0) += 1;
|
||||
}
|
||||
let delivery_status = if all_outputs_completed { "completed" } else { "partial_delivered" };
|
||||
let review_hints = collect_review_hints(project, &input["workspaceId"], &creation, &output_evidence);
|
||||
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,"candidateImages":candidate_images,"candidateCount":candidate_count,
|
||||
"skuBarcodeWarning":sku_barcode_warning.then_some(SKU_BARCODE_WARNING),
|
||||
"skuBarcodeWarning":sku_barcode_warning.then_some(SKU_BARCODE_WARNING),"reviewHints":review_hints,
|
||||
"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});
|
||||
@ -1333,4 +1410,55 @@ mod tests {
|
||||
assert_eq!(canvas_workspace::published_receipt(&pointer).unwrap()["generationId"], output["generationId"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delivery_manifest_collects_non_blocking_review_hints() {
|
||||
let (_root, project, local, input) = fixture();
|
||||
let policy = transfer::Policy { chat: false, scope: "owner", project: &local };
|
||||
let mut creation = creation::load(&project).unwrap();
|
||||
creation["brief"]["templateSelection"] = json!({
|
||||
"compatibilityWarnings": ["模板元数据缺少映射版本字段,已按兼容模式加载"]
|
||||
});
|
||||
write_json(&project.join("creation.json"), &creation).unwrap();
|
||||
let ws_dir = project.join("template-outputs").join(input["workspaceId"].as_str().unwrap());
|
||||
fs::create_dir_all(&ws_dir).unwrap();
|
||||
write_json(&ws_dir.join("workspace.json"), &json!({
|
||||
"template": {
|
||||
"review_hint": "请核对原稿固定证书图是否适用本款",
|
||||
"outputs": [{
|
||||
"id": "S01",
|
||||
"name": "首屏",
|
||||
"slots": [{
|
||||
"fieldId": "S01-I01",
|
||||
"name": "主视觉图",
|
||||
"manualReviewHint": "原稿含烘焙尺寸标线,请核对新图是否完整覆盖"
|
||||
}]
|
||||
}]
|
||||
}
|
||||
})).unwrap();
|
||||
let delivered = deliver_production_bundle(&project, &policy, &input, || Ok(())).unwrap();
|
||||
assert_eq!(delivered["state"], "bundle_saved");
|
||||
let manifest = read_json(&PathBuf::from(delivered["path"].as_str().unwrap()).join("交付清单.json")).unwrap();
|
||||
let hints = manifest["reviewHints"].as_array().unwrap();
|
||||
assert!(hints.iter().any(|h| h == "模板元数据缺少映射版本字段,已按兼容模式加载"));
|
||||
assert!(hints.iter().any(|h| h == "请核对原稿固定证书图是否适用本款"));
|
||||
assert!(hints.iter().any(|h| h == "主视觉图:原稿含烘焙尺寸标线,请核对新图是否完整覆盖"));
|
||||
|
||||
let unit_hints = collect_review_hints(
|
||||
&project,
|
||||
&input["workspaceId"],
|
||||
&creation,
|
||||
&[json!({
|
||||
"outputId": "main_images",
|
||||
"unapprovedFixedTextLayer": "旧卖点文案",
|
||||
"visibleSampleLayer": "示例样图",
|
||||
"missingFonts": ["Alibaba-PuHuiTi-M"],
|
||||
"skuBarcodeWarning": true
|
||||
})],
|
||||
);
|
||||
assert!(unit_hints.iter().any(|h| h.contains("旧卖点文案")));
|
||||
assert!(unit_hints.iter().any(|h| h.contains("示例样图")));
|
||||
assert!(unit_hints.iter().any(|h| h.contains("Alibaba-PuHuiTi-M")));
|
||||
assert!(unit_hints.iter().any(|h| h == SKU_BARCODE_WARNING));
|
||||
}
|
||||
}
|
||||
|
||||
@ -387,7 +387,7 @@ fn evidence_safe_text(value: &Value, limit: usize) -> Value {
|
||||
}
|
||||
fn evidence_images(value: &Value) -> Value {
|
||||
let Some(images) = value.as_array() else { return Value::Null };
|
||||
json!(images.iter().take(8).map(|image| {
|
||||
json!(images.iter().map(|image| {
|
||||
let reference = image["source"].as_str().and_then(|source| source.strip_prefix("local:"))
|
||||
.filter(|hash| hash.len() == 64 && hash.bytes().all(|byte| byte.is_ascii_hexdigit()))
|
||||
.map(|hash| format!("sha256:{}", hash.to_ascii_lowercase()));
|
||||
@ -399,6 +399,19 @@ fn evidence_images(value: &Value) -> Value {
|
||||
evidence
|
||||
}).collect::<Vec<_>>())
|
||||
}
|
||||
fn evidence_barcode_entries(value: &Value) -> Value {
|
||||
let Some(entries) = value.as_array() else { return Value::Null };
|
||||
json!(entries.iter().filter_map(|entry| {
|
||||
let mut obj = entry.as_object()?.clone();
|
||||
if let Some(images) = obj.get("images") {
|
||||
obj.insert("images".into(), evidence_images(images));
|
||||
}
|
||||
for key in ["url", "localSource", "path"] {
|
||||
obj.remove(key);
|
||||
}
|
||||
Some(Value::Object(obj))
|
||||
}).collect::<Vec<_>>())
|
||||
}
|
||||
fn evidence_output_colors(colors: &Value) -> Value {
|
||||
Value::Object(["detail", "sku_images", "main_images"].into_iter().filter_map(|key| {
|
||||
colors.get(key).map(|color| (key.to_owned(), evidence_safe_text(color, 120)))
|
||||
@ -425,6 +438,9 @@ fn project_evidence(c: &Value, scope: &str, project: &str, doc: u64, current_var
|
||||
brief.insert(field.to_owned(), value);
|
||||
}
|
||||
}
|
||||
if c["brief"].get("barcodeEntries").is_some_and(Value::is_array) {
|
||||
brief.insert("barcodeEntries".into(), evidence_barcode_entries(&c["brief"]["barcodeEntries"]));
|
||||
}
|
||||
if let Some(barcode) = super::creation::detail_barcode(&c["brief"]) {
|
||||
brief.insert("detailBarcode".into(), json!(barcode));
|
||||
}
|
||||
@ -447,16 +463,16 @@ fn project_evidence(c: &Value, scope: &str, project: &str, doc: u64, current_var
|
||||
if let Some(colors) = variant.get("outputColors") {
|
||||
row["outputColors"] = evidence_output_colors(colors);
|
||||
}
|
||||
if let Some(images) = variant["images"].as_array() {
|
||||
if variant["images"].is_array() {
|
||||
row["images"] = evidence_images(&variant["images"]);
|
||||
row["imagesOmitted"] = json!(images.len().saturating_sub(8));
|
||||
row["imagesOmitted"] = json!(0);
|
||||
}
|
||||
row
|
||||
}).collect();
|
||||
brief.insert("variants".into(), json!(variants));
|
||||
}
|
||||
brief.insert("projectionOmitted".into(), json!({"variants":c["brief"]["variants"].as_array().map_or(0, |v| v.len().saturating_sub(64)),
|
||||
"commonImages":c["brief"]["images"].as_array().map_or(0, |v| v.len().saturating_sub(8))}));
|
||||
"commonImages":0}));
|
||||
let screens: Vec<Value> = c["plan"]["screens"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
@ -979,7 +995,7 @@ fn run_inner(b: &mut Backend, input: &Value, events: &mpsc::Sender<Event>, ctx:
|
||||
let id = value["id"].clone();
|
||||
let events = events.clone();
|
||||
let ctx = ctx.clone();
|
||||
let report = (product_prompt && value["input"]["reportUserCanvasChanges"] == true)
|
||||
let report = (value["input"]["reportUserCanvasChanges"] == true)
|
||||
.then(|| json!({"run":requested_run,"accountEpoch":b.access.epoch}));
|
||||
move |mut reply: Value| {
|
||||
if let Some(input) = &report {
|
||||
@ -1838,4 +1854,46 @@ mod tests {
|
||||
entry["service_offers"][0]["route_options"][1]["context_window"] = json!(-1);
|
||||
assert!(parse_route(&entry)["contextWindow"].is_null());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_evidence_includes_barcode_entries_and_more_than_8_images() {
|
||||
let images: Vec<Value> = (0..10).map(|i| json!({
|
||||
"source": format!("local:{i:064x}"),
|
||||
"purpose": "product",
|
||||
"name": format!("img-{i}.png")
|
||||
})).collect();
|
||||
let c = json!({
|
||||
"revision": 3,
|
||||
"brief": {
|
||||
"name": "测试款",
|
||||
"images": images,
|
||||
"barcodeEntries": [{
|
||||
"id": "entry-1",
|
||||
"barcode": "BC-001",
|
||||
"variantId": "white",
|
||||
"url": "https://secret.example/x",
|
||||
"images": [{"source": format!("local:{:064x}", 15), "purpose": "product", "name": "sku.png"}]
|
||||
}],
|
||||
"variants": [{
|
||||
"id": "white",
|
||||
"name": "白色",
|
||||
"images": images
|
||||
}]
|
||||
},
|
||||
"facts": {"status": "ready", "items": [], "missing": []},
|
||||
"sellingPoints": {"selected": [], "batches": []},
|
||||
"plan": {"status": "confirmed", "screens": []}
|
||||
});
|
||||
let evidence = project_evidence(&c, "scope", "proj", 1, &json!("white"));
|
||||
assert_eq!(evidence["brief"]["images"].as_array().unwrap().len(), 10);
|
||||
assert_eq!(evidence["brief"]["variants"][0]["images"].as_array().unwrap().len(), 10);
|
||||
assert_eq!(evidence["brief"]["variants"][0]["imagesOmitted"], 0);
|
||||
assert_eq!(evidence["brief"]["projectionOmitted"]["commonImages"], 0);
|
||||
assert_eq!(evidence["brief"]["barcodeEntries"][0]["barcode"], "BC-001");
|
||||
assert!(evidence["brief"]["barcodeEntries"][0].get("url").is_none());
|
||||
assert_eq!(
|
||||
evidence["brief"]["barcodeEntries"][0]["images"][0]["ref"],
|
||||
format!("sha256:{:064x}", 15)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -769,6 +769,9 @@ fn enterprise_source(pack: &Value, source: &Value, outputs: &[&Value], variant:
|
||||
return Err(format!("容器「{resolved_container_path}」中的文字字段 {}({resolved_inner_path})无法作为原生文字编辑", field["fieldId"]));
|
||||
}
|
||||
let mut mapped = field.clone();
|
||||
if photocraft_ui_egui::jiansun::production_facts::slot_requires_opaque(field) {
|
||||
mapped["requireOpaque"] = json!(true);
|
||||
}
|
||||
if let Some(text) = original_text { mapped["originalText"] = json!(text); }
|
||||
mapped["slotId"] = json!(sha(json!([pack["contentHash"], variant, field["fieldId"]]).to_string().as_bytes()));
|
||||
mapped["nativeLayerId"] = json!(container_id.0);
|
||||
@ -836,6 +839,9 @@ fn enterprise_source(pack: &Value, source: &Value, outputs: &[&Value], variant:
|
||||
return Err(format!("文字字段 {} 无法作为原生文字编辑", field["fieldId"]));
|
||||
}
|
||||
let mut mapped = field.clone();
|
||||
if photocraft_ui_egui::jiansun::production_facts::slot_requires_opaque(field) {
|
||||
mapped["requireOpaque"] = json!(true);
|
||||
}
|
||||
if let Some(bounds) = original_bounds {
|
||||
if bounds.is_empty() { return Err(format!("文字字段「{expected_path}」缺少可核对的原稿范围")); }
|
||||
mapped["nativeFrame"] = json!([bounds.x0, bounds.y0, bounds.x1, bounds.y1]);
|
||||
|
||||
@ -147,6 +147,8 @@ pub fn commit_child(s: &mut Session, index: usize) -> Result<bool> {
|
||||
if ids.is_empty() {
|
||||
return Err(other("the smart object's instances were removed"));
|
||||
}
|
||||
let has_manual_text = child.metadata.text.iter().any(|(key, _)| key.starts_with("jiansun.manual-text."));
|
||||
let has_mapping = doc.metadata.text.iter().any(|(key, _)| key == "jiansun.slot-mapping.v1");
|
||||
for id in ids {
|
||||
let sm = smart_mut(doc, id)?;
|
||||
let name = match &sm.source {
|
||||
@ -157,6 +159,11 @@ pub fn commit_child(s: &mut Session, index: usize) -> Result<bool> {
|
||||
sm.source = SmartSource::Embedded { file_name: format!("{stem}.pcraft"), bytes: bytes.clone() };
|
||||
detach_psd(doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?);
|
||||
refresh_or_fail(doc, id)?;
|
||||
if has_manual_text && has_mapping {
|
||||
let marker_key = format!("jiansun.manual-text.{}", id.0);
|
||||
doc.metadata.text.retain(|(name, _)| name != &marker_key);
|
||||
doc.metadata.text.push((marker_key, "{\"source\":\"human\",\"embedded\":true}".into()));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
|
||||
@ -1054,6 +1054,7 @@ pub struct Workspace {
|
||||
owner_doc: Option<u64>,
|
||||
expected_revision: u64,
|
||||
pi_canvas_basis: Option<Arc<Document>>,
|
||||
manual_edit_observer: Option<(Arc<Document>, u64)>,
|
||||
user_canvas_changes: user_canvas_changes::UserCanvasChanges,
|
||||
pi_manual_edit: bool,
|
||||
queue: VecDeque<Edit>,
|
||||
@ -1717,6 +1718,7 @@ impl Workspace {
|
||||
owner_doc: None,
|
||||
expected_revision: 0,
|
||||
pi_canvas_basis: None,
|
||||
manual_edit_observer: None,
|
||||
user_canvas_changes: Default::default(),
|
||||
pi_manual_edit: false,
|
||||
queue: VecDeque::new(),
|
||||
@ -2167,18 +2169,88 @@ impl Workspace {
|
||||
}
|
||||
|
||||
pub(super) fn sync_pi_canvas_basis_layers(&mut self, doc: &Document, layers: &[photocraft_doc::LayerId]) {
|
||||
let Some(basis) = self.pi_canvas_basis.as_mut().filter(|basis| basis.id == doc.id) else { return; };
|
||||
if layers.is_empty() { return; }
|
||||
let basis = Arc::make_mut(basis);
|
||||
for &id in layers {
|
||||
if let Some((before, after)) = basis.layer_mut(id).zip(doc.layer(id)) {
|
||||
*before = after.clone();
|
||||
if let Some((obs, _)) = self.manual_edit_observer.as_mut().filter(|(obs, _)| obs.id == doc.id) {
|
||||
let obs = Arc::make_mut(obs);
|
||||
for &id in layers {
|
||||
if let Some((before, after)) = obs.layer_mut(id).zip(doc.layer(id)) {
|
||||
*before = after.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(basis) = self.pi_canvas_basis.as_mut().filter(|basis| basis.id == doc.id) {
|
||||
let basis = Arc::make_mut(basis);
|
||||
for &id in layers {
|
||||
if let Some((before, after)) = basis.layer_mut(id).zip(doc.layer(id)) {
|
||||
*before = after.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
self.sync_product_editor_basis_layers(doc, layers);
|
||||
self.user_canvas_changes.sync_layers(doc, layers);
|
||||
}
|
||||
|
||||
fn record_manual_layers_from_observer(&mut self, app: &mut PhotocraftApp) {
|
||||
if self.product_target_hidden || self.professional_child_active(app) {
|
||||
return;
|
||||
}
|
||||
let Some((doc, rev)) = app.session.active().map(|s| (s.doc.clone(), s.revision)) else {
|
||||
self.manual_edit_observer = None;
|
||||
return;
|
||||
};
|
||||
if app.automation_input {
|
||||
self.manual_edit_observer = Some((doc, rev));
|
||||
return;
|
||||
}
|
||||
let Some((before, before_rev)) = self.manual_edit_observer.as_ref() else {
|
||||
self.manual_edit_observer = Some((doc, rev));
|
||||
return;
|
||||
};
|
||||
if before.id != doc.id || product_document_key(before) != product_document_key(&doc) {
|
||||
self.manual_edit_observer = Some((doc, rev));
|
||||
return;
|
||||
}
|
||||
if *before_rev == rev || Arc::ptr_eq(before, &doc) {
|
||||
return;
|
||||
}
|
||||
if photocraft_engine::layer_multi_cmds::selection_only_change(before, &doc) {
|
||||
self.manual_edit_observer = Some((doc, rev));
|
||||
return;
|
||||
}
|
||||
let after_layers: std::collections::HashMap<_, _> =
|
||||
doc.walk().into_iter().map(|(_, _, layer)| (layer.id, layer)).collect();
|
||||
let changed: Vec<u64> = before.walk().into_iter().filter_map(|(_, _, layer)| {
|
||||
let next = after_layers.get(&layer.id)?;
|
||||
if matches!(layer.content, LayerContent::Group(_)) {
|
||||
(layer.visible != next.visible || layer.locks != next.locks || layer.name != next.name)
|
||||
.then_some(layer.id.0)
|
||||
} else {
|
||||
(*next != layer).then_some(layer.id.0)
|
||||
}
|
||||
}).collect();
|
||||
if !changed.is_empty() && let Some(state) = app.session.active_mut() && state.doc.id == doc.id {
|
||||
let mut existing: Vec<u64> = state.doc.metadata.text.iter()
|
||||
.find(|(k, _)| k == "jiansun.manual-layers")
|
||||
.and_then(|(_, v)| serde_json::from_str(v).ok())
|
||||
.unwrap_or_default();
|
||||
let before_len = existing.len();
|
||||
for id in changed {
|
||||
if !existing.contains(&id) {
|
||||
existing.push(id);
|
||||
}
|
||||
}
|
||||
if existing.len() != before_len {
|
||||
let metadata = &mut Arc::make_mut(&mut state.doc).metadata.text;
|
||||
metadata.retain(|(k, _)| k != "jiansun.manual-layers");
|
||||
metadata.push(("jiansun.manual-layers".into(), json!(existing).to_string()));
|
||||
self.draft_changed = true;
|
||||
}
|
||||
self.manual_edit_observer = Some((state.doc.clone(), state.revision));
|
||||
return;
|
||||
}
|
||||
self.manual_edit_observer = Some((doc, rev));
|
||||
}
|
||||
|
||||
fn sync_pi_canvas_write(&mut self, before: &Document, after: &Document) {
|
||||
if before.id != after.id { return; }
|
||||
let after_layers: std::collections::HashMap<_, _> =
|
||||
@ -2870,7 +2942,7 @@ impl Workspace {
|
||||
scope["goalUserEntry"] = json!(true);
|
||||
}
|
||||
}
|
||||
if production || self.template_workflow["canvasFirst"] == true {
|
||||
if !self.product_target_hidden && !self.professional_child_active(app) {
|
||||
self.record_product_view_edits(app);
|
||||
self.park_user_canvas_changes(app);
|
||||
if let Some(changes) = self.user_canvas_changes.take() {
|
||||
@ -4150,6 +4222,7 @@ impl Workspace {
|
||||
self.pi_request_scope = Value::Null;
|
||||
self.note("本地 Agent 连接已断开,草稿已保留");
|
||||
}
|
||||
self.record_manual_layers_from_observer(app);
|
||||
self.track_pi_canvas(app);
|
||||
true
|
||||
}
|
||||
@ -4652,15 +4725,17 @@ impl Workspace {
|
||||
let _ = reply.send(Err(BridgeFailure::new("auth_revoked", false, false, "授权已失效,原操作未应用")));
|
||||
return;
|
||||
}
|
||||
let scoped_tool = (self.pi_request_scope["productProduction"] == true || self.template_workflow["canvasFirst"] == true)
|
||||
&& self.pi_run.as_deref().is_some_and(|run| input["run"].as_str() == Some(run))
|
||||
let scoped_tool = self.pi_run.as_deref().is_some_and(|run| input["run"].as_str() == Some(run))
|
||||
&& app.session.active().is_some_and(|state| self.owner_doc == Some(state.doc.id.0));
|
||||
if method == "pi-user-canvas-changes" {
|
||||
let changes = if scoped_tool && self.production_exit.is_none() {
|
||||
if scoped_tool && self.production_exit.is_none() {
|
||||
self.park_user_canvas_changes(app);
|
||||
self.user_canvas_changes.take()
|
||||
} else { None };
|
||||
let _ = reply.send(Ok((changes.unwrap_or_default(), None)));
|
||||
self.user_canvas_changes.take_or_restore(|changes| {
|
||||
reply.send(Ok((changes.unwrap_or_default(), None))).is_ok()
|
||||
});
|
||||
} else {
|
||||
let _ = reply.send(Ok((Value::Null, None)));
|
||||
}
|
||||
return;
|
||||
}
|
||||
let tool_receipt = scoped_tool && !self.product_target_hidden && input["reportUserCanvasChanges"] == true;
|
||||
|
||||
@ -25,6 +25,7 @@ struct OwnedJob {
|
||||
index: usize,
|
||||
before: u64,
|
||||
before_doc: Option<Arc<photocraft_doc::Document>>,
|
||||
target_layers: Vec<u64>,
|
||||
command: String,
|
||||
cancelled: Arc<AtomicBool>,
|
||||
terminal: Option<Value>,
|
||||
@ -77,6 +78,7 @@ impl State {
|
||||
|
||||
pub(super) fn cancel(&self) {
|
||||
if let Some(token) = &self.cancellation { token.store(true, Ordering::SeqCst); }
|
||||
for job in &self.jobs { job.cancelled.store(true, Ordering::SeqCst); }
|
||||
}
|
||||
|
||||
pub(super) fn cancellation(&self) -> Option<Arc<AtomicBool>> {
|
||||
@ -214,14 +216,17 @@ impl State {
|
||||
}
|
||||
|
||||
fn scope(&mut self, run: &str, document: u64, index: usize) -> Result<(CommandScope, Arc<AtomicBool>), String> {
|
||||
let token = self.token(run)?;
|
||||
let _run_token = self.token(run)?;
|
||||
let job_token = Arc::new(AtomicBool::new(false));
|
||||
if let Some(scope) = &self.scope {
|
||||
if scope.document.0 != document || scope.index != index { return Err("本轮原生能力绑定已改变".into()); }
|
||||
return Ok((scope.clone(), token));
|
||||
if scope.document.0 != document || scope.index != index {
|
||||
return Err("本轮原生能力绑定已改变".into());
|
||||
}
|
||||
return Ok((scope.clone().with_cancellation(job_token.clone()), job_token));
|
||||
}
|
||||
let scope = CommandScope::new(photocraft_doc::DocId(document), index).with_cancellation(token.clone());
|
||||
let scope = CommandScope::new(photocraft_doc::DocId(document), index).with_cancellation(job_token.clone());
|
||||
self.scope = Some(scope.clone());
|
||||
Ok((scope, token))
|
||||
Ok((scope, job_token))
|
||||
}
|
||||
|
||||
pub(super) fn pending_job(&self, run: &str) -> Option<JobId> {
|
||||
@ -507,14 +512,14 @@ pub(super) fn catalog(w: &Workspace, app: &mut PhotocraftApp, input: &Value) ->
|
||||
"nativeTiming":{"listingMs":listing_ms,"availabilityMs":lookup_ms,"totalMs":catalog_started.elapsed().as_millis()}}))
|
||||
}
|
||||
|
||||
fn register_job(w: &mut Workspace, app: &PhotocraftApp, job: JobId, document: u64, before: u64, command: &str, token: Arc<AtomicBool>) -> Result<(), String> {
|
||||
fn register_job(w: &mut Workspace, app: &PhotocraftApp, job: JobId, document: u64, before: u64, command: &str, target_layers: Vec<u64>, token: Arc<AtomicBool>) -> Result<(), String> {
|
||||
let actual = app.session.job(job).or_else(|| app.session.jobs_with_recent().into_iter().find(|info| info.id == job)).ok_or("原生任务编号无对应记录,结果待核查")?;
|
||||
if actual.document.map(|doc| doc.0) != Some(document) || actual.command != command { return Err("原生任务归属不符,结果待核查".into()); }
|
||||
if w.agent_native.jobs.iter().any(|record| record.id == job) { return Err("原生任务编号已登记,不会重复派发".into()); }
|
||||
let before_doc = app.session.active().filter(|state| state.revision == before).map(|state| state.doc.clone());
|
||||
w.agent_native.jobs.push_back(OwnedJob { id:job,run:w.pi_run.clone().ok_or("原生会话已结束")?,account:w.account["id"].clone(),
|
||||
origin:w.origin.clone(),project:w.pi_request_scope["project"]["localId"].clone(),document,
|
||||
index:app.session.active_index().ok_or("原生任务文档索引不可用")?,before,before_doc,command:command.into(),cancelled:token,terminal:None });
|
||||
index:app.session.active_index().ok_or("原生任务文档索引不可用")?,before,before_doc,target_layers,command:command.into(),cancelled:token,terminal:None });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@ -667,7 +672,7 @@ pub(super) fn call(w: &mut Workspace, app: &mut PhotocraftApp, ctx: &egui::Conte
|
||||
if result["pending"] == true {
|
||||
let job = result["job"].as_u64().map(JobId).ok_or_else(|| unknown("原生任务未返回可核查编号".into()))?;
|
||||
let token = token.ok_or_else(|| unknown("读取操作意外启动了原生任务".into()))?;
|
||||
register_job(w, app, job, document, before, &command, token).map_err(unknown)?;
|
||||
register_job(w, app, job, document, before, &command, target_layers.clone(), token).map_err(unknown)?;
|
||||
let result = w.agent_native.project_result(result).map_err(unknown)?;
|
||||
let mut value = receipt(w, document, (before, revision), method, &command, &result, true);
|
||||
value["job"] = json!(job.0);
|
||||
@ -679,7 +684,7 @@ pub(super) fn call(w: &mut Workspace, app: &mut PhotocraftApp, ctx: &egui::Conte
|
||||
}
|
||||
Outcome::AfterJob(job) => {
|
||||
let token = token.ok_or_else(|| unknown("读取操作意外启动了原生任务".into()))?;
|
||||
register_job(w, app, job, document, before, &command, token).map_err(unknown)?;
|
||||
register_job(w, app, job, document, before, &command, target_layers.clone(), token).map_err(unknown)?;
|
||||
let result = json!({"job":job.0,"pending":true});
|
||||
let mut value = receipt(w, document, (before, revision), method, &command, &result, true);
|
||||
value["job"] = json!(job.0);
|
||||
@ -744,6 +749,14 @@ pub(super) fn settle_jobs(w: &mut Workspace, app: &PhotocraftApp) -> Vec<Value>
|
||||
let mut verified_before = None;
|
||||
let mut block = false;
|
||||
let production_workspace = super::pi_bridge::production_workspace_active(w);
|
||||
let target_blocked_jobs: std::collections::HashSet<JobId> = w.agent_native.jobs.iter()
|
||||
.filter(|owned| owned.run == run && owned.terminal.is_none() && owned.document == document)
|
||||
.filter(|owned| owned.target_layers.iter().any(|&id| {
|
||||
w.production_layer_rejection(&active.doc, photocraft_doc::LayerId(id))
|
||||
.is_some_and(|reason| matches!(reason, super::product_production::LayerRejection::UserEdit | super::product_production::LayerRejection::UserLock))
|
||||
}))
|
||||
.map(|owned| owned.id)
|
||||
.collect();
|
||||
for owned in &mut w.agent_native.jobs {
|
||||
if owned.run != run || owned.terminal.is_some() { continue; }
|
||||
let identity_matches = owned.account == w.account["id"] && owned.origin == w.origin && owned.document == document
|
||||
@ -784,14 +797,11 @@ pub(super) fn settle_jobs(w: &mut Workspace, app: &PhotocraftApp) -> Vec<Value>
|
||||
let verified = same && info.state == "done" && info.document.map(|doc| doc.0) == Some(document)
|
||||
&& application["documentId"].as_u64() == Some(document)
|
||||
&& application["index"].as_u64().and_then(|index| usize::try_from(index).ok()) == Some(owned.index)
|
||||
&& application["beforeRevision"].as_u64() == Some(owned.before)
|
||||
&& application["afterRevision"].as_u64() == Some(revision);
|
||||
// A running job has no engine application receipt. Once this same
|
||||
// leased document changes, revoke its application capability before
|
||||
// releasing the bridge's pending slot; the worker itself is neither
|
||||
// cancelled nor replayed. A late completion cannot apply through the
|
||||
// revoked scope or replace this immutable terminal receipt.
|
||||
let superseded = same && revision != owned.before
|
||||
&& application["afterRevision"].as_u64().is_some_and(|after| after <= revision);
|
||||
// Only target-layer UserEdit/UserLock supersedes a running job; unrelated
|
||||
// document revisions never revoke the run's write permission.
|
||||
let target_blocked = target_blocked_jobs.contains(&owned.id);
|
||||
let superseded = same && target_blocked
|
||||
&& info.document.map(|doc| doc.0) == Some(document)
|
||||
&& info.command == owned.command && !application.is_object() && info.state != "done";
|
||||
if info.state == "running" && !superseded { continue; }
|
||||
@ -809,7 +819,7 @@ pub(super) fn settle_jobs(w: &mut Workspace, app: &PhotocraftApp) -> Vec<Value>
|
||||
w.draft_changed = true;
|
||||
w.sync_dirty = true;
|
||||
}
|
||||
} else if !failed_unapplied { block = true; }
|
||||
} else if !failed_unapplied && !superseded { block = true; }
|
||||
let applied = if superseded && info.state == "running" { None } else if info.state == "done" { application.is_object().then_some(true) } else { Some(false) };
|
||||
let receipt = json!({"kind":"native-operation","run":owned.run,"accountId":owned.account,"origin":owned.origin,"projectLocalId":owned.project,
|
||||
"documentId":owned.document,"beforeRevision":owned.before,"afterRevision":application["afterRevision"],"revision":revision,
|
||||
@ -1961,7 +1971,7 @@ mod tests {
|
||||
app.session.command_scope = None;
|
||||
let photocraft_engine::jobs::Started::Job(job) = started else { panic!("expected real native worker") };
|
||||
let before = w.expected_revision;
|
||||
register_job(w, app, job, document, before, "test.scope.worker", token).unwrap();
|
||||
register_job(w, app, job, document, before, "test.scope.worker", Vec::new(), token).unwrap();
|
||||
job
|
||||
}
|
||||
|
||||
@ -2058,50 +2068,48 @@ mod tests {
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn user_revision_supersedes_running_worker_without_replay_and_new_run_can_write() {
|
||||
fn unrelated_user_revision_does_not_block_running_worker_or_run_writes() {
|
||||
let (mut w, mut app, _) = fixture();
|
||||
let before = w.expected_revision;
|
||||
let job = start_owned_worker(&mut w, &mut app);
|
||||
simulate_user_revision(&mut app);
|
||||
let user_revision = app.session.active().unwrap().revision;
|
||||
assert!(user_revision > before);
|
||||
// Unrelated revision bump must not supersede or globally block the run.
|
||||
assert!(settle_jobs(&mut w, &app).is_empty());
|
||||
assert!(!w.pi_write_blocked);
|
||||
assert!(!w.agent_native.cancelled(RUN));
|
||||
let _ = app.session.wait_job(job);
|
||||
let receipts = settle_jobs(&mut w, &app);
|
||||
assert_eq!(receipts.len(), 1);
|
||||
assert_eq!(receipts[0]["state"], "superseded_by_user");
|
||||
assert_eq!(receipts[0]["pending"], false);
|
||||
assert_eq!(receipts[0]["executed"], false);
|
||||
assert!(receipts[0]["applied"].is_null(), "a running worker is not claimed cancelled or applied");
|
||||
assert!(w.agent_native.pending_job(RUN).is_none());
|
||||
assert!(w.agent_native.cancelled(RUN));
|
||||
let mut query = base(&w); query["job"] = json!(job.0);
|
||||
assert_eq!(poll(&mut w, &app, &query).unwrap()["state"], "superseded_by_user");
|
||||
assert!(app.session.wait_job(job).is_err(), "revoked scope prevents a late apply");
|
||||
assert_eq!(app.session.active().unwrap().revision, user_revision);
|
||||
assert!(settle_jobs(&mut w, &app).is_empty(), "late engine completion cannot revive the receipt");
|
||||
|
||||
let new_run = "12345678-1234-1234-1234-123456789013";
|
||||
w.pi_run = Some(new_run.into());
|
||||
w.expected_revision = user_revision;
|
||||
w.pi_write_blocked = false;
|
||||
w.allow_apply = true;
|
||||
w.agent_native.reset_for_run(new_run);
|
||||
let input = json!({"run":new_run,"documentId":w.owner_doc,"revision":user_revision,
|
||||
"method":"engine.execute","params":{"command":"layer.new.layer","params":{"name":"新意图"}}});
|
||||
assert_eq!(call(&mut w, &mut app, &egui::Context::default(), &input).unwrap()["executed"], true);
|
||||
assert!(app.session.active().unwrap().revision > user_revision);
|
||||
assert!(!w.pi_write_blocked, "unrelated revision must not set global pi_write_blocked");
|
||||
assert!(!w.agent_native.cancelled(RUN), "unrelated revision must not cancel the run");
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn user_revision_supersedes_worker_already_rejected_by_engine() {
|
||||
fn target_layer_user_edit_supersedes_only_that_job_without_global_write_block() {
|
||||
let (mut w, mut app, _) = fixture();
|
||||
let job = start_owned_worker(&mut w, &mut app);
|
||||
simulate_user_revision(&mut app);
|
||||
assert!(app.session.wait_job(job).is_err());
|
||||
w.pi_canvas_basis = Some(app.session.active().unwrap().doc.clone());
|
||||
let target_id = app.session.active().unwrap().doc.walk()[0].2.id;
|
||||
let document = w.owner_doc.unwrap();
|
||||
let (scope, token) = w.agent_native.scope(RUN, document, 0).unwrap();
|
||||
app.session.command_scope = Some(scope);
|
||||
let started = app.session.start_job("test.scope.worker", json!({}), "native test worker", false,
|
||||
|_| Ok(()), |session, ()| session.execute("layer.new.layer", json!({"name":"真实worker图层"}))).unwrap();
|
||||
app.session.command_scope = None;
|
||||
let photocraft_engine::jobs::Started::Job(job) = started else { panic!("expected real native worker") };
|
||||
let before = w.expected_revision;
|
||||
register_job(&mut w, &app, job, document, before, "test.scope.worker", vec![target_id.0], token).unwrap();
|
||||
|
||||
let state = app.session.active_mut().unwrap();
|
||||
Arc::make_mut(&mut state.doc).layer_mut(target_id).unwrap().locks.all = true;
|
||||
state.revision += 1;
|
||||
|
||||
let receipts = settle_jobs(&mut w, &app);
|
||||
assert_eq!(receipts.len(), 1);
|
||||
assert_eq!(receipts[0]["state"], "superseded_by_user");
|
||||
assert_eq!(receipts[0]["applied"], false);
|
||||
assert_eq!(receipts[0]["nativeJob"]["state"], "failed");
|
||||
assert!(!w.pi_write_blocked, "target layer supersession must not set global pi_write_blocked");
|
||||
assert!(!w.agent_native.cancelled(RUN), "other layers in the same run remain writable");
|
||||
assert!(app.session.wait_job(job).is_err());
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@ -2211,8 +2219,20 @@ mod tests {
|
||||
#[test]
|
||||
fn reconcile_revoked_worker_stays_unknown_until_actual_cancelled_receipt() {
|
||||
let (mut w, mut app, _) = fixture();
|
||||
let job = start_owned_worker(&mut w, &mut app);
|
||||
simulate_user_revision(&mut app);
|
||||
w.pi_canvas_basis = Some(app.session.active().unwrap().doc.clone());
|
||||
let target_id = app.session.active().unwrap().doc.walk()[0].2.id;
|
||||
let document = w.owner_doc.unwrap();
|
||||
let (scope, token) = w.agent_native.scope(RUN, document, 0).unwrap();
|
||||
app.session.command_scope = Some(scope);
|
||||
let started = app.session.start_job("test.scope.worker", json!({}), "native test worker", false,
|
||||
|_| Ok(()), |session, ()| session.execute("layer.new.layer", json!({"name":"真实worker图层"}))).unwrap();
|
||||
app.session.command_scope = None;
|
||||
let photocraft_engine::jobs::Started::Job(job) = started else { panic!("expected real native worker") };
|
||||
let before = w.expected_revision;
|
||||
register_job(&mut w, &app, job, document, before, "test.scope.worker", vec![target_id.0], token).unwrap();
|
||||
let state = app.session.active_mut().unwrap();
|
||||
Arc::make_mut(&mut state.doc).layer_mut(target_id).unwrap().locks.all = true;
|
||||
state.revision += 1;
|
||||
assert_eq!(settle_jobs(&mut w, &app)[0]["state"], "superseded_by_user");
|
||||
let new_run = "12345678-1234-1234-1234-123456789013";
|
||||
w.pi_run = Some(new_run.into());
|
||||
|
||||
@ -1074,6 +1074,70 @@ fn visible_retouch_layers(doc: &Document, target: u64) -> impl Iterator<Item = p
|
||||
.filter(move |id| doc.layer(*id).is_some_and(|layer| layer.visible))
|
||||
}
|
||||
|
||||
fn apply_opaque_white_background(bytes: Vec<u8>, contain: bool, target_frame: Option<(u32, u32)>) -> Result<Vec<u8>, String> {
|
||||
let image = photocraft_codecs::decode(&bytes).map_err(|e| format!("候选图片无法解码:{e}"))?;
|
||||
let (nw, nh) = image.dimensions();
|
||||
if nw == 0 || nh == 0 {
|
||||
return Err("候选图片尺寸无效".into());
|
||||
}
|
||||
let mut rgba = image.to_rgba8();
|
||||
let has_transparency = rgba.chunks_exact(4).any(|px| px[3] < 255);
|
||||
if !contain && !has_transparency {
|
||||
return Ok(bytes);
|
||||
}
|
||||
if !contain {
|
||||
for px in rgba.chunks_exact_mut(4) {
|
||||
let a = px[3] as u32;
|
||||
if a < 255 {
|
||||
let inv = 255 - a;
|
||||
px[0] = ((px[0] as u32 * a + 255 * inv + 127) / 255) as u8;
|
||||
px[1] = ((px[1] as u32 * a + 255 * inv + 127) / 255) as u8;
|
||||
px[2] = ((px[2] as u32 * a + 255 * inv + 127) / 255) as u8;
|
||||
px[3] = 255;
|
||||
}
|
||||
}
|
||||
let flattened = photocraft_codecs::Image::from_u8(nw, nh, photocraft_codecs::ChannelLayout::Rgba, rgba)
|
||||
.map_err(|e| format!("白底合成失败:{e}"))?;
|
||||
return photocraft_codecs::encode(&flattened, photocraft_codecs::Format::Png, &Default::default())
|
||||
.map_err(|e| format!("白底合成编码失败:{e}"));
|
||||
}
|
||||
let (tw, th) = target_frame.filter(|&(w, h)| w > 0 && h > 0).unwrap_or((nw, nh));
|
||||
let (cw, ch, dst_w, dst_h) = if (nw as u64) * (th as u64) >= (nh as u64) * (tw as u64) {
|
||||
let dst_w = nw.max(tw).min(8192);
|
||||
let cw = dst_w;
|
||||
let ch = ((cw as u64 * th as u64) / tw as u64).clamp(1, 8192) as u32;
|
||||
let dst_h = ((dst_w as u64 * nh as u64) / nw as u64).clamp(1, ch as u64) as u32;
|
||||
(cw, ch, dst_w, dst_h)
|
||||
} else {
|
||||
let dst_h = nh.max(th).min(8192);
|
||||
let ch = dst_h;
|
||||
let cw = ((ch as u64 * tw as u64) / th as u64).clamp(1, 8192) as u32;
|
||||
let dst_w = ((dst_h as u64 * nw as u64) / nh as u64).clamp(1, cw as u64) as u32;
|
||||
(cw, ch, dst_w, dst_h)
|
||||
};
|
||||
let mut canvas = vec![255u8; (cw as usize) * (ch as usize) * 4];
|
||||
let ox = (cw - dst_w) / 2;
|
||||
let oy = (ch - dst_h) / 2;
|
||||
for dy in 0..dst_h {
|
||||
let sy = (dy as u64 * nh as u64 / dst_h as u64).min((nh - 1) as u64) as u32;
|
||||
for dx in 0..dst_w {
|
||||
let sx = (dx as u64 * nw as u64 / dst_w as u64).min((nw - 1) as u64) as u32;
|
||||
let si = ((sy * nw + sx) * 4) as usize;
|
||||
let di = (((oy + dy) * cw + (ox + dx)) * 4) as usize;
|
||||
let a = rgba[si + 3] as u32;
|
||||
let inv = 255 - a;
|
||||
canvas[di] = ((rgba[si] as u32 * a + 255 * inv + 127) / 255) as u8;
|
||||
canvas[di + 1] = ((rgba[si + 1] as u32 * a + 255 * inv + 127) / 255) as u8;
|
||||
canvas[di + 2] = ((rgba[si + 2] as u32 * a + 255 * inv + 127) / 255) as u8;
|
||||
canvas[di + 3] = 255;
|
||||
}
|
||||
}
|
||||
let composited = photocraft_codecs::Image::from_u8(cw, ch, photocraft_codecs::ChannelLayout::Rgba, canvas)
|
||||
.map_err(|e| format!("白底合成失败:{e}"))?;
|
||||
photocraft_codecs::encode(&composited, photocraft_codecs::Format::Png, &Default::default())
|
||||
.map_err(|e| format!("白底合成编码失败:{e}") )
|
||||
}
|
||||
|
||||
/// Prepare the same slot replacement for a read-only preview and a committed adoption.
|
||||
pub fn prepare_adoption_document(
|
||||
doc: &Document, meta: &Value, bytes: Vec<u8>, ticket: &photocraft_engine::smart_cmds::SourceTicket,
|
||||
@ -1085,6 +1149,22 @@ pub fn prepare_adoption_document(
|
||||
let candidate = meta["candidateId"].as_str().ok_or("候选身份缺失")?;
|
||||
let variant = meta["variantId"].as_str().ok_or("花色身份缺失")?;
|
||||
let target = doc.layer(photocraft_doc::LayerId(layer)).ok_or("原图位不存在")?;
|
||||
let require_opaque = super::production_facts::slot_requires_opaque(meta)
|
||||
|| document_mapping(doc).is_some_and(|mapping| {
|
||||
mapping["outputs"].as_array().into_iter().flatten()
|
||||
.flat_map(|page| page["mapping"]["fields"].as_array().into_iter().flatten())
|
||||
.any(|field| {
|
||||
(field["nativeLayerId"].as_u64() == Some(layer) || field["slotId"].as_str() == Some(slot))
|
||||
&& super::production_facts::slot_requires_opaque(field)
|
||||
})
|
||||
});
|
||||
let bytes = if require_opaque {
|
||||
let target_frame = meta["frame"]["width"].as_f64().zip(meta["frame"]["height"].as_f64())
|
||||
.and_then(|(w, h)| (w > 0.0 && h > 0.0).then_some((w.round() as u32, h.round() as u32)));
|
||||
apply_opaque_white_background(bytes, meta["fit"] == "contain", target_frame)?
|
||||
} else {
|
||||
bytes
|
||||
};
|
||||
let key = format!("jiansun.adopted.{variant}.{slot}");
|
||||
let same_candidate = doc.metadata.text.iter().any(|(k, value)| *k == key && value == candidate)
|
||||
&& matches!(&target.content, LayerContent::Smart(smart)
|
||||
@ -7672,6 +7752,65 @@ pub(super) mod tests {
|
||||
w.canvas_workspace.output = "main_images".into();
|
||||
w.canvas_workspace.variant = "cream".into();
|
||||
w.canvas_workspace.scope_blocked = false;
|
||||
assert_eq!(w.toolbar_output_and_variant(&app), ("main_images".into(), "cream".into()));
|
||||
assert_eq!(w.toolbar_output_and_variant(&app), ("main_images".into(), "cream".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn require_opaque_composites_transparent_and_contain_slots_over_pure_white() {
|
||||
use photocraft_doc::{Affine, ColorMode, Layer, LayerContent, SampleType, Size, SmartObject, SmartSource};
|
||||
let mut source_doc = Document::new("slot", Size::new(8, 12), ColorMode::Rgb, SampleType::U8);
|
||||
source_doc.layers.push(Layer::new("bg", LayerContent::Raster(photocraft_raster::Surface::new(photocraft_color::PixelFormat::RGBA8))));
|
||||
let source_bytes = photocraft_format::save_to_bytes(&source_doc, &Default::default()).unwrap();
|
||||
let mut doc = Document::new("canvas", Size::new(8, 12), ColorMode::Rgb, SampleType::U8);
|
||||
let smart = SmartObject::new(
|
||||
SmartSource::Embedded { file_name: "slot.pcraft".into(), bytes: std::sync::Arc::new(source_bytes.clone()) },
|
||||
Affine::default(),
|
||||
None,
|
||||
);
|
||||
let layer_id = doc.insert_above(None, Layer::new("图位", LayerContent::Smart(smart)));
|
||||
let mut session = photocraft_engine::Session::new();
|
||||
session.add_document(doc.clone(), None);
|
||||
let state = session.active().unwrap();
|
||||
let LayerContent::Smart(sm) = &state.doc.layer(layer_id).unwrap().content else { unreachable!() };
|
||||
let ticket = photocraft_engine::smart_cmds::freeze_source(&session, state.doc.id, state.revision, layer_id, sm.contents_id).unwrap();
|
||||
|
||||
let mut rgba = vec![0u8; 4 * 4 * 4];
|
||||
let idx = (4 + 1) * 4;
|
||||
rgba[idx] = 255;
|
||||
rgba[idx + 3] = 255;
|
||||
let candidate = photocraft_codecs::Image::from_u8(4, 4, photocraft_codecs::ChannelLayout::Rgba, rgba).unwrap();
|
||||
let candidate_png = photocraft_codecs::encode(&candidate, photocraft_codecs::Format::Png, &Default::default()).unwrap();
|
||||
|
||||
let meta_opaque = json!({
|
||||
"nativeLayerId": layer_id.0,
|
||||
"slotId": "S01-I01",
|
||||
"candidateId": "cand-opaque",
|
||||
"variantId": "v1",
|
||||
"fit": "contain",
|
||||
"requireOpaque": true,
|
||||
"frame": {"x": 0, "y": 0, "width": 8, "height": 12}
|
||||
});
|
||||
let prepared = prepare_adoption_document(&doc, &meta_opaque, candidate_png.clone(), &ticket, false).unwrap();
|
||||
let LayerContent::Smart(out_smart) = &prepared.document.layer(layer_id).unwrap().content else { unreachable!() };
|
||||
let SmartSource::Embedded { bytes, .. } = &out_smart.source else { unreachable!() };
|
||||
let decoded = photocraft_codecs::decode(bytes).unwrap();
|
||||
assert_eq!(decoded.dimensions(), (8, 12));
|
||||
let out_rgba = decoded.to_rgba8();
|
||||
assert!(out_rgba.chunks_exact(4).all(|px| px[3] == 255), "all pixels must be opaque");
|
||||
assert_eq!(&out_rgba[0..4], &[255, 255, 255, 255], "letterbox margin must be pure white");
|
||||
|
||||
let meta_normal = json!({
|
||||
"nativeLayerId": layer_id.0,
|
||||
"slotId": "S01-I01",
|
||||
"candidateId": "cand-normal",
|
||||
"variantId": "v1",
|
||||
"fit": "cover",
|
||||
"frame": {"x": 0, "y": 0, "width": 8, "height": 12}
|
||||
});
|
||||
let prepared_normal = prepare_adoption_document(&doc, &meta_normal, candidate_png, &ticket, false).unwrap();
|
||||
let LayerContent::Smart(normal_smart) = &prepared_normal.document.layer(layer_id).unwrap().content else { unreachable!() };
|
||||
let SmartSource::Embedded { bytes: normal_bytes, .. } = &normal_smart.source else { unreachable!() };
|
||||
let normal_decoded = photocraft_codecs::decode(normal_bytes).unwrap();
|
||||
assert_eq!(normal_decoded.to_rgba8()[3], 0, "unannotated slot preserves transparency");
|
||||
}
|
||||
}
|
||||
|
||||
@ -548,18 +548,18 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co
|
||||
}
|
||||
"pi-detail-copy-apply" => {
|
||||
let match_fields = input["matchFields"] == true;
|
||||
if !production_workspace_active(w) || w.pi_write_blocked || !w.queue.is_empty() {
|
||||
if !production_workspace_active(w) || w.pi_write_blocked {
|
||||
return Err("文案未取得当前画布写入许可,原内容保留".into());
|
||||
}
|
||||
let active = app.session.active().ok_or("原项目未打开")?;
|
||||
if !w.queue.is_empty() {
|
||||
return Ok(json!({"retryWrite":true,"revision":active.revision}));
|
||||
}
|
||||
if match_fields {
|
||||
// A field write is keyed by its layer. The target's own protection decides below;
|
||||
// neither the revision it was read at nor a save or another field's edit gates it.
|
||||
super::agent_native::guard_with_background_save(w, app, input, false)?;
|
||||
} else if super::canvas_workspace::detail_write_waiting(w, app)
|
||||
|| active.revision != w.expected_revision
|
||||
|| input["revision"].as_u64() != Some(active.revision)
|
||||
{
|
||||
} else if super::canvas_workspace::detail_write_waiting(w, app) {
|
||||
return Ok(json!({"retryWrite":true,"revision":active.revision}));
|
||||
}
|
||||
let fields = detail_copy_fields(&active.doc, None, None);
|
||||
@ -1938,13 +1938,9 @@ mod tests {
|
||||
let items = json!([{"layer":first,"text":"小壹标题"},{"layer":second,"text":"小壹副标题"},
|
||||
{"layer":sample,"text":"本款商品说明\nNew model","expectedText":"旧款标题\nOld batch"},{"layer":narrow,"text":"WWW"},
|
||||
{"layer":optional,"text":"","expectedText":"旧规格"}]);
|
||||
let stale = action_impl(&mut w, &mut app, None, "pi-detail-copy-apply",
|
||||
&json!({"run":run,"revision":original,"items":items}), true).unwrap();
|
||||
assert_eq!(stale["retryWrite"], true);
|
||||
let revision = app.session.active().unwrap().revision;
|
||||
action(&mut w, &mut app, "pi-write-request", &json!({"run":run,"revision":revision})).unwrap();
|
||||
let receipt = action_impl(&mut w, &mut app, None, "pi-detail-copy-apply",
|
||||
&json!({"run":run,"revision":revision,"items":items}), true).unwrap();
|
||||
&json!({"run":run,"revision":original,"items":items}), true).unwrap();
|
||||
assert!(receipt.get("retryWrite").is_none());
|
||||
assert_eq!(receipt["appliedLayers"], json!([second, sample, narrow, optional]));
|
||||
assert_eq!(receipt["canvasFacts"][3]["layer"], optional);
|
||||
assert_eq!(receipt["canvasFacts"][3]["emptyBounds"], true);
|
||||
@ -2252,5 +2248,13 @@ mod tests {
|
||||
|
||||
let screen = action_impl(&mut w, &mut app, None, "pi-product-screen", &json!({"run":run,"page":0,"signatureOnly":true}), true).unwrap();
|
||||
assert_eq!(screen["page"], 0);
|
||||
|
||||
w.queue.push_back(super::Edit { command: "pi-save".into(), params: json!({}), label: "save".into() });
|
||||
let queued = action_impl(&mut w, &mut app, None, "pi-detail-copy-apply", &json!({
|
||||
"run":run,"documentId":doc,"revision":revision,"matchFields":true,
|
||||
"items":[{"layer":copy_layer,"text":"排队时写入","expectedText":"新标题"}]
|
||||
}), true).unwrap();
|
||||
assert_eq!(queued["retryWrite"], true);
|
||||
assert_eq!(queued["revision"], app.session.active().unwrap().revision);
|
||||
}
|
||||
}
|
||||
|
||||
@ -236,6 +236,11 @@ impl Workspace {
|
||||
return Some(LayerRejection::Precondition);
|
||||
}
|
||||
let variant = self.template_workflow["variantId"].as_str().unwrap_or(&self.canvas_workspace.variant);
|
||||
let has_manual_layer = doc.metadata.text.iter().any(|(name, value)| {
|
||||
name == "jiansun.manual-layers"
|
||||
&& serde_json::from_str::<Vec<u64>>(value).is_ok_and(|ids| ids.contains(&layer.0))
|
||||
});
|
||||
if has_manual_layer { return Some(LayerRejection::UserEdit); }
|
||||
let marked = doc.layer(layer).is_some_and(|layer| {
|
||||
match &layer.content {
|
||||
photocraft_doc::LayerContent::Text(text) => {
|
||||
@ -245,9 +250,14 @@ impl Workspace {
|
||||
doc.metadata.text.iter().any(|(name, value)| *name == key
|
||||
&& serde_json::from_str::<Value>(value).is_ok_and(|value| value["sha256"] == digest))
|
||||
}
|
||||
photocraft_doc::LayerContent::Smart(_) => super::super::agent_canvas_read::template_field(doc, layer)["slotId"].as_str()
|
||||
.is_some_and(|slot| canvas_workspace::manual_image(doc, slot, variant).is_some()
|
||||
|| canvas_workspace::user_adopted(doc, slot, variant)),
|
||||
photocraft_doc::LayerContent::Smart(_) => {
|
||||
let text_key = format!("jiansun.manual-text.{}", layer.id.0);
|
||||
let embedded_manual = doc.metadata.text.iter().any(|(name, value)| *name == text_key
|
||||
&& serde_json::from_str::<Value>(value).is_ok_and(|v| v["embedded"] == true && v["source"] == "human"));
|
||||
embedded_manual || super::super::agent_canvas_read::template_field(doc, layer)["slotId"].as_str()
|
||||
.is_some_and(|slot| canvas_workspace::manual_image(doc, slot, variant).is_some()
|
||||
|| canvas_workspace::user_adopted(doc, slot, variant))
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
});
|
||||
|
||||
@ -14,6 +14,16 @@ fn mapped_fields(mapping: &Value) -> impl Iterator<Item = &Value> {
|
||||
.flat_map(|page| page["mapping"]["fields"].as_array().into_iter().flatten())
|
||||
}
|
||||
|
||||
pub fn slot_requires_opaque(field: &Value) -> bool {
|
||||
if field["requireOpaque"] == true || field["require_opaque"] == true {
|
||||
return true;
|
||||
}
|
||||
let replacement = &field["ps_style"]["replacement"];
|
||||
replacement == "opaque_white"
|
||||
|| replacement["requireOpaque"] == true
|
||||
|| replacement["require_opaque"] == true
|
||||
}
|
||||
|
||||
pub fn layer_frame(doc: &Document, layer: &Layer) -> Rect {
|
||||
if let Some(mask) = &layer.vector_mask
|
||||
&& mask.enabled
|
||||
|
||||
@ -5,6 +5,7 @@ use photocraft_doc::{Layer, LayerId, SmartSource};
|
||||
|
||||
const LIMIT: usize = 40;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct CanvasDelta {
|
||||
before: Arc<Document>,
|
||||
after: Arc<Document>,
|
||||
@ -66,6 +67,16 @@ impl UserCanvasChanges {
|
||||
self.local.push((since, revision, change));
|
||||
}
|
||||
|
||||
pub(super) fn take_or_restore(&mut self, send: impl FnOnce(Option<Value>) -> bool) {
|
||||
let parked = self.parked.clone();
|
||||
let local = self.local.clone();
|
||||
let taken = self.take();
|
||||
if !send(taken) {
|
||||
self.parked = parked;
|
||||
self.local = local;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn take(&mut self) -> Option<Value> {
|
||||
let mut report = ChangeReport::default();
|
||||
for delta in self.parked.drain(..) {
|
||||
@ -177,8 +188,7 @@ impl ChangeReport {
|
||||
|
||||
impl Workspace {
|
||||
pub(super) fn park_user_canvas_changes(&mut self, app: &PhotocraftApp) {
|
||||
if self.template_workflow["canvasFirst"] != true && self.product_production.is_none()
|
||||
|| self.product_target_hidden || self.professional_child_active(app) {
|
||||
if self.product_target_hidden || self.professional_child_active(app) {
|
||||
return;
|
||||
}
|
||||
if let Some(active) = app.session.active() {
|
||||
|
||||
@ -584,7 +584,11 @@ fn projected_image(image: &Value) -> Value {
|
||||
.filter(|hash| hash.len() == 64 && hash.bytes().all(|b| b.is_ascii_hexdigit()))
|
||||
.map(|hash| format!("sha256:{}", hash.to_ascii_lowercase()));
|
||||
let purpose = image["purpose"].as_str().filter(|v| matches!(*v, "product" | "scene")).unwrap_or("");
|
||||
json!({"ref":reference,"purpose":purpose,"name":safe_reference_text(&image["name"],160),"description":safe_reference_text(&image["description"],160)})
|
||||
let mut projected = json!({"ref":reference,"purpose":purpose,"name":safe_reference_text(&image["name"],160),"description":safe_reference_text(&image["description"],160)});
|
||||
for key in ["imageRole","fieldKey","templateId","barcode","kind","label","assetId"] {
|
||||
if let Some(value) = image.get(key) { projected[key] = value.clone(); }
|
||||
}
|
||||
projected
|
||||
}
|
||||
|
||||
fn projected_images(value: &Value) -> Value {
|
||||
@ -594,6 +598,20 @@ fn projected_images(value: &Value) -> Value {
|
||||
}
|
||||
}
|
||||
|
||||
fn projected_barcode_entries(value: &Value) -> Value {
|
||||
let Some(entries) = value.as_array() else { return Value::Null };
|
||||
json!(entries.iter().filter_map(|entry| {
|
||||
let mut obj = entry.as_object()?.clone();
|
||||
if let Some(images) = obj.get("images") {
|
||||
obj.insert("images".into(), projected_images(images));
|
||||
}
|
||||
for key in ["url", "localSource", "path"] {
|
||||
obj.remove(key);
|
||||
}
|
||||
Some(Value::Object(obj))
|
||||
}).collect::<Vec<_>>())
|
||||
}
|
||||
|
||||
fn projected_brief(w: &Workspace) -> Value {
|
||||
let mut brief = serde_json::Map::new();
|
||||
if let Some(selection) = w.creation_brief.get("outputVariantIds") {
|
||||
@ -602,7 +620,26 @@ fn projected_brief(w: &Workspace) -> Value {
|
||||
for key in ["name", "brandId", "brandName", "categoryId", "categoryName", "identifierType", "identifier", "variant", "colorName"] {
|
||||
brief.insert(key.into(), json!(clip(&w.creation_brief[key], 160)));
|
||||
}
|
||||
brief.insert("note".into(), json!(clip(&w.creation_brief["note"], 1000)));
|
||||
brief.insert("note".into(), json!(w.creation_brief["note"].as_str().unwrap_or_default()));
|
||||
for field in ["intake", "barcodeBindings", "deliverySpu", "platformFacts", "normalizedProduct"] {
|
||||
if let Some(mut value) = w.creation_brief.get(field).cloned() {
|
||||
if field == "normalizedProduct" {
|
||||
if let Some(assets) = value.get_mut("assets").and_then(Value::as_array_mut) {
|
||||
for asset in assets.iter_mut().filter_map(Value::as_object_mut) {
|
||||
asset.remove("url");
|
||||
asset.remove("localSource");
|
||||
}
|
||||
}
|
||||
}
|
||||
brief.insert(field.into(), value);
|
||||
}
|
||||
}
|
||||
if w.creation_brief.get("barcodeEntries").is_some_and(Value::is_array) {
|
||||
brief.insert("barcodeEntries".into(), projected_barcode_entries(&w.creation_brief["barcodeEntries"]));
|
||||
}
|
||||
if let Some(barcode) = super::production_facts::product_brief::detail_barcode(&w.creation_brief) {
|
||||
brief.insert("detailBarcode".into(), json!(barcode));
|
||||
}
|
||||
let dimensions = ["length", "width", "height", "unit"]
|
||||
.into_iter()
|
||||
.map(|key| (key.into(), json!(clip(&w.creation_brief["dimensions"][key], 24))))
|
||||
@ -2776,6 +2813,41 @@ mod tests {
|
||||
assert!(evidence["brief"].get("variants").is_none());
|
||||
w.creation_brief["variants"] = json!(null);
|
||||
let evidence_null = product_evidence(&w);
|
||||
assert!(evidence_null["brief"].get("variants").is_none());
|
||||
assert!(evidence_null["brief"].get("variants").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn projected_brief_preserves_intake_barcode_entries_platform_facts_and_full_note() {
|
||||
let (mut w, _app, _requests) = fixture();
|
||||
let long_note = "长备注".repeat(450);
|
||||
assert!(long_note.chars().count() > 1000);
|
||||
w.creation_brief["note"] = json!(long_note);
|
||||
w.creation_brief["intake"] = json!({"productValues": {"spec": "1200mm"}, "barcodeValues": {"BC-1": {"thickness": "25mm"}}});
|
||||
w.creation_brief["barcodeEntries"] = json!([{
|
||||
"id": "e1",
|
||||
"barcode": "BC-1",
|
||||
"variantId": "v1",
|
||||
"localSource": "C:\\secret\\local.png",
|
||||
"images": [{"source": format!("local:{:064x}", 9), "purpose": "product", "name": "main.png", "imageRole": "sku-main"}]
|
||||
}]);
|
||||
w.creation_brief["barcodeBindings"] = json!({"v1": ["BC-1"]});
|
||||
w.creation_brief["deliverySpu"] = json!("SPU-99");
|
||||
w.creation_brief["platformFacts"] = json!({"brand": "TestBrand"});
|
||||
w.creation_brief["normalizedProduct"] = json!({"identity": {"spu": "SPU-99"}, "assets": [{"id": "a1", "url": "https://secret", "localSource": "C:\\x"}]});
|
||||
w.creation_brief["detailBarcode"] = json!("BC-1");
|
||||
|
||||
let evidence = product_evidence(&w);
|
||||
let brief = &evidence["brief"];
|
||||
assert_eq!(brief["note"], long_note);
|
||||
assert_eq!(brief["intake"]["productValues"]["spec"], "1200mm");
|
||||
assert_eq!(brief["barcodeBindings"]["v1"], json!(["BC-1"]));
|
||||
assert_eq!(brief["deliverySpu"], "SPU-99");
|
||||
assert_eq!(brief["platformFacts"]["brand"], "TestBrand");
|
||||
assert_eq!(brief["detailBarcode"], "BC-1");
|
||||
assert!(brief["normalizedProduct"]["assets"][0].get("url").is_none());
|
||||
assert!(brief["normalizedProduct"]["assets"][0].get("localSource").is_none());
|
||||
assert!(brief["barcodeEntries"][0].get("localSource").is_none());
|
||||
assert_eq!(brief["barcodeEntries"][0]["images"][0]["ref"], format!("sha256:{:064x}", 9));
|
||||
assert_eq!(brief["barcodeEntries"][0]["images"][0]["imageRole"], "sku-main");
|
||||
}
|
||||
}
|
||||
|
||||
@ -479,9 +479,12 @@ fn commit_here(app: &mut PhotocraftApp, mods: egui::Modifiers) {
|
||||
let name = photocraft_engine::type_cmds::layer_name(&text);
|
||||
let _ = app.run("type.edit", json!({"layer": ed.layer, "name": name, "coalesce": ed.session}));
|
||||
}
|
||||
if !app.automation_input && let Some(state) = app.session.active_mut()
|
||||
if !app.automation_input
|
||||
&& let Some((doc_id, is_smart_child)) = app.session.active().map(|s| (s.doc.id, app.session.smart_links.iter().any(|l| l.child == s.doc.id)))
|
||||
&& let Some(state) = app.session.active_mut()
|
||||
&& state.doc.id == doc_id
|
||||
&& state.coalesce.as_deref() == Some(ed.session.as_str())
|
||||
&& state.doc.metadata.text.iter().any(|(key, _)| key == "jiansun.slot-mapping.v1")
|
||||
&& (is_smart_child || state.doc.metadata.text.iter().any(|(key, _)| key == "jiansun.slot-mapping.v1"))
|
||||
&& state.history.entries().len().checked_sub(2).and_then(|index| state.history.state(index))
|
||||
.is_none_or(|before| text_layer(&before, LayerId(ed.layer)).is_none_or(|before| before.text != text))
|
||||
{
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user