diff --git a/apps/detail-photocraft/apps/photocraft/src/jiansun_knowledge_http.rs b/apps/detail-photocraft/apps/photocraft/src/jiansun_knowledge_http.rs index 3434762b..ebeba77b 100644 --- a/apps/detail-photocraft/apps/photocraft/src/jiansun_knowledge_http.rs +++ b/apps/detail-photocraft/apps/photocraft/src/jiansun_knowledge_http.rs @@ -39,6 +39,15 @@ const SESSION_UNAVAILABLE: &str = "小壹知识库自动授权配置错误,请 const UPSTREAM_MISCONFIGURED: &str = "企业知识库连接地址配置错误,请联系管理员"; const TOKEN_PREFIX: &str = "ekb_xiaoyi_session_"; +const CREDENTIAL_CACHE_TTL: Duration = Duration::from_secs(15); + +#[derive(Clone)] +struct CachedCredential { + token: String, + cached_at: std::time::Instant, + expires_at: Option, +} + #[derive(Clone)] struct Account { origin: String, @@ -47,6 +56,15 @@ struct Account { access: super::AccountAccess, http: super::NetworkClient, channel: Arc, + cached: Arc>>, +} + +impl Account { + fn clear_cached(&self) { + if let Ok(mut guard) = self.cached.lock() { + *guard = None; + } + } } static ACCOUNT: LazyLock>> = LazyLock::new(|| Mutex::new(None)); @@ -75,6 +93,7 @@ pub(super) fn set_account(backend: &super::Backend) { access: backend.access.clone(), http: backend.http.clone(), channel: Arc::new(AtomicU8::new(0)), + cached: Arc::new(Mutex::new(None)), }); } @@ -94,7 +113,14 @@ fn current_account() -> R { fn account_credential(account: &Account) -> R { account.access.check().map_err(|_| PORTAL_LOGIN)?; - // Each direct read uses the current material-library account and role. + if let Ok(guard) = account.cached.lock() + && let Some(entry) = guard.as_ref() + && entry.cached_at.elapsed() < CREDENTIAL_CACHE_TTL + && entry.expires_at.is_none_or(|exp| std::time::Instant::now() + Duration::from_secs(2) < exp) + { + return Ok(entry.token.clone()); + } + // Each uncached exchange uses the current material-library account and role. let request = account.http.get(format!("{}/api/desktop/knowledge/session", account.origin)) .bearer_auth(&account.token).timeout(Duration::from_secs(8)); let deadline = std::time::Instant::now() + Duration::from_secs(8); @@ -117,8 +143,14 @@ fn account_credential(account: &Account) -> R { match status { 404 => return Err(SESSION_MISSING.into()), 503 if misconfigured => return Err(SESSION_UNAVAILABLE.into()), - 401 => return Err(PORTAL_LOGIN.into()), - 403 => return Err(PORTAL_FORBIDDEN.into()), + 401 => { + account.clear_cached(); + return Err(PORTAL_LOGIN.into()); + } + 403 => { + account.clear_cached(); + return Err(PORTAL_FORBIDDEN.into()); + } 200 => {} 500..=599 => return Err(PORTAL_SERVER.into()), _ => return Err(AUTOMATIC_INVALID.into()), @@ -132,10 +164,24 @@ fn account_credential(account: &Account) -> R { let token = value["token"].as_str().filter(|token| token.starts_with(TOKEN_PREFIX)) .ok_or(AUTOMATIC_INVALID)?; // The knowledge server checks expiry with its own clock. - value["expiresAt"].as_str() + let parsed_expiry = value["expiresAt"].as_str() .and_then(|expiry| chrono::DateTime::parse_from_rfc3339(expiry).ok()) .ok_or(AUTOMATIC_INVALID)?; - normalize_key(token).map_err(|_| AUTOMATIC_INVALID.into()) + let normalized = normalize_key(token).map_err(|_| AUTOMATIC_INVALID)?; + let expires_at = (parsed_expiry.with_timezone(&chrono::Utc) - chrono::Utc::now()) + .to_std() + .ok() + .map(|ttl| std::time::Instant::now() + ttl); + if account.access.check().is_ok() + && let Ok(mut guard) = account.cached.lock() + { + *guard = Some(CachedCredential { + token: normalized.clone(), + cached_at: std::time::Instant::now(), + expires_at, + }); + } + Ok(normalized) } fn verify_automatic_key() -> Value { @@ -414,7 +460,7 @@ impl KnowledgeClients { && !matches!(url.host(), Some(url::Host::Ipv4(ip)) if ip.is_private())); let cache = if public_https { &self.https } else { &self.direct }; cache.get_or_init(|| { - let builder = super::network_builder(Duration::from_secs(self.timeout_seconds)).pool_max_idle_per_host(0); + let builder = super::network_builder(Duration::from_secs(self.timeout_seconds)); if public_https { builder.build() } else { builder.no_proxy().connect_timeout(Duration::from_secs(2)).build() } }).as_ref().map_err(|_| NETWORK.into()) } @@ -485,6 +531,9 @@ fn automatic_response( }; account.access.check().map_err(|_| PORTAL_LOGIN)?; let status = response.status().as_u16(); + if matches!(status, 401 | 403) { + account.clear_cached(); + } if channel == Direct && status == 401 { return Err(AUTOMATIC_INVALID.into()); } if knowledge_transient_status(status) { if status == 503 && let Ok(value) = super::response_json(&mut response, 16 * 1024) { @@ -730,8 +779,13 @@ mod tests { origin, token: "synthetic-desktop-session".into(), account_id: "test-user".into(), access: access.clone(), http: client.into(), channel: Arc::new(AtomicU8::new(0)), + cached: Arc::new(Mutex::new(None)), }; assert!(matches!(account_credential(&account), Ok(token) if token == TOKEN)); + // Within 15s TTL, repeated calls reuse the cached credential without hitting the server. + assert!(matches!(account_credential(&account), Ok(token) if token == TOKEN)); + // Clearing cache (e.g. after upstream 401/403) forces re-exchange on next call. + account.clear_cached(); assert!(matches!(account_credential(&account), Err(error) if error == PORTAL_FORBIDDEN)); server.join().unwrap(); access.invalidate(); @@ -761,6 +815,7 @@ mod tests { origin, token: "synthetic-desktop-session".into(), account_id: "test-user".into(), access: super::super::AccountAccess::default(), http: client(5).unwrap().into(), channel: Arc::new(AtomicU8::new(0)), + cached: Arc::new(Mutex::new(None)), }; let error = account_credential(&account).unwrap_err(); assert_eq!(error, message); @@ -809,6 +864,7 @@ mod tests { origin, token: "synthetic-desktop-session".into(), account_id: "test-user".into(), access: super::super::AccountAccess::default(), http: super::super::NetworkClient::new(false).unwrap(), channel: Arc::new(AtomicU8::new(0)), + cached: Arc::new(Mutex::new(None)), }; assert_eq!(account_credential(&account).unwrap(), "ekb_xiaoyi_session_retry-fixture"); server.join().unwrap(); @@ -827,6 +883,7 @@ mod tests { token: "synthetic-desktop-portal-session".into(), account_id: "test-user".into(), access: super::super::AccountAccess::default(), http: super::super::NetworkClient::new(false).unwrap(), channel: Arc::new(AtomicU8::new(0)), + cached: Arc::new(Mutex::new(None)), }; const MANIFEST: &str = "/api/xiaoyi/v1/templates/chair/releases/v1/manifest"; const BUNDLE: &str = "/api/xiaoyi/v1/templates/chair/releases/v1/bundle"; diff --git a/apps/detail-photocraft/crates/engine/src/cmd.rs b/apps/detail-photocraft/crates/engine/src/cmd.rs index 8d3828af..5adfc37c 100644 --- a/apps/detail-photocraft/crates/engine/src/cmd.rs +++ b/apps/detail-photocraft/crates/engine/src/cmd.rs @@ -165,7 +165,7 @@ pub use adjust_params::{adjustment_from_params, adjustment_kind}; pub(crate) use enabled::{always, check_all_unlocked, check_pixels_unlocked, has_paintable, is_mask_target, paint_surface}; use enabled::{can_redo, can_undo, has_doc, has_layer, has_pixel_layer, has_pixel_or_channel, has_selection}; pub use layer_params::blend_from_str; -pub(crate) use layer_params::{NEW_LAYER_PATH, explicit_layer, layer_listing, layer_panel_option, layer_param, mask_at_depth, mask_new_layer, selection_mask}; +pub(crate) use layer_params::{NEW_LAYER_PATH, explicit_layer, layer_listing, layer_panel_option, layer_param, mask_at_depth, mask_new_layer, parse_layer_id, selection_mask}; use ops::{arrange, merge_group, set_mask, set_mask_and_deselect}; pub(crate) use ops::{layer_copy, translate_layer}; use params::{bad, set_clipped}; @@ -606,7 +606,7 @@ fn build() -> Vec { let doc = &s.active().ok_or(EngineError::NoDocument)?.doc; let mut ids = Vec::with_capacity(a.len()); for v in a { - let id = v.as_u64().map(LayerId).ok_or_else(|| bad("layer.setProps", format!("`layers` holds layer ids, got {v}")))?; + let id = parse_layer_id(v).ok_or_else(|| bad("layer.setProps", format!("`layers` holds layer ids, got {v}")))?; if doc.layer(id).is_none() { return Err(EngineError::NoLayer(id)); } @@ -622,12 +622,13 @@ fn build() -> Vec { return Err(bad("layer.setProps", "`name` renames one layer, not several")); } // Opacity and Fill are fractions here, while the Layer Style commands take - // percentages: a value outside 0..1 is refused, never clamped to 100 % (#5242). + // percentages: accept 0..1 as well as (1..=100] percentages normalized to 0..1. let unit = |key: &str| -> Result> { let Some(v) = p.get(key) else { return Ok(None) }; match v.as_f64() { Some(x) if (0.0..=1.0).contains(&x) => Ok(Some(x as f32)), - _ => Err(bad("layer.setProps", format!("{key} must be a number in 0..1 (1 = 100 %), got {v}"))), + Some(x) if x > 1.0 && x <= 100.0 => Ok(Some((x / 100.0) as f32)), + _ => Err(bad("layer.setProps", format!("{key} must be a number in 0..1 (or 0..100 %), got {v}"))), } }; let (opacity, fill) = (unit("opacity")?, unit("fill")?); @@ -651,10 +652,9 @@ fn build() -> Vec { s.edit_with(label, record, |doc, _| { // The Background has no opacity, fill or blend mode: like Photoshop, setting // one that changes its look turns it into a normal layer ("Layer 0") first. - let num = |k: &str| p.get(k).and_then(Value::as_f64).is_some_and(|v| v < 1.0); let blends = p.get("blend").and_then(Value::as_str).and_then(blend_from_str).is_some_and(|b| b != photocraft_color::BlendMode::Normal); for &id in &ids { - if num("opacity") || num("fill") || blends { + if opacity.is_some_and(|v| v < 1.0) || fill.is_some_and(|v| v < 1.0) || blends { crate::extra_cmds::background_to_layer(doc, id); } let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; diff --git a/apps/detail-photocraft/crates/engine/src/cmd/layer_params.rs b/apps/detail-photocraft/crates/engine/src/cmd/layer_params.rs index f298893b..019fce05 100644 --- a/apps/detail-photocraft/crates/engine/src/cmd/layer_params.rs +++ b/apps/detail-photocraft/crates/engine/src/cmd/layer_params.rs @@ -1,18 +1,45 @@ use super::params::bad; use super::{BlendMode, Document, EngineError, Layer, LayerId, LayerMask, Result, SampleType, Session, Value}; +/// Parses a JSON layer ID from an unsigned integer, non-negative integer float (`12.0`), +/// or pure ASCII-digit string (`"123"`). +pub(crate) fn parse_layer_id(v: &Value) -> Option { + match v { + Value::Number(n) => n + .as_u64() + .or_else(|| { + let f = n.as_f64()?; + (f.is_finite() && f >= 0.0 && f.fract() == 0.0 && (f as u64) as f64 == f).then_some(f as u64) + }) + .map(LayerId), + Value::String(s) => { + let trimmed = s.trim(); + (!trimmed.is_empty() && trimmed.bytes().all(|b| b.is_ascii_digit())) + .then(|| trimmed.parse::().ok()) + .flatten() + .map(LayerId) + } + _ => None, + } +} + /// The layer a command's `"layer"` param names: an id, or a name (the topmost layer of that /// name, as Photoshop's "select layer by name" action step finds it, so a loaded action replays /// in another document; a name that matches no layer exactly matches regardless of case, so /// `"background"` finds the Background). `None` when the param is absent. pub(crate) fn explicit_layer(s: &Session, p: &Value) -> Result> { match p.get("layer") { - Some(Value::Number(n)) => { - n.as_u64().map(|id| Some(LayerId(id))).ok_or_else(|| EngineError::Other(format!("layer id {n} is not a non-negative integer"))) + Some(v @ Value::Number(_)) => { + parse_layer_id(v).map(Some).ok_or_else(|| EngineError::Other(format!("layer id {v} is not a non-negative integer"))) } - Some(Value::String(name)) => { + Some(v @ Value::String(name)) => { let d = s.active().ok_or(EngineError::NoDocument)?; let layers = d.doc.walk(); + if let Some(id) = parse_layer_id(v) + && (d.doc.layer(id).is_some() || !layers.iter().any(|(_, _, l)| l.name.eq_ignore_ascii_case(name))) + { + return Ok(Some(id)); + } let mut top_down = layers.iter().rev(); top_down .clone() 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 8969a28e..500b93a7 100644 --- a/apps/detail-photocraft/crates/engine/src/cmd/type_cmds.rs +++ b/apps/detail-photocraft/crates/engine/src/cmd/type_cmds.rs @@ -24,8 +24,9 @@ fn has_doc(s: &Session) -> std::result::Result<(), String> { } fn layer_id(s: &Session, p: &Value) -> Result { - match p.get("layer").and_then(Value::as_u64) { - Some(id) => Ok(LayerId(id)), + match p.get("layer").filter(|v| !v.is_null()) { + Some(v) => crate::commands::parse_layer_id(v) + .ok_or_else(|| EngineError::Other(format!("layer id {v} is not a non-negative integer"))), None => s.active().and_then(|d| d.active_layer).ok_or(EngineError::Other("no active layer".into())), } } @@ -41,13 +42,29 @@ fn f32p(p: &Value, k: &str) -> Option { fn color(v: &Value) -> Option { match v { Value::Array(a) if a.len() >= 3 => { - let c: Vec = a.iter().map(|x| x.as_f64().unwrap_or(0.0) as f32).collect(); - c.iter().take(4).all(|v| v.is_finite()).then(|| Color::rgba(c[0], c[1], c[2], c.get(3).copied().unwrap_or(1.0))) + let mut c: Vec = a.iter().map(|x| x.as_f64().unwrap_or(0.0) as f32).collect(); + if !c.iter().take(4).all(|v| v.is_finite()) { + return None; + } + if c.iter().take(3).any(|&x| x > 1.0 && x <= 255.0) { + for x in c.iter_mut().take(3) { + *x /= 255.0; + } + } + if let Some(alpha) = c.get_mut(3) + && *alpha > 1.0 + && *alpha <= 255.0 + { + *alpha /= 255.0; + } + Some(Color::rgba(c[0], c[1], c[2], c.get(3).copied().unwrap_or(1.0))) } Value::String(s) => { - let s = s.trim_start_matches('#'); + let s = s.trim().trim_start_matches('#'); let h = |i: usize| s.get(i..i + 2).and_then(|x| u8::from_str_radix(x, 16).ok()).map(|v| f32::from(v) / 255.0); + let h1 = |i: usize| s.get(i..i + 1).and_then(|x| u8::from_str_radix(x, 16).ok()).map(|v| f32::from(v * 17) / 255.0); match s.len() { + 3 => Some(Color::rgb(h1(0)?, h1(1)?, h1(2)?)), 6 => Some(Color::rgb(h(0)?, h(2)?, h(4)?)), 8 => Some(Color::rgba(h(0)?, h(2)?, h(4)?, h(6)?)), _ => None, @@ -1372,6 +1389,23 @@ fn step_size(s: &mut Session, p: &Value, up: bool, default_by: f32) -> Result isolated.native_disabled_reason_with(id, ¶ms), + Ok(params) => match isolated.native_disabled_reason_with(id, ¶ms) { + Some(reason) + if reason.starts_with("no active layer") + && isolated.active().is_some_and(|st| !st.doc.layers.is_empty()) + && crate::commands::find(id).is_some_and(|spec| { + spec.params.contains("\"layer\":") + || spec.params.contains("\"layers\":") + || spec.params.contains("via layer") + }) => + { + None + } + other => other, + }, Err(error) => Some(error.to_string()), } }).collect()) diff --git a/apps/detail-photocraft/crates/engine/src/layer_style.rs b/apps/detail-photocraft/crates/engine/src/layer_style.rs index 904a078c..d662b01a 100644 --- a/apps/detail-photocraft/crates/engine/src/layer_style.rs +++ b/apps/detail-photocraft/crates/engine/src/layer_style.rs @@ -1238,7 +1238,7 @@ fn delete_effect(s: &mut Session, p: &Value, effect: &Value) -> Result { let index = effect.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad(CMD, "`effect` must be an effect index"))?; let d = s.active().ok_or(EngineError::NoDocument)?; let id = match p.get("layer").filter(|v| !v.is_null()) { - Some(v) => photocraft_doc::LayerId(v.as_u64().ok_or_else(|| bad(CMD, "`layer` must be a layer id"))?), + Some(v) => crate::commands::parse_layer_id(v).ok_or_else(|| bad(CMD, "`layer` must be a layer id"))?, None => d.active_layer.ok_or_else(|| bad(CMD, "no active layer. Select the target with layer.select or pass its numeric layer ID"))?, }; let count = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?.effects.items.len(); diff --git a/apps/detail-photocraft/crates/engine/src/session/execute.rs b/apps/detail-photocraft/crates/engine/src/session/execute.rs index 99d01116..35649065 100644 --- a/apps/detail-photocraft/crates/engine/src/session/execute.rs +++ b/apps/detail-photocraft/crates/engine/src/session/execute.rs @@ -164,26 +164,39 @@ impl Session { fn names_existing_layer(&self, id: &str, params: &Value) -> bool { if id == "layer.setProps" && let Some(layers) = params["layers"].as_array() { return !layers.is_empty() && self.active().is_some_and(|state| layers.iter().all(|layer| - layer.as_u64().is_some_and(|id| state.doc.layer(LayerId(id)).is_some()))); + commands::parse_layer_id(layer).is_some_and(|id| state.doc.layer(id).is_some()))); } (matches!(id, "layer.hideLayers" | "layer.showLayers" | "layer.renameLayer") || (id == "layer.setProps" && params.as_object().is_some_and(|o| o.contains_key("visible") && o.keys().all(|k| matches!(k.as_str(), "layer" | "visible" | "coalesce"))))) - && params.get("layer").and_then(Value::as_u64).is_some_and(|l| self.active().is_some_and(|st| st.doc.layer(LayerId(l)).is_some())) + && params.get("layer").and_then(commands::parse_layer_id).is_some_and(|l| self.active().is_some_and(|st| st.doc.layer(l).is_some())) } - /// The precondition of a command whose params document `"layer":id` (it acts on that layer), - /// when `params` name an existing layer of the active document: checked on that layer rather - /// than on the active one, which stays active (#466). A script, action or agent can then - /// Replace Contents, Rasterize or Merge Down a layer without selecting it first. `None` for - /// other commands, or without such a layer. + /// The precondition of a command when `params` name an existing `"layer"` or `"layers"` + /// target of the active document: checked on that layer rather than on the active one, which + /// stays active (#466). A script, action or agent can then run layer commands (including + /// `layer.layerStyle.*`, `edit.transform`, `shape.info`, `layer.delete`, `layer.setProps`) + /// without selecting the layer first. `None` when no valid explicit target is provided. pub(crate) fn explicit_layer_enabled(&mut self, spec: &commands::CommandSpec, params: &Value) -> Option> { - if !spec.params.contains("\"layer\":id") { + let target = if params.get("layer").is_some_and(|v| !v.is_null()) { + let id = commands::explicit_layer(self, params).ok().flatten()?; + self.active()?.doc.layer(id)?; + id + } else if let Some(layers) = params.get("layers").and_then(Value::as_array).filter(|a| !a.is_empty()) { + let d = self.active()?; + let mut first = None; + for v in layers { + let id = commands::parse_layer_id(v)?; + d.doc.layer(id)?; + if first.is_none() { + first = Some(id); + } + } + first? + } else { return None; - } - let target = LayerId(params.get("layer")?.as_u64()?); + }; let d = self.active_mut()?; - d.doc.layer(target)?; let active = d.active_layer.replace(target); let r = self.precondition(spec, params); if let Some(d) = self.active_mut() { @@ -329,3 +342,34 @@ impl Session { st.last_damage = Some(st.last_damage.map_or(rect, |d| d.intersect(&rect))); } } + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn explicit_layer_bypasses_no_active_layer_and_normalizes_props() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 32, "height": 32})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Target"})).unwrap(); + let id = s.active().unwrap().active_layer.unwrap().0; + s.active_mut().unwrap().active_layer = None; + + // layer.layerStyle.stroke without active_layer (explicit numeric, float, string ID) + assert!(s.execute("layer.layerStyle.stroke", json!({"layer": id, "size": 2})).is_ok()); + assert!(s.execute("layer.layerStyle.stroke", json!({"layer": id as f64, "size": 3})).is_ok()); + assert!(s.execute("layer.layerStyle.stroke", json!({"layer": id.to_string(), "size": 4})).is_ok()); + assert!(s.active().unwrap().active_layer.is_none()); + + // layer.setProps with percentage opacity/fill and no active_layer + assert!(s.execute("layer.setProps", json!({"layer": id, "opacity": 50, "fill": 25})).is_ok()); + let layer = s.active().unwrap().doc.layer(LayerId(id)).unwrap(); + assert!((layer.opacity - 0.5).abs() < 1e-4); + assert!((layer.fill_opacity - 0.25).abs() < 1e-4); + + // layer.setProps with layers array and no active_layer + assert!(s.execute("layer.setProps", json!({"layers": [id as f64], "visible": false})).is_ok()); + assert!(!s.active().unwrap().doc.layer(LayerId(id)).unwrap().visible); + } +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_canvas_read.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_canvas_read.rs index 2e94f100..d529a204 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_canvas_read.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/agent_canvas_read.rs @@ -32,8 +32,78 @@ fn filter_matches(layer: &Layer, needle: &str) -> bool { fn summary_layer(doc: &Document, path: &[usize], layer: &Layer) -> Value { let parent = path.split_last().and_then(|(_, parent)| doc.layer_at(parent)).map(|layer| layer.id.0); let children = match &layer.content { LayerContent::Group(group) => group.children.len(), _ => 0 }; - json!({"id":layer.id.0,"name":clipped(&layer.name,160),"kind":layer.content.kind_name(), - "depth":path.len().saturating_sub(1),"parentLayerId":parent,"childCount":children}) + let field = template_field(doc, layer); + let mut row = json!({"id":layer.id.0,"name":clipped(&layer.name,160),"kind":layer.content.kind_name(), + "depth":path.len().saturating_sub(1),"parentLayerId":parent,"childCount":children}); + if is_user_edited(doc, layer, &field) { + row["userEdited"] = json!(true); + } + if let Some(allowed) = layer_allowed_changes(doc, layer) { + row["allowedChanges"] = json!(allowed); + } + row +} + +fn is_user_edited(doc: &Document, layer: &Layer, field: &Value) -> bool { + let has_manual_layer = doc.metadata.text.iter().any(|(name, value)| { + name == "jiansun.manual-layers" + && serde_json::from_str::>(value).is_ok_and(|ids| ids.contains(&layer.id.0)) + }); + if has_manual_layer { + return true; + } + let text_key = format!("jiansun.manual-text.{}", layer.id.0); + let marked_text_or_smart = match &layer.content { + LayerContent::Text(text) => { + use sha2::{Digest, Sha256}; + let digest = format!("{:x}", Sha256::digest(text.text.as_bytes())); + doc.metadata.text.iter().any(|(name, value)| { + *name == text_key && serde_json::from_str::(value).is_ok_and(|v| v["sha256"] == digest) + }) + } + LayerContent::Smart(_) => doc.metadata.text.iter().any(|(name, value)| { + *name == text_key + && serde_json::from_str::(value).is_ok_and(|v| v["embedded"] == true && v["source"] == "human") + }), + _ => false, + }; + if marked_text_or_smart { + return true; + } + if let Some(slot) = field["slotId"].as_str() { + let variant = field["variantId"].as_str().unwrap_or_default(); + if !variant.is_empty() + && (super::canvas_workspace::manual_image(doc, slot, variant).is_some() + || super::canvas_workspace::user_adopted(doc, slot, variant)) + { + return true; + } + let suffix = format!(".{slot}"); + if doc.metadata.text.iter().any(|(name, value)| { + (name.starts_with("jiansun.user-adopted.") || name.starts_with("jiansun.manual-image.")) + && name.ends_with(&suffix) + && !value.is_empty() + && value != "false" + }) { + return true; + } + } + false +} + +fn layer_allowed_changes(doc: &Document, layer: &Layer) -> Option> { + let (_, raw) = doc.metadata.text.iter().find(|(key, _)| key == "jiansun.allowed-changes.v1")?; + let rules = serde_json::from_str::(raw).ok()?.as_array()?.clone(); + let psd_id = layer.psd_id.map(u64::from); + Some( + rules + .into_iter() + .filter(|rule| match rule.get("psdLayerId") { + Some(id) => id.as_u64().is_some() && psd_id == id.as_u64(), + None => true, + }) + .collect(), + ) } pub(super) fn template_field(doc: &Document, layer: &Layer) -> Value { @@ -74,13 +144,23 @@ pub(super) fn project_layer(doc: &Document, path: &[usize], layer: &Layer, detai _ => Value::Null, } } else { Value::Null }; - json!({"id":layer.id.0,"name":clipped(&layer.name,160),"kind":layer.content.kind_name(), + let field = template_field(doc, layer); + let user_edited = is_user_edited(doc, layer, &field); + let allowed = layer_allowed_changes(doc, layer); + let mut projected = json!({"id":layer.id.0,"name":clipped(&layer.name,160),"kind":layer.content.kind_name(), "text":text.map(|text|clipped(text,text_limit)),"textLength":text.map(|text|text.chars().count()), "textTruncated":text.is_some_and(|text|text.chars().nth(text_limit).is_some()), - "appearance":appearance,"templateField":template_field(doc,layer),"bounds":if bounds.is_empty(){Value::Null}else{json!(bounds)}, + "appearance":appearance,"templateField":field,"bounds":if bounds.is_empty(){Value::Null}else{json!(bounds)}, "geometry":{"bounds":if bounds.is_empty(){Value::Null}else{json!(bounds)},"depth":path.len().saturating_sub(1),"parentLayerId":parent}, "visible":layer.visible,"effectiveVisible":effective_visible,"opacity":layer.opacity, - "locked":doc.locks_at(path),"hasMask":layer.mask.is_some(),"hasVectorMask":layer.vector_mask.is_some()}) + "locked":doc.locks_at(path),"hasMask":layer.mask.is_some(),"hasVectorMask":layer.vector_mask.is_some()}); + if user_edited { + projected["userEdited"] = json!(true); + } + if let Some(allowed) = allowed { + projected["allowedChanges"] = json!(allowed); + } + projected } pub(super) fn read_page(w: &Workspace, app: &PhotocraftApp, input: &Value) -> Result { @@ -450,4 +530,36 @@ mod tests { app.session.execute("file.new",json!({"width":10,"height":10})).unwrap(); assert!(read_page(&w,&app,&json!({})).is_err()); } + + #[test] + fn user_edited_and_allowed_changes_are_projected_without_noise() { + let (w, mut app, ids) = fixture(3); + let group = Layer::new("手改分组", LayerContent::Group(Group { children: vec![], expanded: true, artboard: None, frame_stroke: None })); + let group_id = group.id; + { + let doc = Arc::make_mut(&mut app.session.active_mut().unwrap().doc); + doc.layers.push(group); + doc.layer_mut(ids[0]).unwrap().psd_id = Some(101); + doc.layer_mut(ids[1]).unwrap().psd_id = Some(102); + doc.metadata.text.push(("jiansun.manual-layers".into(), json!([ids[0].0, group_id.0]).to_string())); + doc.metadata.text.push(( + "jiansun.allowed-changes.v1".into(), + json!([{"command":"type.edit","psdLayerId":102,"params":{"text":"x"}}]).to_string(), + )); + } + let page = read_page(&w, &app, &json!({})).unwrap(); + let layers = page["context"]["layers"].as_array().unwrap(); + assert_eq!(layers[0]["userEdited"], true); + assert!(layers[1].get("userEdited").is_none()); + assert_eq!(layers[1]["allowedChanges"].as_array().unwrap().len(), 1); + assert_eq!(layers[1]["allowedChanges"][0]["command"], "type.edit"); + assert!(layers[0]["allowedChanges"].as_array().unwrap().is_empty()); + + let detail = read_page(&w, &app, &json!({"layer": ids[0].0})).unwrap(); + assert_eq!(detail["context"]["layers"][0]["userEdited"], true); + + let summary = read_page(&w, &app, &json!({"mode":"summary"})).unwrap(); + let sum_layers = summary["context"]["layers"].as_array().unwrap(); + assert_eq!(sum_layers[0]["userEdited"], true); + } } diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production/lifecycle.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production/lifecycle.rs index 44758553..bf3270fb 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production/lifecycle.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/product_production/lifecycle.rs @@ -315,10 +315,18 @@ impl Workspace { run.goal_user_entry = Some(text.clone()); if self.production_stop["state"] == "interrupted" { self.error.clear(); } self.production_stop = json!({"mode":null,"state":"idle","reason":null,"error":null}); - run.phase = match &run.phase { + let next_phase = match &run.phase { Phase::Paused(pause) => Self::production_resume_phase(&pause["waitingOriginals"]), _ => Phase::AwaitingSave, }; + if matches!(next_phase, Phase::AwaitingSave) { + run.await_canvas_save(); + } else { + run.phase = next_phase; + } + if self.saving.is_some_and(|(doc, _)| doc != run.doc) { + self.saving = None; + } self.pi_write_blocked = false; self.agent_effects_paused = false; self.messages.push(json!({"role":"user","text":text})); @@ -816,11 +824,21 @@ impl Workspace { self.production_canvas_open_failed(app, "save", "当前画布与所选输出或花色不一致,请重新打开"); } else if saved { self.bind_production_canvas(app); - } else if !self.enqueue_project_draft(canvas, !self.draft_changed) { + } else if self.saving.is_none() && !self.product_view_save_pending() + && !self.enqueue_project_draft(canvas, !self.draft_changed) + { self.production_canvas_open_failed(app, "save", "本机保存服务已断开,未绑定所选工作画布"); } } else if saved && self.saving.is_none() && self.busy.is_none() && self.pending_slot_apply.is_none() { - self.production_start_session(app); + if self.can_start_production_turn() { + self.production_start_session(app); + } else if let Some(run) = self.product_production.as_mut() { + run.phase = Phase::AgentRetryAt(Instant::now() + Duration::from_secs(1)); + } + } else if !saved && self.saving.is_none() && !self.product_view_save_pending() + && !self.enqueue_project_draft(canvas, !self.draft_changed) + { + self.slot_apply_save_failed(app, "本机保存服务已断开,请重试"); } return; } @@ -838,3 +856,64 @@ impl Workspace { } } } + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::mpsc; + + fn test_workspace() -> (Workspace, PhotocraftApp, mpsc::Receiver, u64, u64) { + let (tx, rx) = mpsc::channel(); + let (_, event_rx) = mpsc::channel(); + let mut w = Workspace::new(tx, event_rx); + let _ = rx.try_recv(); + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width":40,"height":50})).unwrap(); + let app = PhotocraftApp::new(session, crate::Services::default()); + let state = app.session.active().unwrap(); + let doc = state.doc.id.0; + let rev = state.revision; + let project = w.local_identity("project"); + w.open_projects.insert(doc, project.clone()); + w.template_workflow = json!({"workspaceId":"workspace"}); + w.busy = None; + w.loaded_draft = Some(doc); + w.model_ready = true; + w.image_ready = true; + (w, app, rx, doc, rev) + } + + #[test] + fn awaiting_save_with_no_opening_exits_when_turn_cannot_start_and_triggers_save_when_unsaved() { + let (mut w, app, rx, doc, rev) = test_workspace(); + let project = w.open_projects[&doc].clone(); + w.persisted_revisions.insert(doc, rev); + w.pi_run = Some("prev-turn".into()); + w.product_production = Some(Run::new(doc, project.clone(), json!("workspace"), vec![], None, Phase::AwaitingSave)); + w.production_tick(&app); + assert!(matches!( + w.product_production.as_ref().unwrap().phase, + Phase::AgentRetryAt(_) + ), "saved canvas must leave Phase::AwaitingSave instead of timing out"); + + // When not saved and no save is in flight, production_tick actively enqueues Save. + w.persisted_revisions.remove(&doc); + w.pi_run = None; + w.product_production = Some(Run::new(doc, project, json!("workspace"), vec![], None, Phase::AwaitingSave)); + w.production_tick(&app); + assert!(matches!(rx.try_recv(), Ok(Request::Save(_, _, _)))); + } + + #[test] + fn resume_paused_production_refreshes_expired_canvas_save_deadline() { + let (mut w, app, _rx, doc, rev) = test_workspace(); + let project = w.open_projects[&doc].clone(); + w.persisted_revisions.insert(doc, rev); + let mut run = Run::new(doc, project, json!("workspace"), vec![], None, Phase::Paused(json!({}))); + run.canvas_save_deadline = Instant::now() - Duration::from_secs(120); + w.product_production = Some(run); + w.resume_paused_production(&app, "继续整套制作".into()); + assert!(w.error.is_empty(), "resuming must not immediately time out on stale deadline: {}", w.error); + assert!(w.product_production.as_ref().is_some_and(|r| r.canvas_save_deadline > Instant::now())); + } +} diff --git a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_state.rs b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_state.rs index da724279..dc87499d 100644 --- a/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_state.rs +++ b/apps/detail-photocraft/crates/ui-egui/src/jiansun/stitch_state.rs @@ -273,7 +273,10 @@ impl ErrorCategory { if raw.starts_with("本地SDK操作失败") { return Self::CanvasOperationFailed; } - if raw.is_ascii() { Self::Unknown } else { Self::Business } + if is_validation_error(raw) { + return Self::ToolRejected; + } + if is_technical_error(raw) { Self::Unknown } else { Self::Business } } pub(super) fn title(self, raw: &str) -> &str { @@ -332,6 +335,30 @@ impl ErrorCategory { } } +fn is_validation_error(raw: &str) -> bool { + let lower = raw.to_ascii_lowercase(); + lower.contains("validation failed") + || lower.contains("unknown field") + || lower.contains("additionalproperties") + || lower.contains("must have required property") +} + +fn is_technical_error(raw: &str) -> bool { + if raw.is_ascii() { + return true; + } + let lower = raw.to_ascii_lowercase(); + lower.contains("\n at ") + || lower.contains("\nat ") + || lower.contains("stack backtrace:") + || lower.contains("panicked at ") + || lower.contains("typeerror:") + || lower.contains("referenceerror:") + || lower.contains("syntaxerror:") + || lower.contains("rangeerror:") + || lower.contains("error: ") +} + /// 画布上一个字段(图位)的处理状态。文案只用于显示,判定一律读枚举。 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub(super) enum FieldState { Original, Processed, Changed } @@ -628,6 +655,19 @@ mod tests { assert_eq!(ErrorCategory::classify("the linked file cannot be read"), ErrorCategory::ImageLinkedMissing); assert_eq!(ErrorCategory::classify("本地SDK操作失败:x"), ErrorCategory::CanvasOperationFailed); assert_eq!(ErrorCategory::classify("engine operation failed"), ErrorCategory::Unknown); + // 混排中英技术报错不得按 Business 原文放行进 UI。 + assert_eq!( + ErrorCategory::classify("工具参数错误:Validation failed for tool \"canvas_edit\""), + ErrorCategory::ToolRejected + ); + assert_eq!( + ErrorCategory::classify("提交失败:unknown field `foo` 不被接受"), + ErrorCategory::ToolRejected + ); + assert_eq!( + ErrorCategory::classify("执行异常\n at runTool (native-tools.mjs:12:3)"), + ErrorCategory::Unknown + ); // 待核查与未发出是告警,不是失败;其余仍是失败色。 assert_eq!(ErrorCategory::UnknownResult.severity(), Severity::Warning); assert_eq!(ErrorCategory::ToolRejected.severity(), Severity::Warning);