From 7a3fb23def43664a33e5dc88e8a8672624746bfa Mon Sep 17 00:00:00 2001 From: 0xlillith <35337584+0xlillith@users.noreply.github.com> Date: Fri, 23 Oct 2026 20:53:06 +0200 Subject: [PATCH 1/2] wip(library): reconcile exact rich-catalog replacement semantics (#1062) Source-only scoped extraction from original 0f801962 / #1086 on the refreshed #1060 card prerequisite. Preserve current asynchronous picker guards and source-ID handles. Scalar v1 and rich-v2-without-PBR clear existing PBR; supplied rich PBR is retained. No new saved concept or duplicate card descriptor. Formatting and source review completed; compile/native acceptance is still pending. --- crates/engine/src/cmd/libraries.rs | 24 +++- crates/engine/src/cmd/libraries_tests.rs | 119 ++++++++++++++- .../cmd/material_card_persistence_tests.rs | 6 +- crates/engine/src/cmd/pbr_appearance_tests.rs | 12 +- crates/io/src/catalog.rs | 121 ++++++++++++---- crates/io/src/catalog_tests.rs | 18 ++- crates/io/src/catalog_v2_tests.rs | 135 ++++++++++++++++++ crates/ui-egui/src/dialogs_library.rs | 2 +- crates/ui-egui/src/dialogs_library_tests.rs | 51 +++++-- docs/book/src/dev/local-libraries.md | 50 +++++-- 10 files changed, 466 insertions(+), 72 deletions(-) create mode 100644 crates/io/src/catalog_v2_tests.rs diff --git a/crates/engine/src/cmd/libraries.rs b/crates/engine/src/cmd/libraries.rs index ad64fef61d9..8f79c1919c8 100644 --- a/crates/engine/src/cmd/libraries.rs +++ b/crates/engine/src/cmd/libraries.rs @@ -1,4 +1,4 @@ -//! Scalar local libraries: inspect/export files and copy exact revisions into a design. +//! Local material libraries: inspect/export files and copy exact revisions into a design. use super::CommandSpec; use crate::{Result, Session, params::bad}; use serde::Deserialize; @@ -7,9 +7,9 @@ use solidcraft_io::catalog::{Catalog, Definition, Provenance}; pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("library.inspect", "Inspect Local Library", inspect).icon("inspect").noundo().doc_only() - .params("path: scalar library JSON; returns validated catalog and exact entry revisions, without changing the design"), + .params("path: v1/v2 library JSON; returns validated catalog and exact entry revisions, without changing the design"), CommandSpec::new("library.export", "Export Design Library", export).icon("export").noundo().doc_only() - .params("path: .json; id? (default user.local), name?, provenance?, overwrite? false. Copies assigned looks and design-local physical definitions; never changes the design"), + .params("path: .json; id? (default user.local), name?, provenance?, overwrite? false, format? solidcraft-library/2 (default) | solidcraft-library/1 (refuses PBR/cards). Copies assigned looks and design-local physical definitions; never changes the design"), CommandSpec::new("library.apply", "Apply Local Library Entry", apply).icon("import").enabled(super::not_in_sketch) .params("path, entry: qualified ID, revision: exact content SHA-256; targets?: {bodies?, faces?: [{body,point}], components?}; name?: physical material name on import. Copies values in one undo step; material conflicts are explicit"), ]; @@ -31,6 +31,11 @@ struct Export { provenance: Provenance, #[serde(default)] overwrite: bool, + #[serde(default = "default_format")] + format: String, +} +fn default_format() -> String { + solidcraft_io::catalog::FORMAT.into() } fn default_id() -> String { "user.local".into() @@ -107,7 +112,9 @@ fn export(s: &mut Session, p: &Value) -> Result { if !request.path.to_ascii_lowercase().ends_with(".json") { return Err(bad(cmd, "library export path must end in .json")); } - let catalog = Catalog::from_document(&s.doc, &request.id, &request.name, request.provenance).map_err(|e| bad(cmd, e.to_string()))?; + let catalog = Catalog::from_document(&s.doc, &request.id, &request.name, request.provenance) + .and_then(|catalog| catalog.in_format(&request.format)) + .map_err(|e| bad(cmd, e.to_string()))?; let bytes = catalog.encode().map_err(|e| bad(cmd, e.to_string()))?; #[cfg(not(target_arch = "wasm32"))] let result = if request.overwrite { @@ -146,6 +153,9 @@ fn apply(s: &mut Session, p: &Value) -> Result { target["appearance"] = json!(look.name); target["color"] = json!(look.color); target["opacity"] = json!(look.opacity); + if let Some(pbr) = look.pbr { + target["pbr"] = json!(pbr); + } nested(s, "appearance.assign", &target)? } Definition::Material(material) => { @@ -172,6 +182,12 @@ fn apply(s: &mut Session, p: &Value) -> Result { if let Some(look) = &material.appearance { params["color"] = json!(look.color); params["opacity"] = json!(look.opacity); + if let Some(pbr) = look.pbr { + params["pbr"] = json!(pbr); + } + } + if let Some(card) = &material.physical_card { + params["physical_card"] = json!(card); } nested(s, "material.create", ¶ms)?; // The existing colour API labels a custom look after its material. diff --git a/crates/engine/src/cmd/libraries_tests.rs b/crates/engine/src/cmd/libraries_tests.rs index 0cb53ce9bb8..ddb4f9b57a1 100644 --- a/crates/engine/src/cmd/libraries_tests.rs +++ b/crates/engine/src/cmd/libraries_tests.rs @@ -1,5 +1,5 @@ use super::*; -use solidcraft_io::catalog::{Definition, Entry, FORMAT, ScalarLook, ScalarMaterial}; +use solidcraft_io::catalog::{Definition, Entry, FORMAT, LibraryLook, LibraryMaterial}; use std::sync::{ Arc, atomic::{AtomicU64, Ordering}, @@ -33,16 +33,17 @@ fn catalog() -> Catalog { entries: vec![ Entry::new( "user.test", - Definition::Appearance(ScalarLook { name: "Warm oak colour".into(), color: [180, 120, 70], opacity: 0.8 }), + Definition::Appearance(LibraryLook { name: "Warm oak colour".into(), color: [180, 120, 70], opacity: 0.8, pbr: None }), Provenance::default(), ) .unwrap(), Entry::new( "user.test", - Definition::Material(ScalarMaterial { + Definition::Material(LibraryMaterial { name: "Timber density".into(), density_g_cm3: 0.7, - appearance: Some(ScalarLook { name: "Timber tint".into(), color: [180, 120, 70], opacity: 1.0 }), + physical_card: None, + appearance: Some(LibraryLook { name: "Timber tint".into(), color: [180, 120, 70], opacity: 1.0, pbr: None }), }), Provenance::default(), ) @@ -60,6 +61,113 @@ fn apply_entry(s: &mut Session, file: &File, entry: &Entry, targets: Value) -> R s.execute("library.apply", &json!({"path":file.0,"entry":entry.id,"revision":entry.revision,"targets":targets})) } +fn rich_catalog() -> Catalog { + use solidcraft_doc::{pbr_appearance::PbrParameters, physical_material::ValidatedCard}; + let mut c = catalog(); + if let Definition::Appearance(l) = &mut c.entries[0].definition { + l.opacity = 1.0; + l.pbr = Some(PbrParameters::new(1., 0.25, 1.5).unwrap()); + } + if let Definition::Material(m) = &mut c.entries[1].definition { + m.density_g_cm3 = 0.8; + m.appearance.as_mut().unwrap().pbr = Some(PbrParameters::new(0., 0.65, 1.4).unwrap()); + m.physical_card = Some( + ValidatedCard::from_value(&json!({"schema_version":1,"designation":"Original synthetic candidate","family":"other", + "sources":[{"id":"fixture","title":"Original invented density","kind":"illustrative"}], + "properties":[{"source_id":"fixture","data":{"kind":"density","kg_m3":700.0}}]})) + .unwrap(), + ); + } + for e in &mut c.entries { + *e = Entry::new("user.test", e.definition.clone(), e.provenance.clone()).unwrap(); + } + c +} + +#[test] +fn rich_appearance_copy_preserves_product_response_and_mass_without_source_file() { + let file = File::new(); + let c = rich_catalog(); + file.write(&c); + let mut s = session(); + let mass = s.execute("component.properties", &json!({})).unwrap(); + let scene = crate::product_scene::extract(&s).unwrap(); + let undo = s.undo.len(); + apply_entry(&mut s, &file, &c.entries[0], json!({"bodies":["Body1"]})).unwrap(); + assert_eq!(s.undo.len(), undo + 1); + let after = crate::product_scene::extract(&s).unwrap(); + assert!(Arc::ptr_eq(&scene.meshes[0].mesh, &after.meshes[0].mesh)); + assert_eq!(after.meshes[0].surface.unwrap().metallic(), 1.0); + assert_eq!(s.execute("component.properties", &json!({})).unwrap(), mass); + let saved = solidcraft_io::write_design(&s.doc); + std::fs::remove_file(&file.0).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc.appearances.bodies.is_empty()); + s.execute("edit.redo", &json!({})).unwrap(); + let mut reopened = Session::new(solidcraft_io::read_design(&saved).unwrap()); + assert_eq!(reopened.doc.appearances, s.doc.appearances); + assert_eq!(reopened.execute("component.properties", &json!({})).unwrap(), mass); +} + +#[test] +fn rich_material_copy_retains_engineering_card_label_optics_and_explicit_mass_density() { + let file = File::new(); + let c = rich_catalog(); + file.write(&c); + let mut s = session(); + let undo = s.undo.len(); + apply_entry(&mut s, &file, &c.entries[1], json!({"bodies":["Body1"]})).unwrap(); + assert_eq!(s.undo.len(), undo + 1); + let material = &s.doc.user_materials[0]; + assert_eq!(material.appearance.as_ref().unwrap().name, "Timber tint"); + assert_eq!(material.appearance.as_ref().unwrap().pbr.unwrap().roughness(), 0.65); + assert!(material.physical_card.is_some()); + assert_eq!(material.density, 0.8); + let mass = s.execute("component.properties", &json!({})).unwrap()["total"]["mass_g"].as_f64().unwrap(); + assert!((mass - 0.8).abs() < 1e-8); + let saved = solidcraft_io::write_design(&s.doc); + std::fs::remove_file(&file.0).unwrap(); + let reopened = Session::new(solidcraft_io::read_design(&saved).unwrap()); + assert_eq!(reopened.doc.user_materials, s.doc.user_materials); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc.user_materials.is_empty()); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc.user_materials, reopened.doc.user_materials); +} + +#[test] +fn explicit_v1_export_refuses_richer_data_before_overwriting_and_scalar_v1_still_works() { + let file = File::new(); + let sentinel = b"Existing catalog must survive"; + std::fs::write(&file.0, sentinel).unwrap(); + let mut s = session(); + s.execute( + "appearance.assign", + &json!({"bodies":["Body1"],"color":"#b47846", + "pbr":{"metallic":1,"roughness":0.3,"dielectric_ior":1.5}}), + ) + .unwrap(); + let before = s.doc.clone(); + let history = (s.undo.len(), s.redo.len(), s.revision); + assert!(s.execute("library.export", &json!({"path":file.0,"format":solidcraft_io::catalog::V1_FORMAT,"overwrite":true})).is_err()); + assert_eq!(std::fs::read(&file.0).unwrap(), sentinel); + assert!(Arc::ptr_eq(&before, &s.doc)); + assert_eq!(history, (s.undo.len(), s.redo.len(), s.revision)); + s.execute("library.export", &json!({"path":file.0,"overwrite":true})).unwrap(); + assert_eq!(Catalog::read(&file.0).unwrap().format, FORMAT); + s.execute("appearance.assign", &json!({"bodies":["Body1"],"color":"#b47846"})).unwrap(); + s.execute("library.export", &json!({"path":file.0,"format":solidcraft_io::catalog::V1_FORMAT,"overwrite":true})).unwrap(); + assert_eq!(Catalog::read(&file.0).unwrap().format, solidcraft_io::catalog::V1_FORMAT); + let rich = rich_catalog(); + file.write(&rich); + s.execute("material.create", &json!({"name":"Timber density","density_g_cm3":0.8,"color":"#b47846"})).unwrap(); + let before = s.doc.clone(); + let history = (s.undo.len(), s.redo.len(), s.revision); + assert!(apply_entry(&mut s, &file, &rich.entries[1], json!({"bodies":["Body1"]})).is_err()); + assert!(Arc::ptr_eq(&before, &s.doc)); + assert_eq!(history, (s.undo.len(), s.redo.len(), s.revision)); +} + #[test] fn catalog_export_obeys_file_scope_in_new_file_and_overwrite_modes() { let file = File::new(); @@ -237,7 +345,8 @@ fn lossy_scalar_export_never_creates_or_replaces_a_file_or_changes_history() { std::fs::write(&file.0, b"preserve existing library").unwrap(); } for overwrite in [false, true] { - let error = s.execute("library.export", &json!({"path":file.0,"overwrite":overwrite})).unwrap_err(); + let error = + s.execute("library.export", &json!({"path":file.0,"overwrite":overwrite,"format":solidcraft_io::catalog::V1_FORMAT})).unwrap_err(); assert!(error.to_string().contains("cannot preserve PBR")); if existing { assert_eq!(std::fs::read(&file.0).unwrap(), b"preserve existing library"); diff --git a/crates/engine/src/cmd/material_card_persistence_tests.rs b/crates/engine/src/cmd/material_card_persistence_tests.rs index 819211615c6..3934497cacc 100644 --- a/crates/engine/src/cmd/material_card_persistence_tests.rs +++ b/crates/engine/src/cmd/material_card_persistence_tests.rs @@ -71,7 +71,11 @@ fn omission_retains_null_clears_and_unrelated_material_edits_retain_cards() { s.execute("material.edit", &p).unwrap(); assert_eq!(s.doc.user_materials[1].physical_card, original); } - let error = solidcraft_io::catalog::ScalarMaterial::from_material(&s.doc.user_materials[1]).unwrap_err(); + let mut only_card = Document::default(); + only_card.user_materials.push(s.doc.user_materials[1].clone()); + let error = solidcraft_io::catalog::Catalog::from_document(&only_card, "user.fixture", "Original", Default::default()) + .and_then(|c| c.in_format(solidcraft_io::catalog::V1_FORMAT)) + .unwrap_err(); assert!(error.to_string().contains("engineering cards")); s.execute("material.edit", &json!({"material":"Renamed","physical_card":null})).unwrap(); assert!(s.doc.user_materials[1].physical_card.is_none()); diff --git a/crates/engine/src/cmd/pbr_appearance_tests.rs b/crates/engine/src/cmd/pbr_appearance_tests.rs index 00cd3e06848..4f4ebfca05f 100644 --- a/crates/engine/src/cmd/pbr_appearance_tests.rs +++ b/crates/engine/src/cmd/pbr_appearance_tests.rs @@ -89,7 +89,11 @@ fn invalid_optical_requests_refuse_atomically_and_scalar_export_cannot_lose_them "pbr":{"metallic":0,"roughness":0.5,"dielectric_ior":1.5}}), ) .unwrap(); - assert!(solidcraft_io::catalog::Catalog::from_document(&s.doc, "user.fixture", "Original", Default::default()).is_err()); + assert!( + solidcraft_io::catalog::Catalog::from_document(&s.doc, "user.fixture", "Original", Default::default()) + .and_then(|c| c.in_format(solidcraft_io::catalog::V1_FORMAT)) + .is_err() + ); let mut invalid: serde_json::Value = serde_json::from_str(&s.doc.to_json()).unwrap(); invalid["appearances"]["bodies"]["Specimen"]["opacity"] = json!(0.5); assert!(crate::doc::Document::from_json(&invalid.to_string()).is_err()); @@ -115,7 +119,11 @@ fn physical_default_look_and_face_override_keep_independent_optical_meaning() { assert!(scene.meshes[0].surface.is_some()); assert!(scene.meshes[0].faces.iter().any(|f| f.color == [0, 128, 160] && f.surface.is_none())); assert_eq!(s.doc.user_materials[0].density, 0.7); - assert!(solidcraft_io::catalog::Catalog::from_document(&s.doc, "user.fixture", "Original", Default::default()).is_err()); + assert!( + solidcraft_io::catalog::Catalog::from_document(&s.doc, "user.fixture", "Original", Default::default()) + .and_then(|c| c.in_format(solidcraft_io::catalog::V1_FORMAT)) + .is_err() + ); } #[test] diff --git a/crates/io/src/catalog.rs b/crates/io/src/catalog.rs index 158273b1d2d..ad24ec9bb97 100644 --- a/crates/io/src/catalog.rs +++ b/crates/io/src/catalog.rs @@ -1,11 +1,12 @@ -//! Portable scalar libraries; no renderer, network, external resources or design links. +//! Portable material libraries; no network, external resources or design links. use crate::{IoError, Result}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use solidcraft_doc::{Document, UserMaterial, appearance::Look, valid_density}; use std::collections::BTreeMap; -pub const FORMAT: &str = "solidcraft-library/1"; +pub const FORMAT: &str = "solidcraft-library/2"; +pub const V1_FORMAT: &str = "solidcraft-library/1"; pub const MAX_BYTES: usize = 4 * 1024 * 1024; pub const MAX_ENTRIES: usize = 1024; /// Bound source inspection even when many assignments reuse the same definition. @@ -51,50 +52,57 @@ impl Provenance { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] -pub struct ScalarLook { +pub struct LibraryLook { pub name: String, pub color: [u8; 3], pub opacity: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pbr: Option, } -impl ScalarLook { +impl LibraryLook { pub fn from_look(look: &Look) -> Result { - if look.pbr.is_some() { - return Err(invalid("scalar catalog v1 cannot preserve PBR parameters; export refused")); - } - Ok(Self { name: look.name.clone(), color: look.color, opacity: look.opacity }) + let out = Self { name: look.name.clone(), color: look.color, opacity: look.opacity, pbr: look.pbr }; + out.validate()?; + Ok(out) } pub fn to_look(&self) -> Look { - Look { name: self.name.clone(), color: self.color, opacity: self.opacity, pbr: None } + Look { name: self.name.clone(), color: self.color, opacity: self.opacity, pbr: self.pbr } } fn validate(&self) -> Result<()> { if !text(&self.name, 128) || !self.opacity.is_finite() || !(0.0..=1.0).contains(&self.opacity) { return Err(invalid("library appearance needs a 1–128 byte name and finite opacity 0–1")); } + self.to_look().opaque_surface().map_err(|e| invalid(e.to_string()))?; Ok(()) } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] -pub struct ScalarMaterial { +pub struct LibraryMaterial { pub name: String, pub density_g_cm3: f64, #[serde(default, skip_serializing_if = "Option::is_none")] - pub appearance: Option, + pub appearance: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub physical_card: Option, } -impl ScalarMaterial { +impl LibraryMaterial { pub fn from_material(material: &UserMaterial) -> Result { - if material.physical_card.is_some() { - return Err(invalid("scalar catalog v1 cannot preserve engineering cards; export refused")); - } Ok(Self { name: material.name.clone(), density_g_cm3: material.density, - appearance: material.appearance.as_ref().map(ScalarLook::from_look).transpose()?, + appearance: material.appearance.as_ref().map(LibraryLook::from_look).transpose()?, + physical_card: material.physical_card.clone(), }) } pub fn to_material(&self, name: String) -> UserMaterial { - UserMaterial { name, density: self.density_g_cm3, appearance: self.appearance.as_ref().map(ScalarLook::to_look), physical_card: None } + UserMaterial { + name, + density: self.density_g_cm3, + appearance: self.appearance.as_ref().map(LibraryLook::to_look), + physical_card: self.physical_card.clone(), + } } fn validate(&self) -> Result<()> { if !text(&self.name, 128) || !valid_density(self.density_g_cm3) { @@ -110,10 +118,16 @@ impl ScalarMaterial { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(tag = "kind", content = "value", rename_all = "snake_case", deny_unknown_fields)] pub enum Definition { - Appearance(ScalarLook), - Material(ScalarMaterial), + Appearance(LibraryLook), + Material(LibraryMaterial), } impl Definition { + fn requires_v2(&self) -> bool { + match self { + Self::Appearance(look) => look.pbr.is_some(), + Self::Material(material) => material.physical_card.is_some() || material.appearance.as_ref().is_some_and(|l| l.pbr.is_some()), + } + } pub fn name(&self) -> &str { match self { Self::Appearance(l) => &l.name, @@ -143,7 +157,8 @@ pub struct Entry { pub definition: Definition, } impl Entry { - /// Revision is SHA-256 of compact serde JSON `[provenance, definition]` in this v1 contract. + /// SHA-256 of compact serde JSON `[provenance, definition]`. Absent v2 fields + /// are omitted, preserving the exact v1 scalar writer contract. pub fn content_revision(&self) -> Result { self.provenance.validate()?; self.definition.validate()?; @@ -210,11 +225,15 @@ fn bounded_entries<'de, D: serde::Deserializer<'de>>(deserializer: D) -> std::re } impl Catalog { pub fn validate(&self) -> Result<()> { - if self.format != FORMAT || !identifier(&self.id) || !text(&self.name, 128) || self.entries.len() > MAX_ENTRIES { - return Err(invalid("unsupported or invalid scalar library (v1, 1024 entries, 128 byte name)")); + if !matches!(self.format.as_str(), FORMAT | V1_FORMAT) || !identifier(&self.id) || !text(&self.name, 128) || self.entries.len() > MAX_ENTRIES + { + return Err(invalid("unsupported or invalid library (v1/v2, 1024 entries, 128 byte name)")); } let mut ids = std::collections::BTreeSet::new(); for entry in &self.entries { + if self.format == V1_FORMAT && entry.definition.requires_v2() { + return Err(invalid("catalog v1 cannot preserve PBR or engineering cards; export refused")); + } entry.validate(&self.id)?; if !ids.insert(&entry.id) { return Err(invalid("duplicate library entry identity")); @@ -226,18 +245,53 @@ impl Catalog { if bytes.len() > MAX_BYTES { return Err(invalid("scalar library exceeds 4 MiB")); } + // Keep the v1 wire schema strict, including newly recognized null fields. + // This bounded raw preflight is not arbitrary JSON canonicalization. + let raw: serde_json::Value = serde_json::from_slice(bytes).map_err(|e| invalid(format!("invalid library: {e}")))?; + if raw.get("format").and_then(serde_json::Value::as_str) == Some(V1_FORMAT) + && let Some(entries) = raw.get("entries").and_then(serde_json::Value::as_array) + { + if entries.len() > MAX_ENTRIES { + return Err(invalid("library exceeds 1024 entries")); + } + for entry in entries { + if let Some(value) = entry.get("definition").and_then(|d| d.get("value")) { + let has = |v: &serde_json::Value, key: &str| v.as_object().is_some_and(|o| o.contains_key(key)); + if has(value, "pbr") || has(value, "physical_card") || value.get("appearance").is_some_and(|a| has(a, "pbr")) { + return Err(invalid("v1 definitions cannot contain v2 fields")); + } + } + } + } + drop(raw); let catalog: Self = serde_json::from_slice(bytes).map_err(|e| invalid(format!("invalid scalar library: {e}")))?; catalog.validate()?; Ok(catalog) } pub fn encode(&self) -> Result> { self.validate()?; + let mut budget = 4096usize; + for entry in &self.entries { + budget = budget.saturating_add(entry_encoded_bound(entry)?); + if budget > MAX_BYTES { + return Err(invalid("library exceeds 4 MiB encoded admission budget")); + } + } let bytes = serde_json::to_vec_pretty(self).map_err(|e| invalid(e.to_string()))?; if bytes.len() > MAX_BYTES { return Err(invalid("scalar library exceeds 4 MiB")); } Ok(bytes) } + /// Change only the envelope version; reject any lossy downgrade. + pub fn in_format(mut self, format: &str) -> Result { + if !matches!(format, FORMAT | V1_FORMAT) { + return Err(invalid("unsupported library format")); + } + self.format = format.into(); + self.validate()?; + Ok(self) + } pub fn read(path: &str) -> Result { // Check the VFS size first as well: its browser read clones the stored bytes. if crate::vfs::len(path).map_err(|e| invalid(e.to_string()))? > MAX_BYTES as u64 { @@ -261,6 +315,7 @@ impl Catalog { return Err(invalid("library export exceeds 100000 source references")); } let mut entries = BTreeMap::new(); + let mut budget = 4096usize; let mut insert = |definition| -> Result<()> { let entry = Entry::new(id, definition, provenance.clone())?; if let Some(previous) = entries.get(&entry.id) { @@ -271,17 +326,21 @@ impl Catalog { if entries.len() >= MAX_ENTRIES { return Err(invalid("scalar library exceeds 1024 unique entries")); } + budget = budget.saturating_add(entry_encoded_bound(&entry)?); + if budget > MAX_BYTES { + return Err(invalid("library exceeds 4 MiB encoded admission budget")); + } entries.insert(entry.id.clone(), entry); } Ok(()) }; for look in doc.appearances.bodies.values().chain(doc.appearances.components.values()).chain(doc.appearances.faces.iter().map(|f| &f.look)) { - insert(Definition::Appearance(ScalarLook::from_look(look)?))?; + insert(Definition::Appearance(LibraryLook::from_look(look)?))?; } for material in &doc.user_materials { - insert(Definition::Material(ScalarMaterial::from_material(material)?))?; + insert(Definition::Material(LibraryMaterial::from_material(material)?))?; if let Some(look) = &material.appearance { - insert(Definition::Appearance(ScalarLook::from_look(look)?))?; + insert(Definition::Appearance(LibraryLook::from_look(look)?))?; } } let out = Self { format: FORMAT.into(), id: id.into(), name: name.into(), entries: entries.into_values().collect() }; @@ -290,6 +349,18 @@ impl Catalog { } } +/// Bound retained unique definitions and the final pretty writer before a full +/// catalog allocation. Each admitted entry is bounded independently; reserve +/// envelope text, four spaces per nested line, separators and a final newline. +fn entry_encoded_bound(entry: &Entry) -> Result { + let bytes = serde_json::to_vec_pretty(entry).map_err(|e| invalid(e.to_string()))?; + let lines = bytes.iter().filter(|b| **b == b'\n').count().saturating_add(1); + Ok(bytes.len().saturating_add(lines.saturating_mul(4)).saturating_add(2)) +} + #[cfg(test)] #[path = "catalog_tests.rs"] mod tests; +#[cfg(test)] +#[path = "catalog_v2_tests.rs"] +mod v2_tests; diff --git a/crates/io/src/catalog_tests.rs b/crates/io/src/catalog_tests.rs index 5da65a97691..20d5b1c7eab 100644 --- a/crates/io/src/catalog_tests.rs +++ b/crates/io/src/catalog_tests.rs @@ -4,7 +4,7 @@ use serde_json::json; fn catalog() -> Catalog { let entry = Entry::new( "user.test", - Definition::Appearance(ScalarLook { name: "Warm oak colour".into(), color: [180, 120, 70], opacity: 0.8 }), + Definition::Appearance(LibraryLook { name: "Warm oak colour".into(), color: [180, 120, 70], opacity: 0.8, pbr: None }), Provenance::default(), ) .unwrap(); @@ -34,7 +34,7 @@ fn strict_schema_rejects_unknown_kinds_fields_versions_and_bad_identity() { for changed in [ { let mut v = value.clone(); - v["format"] = json!("solidcraft-library/2"); + v["format"] = json!("solidcraft-library/99"); v }, { @@ -96,14 +96,17 @@ fn scalar_validation_refuses_nonfinite_density_opacity_counts_strings_and_oversi assert!( Entry::new( "user.test", - Definition::Material(ScalarMaterial { name: "Timber".into(), density_g_cm3: density, appearance: None }), + Definition::Material(LibraryMaterial { name: "Timber".into(), density_g_cm3: density, appearance: None, physical_card: None }), Provenance::default() ) .is_err() ); } for name in ["".into(), "x".repeat(129), "bad\nname".into(), " leading".into()] { - assert!(Entry::new("user.test", Definition::Appearance(ScalarLook { name, color: [1, 2, 3], opacity: 1.0 }), Provenance::default()).is_err()); + assert!( + Entry::new("user.test", Definition::Appearance(LibraryLook { name, color: [1, 2, 3], opacity: 1.0, pbr: None }), Provenance::default()) + .is_err() + ); } assert!(Catalog::decode(&vec![b' '; MAX_BYTES + 1]).is_err()); let source = Provenance { source_url: Some("x".repeat(2049)), ..Default::default() }; @@ -112,7 +115,7 @@ fn scalar_validation_refuses_nonfinite_density_opacity_counts_strings_and_oversi #[test] fn design_export_deduplicates_exact_looks_and_keeps_physical_properties_distinct() { let mut doc = Document::default(); - let look = ScalarLook { name: "Warm oak colour".into(), color: [180, 120, 70], opacity: 0.8 }.to_look(); + let look = LibraryLook { name: "Warm oak colour".into(), color: [180, 120, 70], opacity: 0.8, pbr: None }.to_look(); doc.appearances.bodies.insert("Body1".into(), look.clone()); doc.appearances.bodies.insert("Body2".into(), look.clone()); doc.user_materials.push(UserMaterial { name: "Timber density".into(), density: 0.7, appearance: Some(look), physical_card: None }); @@ -127,7 +130,7 @@ fn design_export_deduplicates_exact_looks_and_keeps_physical_properties_distinct #[test] fn scalar_export_refuses_pbr_in_every_design_owned_appearance_location() { use solidcraft_doc::{appearance::FaceLook, pbr_appearance::PbrParameters}; - let mut look = ScalarLook { name: "Original PBR specimen".into(), color: [180, 120, 70], opacity: 1.0 }.to_look(); + let mut look = LibraryLook { name: "Original PBR specimen".into(), color: [180, 120, 70], opacity: 1.0, pbr: None }.to_look(); look.pbr = Some(PbrParameters::new(1.0, 0.3, 1.5).unwrap()); for location in 0..4 { let mut doc = Document::default(); @@ -154,7 +157,8 @@ fn scalar_export_refuses_pbr_in_every_design_owned_appearance_location() { }), } let before = doc.clone(); - let error = Catalog::from_document(&doc, "user.test", "Test", Provenance::default()).unwrap_err(); + let rich = Catalog::from_document(&doc, "user.test", "Test", Provenance::default()).unwrap(); + let error = rich.in_format(V1_FORMAT).unwrap_err(); assert!(error.to_string().contains("cannot preserve PBR")); assert_eq!(doc, before); } diff --git a/crates/io/src/catalog_v2_tests.rs b/crates/io/src/catalog_v2_tests.rs new file mode 100644 index 00000000000..a2e7838cfc0 --- /dev/null +++ b/crates/io/src/catalog_v2_tests.rs @@ -0,0 +1,135 @@ +use super::*; +use serde_json::{Value, json}; +use solidcraft_doc::{pbr_appearance::PbrParameters, physical_material::ValidatedCard}; + +// Exact bytes and revisions captured from the pre-v2 writer at 75e66eea. +const V1: &str = r#"{ + "format": "solidcraft-library/1", + "id": "user.test", + "name": "Original v1 fixture", + "entries": [ + { + "id": "user.test/appearance-c17adc43c1eb8c7d", + "revision": "c17adc43c1eb8c7d6badd7e7821150509bf513eb29c75a90c4027f46d9b49437", + "provenance": { + "license": "LicenseRef-User-Provided" + }, + "definition": { + "kind": "appearance", + "value": { + "name": "Original scalar study", + "color": [ + 180, + 120, + 70 + ], + "opacity": 0.8 + } + } + } + ] +}"#; + +fn card() -> ValidatedCard { + ValidatedCard::from_value(&json!({"schema_version":1,"designation":"Original synthetic card","family":"other", + "sources":[{"id":"fixture","title":"Original invented constants","kind":"illustrative"}], + "properties":[{"source_id":"fixture","data":{"kind":"elasticity","model":{ + "symmetry":"isotropic","young_modulus_pa":12.25e9,"poisson_ratio":0.25}}}]})) + .unwrap() +} + +fn rich() -> Catalog { + let mut doc = Document::default(); + let mut look = Look::custom([180, 120, 70], 1.0); + look.name = "Original opaque study".into(); + look.pbr = Some(PbrParameters::new(1.0, 0.3, 1.5).unwrap()); + doc.appearances.bodies.insert("Body1".into(), look.clone()); + doc.user_materials.push(UserMaterial { name: "Original candidate".into(), density: 0.8, appearance: Some(look), physical_card: Some(card()) }); + Catalog::from_document(&doc, "user.test", "Original v2 fixture", Default::default()).unwrap() +} + +#[test] +fn pinned_v1_bytes_revisions_and_scalar_material_canonical_fields_are_preserved() { + let old = Catalog::decode(V1.as_bytes()).unwrap(); + assert_eq!(old.encode().unwrap(), V1.as_bytes()); + let upgraded = old.clone().in_format(FORMAT).unwrap(); + assert_eq!(upgraded.entries, old.entries); + assert_eq!(upgraded.encode().unwrap(), V1.replacen(V1_FORMAT, FORMAT, 1).as_bytes()); + let material = LibraryMaterial { + name: "Original scalar material".into(), + density_g_cm3: 0.7, + appearance: Some(LibraryLook { name: "Original scalar material".into(), color: [180, 120, 70], opacity: 1.0, pbr: None }), + physical_card: None, + }; + let provenance = Provenance { + license: "MIT OR Apache-2.0".into(), + author: Some("SolidCraft contributors".into()), + source_url: Some("https://example.invalid/original".into()), + }; + let entry = Entry::new("user.test", Definition::Material(material), provenance).unwrap(); + assert_eq!(entry.revision, "3dc003a875463baef587b85b9883f227cb546178317271c60078989bdb86c245"); + assert_eq!(entry.id, "user.test/material-3dc003a875463bae"); +} + +#[test] +fn v2_roundtrip_keeps_optics_cards_and_revisions_cover_richer_data() { + let original = rich(); + let copy = Catalog::decode(&original.encode().unwrap()).unwrap(); + assert_eq!(copy, original); + assert!(copy.clone().in_format(V1_FORMAT).is_err()); + let mut changed = copy.clone(); + for entry in &mut changed.entries { + match &mut entry.definition { + Definition::Appearance(l) => l.pbr = Some(PbrParameters::new(0., 0.8, 1.4).unwrap()), + Definition::Material(m) => { + assert_eq!(m.to_material(m.name.clone()).physical_card, Some(card())); + let mut v = serde_json::to_value(card()).unwrap(); + v["designation"] = json!("Changed synthetic designation"); + m.physical_card = Some(ValidatedCard::from_value(&v).unwrap()); + } + } + assert_ne!(entry.content_revision().unwrap(), entry.revision); + } + assert!(changed.validate().is_err()); +} + +#[test] +fn wire_versions_unknown_fields_invalid_optics_and_hostile_cards_refuse() { + let legacy: Value = serde_json::from_str(V1).unwrap(); + for value in [Value::Null, json!({"metallic":0,"roughness":0.3,"dielectric_ior":1.5})] { + let mut bad = legacy.clone(); + bad["entries"][0]["definition"]["value"]["pbr"] = value; + assert!(Catalog::decode(&serde_json::to_vec(&bad).unwrap()).is_err()); + } + let v = serde_json::to_value(rich()).unwrap(); + let appearance = v["entries"].as_array().unwrap().iter().position(|e| e["definition"]["kind"] == "appearance").unwrap(); + let material = v["entries"].as_array().unwrap().iter().position(|e| e["definition"]["kind"] == "material").unwrap(); + for (path, value) in [("opacity", json!(0.5)), ("pbr", json!({"metallic":0,"roughness":0,"dielectric_ior":1.5})), ("unknown", json!(true))] { + let mut bad = v.clone(); + bad["entries"][appearance]["definition"]["value"][path] = value; + assert!(Catalog::decode(&serde_json::to_vec(&bad).unwrap()).is_err()); + } + let mut bad = v.clone(); + bad["entries"][material]["definition"]["value"]["physical_card"]["sources"] = json!(vec![json!({}); 33]); + assert!(Catalog::decode(&serde_json::to_vec(&bad).unwrap()).is_err()); + let mut downgraded = v.clone(); + downgraded["format"] = json!(V1_FORMAT); + assert!(Catalog::decode(&serde_json::to_vec(&downgraded).unwrap()).is_err()); +} + +#[test] +fn rich_export_bounds_retained_definitions_before_whole_catalog_encoding() { + let mut v = serde_json::to_value(card()).unwrap(); + v["properties"] = json!([]); + v["sources"] = json!( + (0..32) + .map(|i| json!({"id":format!("s{i}"),"title":"Original synthetic metadata","kind":"illustrative","reference":"x".repeat(2048)})) + .collect::>() + ); + let record = ValidatedCard::from_value(&v).unwrap(); + let mut doc = Document::default(); + for i in 0..64 { + doc.user_materials.push(UserMaterial { name: format!("Candidate {i}"), density: 0.8, appearance: None, physical_card: Some(record.clone()) }); + } + assert!(Catalog::from_document(&doc, "user.test", "Original large fixture", Default::default()).unwrap_err().to_string().contains("4 MiB")); +} diff --git a/crates/ui-egui/src/dialogs_library.rs b/crates/ui-egui/src/dialogs_library.rs index 6633560ddb7..83666407c41 100644 --- a/crates/ui-egui/src/dialogs_library.rs +++ b/crates/ui-egui/src/dialogs_library.rs @@ -235,8 +235,8 @@ fn import_rows(app: &mut SolveApp, ui: &mut egui::Ui, k: &mut Ap, inputs: &[SelI Ok(_) => { if let Definition::Appearance(look) = entry.definition { k.color = look.color; - k.pbr = None; k.opacity = look.opacity; + k.pbr = look.pbr; k.look = Some(look.name.clone()); k.remove_override = false; k.applied = selected_params(k, picked); diff --git a/crates/ui-egui/src/dialogs_library_tests.rs b/crates/ui-egui/src/dialogs_library_tests.rs index 9fb44dd263d..01444f6201d 100644 --- a/crates/ui-egui/src/dialogs_library_tests.rs +++ b/crates/ui-egui/src/dialogs_library_tests.rs @@ -4,21 +4,32 @@ use solidcraft_engine::{Sel, Session}; #[test] fn catalog_clicked_load_apply_export_and_ok_keep_one_design_undo_step() { + clicked_catalog(None, "solidcraft-library/1").unwrap(); +} + +#[test] +fn catalog_clicked_pbr_load_apply_export_and_ok_retains_the_optical_response() { + clicked_catalog(Some(solidcraft_engine::doc::pbr_appearance::PbrParameters::new(1., 0.3, 1.5).unwrap()), "solidcraft-library/2").unwrap(); +} + +#[test] +fn catalog_clicked_rich_entry_without_pbr_clears_the_old_optical_response() { + clicked_catalog(None, "solidcraft-library/2").unwrap(); +} + +fn clicked_catalog(pbr: Option, format: &str) -> Result<(), Box> { let mut h = Harness::new(); h.call("ui.resize", json!({"width":1600,"height":1400})); let path = h.dir.join("source-library.json").to_string_lossy().into_owned(); let mut source = Session::default(); - source.execute("solid.box", &json!({"length":10,"width":10,"height":10})).unwrap(); - source.execute("appearance.assign", &json!({"bodies":["Body1"],"appearance":"Warm oak colour","color":[180,120,70],"opacity":0.8})).unwrap(); - source.execute("library.export", &json!({"path":path})).unwrap(); - h.app.run("solid.box", json!({"length":10,"width":10,"height":10})).unwrap(); - h.app - .run( - "appearance.assign", - json!({"bodies":["Body1"],"color":[20,20,20], - "pbr":{"metallic":1.0,"roughness":0.3,"dielectric_ior":1.5}}), - ) - .unwrap(); + source.execute("solid.box", &json!({"length":10,"width":10,"height":10}))?; + source.execute( + "appearance.assign", + &json!({"bodies":["Body1"],"appearance":"Warm oak colour","color":[180,120,70],"opacity":if pbr.is_some(){1.0}else{0.8},"pbr":pbr}), + )?; + source.execute("library.export", &json!({"path":path,"format":format}))?; + h.app.run("solid.box", json!({"length":10,"width":10,"height":10}))?; + h.app.run("appearance.assign", json!({"bodies":["Body1"],"color":[20,20,20],"pbr":{"metallic":1.0,"roughness":0.6,"dielectric_ior":1.7}}))?; h.app.session.mark_saved(); h.app.session.selection = vec![Sel::Body { name: "Body1".into() }]; h.app.start("appearance.assign"); @@ -57,18 +68,28 @@ fn catalog_clicked_load_apply_export_and_ok_keep_one_design_undo_step() { h.step(&json!({"click":{"handle":"library:entry:0"}})).unwrap(); h.step(&json!({"widget":"Apply library appearance"})).unwrap(); assert_eq!(h.app.session.doc.appearances.bodies["Body1"].name, "Warm oak colour"); - assert!(h.app.session.doc.appearances.bodies["Body1"].pbr.is_none()); + assert_eq!(h.app.session.doc.appearances.bodies["Body1"].pbr, pbr); + if let Some(dialog) = &h.app.dialog + && let Kind::Appearance(state) = &dialog.kind + { + assert_eq!(state.pbr, pbr); + } + assert_eq!(h.app.session.undo.len(), undo + 1); let revision = h.app.session.revision; - h.step(&json!({"widget":"Export design library..."})).unwrap(); + h.step(&json!({"widget":"Export design library..."}))?; let exported = h.dir.join("my-library.solidcraft-library.json"); - let catalog = Catalog::read(&exported.to_string_lossy()).unwrap(); + let catalog = Catalog::read(&exported.to_string_lossy())?; assert_eq!(catalog.entries.len(), 1); assert_eq!(catalog.entries[0].definition.name(), "Warm oak colour"); + if let Definition::Appearance(look) = &catalog.entries[0].definition { + assert_eq!(look.pbr, pbr); + } assert_eq!(h.app.session.revision, revision); - h.step(&json!({"widget":"OK"})).unwrap(); + h.step(&json!({"widget":"OK"}))?; assert!(h.app.dialog.is_none()); assert_eq!(h.app.session.undo.len(), undo + 1); + Ok(()) } fn appearance_fixture() -> Result<(Harness, Arc<()>), String> { diff --git a/docs/book/src/dev/local-libraries.md b/docs/book/src/dev/local-libraries.md index fc7eda1626e..763457c1bc5 100644 --- a/docs/book/src/dev/local-libraries.md +++ b/docs/book/src/dev/local-libraries.md @@ -1,9 +1,10 @@ -# Local scalar libraries +# Local material libraries -The first local-library slice (#846) reuses the existing appearance and physical -material commands. It is a small consumer of the broader [library proposal](libraries.md), -not the complete resource-pack implementation. It adds no texture mapping, wood grain, -PBR shader, HDRI lighting, online discovery or document-format version. +The first scalar slice (#846) and portable v2 extension (#1062) reuse existing +appearance/material commands. V2 transports existing opaque PBR looks and validated +engineering cards; it does not add a shader, texture mapping, wood grain, HDRI, +online discovery or document-format version. This remains a small consumer of +the broader [library proposal](libraries.md). ## Desktop workflow @@ -16,7 +17,7 @@ PBR shader, HDRI lighting, online discovery or document-format version. 3. Open that library in another design, search its appearance presets, select one and choose **Apply library appearance**. The normal body/face/component targets are reused. OK after this immediate application does not add a second undo step. -4. Save the design. Its selected scalar definitions are ordinary copied design data; +4. Save the design. Its selected definitions are ordinary copied design data; the source library can be moved or removed without changing the saved result. Export does not edit the design, its dirty state or history. An existing file is refused @@ -72,11 +73,30 @@ outer undo transaction through the existing material commands. Mass remains the volume × density calculation; a generic illustrative density is not an engineering grade. `library.export` also accepts `id` (default `user.local`), `name` (default `My library`), -`provenance` and `overwrite` (default false). Only explicit assignments/design-local +`provenance`, `overwrite` (default false) and `format` (default `solidcraft-library/2`). +Explicit `solidcraft-library/1` refuses PBR or engineering-card loss before publishing, +including with overwrite enabled. Only explicit assignments/design-local definitions are inspected, without evaluating geometry. Duplicate exact definitions are deduplicated; different values with the same display name remain distinct entries. -## Scalar catalog v1 +## Portable catalog v2 and scalar v1 compatibility + +`solidcraft-library/2` extends the same envelope and definition kinds with optional +`pbr: {metallic, roughness, dielectric_ior}` on appearance values and optional +`physical_card` on material values. PBR uses the existing bounded opaque contract +and requires opacity exactly one. Cards use the existing bounded SI validator; +source/condition records survive import, but validation does not authenticate or +approve their sources. A card does not replace assigned mass density or supply a +solver. Materials can carry both a card and an independent default PBR look. + +Absent richer fields are omitted from serialization. Existing v1 scalar bytes, +content revisions and identities are preserved exactly; regression fixtures pin +an appearance and a material revision from the pre-v2 writer. Changing only the +envelope version does not change a revision. Nonempty PBR/card data participates +in it. V1 wire input rejects even null v2-only fields; it cannot disguise richer +data with an older format marker. Older readers refuse v2. + +The following v1 shape remains readable and writable explicitly: The independent JSON format marker is `solidcraft-library/1`. It has `id`, `name` and an `entries` array. Each entry has `id`, `revision`, `provenance` and a typed `definition`: @@ -105,18 +125,24 @@ Provenance contains a required `license`, optional `author` and optional `source It is supplied metadata, not verified permission or a publisher signature. URLs are never fetched. The default `LicenseRef-User-Provided` does not claim that user data is openly licensed. No external art/data is bundled in this slice. Catalog provenance/revisions stay -in the catalog: the first consumer copies scalar values into existing `Look`/`UserMaterial` -records, without a persistent catalog-origin/update receipt. Full resource embedding, +in the catalog: values are copied into existing `Look`/`UserMaterial` records, +without a persistent catalog-origin/update receipt. Engineering-card sources and +conditions belong to the card and are copied with it. Full resource embedding, design-owned provenance, scopes and explicit update links remain proposed follow-ups. ## Bounds and failure behavior -The reader accepts at most 4 MiB encoded JSON and 1,024 entries. Entry decoding stops at +The reader accepts at most 4 MiB encoded JSON and 1,024 entries. A bounded raw wire +preflight preserves v1 field rules before typed decoding. Entry decoding stops at the count cap with fallible vector growth. Names are trimmed, nonempty and at most 128 UTF-8 bytes; provenance license/author/source URL limits are 128/256/2,048 bytes. Control characters, invalid identifiers, duplicate identities, bad revisions and nonfinite scalar values fail. Export inspects at most 100,000 source references, deduplicating into at most -1,024 entries. These are encoded/work limits, not a process-memory or latency guarantee. +1,024 entries. Rich export bounds retained unique definitions before whole-catalog +encoding, reserving 4 KiB for the envelope and counting each entry's pretty bytes plus +nested-line indentation. This conservative writer admission can refuse a catalog +close to 4 MiB even when a compact representation fits. These are encoded/work limits, +not a process-memory or latency guarantee. Native reads are bounded regular-file reads; browser reads check VFS size before cloning. Native no-clobber writes reuse atomic new-file publication; explicit replacement is atomic From ee4cb5d2fa56f6c9af223753fad85299cf54fbd2 Mon Sep 17 00:00:00 2001 From: 0xlillith <35337584+0xlillith@users.noreply.github.com> Date: Fri, 23 Oct 2026 21:50:12 +0200 Subject: [PATCH 2/2] test(library): preserve explicit downgrade and fallible UI regressions (#1062) Request scalar v1 explicitly in the card downgrade refusal regression; rich v2 remains the default lossless writer. Propagate fallible harness actions with ? in the shared clicked-catalog helper, preserving all assertions. No production code, limits or ignore changes. Fresh grouped IO/engine/UI tests, scoped strict Clippy and WASM pass on this exact tree. --- .../src/cmd/material_card_persistence_tests.rs | 8 ++++++-- crates/ui-egui/src/dialogs_library_tests.rs | 14 +++++++------- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/material_card_persistence_tests.rs b/crates/engine/src/cmd/material_card_persistence_tests.rs index 3934497cacc..6afe0d20fa6 100644 --- a/crates/engine/src/cmd/material_card_persistence_tests.rs +++ b/crates/engine/src/cmd/material_card_persistence_tests.rs @@ -168,8 +168,12 @@ fn scalar_catalog_refuses_card_export_without_creating_or_replacing_files_or_his std::fs::write(&file.0, b"keep existing catalog").unwrap(); } for overwrite in [false, true] { - let error = s.execute("library.export", &json!({"path":file.0,"overwrite":overwrite})).unwrap_err(); - assert!(error.to_string().contains("cannot preserve engineering cards")); + // The default writer is rich v2. Request scalar v1 explicitly so this + // regression still exercises refusal rather than a valid lossless copy. + let error = + s.execute("library.export", &json!({"path":file.0,"overwrite":overwrite,"format":solidcraft_io::catalog::V1_FORMAT})).unwrap_err(); + let message = error.to_string(); + assert!(message.contains("catalog v1") && message.contains("engineering cards"), "{message}"); if existing { assert_eq!(std::fs::read(&file.0).unwrap(), b"keep existing catalog"); } else { diff --git a/crates/ui-egui/src/dialogs_library_tests.rs b/crates/ui-egui/src/dialogs_library_tests.rs index 01444f6201d..4f53237c2d1 100644 --- a/crates/ui-egui/src/dialogs_library_tests.rs +++ b/crates/ui-egui/src/dialogs_library_tests.rs @@ -40,7 +40,7 @@ fn clicked_catalog(pbr: Option