From bf6df62b921eae5ca23365e41b794ce8af937956 Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Fri, 27 Nov 2026 21:43:19 +0800 Subject: [PATCH 1/2] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=B0=8F=E5=A3=B9?= =?UTF-8?q?=E8=B7=A8=E6=88=90=E5=93=81=E7=94=BB=E5=B8=83=E5=9B=9E=E5=A1=AB?= =?UTF-8?q?=E4=B8=8E=E6=89=8B=E6=94=B9=E4=BF=9D=E6=8A=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- apps/detail-agent-pi/src/workflow-context.mjs | 2 +- apps/detail-agent-pi/src/workflow-execute.mjs | 8 +- .../test/workflow-not-dispatched.test.mjs | 7 + .../crates/engine/src/cmd/smart_cmds.rs | 2 +- .../engine/src/cmd/smart_cmds/bounded.rs | 7 + .../crates/engine/src/cmd/type_cmds.rs | 10 +- .../crates/ui-egui/src/jiansun.rs | 10 +- .../ui-egui/src/jiansun/canvas_workspace.rs | 39 ++- .../crates/ui-egui/src/jiansun/pi_bridge.rs | 41 ++- .../ui-egui/src/jiansun/product_production.rs | 242 ++++++++++++++++-- .../ui-egui/src/jiansun/workflow_bridge.rs | 44 +++- docs/development/xiaoyi/status.md | 3 + 12 files changed, 329 insertions(+), 86 deletions(-) diff --git a/apps/detail-agent-pi/src/workflow-context.mjs b/apps/detail-agent-pi/src/workflow-context.mjs index 7049396c..39b089f2 100644 --- a/apps/detail-agent-pi/src/workflow-context.mjs +++ b/apps/detail-agent-pi/src/workflow-context.mjs @@ -5,7 +5,7 @@ const blockedValue = /(?:data:image\/|;base64,|[a-z]:[\\/]|\\\\[^\s]+|file:\/\/| fields.add('screenCount'); fields.add('persistence'); for (const name of ['template','enterprise','releaseId','templateVersion']) fields.add(name); -for (const name of ['canvasFirst','subject','productVariantId','variantId','variantLabel','candidateId','parentCandidateId','adoptedCandidateId','pageId','nativeLayerId','taskId','previewId','operationId','operation','workflow']) fields.add(name); +for (const name of ['canvasFirst','subject','productVariantId','variantId','variantLabel','candidateId','parentCandidateId','adoptedCandidateId','pageId','nativeLayerId','taskId','previewId','operationId','operation','workflow','manuallyEdited','writeBlockReason']) fields.add(name); /** A small data-only view. Pixels, paths, model prompts and private task bodies * never enter the transcript, even if a future native reply includes them. */ diff --git a/apps/detail-agent-pi/src/workflow-execute.mjs b/apps/detail-agent-pi/src/workflow-execute.mjs index 429f69c2..4c1c3a20 100644 --- a/apps/detail-agent-pi/src/workflow-execute.mjs +++ b/apps/detail-agent-pi/src/workflow-execute.mjs @@ -143,9 +143,10 @@ export async function executeWorkflow(host, args, signal, { timeoutMs, pause = d scope.writesBlocked = true; scope.stopReason = message; } + const reason = result.error.reason ?? result.error.code; await host.store.appendEvent({type:'workflow_operation_not_dispatched',run,documentId,operationId,baseRevision:result.baseRevision, - intent:args.intent,slotId:args.slotId,productVariantId:args.productVariantId,code:result.error.code,message}); - throw new BridgeError(message,'local_precondition_failed'); + intent:args.intent,slotId:args.slotId,productVariantId:args.productVariantId,code:result.error.code,reason,message}); + throw new BridgeError(message,reason); } const phases=observedOriginal?receiptPhases:['submitted']; if (result?.operationId !== operationId || !phases.includes(result.phase)) throw Error('工作流操作提交状态无效,原操作需核查;不会重发'); @@ -175,6 +176,9 @@ export async function executeWorkflow(host, args, signal, { timeoutMs, pause = d scope.retain({kind:'workflow',operationId,run,documentId,identity,epoch}); return {operation:{phase:'unknown',operationId,candidateId:result.candidateId}}; } + if (result.phase === 'failed' && result.writeBlockReason) { + throw new BridgeError(workflowResult(result).message,result.writeBlockReason,{dispatched:true}); + } if (result.phase !== 'complete') throw Error(workflowResult(result).message || (result.phase === 'failed' ? '原工作流操作失败,请核查结果;不会重发' : '原工作流操作结果未知,请核查原请求;不会重发')); const operation = workflowResult({ ...result, intent: args.intent, outputId: args.outputId, slotId: args.slotId, productVariantId: args.productVariantId, diff --git a/apps/detail-agent-pi/test/workflow-not-dispatched.test.mjs b/apps/detail-agent-pi/test/workflow-not-dispatched.test.mjs index 95b14b87..d26444de 100644 --- a/apps/detail-agent-pi/test/workflow-not-dispatched.test.mjs +++ b/apps/detail-agent-pi/test/workflow-not-dispatched.test.mjs @@ -35,6 +35,13 @@ test('an identity-bound local rejection stops the turn without an unknown image assert.equal(x.calls.length,1); }); +test('preserves a new layer lock as the reason a write was not dispatched',async()=>{ + const x = fixture(receipt=>({...receipt,error:{...receipt.error,reason:'layer_newly_locked'}})); + await assert.rejects(executeWorkflow(x.host,args),{category:'layer_newly_locked',dispatched:false}); + assert.equal(x.events[0].code,'local_precondition_failed'); + assert.equal(x.events[0].reason,'layer_newly_locked'); +}); + test('a malformed or foreign rejection cannot clear a possibly dispatched operation',async()=>{ for (const [key,value] of Object.entries({operationId:'other',run:'other',documentId:8,baseRevision:-1, accountId:'other',origin:'https://other.test',projectLocalId:'other',accepted:true,dispatched:true, diff --git a/apps/detail-photocraft/crates/engine/src/cmd/smart_cmds.rs b/apps/detail-photocraft/crates/engine/src/cmd/smart_cmds.rs index 96a319a7..2dcd4a32 100644 --- a/apps/detail-photocraft/crates/engine/src/cmd/smart_cmds.rs +++ b/apps/detail-photocraft/crates/engine/src/cmd/smart_cmds.rs @@ -138,7 +138,7 @@ macro_rules! spec { } mod bounded; -pub use bounded::{BoundedSource, SourceSnapshot, SourceTicket, freeze_source, prepare_bounded_source, refresh_layer_with_bounded_source, replace_contents_bounded, replace_instance_bounded_fit, replace_instance_bytes, replace_instance_bytes_fit, update_instance_source_bytes}; +pub use bounded::{BoundedSource, SourceSnapshot, SourceTicket, freeze_source, prepare_bounded_source, refresh_layer_with_bounded_source, replace_contents_bounded, replace_instance_bounded_fit, replace_instance_bytes, replace_instance_bytes_fit, replace_template_instance_bounded_fit, update_instance_source_bytes}; mod contents; mod filters; mod placing; diff --git a/apps/detail-photocraft/crates/engine/src/cmd/smart_cmds/bounded.rs b/apps/detail-photocraft/crates/engine/src/cmd/smart_cmds/bounded.rs index 2ec84c6d..7431a649 100644 --- a/apps/detail-photocraft/crates/engine/src/cmd/smart_cmds/bounded.rs +++ b/apps/detail-photocraft/crates/engine/src/cmd/smart_cmds/bounded.rs @@ -324,6 +324,13 @@ pub fn replace_instance_bounded_fit(s: &mut Session, id: LayerId, original: Opti let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; crate::commands::check_pixels_unlocked(doc, id)?; if doc.path_of(id).is_some_and(|path| doc.locks_at(&path).position) { return Err(other("image position is locked")); } + replace_template_instance_bounded_fit(s, id, original, candidate, contain) +} + +/// Prepare a mapped image replacement after the caller compares live locks +/// with the production baseline. Keep the original layer and group locks in place. +pub fn replace_template_instance_bounded_fit(s: &mut Session, id: LayerId, original: Option<&BoundedSource>, candidate: &BoundedSource, contain: bool) -> Result { + let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; let old = smart(doc, id)?; if old.warp.is_some() || old.perspective.is_some() { return Err(other("flatten the image's warp before replacing this slot")); } let (nw, nh) = (candidate.document.size.width as f64, candidate.document.size.height as f64); diff --git a/apps/detail-photocraft/crates/engine/src/cmd/type_cmds.rs b/apps/detail-photocraft/crates/engine/src/cmd/type_cmds.rs index 232090bb..cd4c4c28 100644 --- a/apps/detail-photocraft/crates/engine/src/cmd/type_cmds.rs +++ b/apps/detail-photocraft/crates/engine/src/cmd/type_cmds.rs @@ -766,12 +766,18 @@ pub(crate) fn check_text_unlocked(doc: &Document, id: LayerId) -> Result<()> { /// Replace several editable text layers in one document and history update. pub fn replace_layer_texts(session: &mut Session, label: &str, edits: &[(LayerId, String)]) -> Result<()> { + let current = &session.active().ok_or(EngineError::NoDocument)?.doc; + for (id, _) in edits { + check_text_unlocked(current, *id)?; + } replace_layer_texts_with(session, label, edits, true, |text, value| { set_text(text, value); Ok(()) }) } +/// Apply published template fields after the caller checks the mapping and +/// compares live locks with the production baseline. pub fn replace_template_layer_texts(session: &mut Session, label: &str, edits: &[(LayerId, String)]) -> Result<()> { replace_layer_texts_with(session, label, edits, false, set_template_text) } @@ -780,10 +786,6 @@ fn replace_layer_texts_with( session: &mut Session, label: &str, edits: &[(LayerId, String)], rename: bool, set: impl Fn(&mut TextLayer, &str) -> Result<()>, ) -> Result<()> { - let current = &session.active().ok_or(EngineError::NoDocument)?.doc; - for (id, _) in edits { - check_text_unlocked(current, *id)?; - } session.edit(label, |doc, _| { let (dpi, format) = (doc.resolution_dpi, doc.pixel_format()); for (id, value) in edits { diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs index 2e7d241c..da89fd5b 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun.rs @@ -1902,15 +1902,7 @@ impl Workspace { } fn detail_layer_unchanged(&self, doc: &Document, layer: photocraft_doc::LayerId) -> bool { - if self.product_layer_protected(layer) { return false; } - let Some(basis) = &self.pi_canvas_basis else { return false; }; - basis.id == doc.id && basis.size == doc.size && basis.mode == doc.mode - && basis.depth == doc.depth && basis.icc_profile == doc.icc_profile && basis.global_light == doc.global_light - && basis.layer(layer).zip(doc.layer(layer)).is_some_and(|(before, now)| before == now) - && doc.path_of(layer).is_some_and(|path| { - let locks = doc.locks_at(&path); - !(locks.all || locks.position || locks.pixels) - }) + self.production_layer_rejection(doc, layer).is_none() } fn handover(&mut self) { diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/canvas_workspace.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/canvas_workspace.rs index bab39f5c..7e98f44f 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/canvas_workspace.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/canvas_workspace.rs @@ -971,6 +971,15 @@ fn valid_detail_adoption(w: &Workspace, doc: &Document, meta: &Value) -> bool { && variant_unchanged && w.detail_layer_unchanged(doc, layer) } +fn adoption_block_reason(w: &Workspace, app: &PhotocraftApp, meta: &mut Value) -> Option { + if meta["detailBatch"] != true { return None; } + let state = app.session.active()?; + let layer = meta["nativeLayerId"].as_u64().map(photocraft_doc::LayerId)?; + let reason = w.production_layer_rejection(&state.doc, layer)?; + meta["writeBlockReason"] = json!(reason.code()); + Some(format!("{},候选已保留", reason.message())) +} + fn adoption_write_mode(w: &Workspace, app: &PhotocraftApp) -> Option { let state = app.session.active()?; if app.layer_mask_targeted() || app.ui.mask_target || app.ui.vector_mask_target || app.ui.transform.is_some() @@ -1449,7 +1458,7 @@ impl Workspace { // Only an acknowledged skeleton switch or initial document bind navigates. } - pub(super) fn canvas_adopt(&mut self, app: &mut PhotocraftApp, bytes: Vec, meta: Value) -> Option<(Value, bool)> { + pub(super) fn canvas_adopt(&mut self, app: &mut PhotocraftApp, bytes: Vec, mut meta: Value) -> Option<(Value, bool)> { use std::sync::atomic::Ordering; let pending = self.canvas_workspace.pending_adoption.clone()?; let batch = meta["detailBatch"] == true; @@ -1470,7 +1479,8 @@ impl Workspace { if pending["slotId"] == meta["slotId"] && pending["candidateId"] == meta["candidateId"] && pending["variantId"] == meta["variantId"] { self.canvas_workspace.pending_adoption = None; } - self.error = "当前项目或画布已有变化,候选已保留,未覆盖编辑".into(); + self.error = adoption_block_reason(self, app, &mut meta) + .unwrap_or_else(|| "当前项目或画布已有变化,候选已保留,未覆盖编辑".into()); return Some((meta, false)); } if self.canvas_workspace.adoption_worker.is_some() { return None; } @@ -1530,7 +1540,13 @@ impl Workspace { .then(|| AdoptionSnapshot { before_doc:std::sync::Arc::new(before.clone()), source_digest }); let mut prepared = photocraft_engine::Session::new(); prepared.add_document(before, None); - photocraft_engine::smart_cmds::replace_instance_bounded_fit(&mut prepared, photocraft_doc::LayerId(layer), original.as_ref(), &candidate_source, worker_meta["fit"] == "contain").map_err(|e| e.to_string())?; + let replace = if batch { + photocraft_engine::smart_cmds::replace_template_instance_bounded_fit + } else { + photocraft_engine::smart_cmds::replace_instance_bounded_fit + }; + replace(&mut prepared, photocraft_doc::LayerId(layer), original.as_ref(), &candidate_source, worker_meta["fit"] == "contain") + .map_err(|error| error.to_string())?; let mut updated = prepared.active().ok_or("候选无法准备")?.doc.as_ref().clone(); let key = format!("jiansun.adopted.{variant}.{slot}"); let first_placement = !updated.metadata.text.iter().any(|(k, _)| *k == key); @@ -1594,8 +1610,10 @@ impl Workspace { #[cfg(not(target_arch = "wasm32"))] if let Some(id) = worker.prewarm_id { crate::canvas::cancel_agent_adoption_prewarm(app, ctx, id); } if self.canvas_workspace.pending_adoption.as_ref() == Some(&worker.pending) { self.canvas_workspace.pending_adoption = None; } - self.error = source_error.unwrap_or_else(|| "当前项目或画布已有变化,候选已保留,未覆盖编辑".into()); - return Some((worker.meta, false)); + let mut meta = worker.meta; + self.error = adoption_block_reason(self, app, &mut meta).or(source_error) + .unwrap_or_else(|| "当前项目或画布已有变化,候选已保留,未覆盖编辑".into()); + return Some((meta, false)); } let prewarm_id = worker.prewarm_id; let prepared = if let Some(id) = prewarm_id { @@ -1710,7 +1728,8 @@ impl Workspace { }; if !valid { if self.canvas_workspace.pending_adoption.as_ref() == Some(&worker.pending) { self.canvas_workspace.pending_adoption = None; } - self.error = "当前项目或画布已有变化,候选已保留,未覆盖编辑".into(); + self.error = adoption_block_reason(self, app, &mut meta) + .unwrap_or_else(|| "当前项目或画布已有变化,候选已保留,未覆盖编辑".into()); return Some((meta, false)); } self.canvas_workspace.pending_adoption = None; @@ -3520,7 +3539,7 @@ pub(crate) fn protects_layer_deletion(app: &PhotocraftApp, command: &str, params } #[cfg(test)] -mod tests { +pub(super) mod tests { use super::*; use super::super::Event; @@ -3952,7 +3971,7 @@ mod tests { assert!(requests.try_iter().all(|request| !matches!(request, Request::Action(method, _) if method == "slot-append")), "presentation must never dispatch an image generation"); } - pub(super) fn native_fixture() -> (Workspace, PhotocraftApp, mpsc::Receiver, u64, Vec) { + pub(in crate::jiansun) fn native_fixture() -> (Workspace, PhotocraftApp, mpsc::Receiver, u64, Vec) { use photocraft_doc::{Affine, Layer, LayerContent, SmartObject, SmartSource}; let png = |w, h, color| { let image = photocraft_codecs::Image::from_u8(w, h, photocraft_codecs::ChannelLayout::Rgba, vec![color; (w * h * 4) as usize]).unwrap(); @@ -4002,7 +4021,7 @@ mod tests { static ADOPTION_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); - fn adopt_and_wait(w: &mut Workspace, app: &mut PhotocraftApp, bytes: Vec, meta: Value) { + pub(in crate::jiansun) fn adopt_and_wait(w: &mut Workspace, app: &mut PhotocraftApp, bytes: Vec, meta: Value) { let _guard = ADOPTION_TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner()); let deadline = std::time::Instant::now() + std::time::Duration::from_secs(15); let pending = w.canvas_workspace.pending_adoption.clone(); @@ -5281,7 +5300,7 @@ mod tests { Err(error) => error, Ok(receipt) => receipt["error"]["message"].as_str().unwrap_or("").to_owned(), }; - assert_eq!(reason, "当前图位已有手动修改,候选已保留"); + assert_eq!(reason, "当前图层已有手动修改,候选已保留"); } #[test] diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/pi_bridge.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/pi_bridge.rs index b9e7e71c..275769dc 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/pi_bridge.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/pi_bridge.rs @@ -195,13 +195,8 @@ fn production_text_frame(field: &Value) -> Option { fn pending_detail_copy(w: &Workspace, doc: &photocraft_doc::Document, field: &Value) -> bool { let Some(id) = field["layer"].as_u64().map(photocraft_doc::LayerId) else { return false }; - if field["templateSample"] == true { - return !w.product_layer_protected(id) && doc.path_of(id).is_some_and(|path| { - let locks = doc.locks_at(&path); - !locks.all && !locks.position && !locks.pixels - }); - } - field["currentText"].as_str().is_none_or(|text| text.trim().is_empty()) && w.detail_layer_unchanged(doc, id) + (field["templateSample"] == true || field["currentText"].as_str().is_none_or(|text| text.trim().is_empty())) + && w.detail_layer_unchanged(doc, id) } fn image_linked_copy(doc: &photocraft_doc::Document, slot_id: &Value) -> Vec { @@ -430,24 +425,16 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co let layer = item["layer"].as_u64().filter(|id| seen.insert(*id)).ok_or("文字格身份重复或无效")?; let id = photocraft_doc::LayerId(layer); let Some(field) = fields.iter().find(|row| row["layer"] == layer) else { - rejected.push(json!({"layer":layer,"reason":"该文字格已填写或不属于模板"})); + rejected.push(json!({"layer":layer,"code":"layer_precondition_failed","reason":"该文字格不属于当前模板映射"})); continue; }; let current = field["currentText"].as_str().unwrap_or_default(); - let writable = || active.doc.path_of(id).is_some_and(|path| { - let locks = active.doc.locks_at(&path); - !(locks.all || locks.position || locks.pixels) - }); - if match_fields { - if w.product_layer_protected(id) || item["expectedText"].as_str() != Some(current) || !writable() { - rejected.push(json!({"layer":layer,"reason":"文字格原文或编辑权限已变化,保留当前内容"})); - continue; - } - } else if w.product_layer_protected(id) { + if let Some(reason) = w.production_layer_rejection(&active.doc, id) { + rejected.push(json!({"layer":layer,"code":reason.code(),"reason":reason.message()})); continue; - } else if current.trim().is_empty() { - if !w.detail_layer_unchanged(&active.doc, id) { continue; } - } else if item["expectedText"].as_str() != Some(current) || !writable() { + } + if (match_fields || !current.trim().is_empty()) && item["expectedText"].as_str() != Some(current) { + rejected.push(json!({"layer":layer,"code":"layer_precondition_failed","reason":"文字格原文与读取值不一致,保留当前内容"})); continue; } let text = item["text"].as_str().ok_or("缺少填写文字")?; @@ -472,9 +459,8 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co let remaining = fields.iter().filter(|field| pending_detail_copy(w, &active.doc, field) && !edits.iter().any(|(layer, _)| field["layer"] == layer.0)).count(); if count == 0 { return Ok(json!({"applied":0,"appliedLayers":[],"pending":remaining,"rejected":rejected,"revision":active.revision})); } - let edited_ids: Vec<_> = edits.iter() - .filter_map(|(id, _)| w.detail_layer_unchanged(&active.doc, *id).then_some(*id)).collect(); - if !edited_ids.is_empty() { w.record_product_view_edits(app); } + let edited_ids: Vec<_> = edits.iter().map(|(id, _)| *id).collect(); + w.record_product_view_edits(app); photocraft_engine::type_cmds::replace_template_layer_texts(&mut app.session, "回填商品文案", &edits) .map_err(|error| error.to_string())?; if !w.product_target_hidden { app.sync_views(); } @@ -651,6 +637,8 @@ fn action_impl(w: &mut Workspace, app: &mut PhotocraftApp, ctx: Option<&egui::Co let production_progress = private && w.pi_request_scope["productProduction"] == true && input["production"].is_object(); if !production_progress && (!text.is_empty() || thinking.is_none()) { w.stream_reply = text.into(); } if production_progress + && input["production"]["outputId"] == w.pi_request_scope["outputId"] + && input["production"]["variantId"] == w.pi_request_scope["variantId"] && let Some(notice) = w.workflow.set_production_progress(&input["production"]) { w.messages.push(json!({"role":"assistant","kind":"activity","text":notice,"run":w.pi_run})); @@ -1494,6 +1482,8 @@ mod tests { assert_eq!(receipt["revision"], revision + 1); assert_eq!(receipt["rejected"].as_array().unwrap().iter().map(|rejection| rejection["layer"].as_u64().unwrap()) .collect::>(), vec![title, locked]); + assert_eq!(receipt["rejected"][0]["code"], "layer_manually_edited"); + assert_eq!(receipt["rejected"][1]["code"], "layer_newly_locked"); let read = action_impl(&mut w, &mut app, None, "pi-detail-copy-fields", &json!({"run":run,"documentId":doc,"includeFilled":true}), true).unwrap(); assert_eq!(read["fields"][0]["currentText"], "用户标题"); @@ -1574,7 +1564,8 @@ mod tests { let receipt = action_impl(&mut w, &mut app, None, "pi-detail-copy-apply", &json!({"run":run,"revision":revision,"items":items}), true).unwrap(); assert_eq!(receipt["appliedLayers"], json!([second, sample, narrow, optional])); - assert!(receipt["rejected"].as_array().unwrap().is_empty()); + assert_eq!(receipt["rejected"][0]["layer"], first); + assert_eq!(receipt["rejected"][0]["code"], "layer_manually_edited"); assert!(receipt["layoutWarnings"].as_array().unwrap().iter().any(|warning| warning["layer"] == narrow)); assert_eq!(receipt["pending"], 0); let doc = &app.session.active().unwrap().doc; diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production.rs index fe490c65..e0215e7b 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production.rs @@ -71,8 +71,8 @@ pub(super) struct Views { saving: Option, failed_revision: Option, can_reuse_saved_view: bool, - editor_basis: Option>, - user_layers: HashMap>, + editor_basis: Option<(Stage, Arc)>, + user_layers: HashMap>, waiting_stage: Option, } @@ -91,6 +91,54 @@ impl Views { } } +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) enum LayerRejection { + UserEdit, + UserLock, + Precondition, +} + +impl LayerRejection { + pub(super) fn code(self) -> &'static str { + match self { + Self::UserEdit => "layer_manually_edited", + Self::UserLock => "layer_newly_locked", + Self::Precondition => "layer_precondition_failed", + } + } + + pub(super) fn message(self) -> &'static str { + match self { + Self::UserEdit => "当前图层已有手动修改", + Self::UserLock => "当前图层或其父组有制作期间新增的锁", + Self::Precondition => "当前图层的写入前置条件已变化", + } + } + + fn check(basis: &Document, doc: &Document, id: LayerId) -> Option { + if basis.id != doc.id { return Some(Self::Precondition); } + let Some(path) = doc.path_of(id) else { return Some(Self::Precondition); }; + let Some(before) = basis.layer(id) else { return Some(Self::Precondition); }; + let now = doc.layer_at(&path).unwrap(); + // Check each ancestor as well as the target, even if a template + // ancestor already contributes the same effective lock. + if (1..=path.len()).filter_map(|n| doc.layer_at(&path[..n])).any(|layer| { + let old = basis.layer(layer.id).map_or_else(Default::default, |layer| layer.locks); + let new = layer.locks; + new.all && !old.all || new.pixels && !old.pixels || new.position && !old.position + || new.transparency && !old.transparency || new.artboard && !old.artboard + }) { + return Some(Self::UserLock); + } + if basis.size != doc.size || before != now { return Some(Self::UserEdit); } + if basis.mode != doc.mode || basis.depth != doc.depth + || basis.icc_profile != doc.icc_profile || basis.global_light != doc.global_light { + return Some(Self::Precondition); + } + None + } +} + impl Workspace { pub(super) fn accepts_production_epoch(&self, epoch: &Value) -> bool { epoch.is_null() || epoch.as_u64() == Some(self.write_epoch) @@ -215,10 +263,18 @@ impl Workspace { self.production_canvas(app).map(|(state, _)| (state.doc.id.0, state.revision)) } - pub(super) fn product_layer_protected(&self, layer: LayerId) -> bool { - self.product_production.as_ref().and_then(|run| run.bound.as_ref()) - .and_then(|stage| self.product_views.user_layers.get(stage)) - .is_some_and(|layers| layers.contains(&layer)) + pub(super) fn production_layer_rejection(&self, doc: &Document, layer: LayerId) -> Option { + let key = &self.pi_request_scope["documentKey"]; + if key.is_object() && *key != super::product_document_key(doc) { + return Some(LayerRejection::Precondition); + } + let live = self.pi_canvas_basis.as_ref().map_or(Some(LayerRejection::Precondition), |basis| { + LayerRejection::check(basis, doc, layer) + }); + if live == Some(LayerRejection::UserLock) { return live; } + let recorded = Stage::read(&self.template_workflow) + .and_then(|stage| self.product_views.user_layers.get(&stage)?.get(&layer).copied()); + recorded.or(live) } pub(super) fn with_product_target(&mut self, app: &mut PhotocraftApp, action: impl FnOnce(&mut Self, &mut PhotocraftApp) -> T) -> T { @@ -376,13 +432,14 @@ impl Workspace { } pub(super) fn sync_product_editor_basis_layers(&mut self, doc: &Document, layers: &[LayerId]) { - let Some(basis) = self.product_views.editor_basis.as_mut() - .filter(|basis| basis.id == doc.id && basis.size == doc.size) else { return; }; - let user_layers = Stage::read(&self.template_workflow) - .and_then(|stage| self.product_views.user_layers.get(&stage)); + if self.product_target_hidden { return; } + let Some(stage) = Stage::read(&self.template_workflow) else { return; }; + let Some((_, basis)) = self.product_views.editor_basis.as_mut() + .filter(|(owner, basis)| *owner == stage && basis.id == doc.id && basis.size == doc.size) else { return; }; + let user_layers = self.product_views.user_layers.get(&stage); let basis = Arc::make_mut(basis); for &id in layers { - if user_layers.is_some_and(|layers| layers.contains(&id)) { continue; } + if user_layers.is_some_and(|layers| layers.contains_key(&id)) { continue; } if let Some((before, after)) = basis.layer_mut(id).zip(doc.layer(id)) { *before = after.clone(); } @@ -390,18 +447,20 @@ impl Workspace { } pub(super) fn record_product_view_edits(&mut self, app: &PhotocraftApp) { - let Some(basis) = self.product_views.editor_basis.as_ref() else { return; }; + if self.product_target_hidden { return; } + let Some((stage, basis)) = self.product_views.editor_basis.as_ref() else { return; }; let Some(state) = app.session.active() else { return; }; - if basis.id != state.doc.id { return; } - let Some(stage) = Stage::read(&self.template_workflow) else { return; }; + if basis.id != state.doc.id || Stage::read(&self.template_workflow).as_ref() != Some(stage) { return; } let Some(mapping) = canvas_workspace::document_mapping(&state.doc) else { return; }; - let changed = self.product_views.user_layers.entry(stage).or_default(); + let changed = self.product_views.user_layers.entry(stage.clone()).or_default(); for id in mapping["outputs"].as_array().into_iter().flatten() .flat_map(|page| page["mapping"]["fields"].as_array().into_iter().flatten()) .filter_map(|field| field["nativeLayerId"].as_u64()).map(LayerId) { - if basis.size != state.doc.size || basis.layer(id) != state.doc.layer(id) { - changed.insert(id); + match LayerRejection::check(basis, &state.doc, id) { + Some(LayerRejection::UserLock) => { changed.insert(id, LayerRejection::UserLock); } + Some(LayerRejection::UserEdit) => { changed.entry(id).or_insert(LayerRejection::UserEdit); } + _ => {} } } } @@ -476,7 +535,7 @@ impl Workspace { self.persisted_revisions.remove(&worker.doc.id.0); active.path = meta["previousViewPath"].as_str().map(str::to_owned); self.canvas_workspace.scope_switch_in_flight = false; - self.product_views.editor_basis = Some(active.doc.clone()); + self.product_views.editor_basis = visible.map(|stage| (stage, active.doc.clone())); self.product_views.worker = Some(Canvas { document: worker, workflow: meta["workflow"].clone(), workspace: canvas_workspace::State::default(), camera: None }); self.with_product_target(app, |w, app| { @@ -588,13 +647,13 @@ impl Workspace { } else { self.product_views.worker = Some(view); } - self.product_views.editor_basis = app.session.active().map(|state| state.doc.clone()); + self.product_views.editor_basis = app.session.active().map(|state| (request.stage, state.doc.clone())); self.product_views.can_reuse_saved_view = true; } ViewTarget::Loaded(doc, value) => { // A result can finish loading as its production stage starts. // In that case the already open worker is the live editor. - if self.product_views.worker.as_ref().and_then(|worker| Stage::read(&worker.workflow)) == Some(request.stage) { + if self.product_views.worker.as_ref().and_then(|worker| Stage::read(&worker.workflow)).as_ref() == Some(&request.stage) { let Some(mut worker) = self.product_views.worker.take() else { return; }; worker.swap_view(self, app); self.product_views.remember(worker, Stage::read(&self.template_workflow)); @@ -608,7 +667,7 @@ impl Workspace { } else { self.product_views.worker = Some(view); } - self.product_views.editor_basis = app.session.active().map(|state| state.doc.clone()); + self.product_views.editor_basis = app.session.active().map(|state| (request.stage, state.doc.clone())); self.product_views.can_reuse_saved_view = value["canReuseSavedView"] == true; self.canvas_opened(&value); } @@ -1306,6 +1365,9 @@ impl Workspace { self.pi_canvas_basis = Some(canvas.doc.clone()); self.pi_manual_edit = false; self.allow_apply = false; + if run.bound.as_ref() != Some(&stage) { + self.workflow.clear_production_progress(); + } run.bound = Some(stage); run.phase = Phase::Agent; self.checkpoint_production(); @@ -2670,6 +2732,144 @@ mod tests { ])); } + #[test] + fn shared_tab_keeps_sku_writes_and_visible_detail_edits_on_their_own_canvases() { + use super::super::{pi_bridge, workflow_bridge}; + use super::canvas_workspace::tests::{adopt_and_wait, native_fixture}; + use photocraft_doc::{Layer, Size}; + + let (mut w, mut app, _requests, first, bytes) = native_fixture(); + let copy = app.session.execute("type.create", json!({"text":"样稿","size":18})).unwrap()["layer"].as_u64().unwrap(); + let mut sku = app.session.active().unwrap().doc.as_ref().clone(); + let doc = sku.id.0; + sku.size = Size::new(720, 720); + let image = sku.layer(LayerId(first)).unwrap().content.clone(); + let mut second = Layer::new("模板锁定图位", image.clone()); + second.locks.all = true; + let second_id = second.id.0; + sku.layers.push(second); + let third = Layer::new("制作中锁定图位", image); + let third_id = third.id.0; + let group = Layer::group("第三个图位的父组", vec![third]); + let group_id = group.id; + sku.layers.push(group); + sku.layer_mut(LayerId(copy)).unwrap().locks.all = true; + let slots = [("K01-I01", first), ("K01-I02", second_id), ("K02-I01", third_id)]; + let mut fields: Vec<_> = slots.iter().map(|(slot, layer)| + json!({"kind":"image","slotId":slot,"nativeLayerId":layer})).collect(); + fields.push(json!({"kind":"text","nativeLayerId":copy,"fieldId":"K01-T01","originalText":"样稿"})); + sku.metadata.text.retain(|(key, _)| key != "jiansun.slot-mapping.v1"); + sku.metadata.text.push(("jiansun.slot-mapping.v1".into(), json!({ + "version":1,"canvasFirst":true,"workspaceId":"workspace","templateId":"template", + "templateVersion":"1","templateHash":"sku","variantId":"wood","component":"sku_images", + "outputs":[{"documentId":"K01","mapping":{"fields":fields}}] + }).to_string())); + let sku_workflow = json!({ + "workspaceId":"workspace","templateId":"template","templateVersion":"1","templateHash":"sku", + "revision":5,"canvasFirst":true,"outputId":"sku_images","variantId":"wood", + "outputs":[{"outputId":"sku_images","documentId":"K01","height":720}], + "slots":slots.map(|(id, layer)| json!({"id":id,"nativeLayerId":layer, + "variantId":"wood","outputId":"sku_images","documentId":"K01","kind":"image", + "candidates":[{"id":"candidate","status":"complete"}]})), + "capabilities":{"imageDispatchAllowed":true,"localApplyAllowed":true} + }); + let project_id = "12345678-1234-4234-8234-123456789012"; + let local = w.local_identity(project_id); + w.open_projects.insert(doc, local.clone()); + w.workflow.bind_identity(&"a".repeat(64), project_id, doc); + w.owner_doc = Some(doc); + w.loaded_draft = Some(doc); + w.creation_doc = Some(doc); + w.pi_run = Some("sku-run".into()); + w.pi_binding = json!({"accountId":"owner","origin":w.origin}); + w.pi_request_scope = json!({"productProduction":true,"outputId":"detail","variantId":"wood", + "account":{"id":"owner","origin":w.origin},"project":{"documentId":doc,"localId":local}}); + let detail = Stage::read(&w.template_workflow).unwrap(); + let sku_stage = Stage::read(&sku_workflow).unwrap(); + let mut run = Run::new(doc, local, json!("workspace"), vec![detail.clone(), sku_stage.clone()], None, Phase::CanvasRequested); + run.bound = Some(detail.clone()); + run.opening = Some(sku_stage.clone()); + w.product_production = Some(run); + w.workflow.set_production_progress(&json!({"outputId":"detail","variantId":"wood", + "rendered":3,"total":21,"pictureCells":[{"slotId":"S01"}]})); + w.continue_product_canvas(&mut app, Box::new(sku), json!({"continueProduct":true,"doc":doc, + "workspaceId":"workspace","accountId":"owner","origin":w.origin,"outputId":"sku_images", + "variantId":"wood","workflow":sku_workflow})); + assert_eq!(app.session.active().unwrap().doc.id.0, doc); + assert_ne!(app.session.active().unwrap().doc.size, Size::new(720, 720)); + assert!(w.product_view_detached()); + + let ctx = egui::Context::default(); + let dispatch = |w: &mut Workspace, app: &mut PhotocraftApp, index, slot: &str| { + w.track_pi_canvas(app); + w.allow_apply = true; + let read = workflow_bridge::action(w, app, "pi-workflow-read", &json!({"run":"sku-run","documentId":doc})).unwrap(); + workflow_bridge::action(w, app, "pi-workflow-execute", &json!({ + "run":"sku-run","documentId":doc,"version":read["version"],"intent":"adopt_candidate", + "operationId":format!("07803e30-ab64-4e90-90c0-ec4a44518cd{index}"), + "slotId":slot,"candidateId":"candidate","outputId":w.template_workflow["outputId"],"productVariantId":"wood" + })).unwrap() + }; + w.with_product_target(&mut app, |w, app| { + w.bind_production_canvas(app); + w.busy = Some("pi-agent".into()); + let active = app.session.active().unwrap(); + assert_eq!(active.doc.id.0, doc); + assert_eq!(active.doc.size, Size::new(720, 720)); + assert!(w.workflow.production_progress().is_null()); + pi_bridge::private_action_in_ui(w, app, &ctx, "pi-delta", &json!({"run":"sku-run","text":"", + "production":{"outputId":"detail","variantId":"wood","pictureCells":[{"slotId":"S01"}]}})).unwrap(); + assert!(w.workflow.production_progress().is_null()); + + for (index, (slot, layer)) in slots[..2].iter().enumerate() { + let result = dispatch(w, app, index, slot); + assert_eq!(result["phase"], "submitted", "{result}"); + let mut meta = result["__workflowDelegation"]["input"].clone(); + meta["accountId"] = json!("owner"); + meta["origin"] = json!(w.origin); + for (key, source) in [("outputId","outputId"), ("workspaceId","id"), ("templateHash","templateHash")] { + meta[key] = meta["detailWorkspace"][source].clone(); + } + adopt_and_wait(w, app, bytes.clone(), meta.clone()); + assert!(w.error.is_empty(), "{}", w.error); + assert!(w.workflow.adoption_receipt(&meta, true, None)); + assert_eq!(canvas_workspace::adopted(&app.session.active().unwrap().doc, slot, "wood"), Some("candidate")); + assert!(w.detail_layer_unchanged(&app.session.active().unwrap().doc, LayerId(*layer))); + } + assert!(app.session.active().unwrap().doc.layer(LayerId(second_id)).unwrap().locks.all); + let pending = pi_bridge::private_action_in_ui(w, app, &ctx, "pi-detail-copy-fields", + &json!({"run":"sku-run","documentId":doc})).unwrap(); + assert_eq!(pending[0]["layer"], copy); + let revision = app.session.active().unwrap().revision; + let receipt = pi_bridge::private_action_in_ui(w, app, &ctx, "pi-detail-copy-apply", &json!({ + "run":"sku-run","documentId":doc,"revision":revision,"matchFields":true, + "items":[{"layer":copy,"expectedText":"样稿","text":"橡木色"}] + })).unwrap(); + assert_eq!(receipt["appliedLayers"], json!([copy]), "{receipt}"); + assert!(app.session.active().unwrap().doc.layer(LayerId(copy)).unwrap().locks.all); + + app.session.edit("用户锁定图组", |doc, _| { + doc.layer_mut(group_id).unwrap().locks.all = true; + Ok(()) + }).unwrap(); + let receipt = dispatch(w, app, 2, slots[2].0); + assert_eq!(receipt["phase"], "not_dispatched", "{receipt}"); + assert_eq!(receipt["error"]["reason"], "layer_newly_locked"); + }); + assert!(w.product_views.user_layers.get(&sku_stage).is_none()); + app.session.execute("layer.setProps", json!({"layer":first,"name":"用户修改详情图位"})).unwrap(); + let detail_workflow = w.template_workflow.clone(); + let run = w.product_production.as_mut().unwrap(); + run.opening = Some(detail); + run.phase = Phase::CanvasRequested; + assert!(w.join_product_view(&mut app, &json!({"continueProduct":true,"doc":doc,"workspaceId":"workspace", + "accountId":"owner","origin":w.origin,"outputId":"detail","variantId":"wood","workflow":detail_workflow}))); + w.bind_production_canvas(&app); + assert_eq!(w.production_layer_rejection(&app.session.active().unwrap().doc, LayerId(first)) + .map(LayerRejection::code), Some("layer_manually_edited")); + assert_eq!(app.session.active().unwrap().doc.layer(LayerId(first)).unwrap().name, "用户修改详情图位"); + } + #[test] fn reading_another_product_output_keeps_the_agent_lease_and_saves_user_edits_to_their_own_output() { let (tx, requests) = mpsc::channel(); diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/workflow_bridge.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/workflow_bridge.rs index c129d844..68ba4cfb 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/workflow_bridge.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/workflow_bridge.rs @@ -50,6 +50,10 @@ impl State { pub(super) fn clear(&mut self) { self.pending = None; + self.clear_production_progress(); + } + + pub(super) fn clear_production_progress(&mut self) { self.production_progress = Value::Null; } @@ -222,7 +226,10 @@ impl State { && meta["slotId"] == op["slotId"] && meta["variantId"] == op["productVariantId"] && meta["candidateId"] == op["candidateId"] { op["phase"] = json!(if adopted { "complete" } else { "failed" }); if adopted { op["persistence"] = json!("session"); } - else { op["message"] = json!(error); } + else { + op["message"] = json!(error); + if let Some(reason) = meta.get("writeBlockReason") { op["writeBlockReason"] = reason.clone(); } + } return true; } false @@ -659,12 +666,14 @@ fn read(w: &Workspace, version: u64, section: &str, output: &str, offset: usize, let candidates=slot["candidates"].as_array().into_iter().flatten().rev().map(|candidate| json!({"id":clip(&candidate["id"],100),"variant":clip(&candidate["variant"],100),"status":clip(&candidate["status"],24),"sourceType":candidate["sourceType"], "materialTaskId":candidate["materialTaskId"],"sourceRequestId":candidate["sourceRequestId"], "reused":candidate["reusedFrom"].is_object()})).collect::>(); - let manually_edited = w.pi_request_scope["productProduction"] == true && w.pi_canvas_basis.is_some() - && slot["nativeLayerId"].as_u64().is_some_and(|id| active_doc - .is_some_and(|doc| !w.detail_layer_unchanged(doc, photocraft_doc::LayerId(id)))); + let rejection = if w.pi_request_scope["productProduction"] == true && w.pi_canvas_basis.is_some() { + slot["nativeLayerId"].as_u64().zip(active_doc) + .and_then(|(id, doc)| w.production_layer_rejection(doc, photocraft_doc::LayerId(id))) + } else { None }; json!({"id":clip(&slot["id"],160),"fieldId":clip(&slot["fieldId"],100),"documentId":clip(&slot["documentId"],100),"outputId":output, "label":clip(&slot["label"],160),"selectedCandidateId":if w.template_workflow["canvasFirst"]==true{adopted(&slot["id"])}else{slot["selectedCandidateId"].clone()}, - "sourcePolicy":slot["sourcePolicy"],"manuallyEdited":manually_edited,"candidates":candidates, + "sourcePolicy":slot["sourcePolicy"],"manuallyEdited":rejection == Some(super::product_production::LayerRejection::UserEdit), + "writeBlockReason":rejection.map(|reason| reason.code()),"candidates":candidates, "role":slot["role"],"requirements":slot["requirements"], "templatePrompt":slot["templatePrompt"],"relatedFields":slot["relatedFields"], "layoutReference":slot["layoutReference"],"textRegions":slot["textRegions"],"productionRule":slot["productionRule"]}) @@ -795,11 +804,12 @@ fn execute(w: &mut Workspace, app: &mut PhotocraftApp, input: &Value, version: u operation_input["detailWorkspace"] = json!({"id":w.template_workflow["workspaceId"], "templateHash":w.template_workflow["templateHash"],"structureHash":w.template_workflow["structureHash"], "outputId":output_id,"variantId":input["productVariantId"]}); - if intent == "adopt_candidate" && w.pi_canvas_basis.is_some() - && operation_input["nativeLayerId"].as_u64().is_some_and(|id| app.session.active() - .is_some_and(|state| !w.detail_layer_unchanged(&state.doc, photocraft_doc::LayerId(id)))) + if intent == "adopt_candidate" + && let Some((layer, state)) = operation_input["nativeLayerId"].as_u64().zip(app.session.active()) + && let Some(reason) = w.production_layer_rejection(&state.doc, photocraft_doc::LayerId(layer)) { - return Err("当前图位已有手动修改,候选已保留".into()); + return Ok(not_dispatched(w, &id, json!(state.revision), + &format!("{},候选已保留", reason.message()), Some(reason.code()))); } } if let Some(fit) = input.get("fit") { @@ -881,6 +891,15 @@ fn execute(w: &mut Workspace, app: &mut PhotocraftApp, input: &Value, version: u "writeEpoch":w.pi_request_scope["writeEpoch"],"projectLocalId":w.pi_request_scope["project"]["localId"]}})) } +fn not_dispatched(w: &Workspace, id: &str, revision: Value, message: &str, reason: Option<&str>) -> Value { + let mut receipt = json!({"operationId":id,"phase":"not_dispatched","accepted":false,"dispatched":false, + "run":w.pi_run,"documentId":w.owner_doc,"baseRevision":revision,"accountId":w.account["id"], + "origin":w.origin,"projectLocalId":w.pi_request_scope["project"]["localId"], + "error":{"code":"local_precondition_failed","message":message}}); + if let Some(reason) = reason { receipt["error"]["reason"] = json!(reason); } + receipt +} + pub(super) fn action(w: &mut Workspace, app: &mut PhotocraftApp, method: &str, input: &Value) -> Result { active_run(w, app, input)?; let current_guard = guard(w, app); @@ -923,16 +942,14 @@ pub(super) fn action(w: &mut Workspace, app: &mut PhotocraftApp, method: &str, i "message":op["message"],"retryableFailure":op["retryableFailure"],"retryAfterSeconds":op["retryAfterSeconds"]}); copy_expiry(op, &mut receipt); if let Some(persistence) = op.get("persistence") { receipt["persistence"] = persistence.clone(); } + if let Some(reason) = op.get("writeBlockReason") { receipt["writeBlockReason"] = reason.clone(); } Ok(receipt) } "pi-workflow-execute" => { let result = execute(w, app, input, version, available); if let (Err(message), Ok(id)) = (&result, operation_id(input)) && available && !w.workflow.operations.iter().any(|op| op["operationId"] == id) { - return Ok(json!({"operationId":id,"phase":"not_dispatched","accepted":false,"dispatched":false, - "run":w.pi_run,"documentId":w.owner_doc,"baseRevision":current_guard["canvas"]["revision"],"accountId":w.account["id"], - "origin":w.origin,"projectLocalId":w.pi_request_scope["project"]["localId"], - "error":{"code":"local_precondition_failed","message":message}})); + return Ok(not_dispatched(w, &id, current_guard["canvas"]["revision"].clone(), message, None)); } result } @@ -1967,6 +1984,7 @@ mod tests { w.pi_request_scope["productProduction"] = json!(true); w.allow_apply = true; w.product_target_hidden = true; + w.pi_canvas_basis = app.session.active().map(|state| state.doc.clone()); if archived { w.template_workflow["slots"][0]["candidates"][0]["sourceType"] = json!("archived-candidate"); w.template_workflow["slots"][0]["candidates"][0]["reusedFrom"] = json!({"candidateId":"closed-source"}); diff --git a/docs/development/xiaoyi/status.md b/docs/development/xiaoyi/status.md index 3f52405a..3784d778 100644 --- a/docs/development/xiaoyi/status.md +++ b/docs/development/xiaoyi/status.md @@ -244,3 +244,6 @@ R12 续跑首条推理准备 7.674 秒,首次采用 15 分 22 秒。117 笔模 | 模板缺少发布许可 | 旧架构 A03 写着无许可即拦。按后来产品要求,未发布许可时原生命令默认允许并记录。发布了具体范围时按模板声明执行 | | 商品标注的 Skill 规则 | 现有家具 Skill 将指示线配套的文字、尺寸和材质列为人工后期。R6 的 Pi 自行隐藏两组旧标注,副本上仍有独立的旧材质与质保说明。可在正式企业资源明确无人值守对旧字样的更新、留空或隐藏规则,现有发布资源继续使用原版本 | | 电脑桌本款尺寸 | R20 按 SZ012616 查正式知识库未找到对应文件。当前字段范围和已发布的退役记录均未覆盖草稿里仍显示的三处固定旧规格。补本款正式规格表,或在模板发布物明确这些旧数字与标线在缺值时允许隐藏,再续做详情并验收三类输出。见 `batch-09/desk-linked-skill-r20/desk-spec-and-fixed-layers.json` | +## R4 · 2026-11-27 + +- 成品按输出和款式跟踪手改,映射回填沿用模板原锁并保护制作期间新增的锁,切换制作成品时重置图位进度。 From 4c8ed7fe7e57167e2f15da6bedbec84fd26805cd Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Fri, 27 Nov 2026 22:42:09 +0800 Subject: [PATCH 2/2] =?UTF-8?q?=E9=9A=94=E7=A6=BB=E5=B0=8F=E5=A3=B9?= =?UTF-8?q?=E7=94=9F=E4=BA=A7=E4=BB=A3=E7=90=86=E7=9A=84=E6=8A=80=E8=83=BD?= =?UTF-8?q?=E6=9D=A5=E6=BA=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/photocraft-extension.mjs | 3 ++- .../detail-agent-pi/test/native-wire.test.mjs | 4 +-- apps/detail-agent-pi/test/pi.test.mjs | 25 +++++++++++++++++++ 3 files changed, 29 insertions(+), 3 deletions(-) diff --git a/apps/detail-agent-pi/src/photocraft-extension.mjs b/apps/detail-agent-pi/src/photocraft-extension.mjs index 8eafaae7..249b3cd6 100644 --- a/apps/detail-agent-pi/src/photocraft-extension.mjs +++ b/apps/detail-agent-pi/src/photocraft-extension.mjs @@ -44,7 +44,8 @@ export async function createPhotoCraftExtensions(host, existing = [], { noExtensions: true, noThemes: true, noContextFiles: true, additionalExtensionPaths: includeGoal ? [path.join(goalPackage, '.pi', 'extensions', 'pi-goal', 'index.ts')] : [], additionalSkillPaths: includeGoal ? [path.join(goalPackage, 'skills'), productionSkills] : [], - noSkills: !includeProjectResources, noPromptTemplates: !includeProjectResources, + noSkills: includeGoal || !includeProjectResources, + noPromptTemplates: !includeProjectResources, systemPromptOverride: () => systemPrompt, appendSystemPrompt: [], extensionsOverride: result => ({...result, extensions:[...existing, ...result.extensions]}), diff --git a/apps/detail-agent-pi/test/native-wire.test.mjs b/apps/detail-agent-pi/test/native-wire.test.mjs index 19441a5f..af367d7a 100644 --- a/apps/detail-agent-pi/test/native-wire.test.mjs +++ b/apps/detail-agent-pi/test/native-wire.test.mjs @@ -1227,7 +1227,7 @@ test('reading a fresh production goal never starts the strategy, image workers, assert.equal((await host.productionOperations).active,0); }); -test('production loads the project’s native skill and prompt template', async t => { +test('production loads project prompt templates without discovering project skills', async t => { const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'pi-recovery-project-resources-')); t.after(() => cleanup(dir)); const cwd = path.join(dir, 'workspace'); @@ -1240,7 +1240,7 @@ test('production loads the project’s native skill and prompt template', async await fs.writeFile(path.join(promptDir, 'fixture-copy.md'), '---\ndescription: Write a fixture headline.\n---\nDescribe the work surface.'); const {resourceLoader} = await createPhotoCraftExtensions({workingDirectory: cwd, store: {dir}}, [], {includeGoal: true}); - assert.ok(resourceLoader.getSkills().skills.some(skill => skill.name === 'desk-copy')); + assert.ok(!resourceLoader.getSkills().skills.some(skill => skill.name === 'desk-copy')); assert.equal(resourceLoader.getPrompts().prompts.find(prompt => prompt.name === 'fixture-copy')?.content, 'Describe the work surface.'); }); diff --git a/apps/detail-agent-pi/test/pi.test.mjs b/apps/detail-agent-pi/test/pi.test.mjs index 27ca5598..2546b5de 100644 --- a/apps/detail-agent-pi/test/pi.test.mjs +++ b/apps/detail-agent-pi/test/pi.test.mjs @@ -96,12 +96,15 @@ test('Pi production and its worker read the same locked Skill and its relative r productEvidence:{accountScope:id.scope,project:id.project,documentId,brief:{brandName:'试验品牌',categoryName:'灯具'}}})}; let main=0,worker=0,serial=0; const reads=new Map(); + const skillLists=new Map(); const transport={info:info(id.scope),stream(_model,context){ const system=getCurrentSystemPrompt(context.messages); assert.match(system,/lighting<\/name>/); assert.doesNotMatch(system,/PINNED_FINISH|Use the \[fixture notes\]/); const location=system.match(/lighting<\/name>[\s\S]*?([^<]*SKILL\.md)<\/location>/u)[1]; const child=system.includes('完成主代理委托的图位'); + const skillList=system.match(/[\s\S]*?<\/available_skills>/u)[0]; + skillLists.set(child?'worker':'main',[...skillList.matchAll(/([^<]+)<\/name>/gu)].map(match=>match[1]).sort()); const steps=child?[ ['read',{path:location}], ['read',{path:path.join(path.dirname(location),'references','finish.md')}], @@ -120,6 +123,24 @@ test('Pi production and its worker read the same locked Skill and its relative r return step?stream([{type:'toolCall',name:step[0],id:'skill-'+(++serial),arguments:step[1]}]): stream([{type:'text',text:'本轮结束。'}]); }}; + const home=path.join(dir,'home'); + for(const [base,name] of [ + [path.join(home,'.agents','skills'),'personal-skill'], + [path.join(store.dir,'skills'),'global-skill'], + [path.join(store.dir,'workspace','.pi','skills'),'workspace-skill'], + ]){ + const skillDir=path.join(base,name); + await fs.mkdir(skillDir,{recursive:true}); + await fs.writeFile(path.join(skillDir,'SKILL.md'),`---\nname: ${name}\ndescription: An unbound test skill.\n---\nFixture only.`); + } + for(const key of ['HOME','USERPROFILE']){ + const previous=process.env[key]; + process.env[key]=home; + t.after(()=>{ + if(previous===undefined) delete process.env[key]; + else process.env[key]=previous; + }); + } const host=await DetailPiAgent.open({store,canvas,transport,documentId,productionGoal:{outputId:'detail',variantId,workspaceId:randomUUID(),requestedOutputs:[{outputId:'detail',variantId}],skillRunDeadline:runDeadline}}); let loads=0; const documents=[]; @@ -133,6 +154,10 @@ test('Pi production and its worker read the same locked Skill and its relative r host.enterpriseContext.load=async()=>{loads++;return knowledge;}; try { assert.equal((await host.prompt('制作详情页')).production.complete,true); + await t.test('production prompts only list bound and bundled skills',()=>{ + const expected=['lighting','pi-goal-writer','product-image-sources']; + assert.deepEqual(Object.fromEntries(skillLists),{main:expected,worker:expected}); + }); const context=await host.modelContext({}, {loadKnowledge:true}); assert.deepEqual(context.enterpriseKnowledge.sources.map(row=>row.revision),['r4','r7']); assert.equal(loads,1,'read-only context uses the original locked selection');