From 582a285b5d33bba54f7141ae02416f31034afacf Mon Sep 17 00:00:00 2001 From: Khawar Zamman Wani Date: Mon, 2 Nov 2026 19:01:15 +0530 Subject: [PATCH] fix: enforce scoped PSD memory admission and complete retry integration --- Cargo.lock | 1 + apps/photocraft-cli/src/args.rs | 12 + apps/photocraft-cli/src/batch.rs | 2 +- apps/photocraft-cli/src/document.rs | 8 +- crates/automation/src/files.rs | 23 +- crates/automation/src/headless.rs | 16 +- crates/automation/src/rpc.rs | 51 ++- crates/automation/src/rpc/tests.rs | 30 ++ crates/automation/src/server.rs | 90 ++++- crates/engine/Cargo.toml | 1 + crates/engine/src/cmd/file_cmds.rs | 18 +- crates/engine/src/cmd/file_cmds/open.rs | 95 +++-- crates/engine/src/cmd/file_cmds/tests.rs | 137 +++++-- crates/engine/src/error.rs | 3 + crates/engine/src/jobs.rs | 196 +++++++--- crates/io/Cargo.toml | 2 + crates/io/src/flat.rs | 4 +- crates/io/src/lib.rs | 146 +++---- crates/io/src/memory.rs | 278 ++++++++++++-- crates/io/src/psd_budget/tests.rs | 146 ++++++- crates/io/src/psd_gate.rs | 170 +++++++-- crates/io/src/psd_import.rs | 83 +++- crates/io/src/tiff_layers.rs | 13 +- crates/ui-egui/Cargo.toml | 1 + crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/app/files.rs | 20 +- crates/ui-egui/src/control/dispatch.rs | 10 +- crates/ui-egui/src/dialogs/open_prompt.rs | 159 +++++--- crates/ui-egui/src/file_open.rs | 2 +- crates/ui-egui/src/file_open/tests.rs | 2 +- crates/ui-egui/src/jobs_ui.rs | 12 +- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/psd_open_tests.rs | 443 +++++++++++++++++++++- docs/development.md | 11 +- 34 files changed, 1865 insertions(+), 322 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b22b872d1d..e3ba377e6c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5283,6 +5283,7 @@ dependencies = [ "serde_json", "thiserror 2.0.21", "tiff", + "winsafe", "zune-core 0.5.3", "zune-jpegxl", ] diff --git a/apps/photocraft-cli/src/args.rs b/apps/photocraft-cli/src/args.rs index 91b99ef33b..c1772534fd 100644 --- a/apps/photocraft-cli/src/args.rs +++ b/apps/photocraft-cli/src/args.rs @@ -91,6 +91,9 @@ pub(crate) struct ConvertArgs { /// Allow an that is the file, replacing the original #[arg(long)] pub(crate) in_place: bool, + /// Explicitly approve high-memory PSD/PSB imports within the hard memory budget + #[arg(long)] + pub(crate) approve_high_memory: bool, #[command(flatten)] pub(crate) export: ExportArgs, } @@ -102,6 +105,9 @@ pub(crate) struct InfoArgs { /// One line of JSON instead of pretty-printed #[arg(long)] pub(crate) compact: bool, + /// Explicitly approve high-memory PSD/PSB imports within the hard memory budget + #[arg(long)] + pub(crate) approve_high_memory: bool, } /// Open a file (or start a new document), run engine commands in order, save the result @@ -130,6 +136,9 @@ pub(crate) struct RunArgs { /// Allow an --out that is the , replacing the original #[arg(long)] pub(crate) in_place: bool, + /// Explicitly approve high-memory PSD/PSB imports within the hard memory budget + #[arg(long)] + pub(crate) approve_high_memory: bool, #[command(flatten)] pub(crate) export: ExportArgs, /// `--cmd` and `--params` values in command-line order, set by [`parse`]. @@ -169,6 +178,9 @@ pub(crate) struct BatchArgs { /// originals; --in-place allows it #[arg(long)] pub(crate) in_place: bool, + /// Explicitly approve high-memory PSD/PSB imports within the hard memory budget + #[arg(long)] + pub(crate) approve_high_memory: bool, #[command(flatten)] pub(crate) export: ExportArgs, } diff --git a/apps/photocraft-cli/src/batch.rs b/apps/photocraft-cli/src/batch.rs index 02bb1bb702..a9f85fddb1 100644 --- a/apps/photocraft-cli/src/batch.rs +++ b/apps/photocraft-cli/src/batch.rs @@ -81,7 +81,7 @@ pub(crate) fn batch(a: &BatchArgs, out: &mut dyn Write, err: &mut dyn Write) -> // Steps that play another action find it in the set; the session's playback stack // stops an action that calls itself. h.session.actions.list = set.clone(); - h.open(input)?; + h.open_with_approval(input, a.approve_high_memory)?; for (id, p) in &actions { if photocraft_engine::actions_cmds::shell_view_command(id) || photocraft_engine::actions_cmds::shell_save_command(id) diff --git a/apps/photocraft-cli/src/document.rs b/apps/photocraft-cli/src/document.rs index 95d4c28288..941d58814f 100644 --- a/apps/photocraft-cli/src/document.rs +++ b/apps/photocraft-cli/src/document.rs @@ -30,7 +30,9 @@ pub(crate) fn convert(a: &ConvertArgs, _out: &mut dyn Write, err: &mut dyn Write let (input, output) = (&a.input, &a.output); let opts = ExportOptions::from(&a.export); refuse_overwriting_input(a.in_place, input, output)?; - let mut o = files::open(input)?; + let mut import_opts = photocraft_io::ImportOptions::default(); + import_opts.psd_high_memory_approved = a.approve_high_memory; + let mut o = files::open_with_options(input, &import_opts)?; // Preferences › Raw Defaults › Resolution at its default, as `run` and `info` open a raw. photocraft_engine::file_cmds::raw_defaults(&photocraft_engine::Session::new(), &o.warnings, &mut o.document); warn_all(err, &o.warnings); @@ -43,7 +45,7 @@ pub(crate) fn convert(a: &ConvertArgs, _out: &mut dyn Write, err: &mut dyn Write pub(crate) fn info(a: &InfoArgs, out: &mut dyn Write) -> Result { let file = &a.file; let mut h = Headless::trusted_local(); - let opened = h.open(file)?; + let opened = h.open_with_approval(file, a.approve_high_memory)?; let mut doc = h.inspect(None)?; let mut warnings = opened["warnings"].as_array().cloned().unwrap_or_default(); if let Some(st) = h.session.active() { @@ -86,7 +88,7 @@ pub(crate) fn run_cmds(a: &RunArgs, out: &mut dyn Write, err: &mut dyn Write) -> if let Some(out) = &a.out { refuse_overwriting_input(a.in_place, file, out)?; } - let o = h.open(file)?; + let o = h.open_with_approval(file, a.approve_high_memory)?; let ws: Vec = serde_json::from_value(o["warnings"].clone()).unwrap_or_default(); warn_all(err, &ws); reported_fonts.extend(ws); diff --git a/crates/automation/src/files.rs b/crates/automation/src/files.rs index 0b8ff103aa..bfacf1e19f 100644 --- a/crates/automation/src/files.rs +++ b/crates/automation/src/files.rs @@ -18,17 +18,27 @@ pub struct Opened { /// Decode a document that was read through a filesystem capability. pub fn open_bytes(name: &str, bytes: &[u8]) -> Result { + open_bytes_with_options(name, bytes, &photocraft_io::ImportOptions::default()) +} + +/// Decode a document that was read through a filesystem capability with custom import options. +pub fn open_bytes_with_options(name: &str, bytes: &[u8], opts: &photocraft_io::ImportOptions) -> Result { if Path::new(name).extension().is_some_and(|extension| extension.eq_ignore_ascii_case(photocraft_format::EXTENSION)) { let document = photocraft_format::load_from_bytes(bytes)?; return Ok(Opened { warnings: photocraft_io::open_warnings(&document), document, source_read_only: false }); } - let r = photocraft_io::import(name, bytes)?; + let r = photocraft_io::import_with_options(name, bytes, opts)?; Ok(Opened { document: r.document, warnings: r.warnings, source_read_only: r.source_read_only }) } /// Open a document from disk. Directory bundles and `.pcraft` ZIPs load /// natively; everything else goes through `photocraft-io` (PSD, PNG, …). pub fn open(path: &Path) -> Result { + open_with_options(path, &photocraft_io::ImportOptions::default()) +} + +/// Open a document from disk with custom import options. +pub fn open_with_options(path: &Path, opts: &photocraft_io::ImportOptions) -> Result { if path.is_dir() { let document = photocraft_format::load_path(path)?; return Ok(Opened { warnings: photocraft_io::open_warnings(&document), document, source_read_only: false }); @@ -38,17 +48,16 @@ pub fn open(path: &Path) -> Result { // convert or info of a 2 GB file does not hold the file in memory next to the document. #[cfg(any(unix, windows))] { - let r = - photocraft_io::import_file(&name, path, &photocraft_io::ImportOptions::default(), &photocraft_raster::Interrupt::NONE).map_err(|e| match e { - photocraft_io::IoError::Read(msg) => AutomationError::Io(msg), - e => e.into(), - })?; + let r = photocraft_io::import_file(&name, path, opts, &photocraft_raster::Interrupt::NONE).map_err(|e| match e { + photocraft_io::IoError::Read(msg) => AutomationError::Io(msg), + e => e.into(), + })?; Ok(Opened { document: r.document, warnings: r.warnings, source_read_only: r.source_read_only }) } #[cfg(not(any(unix, windows)))] { let bytes = photocraft_format::read_file(path).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?; - open_bytes(&name, &bytes) + open_bytes_with_options(&name, &bytes, opts) } } diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 8b08daa6aa..ca0158cee7 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -90,14 +90,26 @@ impl Headless { /// Open a file and make it the active document. pub fn open(&mut self, path: &Path) -> Result { + self.open_with_approval(path, false) + } + + /// Open a file with optional high-memory approval and make it the active document. + pub fn open_with_approval(&mut self, path: &Path, approve_high_memory: bool) -> Result { + let mut opts = photocraft_io::ImportOptions::default(); + opts.psd_high_memory_approved = approve_high_memory; + self.open_with_options(path, &opts) + } + + /// Open a file with custom import options and make it the active document. + pub fn open_with_options(&mut self, path: &Path, opts: &photocraft_io::ImportOptions) -> Result { let requested = path.to_str().ok_or_else(|| AutomationError::BadRequest("automation paths must be valid UTF-8".into()))?; let mut o = match &self.filesystem { Filesystem::Denied => return Err(AutomationError::BadRequest("automation filesystem access is not granted: read authority is absent".into())), - Filesystem::TrustedLocal => files::open(path)?, + Filesystem::TrustedLocal => files::open_with_options(path, opts)?, Filesystem::Workspace(workspace) => { let bytes = workspace.read(requested)?; let name = path.file_name().and_then(|name| name.to_str()).unwrap_or(requested); - files::open_bytes(name, &bytes)? + files::open_bytes_with_options(name, &bytes, opts)? } }; // Preferences › Raw Defaults › Resolution, as the app's File › Open applies it. diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index 92ece2b943..7608dc6922 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -61,6 +61,33 @@ pub const METHODS: &[&str] = &[ "methods", ]; +fn attach_memory_error_details(obj: &mut Value, err: &AutomationError) { + match err { + AutomationError::Import(photocraft_io::IoError::PsdApprovalRequired { required, soft_limit, hard_limit, available_ram }) + | AutomationError::Engine(photocraft_engine::EngineError::PsdApprovalRequired { required, soft_limit, hard_limit, available_ram, .. }) => { + if let Some(m) = obj.as_object_mut() { + m.insert("required".into(), json!(required)); + m.insert("soft".into(), json!(soft_limit)); + m.insert("softLimit".into(), json!(soft_limit)); + m.insert("hard".into(), json!(hard_limit)); + m.insert("hardLimit".into(), json!(hard_limit)); + if let Some(avail) = available_ram { + m.insert("available".into(), json!(avail)); + m.insert("availableRam".into(), json!(avail)); + } + } + } + AutomationError::Import(photocraft_io::IoError::PsdImportBudget { required, limit }) => { + if let Some(m) = obj.as_object_mut() { + m.insert("required".into(), json!(required)); + m.insert("hard".into(), json!(limit)); + m.insert("hardLimit".into(), json!(limit)); + } + } + _ => {} + } +} + fn bad(msg: impl Into) -> AutomationError { AutomationError::BadRequest(msg.into()) } @@ -107,10 +134,20 @@ impl Headless { "session.list" => Ok(self.session_list()), "doc.open" => { let path = str_of(&p, "path").ok_or_else(|| bad("doc.open needs `path`"))?; - self.open(&PathBuf::from(path)) + let approve = match p.get("approveHighMemory") { + None | Some(Value::Null) => false, + Some(Value::Bool(b)) => *b, + Some(_) => return Err(bad("`approveHighMemory` must be a boolean")), + }; + self.open_with_approval(&PathBuf::from(path), approve) } "doc.place" => { let path = str_of(&p, "path").ok_or_else(|| bad("doc.place needs `path`"))?; + if let Some(v) = p.get("approveHighMemory") { + if !v.is_boolean() { + return Err(bad("`approveHighMemory` must be a boolean")); + } + } let mut opts = p.as_object().cloned().unwrap_or_default(); opts.remove("path"); opts.remove("index"); @@ -224,7 +261,11 @@ impl Headless { let was_error = r.is_err(); let result = match r { Ok(v) => json!({"ok": true, "result": v}), - Err(e) => json!({"ok": false, "error": e.to_string()}), + Err(e) => { + let mut obj = json!({"ok": false, "error": e.to_string()}); + attach_memory_error_details(&mut obj, &e); + obj + } }; if let Err(error) = reply_budget.charge(&result) { failed += 1; @@ -262,7 +303,11 @@ pub fn respond(h: &Mutex, line: &str) -> Value { .unwrap_or_else(|_| Err(AutomationError::Other(format!("internal error: `{method}` panicked")))); match r { Ok(v) => json!({"id": id, "ok": true, "result": v}), - Err(e) => json!({"id": id, "ok": false, "error": e.to_string()}), + Err(e) => { + let mut obj = json!({"id": id, "ok": false, "error": e.to_string()}); + attach_memory_error_details(&mut obj, &e); + obj + } } } diff --git a/crates/automation/src/rpc/tests.rs b/crates/automation/src/rpc/tests.rs index 131df72413..b7ee7feb36 100644 --- a/crates/automation/src/rpc/tests.rs +++ b/crates/automation/src/rpc/tests.rs @@ -1028,3 +1028,33 @@ fn invalid_document_index_is_rejected_not_the_active_document() { assert_eq!(reply["ok"], true, "{reply}"); assert_eq!(count(&h), 1); } + +#[test] +fn approve_high_memory_rejects_invalid_types_and_formats_structured_error() { + let h = session(); + // Non-boolean approveHighMemory is rejected strictly + let reply = respond(&h, r#"{"method":"doc.open","params":{"path":"test.psd","approveHighMemory":"yes"}}"#); + assert_eq!(reply["ok"], false); + assert!(reply["error"].as_str().unwrap().contains("must be a boolean")); + + let reply_place = respond(&h, r#"{"method":"doc.place","params":{"path":"test.psd","approveHighMemory":123}}"#); + assert_eq!(reply_place["ok"], false); + assert!(reply_place["error"].as_str().unwrap().contains("must be a boolean")); + + // Verify attach_memory_error_details adds machine-readable fields + let mut err_obj = json!({"id": 1, "ok": false, "error": "test"}); + let auto_err = crate::AutomationError::Import(photocraft_io::IoError::PsdApprovalRequired { + required: 5000, + soft_limit: 2000, + hard_limit: 8000, + available_ram: Some(10000), + }); + super::attach_memory_error_details(&mut err_obj, &auto_err); + assert_eq!(err_obj["required"], 5000); + assert_eq!(err_obj["soft"], 2000); + assert_eq!(err_obj["softLimit"], 2000); + assert_eq!(err_obj["hard"], 8000); + assert_eq!(err_obj["hardLimit"], 8000); + assert_eq!(err_obj["available"], 10000); + assert_eq!(err_obj["availableRam"], 10000); +} diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index 544dbc90f1..8d053232df 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -50,6 +50,9 @@ pub struct DocIndex { pub struct OpenParams { /// Path beneath the configured automation read root: relative (forward slashes) or absolute. pub path: String, + /// Explicitly approve high-memory PSD/PSB imports that fit within the hard memory budget. + #[serde(default)] + pub approve_high_memory: Option, } #[derive(Debug, Default, Deserialize, JsonSchema)] @@ -483,7 +486,31 @@ fn png_result(png: &[u8], note: String) -> CallToolResult { fn to_result(r: Result) -> Result { Ok(match r { Ok(v) => ok_json(&v), - Err(e) => fail(e), + Err(e) => { + let mut obj = json!({"error": e.to_string()}); + match &e { + AutomationError::Import(photocraft_io::IoError::PsdApprovalRequired { required, soft_limit, hard_limit, available_ram }) + | AutomationError::Engine(photocraft_engine::EngineError::PsdApprovalRequired { required, soft_limit, hard_limit, available_ram, .. }) => { + obj["required"] = json!(required); + obj["soft"] = json!(soft_limit); + obj["softLimit"] = json!(soft_limit); + obj["hard"] = json!(hard_limit); + obj["hardLimit"] = json!(hard_limit); + if let Some(avail) = available_ram { + obj["available"] = json!(avail); + obj["availableRam"] = json!(avail); + } + } + AutomationError::Import(photocraft_io::IoError::PsdImportBudget { required, limit }) => { + obj["required"] = json!(required); + obj["hard"] = json!(limit); + obj["hardLimit"] = json!(limit); + } + _ => {} + } + let text = serde_json::to_string(&obj).unwrap_or_else(|_| e.to_string()); + CallToolResult::error(vec![Content::text(text)]) + } }) } @@ -631,13 +658,18 @@ impl PhotocraftMcp { #[tool(description = "Open an image or document file and make it active. Returns index, size and import warnings.")] async fn doc_open(&self, Parameters(p): Parameters) -> Result { let path = PathBuf::from(&p.path); - if let Some(r) = self.headless_op(move |h| h.open(&path)).await { + let approve = p.approve_high_memory.unwrap_or(false); + if let Some(r) = self.headless_op(move |h| h.open_with_approval(&path, approve)).await { return to_result(r); } let Some(b) = self.bridge_client() else { return Ok(no_backend()); }; - to_result(b.call("app.open", json!({"path": p.path})).await) + let mut params = json!({"path": p.path}); + if approve { + params["approveHighMemory"] = json!(true); + } + to_result(b.call("app.open", params).await) } #[tool( @@ -939,7 +971,36 @@ impl PhotocraftMcp { let was_error = response.is_err(); let result = match response { Ok(value) => json!({"ok": true, "result": value}), - Err(error) => json!({"ok": false, "error": error.to_string()}), + Err(error) => { + let mut obj = json!({"ok": false, "error": error.to_string()}); + match &error { + AutomationError::Import(photocraft_io::IoError::PsdApprovalRequired { required, soft_limit, hard_limit, available_ram }) + | AutomationError::Engine(photocraft_engine::EngineError::PsdApprovalRequired { + required, + soft_limit, + hard_limit, + available_ram, + .. + }) => { + obj["required"] = json!(required); + obj["soft"] = json!(soft_limit); + obj["softLimit"] = json!(soft_limit); + obj["hard"] = json!(hard_limit); + obj["hardLimit"] = json!(hard_limit); + if let Some(avail) = available_ram { + obj["available"] = json!(avail); + obj["availableRam"] = json!(avail); + } + } + AutomationError::Import(photocraft_io::IoError::PsdImportBudget { required, limit }) => { + obj["required"] = json!(required); + obj["hard"] = json!(limit); + obj["hardLimit"] = json!(limit); + } + _ => {} + } + obj + } }; if let Err(error) = reply_budget.charge(&result) { failed += 1; @@ -1255,6 +1316,27 @@ mod tests { assert_eq!(docs, 0, "the step after the budget ran out did not run"); } + #[tokio::test(flavor = "multi_thread")] + async fn mcp_doc_open_schema_and_structured_error() { + let schema = &PhotocraftMcp::tool_router().map["doc_open"].attr.input_schema; + assert_eq!(schema["properties"]["approve_high_memory"]["type"], "boolean"); + + let err = AutomationError::Import(photocraft_io::IoError::PsdApprovalRequired { + required: 6000, + soft_limit: 3000, + hard_limit: 9000, + available_ram: Some(12000), + }); + let res = to_result(Err(err)).unwrap(); + assert_eq!(res.is_error, Some(true)); + let text = &res.content.first().and_then(|c| c.as_text()).unwrap().text; + let v: Value = serde_json::from_str(text).unwrap(); + assert_eq!(v["required"], 6000); + assert_eq!(v["soft"], 3000); + assert_eq!(v["hard"], 9000); + assert_eq!(v["available"], 12000); + } + /// The MCP server applies finished jobs before every tool call too (#503). #[tokio::test(flavor = "multi_thread")] async fn mcp_tools_see_a_finished_background_job() { diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 9c63bfcab4..4c48527a77 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -61,6 +61,7 @@ photocraft-ipp = { workspace = true } [dev-dependencies] photocraft-affinity = { workspace = true, features = ["synth"] } +photocraft-io = { workspace = true, features = ["testgen"] } # Synthetic camera raw files for the open tests. photocraft-raw = { workspace = true, features = ["testgen"] } photocraft-testkit = { workspace = true } diff --git a/crates/engine/src/cmd/file_cmds.rs b/crates/engine/src/cmd/file_cmds.rs index 2dcf8fe84a..097cb54fad 100644 --- a/crates/engine/src/cmd/file_cmds.rs +++ b/crates/engine/src/cmd/file_cmds.rs @@ -68,6 +68,10 @@ pub(crate) fn native(_: &Session) -> std::result::Result<(), String> { if cfg!(target_arch = "wasm32") { Err("not available on the web (no file system)".into()) } else { Ok(()) } } +fn always(_: &Session) -> std::result::Result<(), String> { + Ok(()) +} + pub(crate) fn native_doc(s: &Session) -> std::result::Result<(), String> { native(s)?; has_doc(s) @@ -261,13 +265,21 @@ pub fn specs() -> Vec { native, open_as ), - spec!("file.approveMemory", "Approve High Memory PSD Import", &[], None, r##"{"id":u64,"approve":bool=true}"##, native, approve_memory), + spec!( + "file.approveMemory", + "Approve High Memory PSD Import", + &[], + None, + r##"{"id":u64,"approve":bool=true,"background":bool=true}"##, + always, + approve_memory + ), spec!( "file.placeEmbedded", "Place Embedded…", &["File"], None, - r##"{"path":str,"scale":%? (default: fit when larger than the canvas),"fit":bool? (default: Preferences > General > Resize Image During Place),"smartObject":bool? (default: Preferences > General > Always Create Smart Objects When Placing),"center":[x,y]?}"##, + r##"{"path":str,"scale":%? (default: fit when larger than the canvas),"fit":bool? (default: Preferences > General > Resize Image During Place),"smartObject":bool? (default: Preferences > General > Always Create Smart Objects When Placing),"center":[x,y]?,"approveHighMemory":bool=false (explicitly approve high memory usage)}"##, native_doc, |s, p| place(s, p, false) ), @@ -276,7 +288,7 @@ pub fn specs() -> Vec { "Place Linked…", &["File"], None, - r##"{"path":str,"scale":%?,"fit":bool? (default: Preferences > General > Resize Image During Place),"center":[x,y]?}"##, + r##"{"path":str,"scale":%?,"fit":bool? (default: Preferences > General > Resize Image During Place),"center":[x,y]?,"approveHighMemory":bool=false (explicitly approve high memory usage)}"##, native_doc, |s, p| place(s, p, true) ), diff --git a/crates/engine/src/cmd/file_cmds/open.rs b/crates/engine/src/cmd/file_cmds/open.rs index e9ad7ee998..46b5f71f2c 100644 --- a/crates/engine/src/cmd/file_cmds/open.rs +++ b/crates/engine/src/cmd/file_cmds/open.rs @@ -127,7 +127,13 @@ pub fn open_bytes_as_with_options( }; let mut opts = crate::jobs::import_options(s.prefs()); opts.psd_high_memory_approved = approve_high_memory; - let r = photocraft_io::import_with_options(&decode_name, bytes, &opts).map_err(|e| EngineError::Other(format!("{decode_name}: {e}")))?; + opts.psd_approved_estimate = None; + let r = photocraft_io::import_with_options(&decode_name, bytes, &opts).map_err(|e| match e { + photocraft_io::IoError::PsdApprovalRequired { required, soft_limit, hard_limit, available_ram } => { + EngineError::PsdApprovalRequired { name: decode_name.clone(), required, soft_limit, hard_limit, available_ram } + } + e => EngineError::Other(format!("{decode_name}: {e}")), + })?; let mut doc = r.document; tag_exr_colorspace(s, &decode_name, &mut doc); raw_defaults(s, &r.warnings, &mut doc); @@ -154,35 +160,66 @@ pub(super) fn open_as(s: &mut Session, p: &Value) -> Result { let path = str_param(p, "path", "file.openAs")?.to_string(); let bytes = read_file(&path)?; let as_ext = p.get("as").or_else(|| p.get("format")).and_then(Value::as_str); - let approve_high_memory = p.get("approveHighMemory").and_then(Value::as_bool).unwrap_or(false); + let approve_high_memory = match p.get("approveHighMemory") { + None | Some(Value::Null) => false, + Some(Value::Bool(b)) => *b, + Some(_) => { + return Err(EngineError::BadParams { cmd: "file.openAs".into(), msg: "expected boolean for \"approveHighMemory\"".into() }); + } + }; open_bytes_as_with_options(s, &path, &bytes, as_ext, Some(path.clone()), approve_high_memory) } pub(super) fn approve_memory(s: &mut Session, p: &Value) -> Result { let id = crate::file_cmds::u64_param(p, "id", "file.approveMemory")?; - let approve = p.get("approve").and_then(Value::as_bool).unwrap_or(true); + let approve = match p.get("approve") { + None | Some(Value::Null) => true, + Some(Value::Bool(b)) => *b, + Some(_) => { + return Err(EngineError::BadParams { cmd: "file.approveMemory".into(), msg: "expected boolean for \"approve\"".into() }); + } + }; + let background = match p.get("background") { + None | Some(Value::Null) => true, + Some(Value::Bool(b)) => *b, + Some(_) => { + return Err(EngineError::BadParams { cmd: "file.approveMemory".into(), msg: "expected boolean for \"background\"".into() }); + } + }; if !approve { - s.cancel_pending_preflight(id); + s.cancel_pending_preflight(id) + .ok_or_else(|| EngineError::BadParams { cmd: "file.approveMemory".into(), msg: format!("no pending high-memory preflight for id {id}") })?; return Ok(json!({"id": id, "approved": false, "cancelled": true})); } - let preflight = s - .take_pending_preflight(id) - .ok_or_else(|| EngineError::BadParams { cmd: "file.approveMemory".into(), msg: format!("no pending high-memory preflight for id {id}") })?; - if !preflight.fingerprint.matches(&preflight.source) { - return Err(EngineError::Other("the file has changed since it was checked; please try opening it again".into())); + #[cfg(target_arch = "wasm32")] + { + return Err(EngineError::Other("high-memory approval is not available on the web (WebAssembly limit is 1 GiB)".into())); } - let snapshot = photocraft_io::memory::MemorySnapshot::current(); - let budget = photocraft_io::memory::resolve_budget(snapshot, None); - if preflight.required > budget.hard_limit { - return Err(EngineError::Other(format!( - "available memory has decreased; opening this file needs {} bytes, exceeding current hard limit {} bytes", - preflight.required, budget.hard_limit - ))); - } - let started = s.start_open_approved(&preflight.name, preflight.source, preflight.confirm_damage)?; - match started { - crate::jobs::Started::Done(v) => Ok(json!({"id": id, "approved": true, "result": v})), - crate::jobs::Started::Job(job_id) => Ok(json!({"id": id, "approved": true, "job": job_id.0})), + #[cfg(not(target_arch = "wasm32"))] + { + let preflight = s + .take_pending_preflight(id) + .ok_or_else(|| EngineError::BadParams { cmd: "file.approveMemory".into(), msg: format!("no pending high-memory preflight for id {id}") })?; + let snapshot = photocraft_io::memory::MemorySnapshot::current(); + let budget = photocraft_io::memory::resolve_budget(snapshot, None); + if preflight.required > budget.hard_limit { + return Err(EngineError::Other(format!( + "available memory has decreased; opening this file needs {} bytes, exceeding current hard limit {} bytes", + preflight.required, budget.hard_limit + ))); + } + let started = s.start_open_approved_with_background( + &preflight.name, + preflight.source, + preflight.confirm_damage, + Some(preflight.required), + Some(preflight.fingerprint), + background, + )?; + match started { + crate::jobs::Started::Done(v) => Ok(json!({"id": id, "approved": true, "result": v})), + crate::jobs::Started::Job(job_id) => Ok(json!({"id": id, "approved": true, "job": job_id.0})), + } } } @@ -201,10 +238,22 @@ pub fn place_bytes(s: &mut Session, name: &str, bytes: Vec, linked: Option false, + Some(Value::Bool(b)) => *b, + Some(_) => { + return Err(EngineError::BadParams { cmd: "file.placeEmbedded".into(), msg: "expected boolean for \"approveHighMemory\"".into() }); + } + }; let mut opts = crate::jobs::import_options(s.prefs()); opts.psd_high_memory_approved = approve; - let imported = photocraft_io::import_with_options(name, &bytes, &opts).map_err(|e| EngineError::Other(format!("{name}: {e}")))?; + opts.psd_approved_estimate = None; + let imported = photocraft_io::import_with_options(name, &bytes, &opts).map_err(|e| match e { + photocraft_io::IoError::PsdApprovalRequired { required, soft_limit, hard_limit, available_ram } => { + EngineError::PsdApprovalRequired { name: name.to_string(), required, soft_limit, hard_limit, available_ram } + } + e => EngineError::Other(format!("{name}: {e}")), + })?; if imported.preview_only { return Err(EngineError::Other(format!( "{name}: only this Affinity file's embedded preview could be read; open it with File › Open to see the warning, or export PSD or PNG from Affinity before using it here" diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index b76fd74c9c..958565084c 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -1996,22 +1996,52 @@ fn approve_memory_validates_parameters_and_unknown_ids() { assert!(matches!(s.execute("file.approveMemory", json!({})), Err(EngineError::BadParams { .. }))); assert!(matches!(s.execute("file.approveMemory", json!({"id": "not_a_number"})), Err(EngineError::BadParams { .. }))); assert!(matches!(s.execute("file.approveMemory", json!({"id": 12345})), Err(EngineError::BadParams { .. }))); + assert!( + matches!(s.execute("file.approveMemory", json!({"id": 12345, "approve": false})), Err(EngineError::BadParams { .. })), + "unknown id on cancel must fail" + ); + assert!( + matches!(s.execute("file.approveMemory", json!({"id": 12345, "approve": "true"})), Err(EngineError::BadParams { .. })), + "wrong approve type string must BadParams" + ); + assert!( + matches!(s.execute("file.approveMemory", json!({"id": 12345, "approve": 1})), Err(EngineError::BadParams { .. })), + "wrong approve type int must BadParams" + ); + assert!( + matches!(s.execute("file.openAs", json!({"path": "a.psd", "approveHighMemory": "true"})), Err(EngineError::BadParams { .. })), + "wrong approveHighMemory on openAs must BadParams" + ); + assert!( + matches!(s.execute("file.placeEmbedded", json!({"path": "a.psd", "approveHighMemory": 1})), Err(EngineError::BadParams { .. })), + "wrong approveHighMemory on placeEmbedded must BadParams" + ); + assert!( + matches!(s.execute("file.approveMemory", json!({"id": 12345, "background": "true"})), Err(EngineError::BadParams { .. })), + "wrong background type string must BadParams" + ); + assert!( + matches!(s.execute("file.approveMemory", json!({"id": 12345, "background": 1})), Err(EngineError::BadParams { .. })), + "wrong background type int must BadParams" + ); } #[test] fn approve_memory_cancels_and_removes_pending_preflight() { let mut s = Session::new(); - let id = s.store_pending_preflight(crate::jobs::PendingPsdPreflight { - id: 0, - name: "test.psd".into(), - source: crate::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![1, 2, 3])), - fingerprint: crate::jobs::SourceFingerprint::of(&crate::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![1, 2, 3]))).unwrap(), - required: 1000, - soft_limit: 500, - hard_limit: 2000, - available_ram: Some(4000), - confirm_damage: true, - }); + let id = s + .store_pending_preflight(crate::jobs::PendingPsdPreflight { + id: 0, + name: "test.psd".into(), + source: crate::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![1, 2, 3])), + fingerprint: crate::jobs::SourceFingerprint::of(&crate::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![1, 2, 3]))).unwrap(), + required: 1000, + soft_limit: 500, + hard_limit: 2000, + available_ram: Some(4000), + confirm_damage: true, + }) + .unwrap(); let res = s.execute("file.approveMemory", json!({"id": id, "approve": false})).unwrap(); assert_eq!(res["approved"], false); assert_eq!(res["cancelled"], true); @@ -2027,17 +2057,19 @@ fn approve_memory_refuses_when_source_changes_before_confirmation() { let mut s = Session::new(); let src = crate::jobs::OpenSource::Path(path.clone()); let fp = crate::jobs::SourceFingerprint::of(&src).unwrap(); - let id = s.store_pending_preflight(crate::jobs::PendingPsdPreflight { - id: 0, - name: "change.psd".into(), - source: src, - fingerprint: fp, - required: 1000, - soft_limit: 500, - hard_limit: 2000, - available_ram: Some(4000), - confirm_damage: true, - }); + let id = s + .store_pending_preflight(crate::jobs::PendingPsdPreflight { + id: 0, + name: "change.psd".into(), + source: src, + fingerprint: fp, + required: 1000, + soft_limit: 500, + hard_limit: 2000, + available_ram: Some(4000), + confirm_damage: true, + }) + .unwrap(); // Modify file on disk std::fs::write(&path, b"changed content longer").unwrap(); @@ -2052,17 +2084,19 @@ fn approve_memory_refuses_when_available_ram_decreases() { let mut s = Session::new(); let src = crate::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 16])); let fp = crate::jobs::SourceFingerprint::of(&src).unwrap(); - let id = s.store_pending_preflight(crate::jobs::PendingPsdPreflight { - id: 0, - name: "ram_drop.psd".into(), - source: src, - fingerprint: fp, - required: 8 * gb, - soft_limit: 6 * gb, - hard_limit: 9 * gb, - available_ram: Some(12 * gb), - confirm_damage: true, - }); + let id = s + .store_pending_preflight(crate::jobs::PendingPsdPreflight { + id: 0, + name: "ram_drop.psd".into(), + source: src, + fingerprint: fp, + required: 8 * gb, + soft_limit: 6 * gb, + hard_limit: 9 * gb, + available_ram: Some(12 * gb), + confirm_damage: true, + }) + .unwrap(); // Memory drops: only 6 GiB available -> H = 4.5 GiB < 8 GiB let snap_low = photocraft_io::memory::MemorySnapshot { available_ram: Some(6 * gb), swap_free: None, commit_headroom: None }; @@ -2071,3 +2105,40 @@ fn approve_memory_refuses_when_available_ram_decreases() { assert!(res.is_err(), "decreased memory must refuse"); }); } + +#[test] +fn pending_preflights_cap_fails_closed() { + let mut s = Session::new(); + let src = crate::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 4])); + let fp = crate::jobs::SourceFingerprint::of(&src).unwrap(); + for i in 0..crate::jobs::Session::MAX_PENDING_PREFLIGHTS { + assert!( + s.store_pending_preflight(crate::jobs::PendingPsdPreflight { + id: 0, + name: format!("file_{i}.psd"), + source: src.clone(), + fingerprint: fp.clone(), + required: 1000, + soft_limit: 500, + hard_limit: 2000, + available_ram: Some(4000), + confirm_damage: true, + }) + .is_ok() + ); + } + assert!( + s.store_pending_preflight(crate::jobs::PendingPsdPreflight { + id: 0, + name: "overflow.psd".into(), + source: src, + fingerprint: fp, + required: 1000, + soft_limit: 500, + hard_limit: 2000, + available_ram: Some(4000), + confirm_damage: true, + }) + .is_err() + ); +} diff --git a/crates/engine/src/error.rs b/crates/engine/src/error.rs index 323d3f5203..1a8342099d 100644 --- a/crates/engine/src/error.rs +++ b/crates/engine/src/error.rs @@ -18,6 +18,9 @@ pub enum EngineError { /// ids are not positions (#5058). #[error("no such layer {}; {known}", id.0)] UnknownLayer { id: LayerId, known: String }, + /// Opening a PSD/PSB file requires explicit high-memory confirmation. + #[error("opening “{name}” requires explicit memory approval: {required} bytes required (soft limit {soft_limit}, hard limit {hard_limit})")] + PsdApprovalRequired { name: String, required: u64, soft_limit: u64, hard_limit: u64, available_ram: Option }, #[error("{0}")] Other(String), /// A background job was cancelled (see [`jobs`]); nothing changed. diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs index f7f55d08c2..c6f5623036 100644 --- a/crates/engine/src/jobs.rs +++ b/crates/engine/src/jobs.rs @@ -531,43 +531,52 @@ pub fn import_options(prefs: &crate::prefs::Preferences) -> photocraft_io::Impor /// Fingerprint verifying that a source has not changed between preflight and approval. #[derive(Clone, Debug, PartialEq, Eq)] pub enum SourceFingerprint { - Bytes { len: usize, hash: [u8; 32] }, - Path { path: String, len: u64, modified_nanos: u128 }, + Bytes { + len: usize, + identity: usize, + }, + Path { + path: String, + len: u64, + modified: std::time::SystemTime, + #[cfg(unix)] + dev: u64, + #[cfg(unix)] + ino: u64, + }, } impl SourceFingerprint { pub fn of(source: &OpenSource) -> Result { match source { - OpenSource::Bytes(b) => { - let hash = *blake3::hash(b).as_bytes(); - Ok(SourceFingerprint::Bytes { len: b.len(), hash }) - } + OpenSource::Bytes(b) => Ok(SourceFingerprint::Bytes { len: b.len(), identity: Arc::as_ptr(b) as usize }), OpenSource::Path(p) => { let meta = std::fs::metadata(p).map_err(|e| EngineError::Other(format!("{p}: {e}")))?; let len = meta.len(); - let modified_nanos = meta.modified().ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map_or(0, |d| d.as_nanos()); - Ok(SourceFingerprint::Path { path: p.clone(), len, modified_nanos }) + let modified = meta.modified().map_err(|e| EngineError::Other(format!("{p}: failed to read modification time: {e}")))?; + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + let dev = meta.dev(); + let ino = meta.ino(); + Ok(SourceFingerprint::Path { path: p.clone(), len, modified, dev, ino }) + } + #[cfg(not(unix))] + { + Ok(SourceFingerprint::Path { path: p.clone(), len, modified }) + } } } } - pub fn matches(&self, source: &OpenSource) -> bool { - match (self, source) { - (SourceFingerprint::Bytes { len, hash }, OpenSource::Bytes(b)) => b.len() == *len && blake3::hash(b).as_bytes() == hash, - (SourceFingerprint::Path { path, len, modified_nanos }, OpenSource::Path(p)) => { - if path != p { - return false; - } - match std::fs::metadata(p) { - Ok(meta) => { - let cur_len = meta.len(); - let cur_mod = meta.modified().ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map_or(0, |d| d.as_nanos()); - cur_len == *len && cur_mod == *modified_nanos - } - Err(_) => false, - } - } - _ => false, + pub fn matches(&self, other: &Self) -> bool { + self == other + } + + pub fn matches_source(&self, source: &OpenSource) -> bool { + match Self::of(source) { + Ok(cur) => self.matches(&cur), + Err(_) => false, } } } @@ -611,11 +620,21 @@ impl Session { /// result is `{held, name, warnings, color}` (`color` the question): take it with /// [`Session::take_held_open`] once answered. - pub fn store_pending_preflight(&mut self, mut preflight: PendingPsdPreflight) -> u64 { - self.next_pending_preflight = self.next_pending_preflight.wrapping_add(1); + pub const MAX_PENDING_PREFLIGHTS: usize = 32; + + pub fn store_pending_preflight(&mut self, mut preflight: PendingPsdPreflight) -> Result { + if self.pending_preflights.len() >= Self::MAX_PENDING_PREFLIGHTS { + return Err(EngineError::Other("too many pending high-memory preflights waiting for confirmation".into())); + } + loop { + self.next_pending_preflight = self.next_pending_preflight.checked_add(1).unwrap_or(1); + if self.next_pending_preflight != 0 && !self.pending_preflights.iter().any(|p| p.id == self.next_pending_preflight) { + break; + } + } preflight.id = self.next_pending_preflight; self.pending_preflights.push(preflight); - self.next_pending_preflight + Ok(self.next_pending_preflight) } pub fn take_pending_preflight(&mut self, id: u64) -> Option { @@ -631,46 +650,91 @@ impl Session { self.pending_preflights.clear(); } - pub fn start_open_approved(&mut self, name: &str, source: OpenSource, confirm_damage: bool) -> Result { - self.start_open_inner(name, source, confirm_damage, true) + pub fn start_open_approved( + &mut self, + name: &str, + source: OpenSource, + confirm_damage: bool, + approved_estimate: Option, + expected_fingerprint: Option, + ) -> Result { + self.start_open_approved_with_background(name, source, confirm_damage, approved_estimate, expected_fingerprint, true) + } + + pub fn start_open_approved_with_background( + &mut self, + name: &str, + source: OpenSource, + confirm_damage: bool, + approved_estimate: Option, + expected_fingerprint: Option, + background: bool, + ) -> Result { + self.start_open_inner(name, source, confirm_damage, true, approved_estimate, expected_fingerprint, background) } pub fn start_open(&mut self, name: &str, source: OpenSource) -> Result { - self.start_open_inner(name, source, false, false) + self.start_open_inner(name, source, false, false, None, None, true) } /// Interactive opening: hold a damaged PSD until the user answers a damage /// confirmation, without changing import or subsequent save behaviour. /// Headless callers keep using [`Self::start_open`]. pub fn start_open_for_user(&mut self, name: &str, source: OpenSource) -> Result { - self.start_open_inner(name, source, true, false) + self.start_open_for_user_with_background(name, source, true) + } + + pub fn start_open_for_user_with_background(&mut self, name: &str, source: OpenSource, background: bool) -> Result { + self.start_open_inner(name, source, true, false, None, None, background) } /// Decodes a file in a job and optionally holds damaged PSD content for /// interactive confirmation while leaving headless opens non-interactive. - fn start_open_inner(&mut self, name: &str, source: OpenSource, confirm_damage: bool, approve_high_memory: bool) -> Result { + // Keep the worker and apply closures together with their execution options. + #[allow(clippy::too_many_arguments)] + fn start_open_inner( + &mut self, + name: &str, + source: OpenSource, + confirm_damage: bool, + approve_high_memory: bool, + approved_estimate: Option, + expected_fingerprint: Option, + background: bool, + ) -> Result { let label = format!("Opening {name}"); let name_w = name.to_string(); let name_a = name.to_string(); let mut opts = import_options(self.prefs()); opts.psd_high_memory_approved = approve_high_memory; - self.start_job( + opts.psd_approved_estimate = approved_estimate; + let test_memory_scope = photocraft_io::memory::TestMemoryScope::capture(); + enum WorkResult { + Decoded((photocraft_io::ImportResult, bool)), + PreflightNeeded { required: u64, soft_limit: u64, hard_limit: u64, available_ram: Option, source: OpenSource, fingerprint: SourceFingerprint }, + } + self.start_job_with_spawn( OPEN_JOB, json!({"name": name}), &label, false, + background, move |ctx| { + let _test_memory = test_memory_scope.enter(); ctx.progress(0.0, "Reading"); - enum WorkResult { - Decoded((photocraft_io::ImportResult, bool)), - PreflightNeeded { - required: u64, - soft_limit: u64, - hard_limit: u64, - available_ram: Option, - source: OpenSource, - fingerprint: SourceFingerprint, - }, + + // Identity lookup is best-effort for ordinary opens, but mandatory if a + // file is held for confirmation. Valid non-PSD files do not require timestamps. + let initial_fingerprint = (confirm_damage || expected_fingerprint.is_some()).then(|| SourceFingerprint::of(&source)).transpose(); + if let Some(expected) = &expected_fingerprint { + let cur = initial_fingerprint + .as_ref() + .map_err(|e| EngineError::Other(e.to_string()))? + .as_ref() + .ok_or_else(|| EngineError::Other("missing source identity".into()))?; + if !expected.matches(cur) { + return Err(EngineError::Other("the file has changed since it was checked; please try opening it again".into())); + } } let outcome = match source { @@ -683,8 +747,19 @@ impl Session { Err(photocraft_io::IoError::PsdApprovalRequired { required, soft_limit, hard_limit, available_ram }) if confirm_damage => { let src = OpenSource::Bytes(bytes); let fingerprint = SourceFingerprint::of(&src)?; + let initial = initial_fingerprint + .as_ref() + .map_err(|e| EngineError::Other(e.to_string()))? + .as_ref() + .ok_or_else(|| EngineError::Other("missing source identity".into()))?; + if !initial.matches(&fingerprint) { + return Err(EngineError::Other("the file changed while checking its memory requirements; please open it again".into())); + } WorkResult::PreflightNeeded { required, soft_limit, hard_limit, available_ram, source: src, fingerprint } } + Err(photocraft_io::IoError::PsdApprovalRequired { required, soft_limit, hard_limit, available_ram }) => { + return Err(EngineError::PsdApprovalRequired { name: name_w.clone(), required, soft_limit, hard_limit, available_ram }); + } Err(photocraft_io::IoError::Cancelled) => return Err(EngineError::Cancelled), Err(e) => return Err(EngineError::Other(e.to_string())), } @@ -696,8 +771,19 @@ impl Session { Err(photocraft_io::IoError::PsdApprovalRequired { required, soft_limit, hard_limit, available_ram }) if confirm_damage => { let src = OpenSource::Path(p); let fingerprint = SourceFingerprint::of(&src)?; + let initial = initial_fingerprint + .as_ref() + .map_err(|e| EngineError::Other(e.to_string()))? + .as_ref() + .ok_or_else(|| EngineError::Other("missing source identity".into()))?; + if !initial.matches(&fingerprint) { + return Err(EngineError::Other("the file changed while checking its memory requirements; please open it again".into())); + } WorkResult::PreflightNeeded { required, soft_limit, hard_limit, available_ram, source: src, fingerprint } } + Err(photocraft_io::IoError::PsdApprovalRequired { required, soft_limit, hard_limit, available_ram }) => { + return Err(EngineError::PsdApprovalRequired { name: name_w.clone(), required, soft_limit, hard_limit, available_ram }); + } Err(photocraft_io::IoError::Cancelled) => return Err(EngineError::Cancelled), Err(e) => return Err(EngineError::Other(e.to_string())), } @@ -730,7 +816,7 @@ impl Session { hard_limit, available_ram, confirm_damage, - }); + })?; Ok(json!({ "pendingPreflight": id, "name": name_a, @@ -775,9 +861,25 @@ impl Session { work: impl FnOnce(&JobCtx) -> Result + Send + 'static, apply: impl FnOnce(&mut Session, T) -> Result + Send + 'static, ) -> Result { - self.jobs.spawn = true; + self.start_job_with_spawn(command, params, label, lock_document, true, work, apply) + } + + // Keep the worker and apply closures together with their execution options. + #[allow(clippy::too_many_arguments)] + pub fn start_job_with_spawn( + &mut self, + command: &str, + params: Value, + label: &str, + lock_document: bool, + spawn: bool, + work: impl FnOnce(&JobCtx) -> Result + Send + 'static, + apply: impl FnOnce(&mut Session, T) -> Result + Send + 'static, + ) -> Result { + let prev_spawn = self.jobs.spawn; + self.jobs.spawn = spawn && !cfg!(target_arch = "wasm32"); let r = run(self, label, lock_document, work, apply); - self.jobs.spawn = false; + self.jobs.spawn = prev_spawn; let pending = self.jobs.pending.take(); match (r, pending) { (Err(e), Some(job)) => { diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index 9fe5497f5c..ef6ddffc68 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -14,6 +14,8 @@ workspace = true corpus = [] # HEIC/HEIF decode (forwarded to photocraft-codecs; see its `heif` feature). heif = ["photocraft-codecs/heif"] +# Test support for synthetic memory injection and verification across crates. +testgen = [] [dependencies] photocraft-geom = { workspace = true } diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rs index 44908d8af5..803a09e580 100644 --- a/crates/io/src/flat.rs +++ b/crates/io/src/flat.rs @@ -16,7 +16,7 @@ const BAND_BYTES: usize = 32 << 20; /// Decodes a flat image into a single-layer document; a TIFF with Photoshop layer data opens /// layered (see [`crate::tiff_layers`]). pub fn import_flat(name: &str, bytes: &[u8]) -> Result { - import_flat_with_limit(name, bytes, 0) + import_flat_with_limit(name, bytes, crate::DEFAULT_PSD_IMPORT_PIXEL_BYTES) } /// [`import_flat`] with the caller's PSD pixel allowance, which a layered TIFF is held to. @@ -24,7 +24,7 @@ pub(crate) fn import_flat_with_limit(name: &str, bytes: &[u8], pixel_limit: u64) // Detected once; every step below branches on it. let format = codecs::detect(bytes); if format == Some(Format::Tiff) { - let limit = if pixel_limit > 0 { pixel_limit } else { crate::memory::resolve_budget(crate::memory::MemorySnapshot::current(), None).hard_limit }; + let limit = if pixel_limit > 0 { pixel_limit } else { crate::DEFAULT_PSD_IMPORT_PIXEL_BYTES }; return import_tiff_page_with_limit(name, bytes, None, limit); } let img = codecs::decode_as(format.ok_or(codecs::CodecError::UnknownFormat)?, bytes)?; diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index 550cc43588..5b5cea69a0 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -66,7 +66,7 @@ pub use pcraft_cache::PcraftExportCache; pub mod pixels; pub mod psd_budget; mod psd_export; -pub mod psd_gate; +mod psd_gate; mod psd_import; pub use psd_budget::{DEFAULT_PSD_IMPORT_PIXEL_BYTES, PsdMemoryEstimate, estimate as estimate_psd_memory}; pub mod psd_thumbnail; @@ -360,6 +360,9 @@ pub struct ImportOptions { pub psd_max_pixel_bytes: u64, /// Explicit one-shot authorization for imports that exceed the soft budget but fit within the hard budget. pub psd_high_memory_approved: bool, + /// Optional estimate limit for high-memory approval. When set, approval only applies if + /// the fresh preflight estimate does not exceed this amount. + pub psd_approved_estimate: Option, } impl Default for ImportOptions { @@ -369,6 +372,7 @@ impl Default for ImportOptions { demosaic: raw::Demosaic::default(), psd_max_pixel_bytes: 0, psd_high_memory_approved: false, + psd_approved_estimate: None, } } } @@ -411,46 +415,74 @@ fn import_psd( name: &str, ctl: &photocraft_raster::Interrupt, damaged: &mut bool, - caller_limit: u64, - high_memory_approved: bool, + opts: &ImportOptions, parse: impl FnOnce( &dyn Fn(&PsdFile) -> photocraft_psd::Result, &dyn Fn(&PsdFile) -> bool, ) -> photocraft_psd::Result<(PsdFile, Option>>)>, ) -> Result { - // A merged image the import reads is decoded with the parse: a ZIP one is inflated once. - // A failed read of the file (one parsed from its source) is a read error, as reading the - // whole file first would report it. let preflight_error = std::cell::RefCell::new(None); + let admission_guard: std::cell::RefCell> = std::cell::RefCell::new(None); + let parsed = parse( &|file| { // Only an import that keeps the layer tree is bound by the group nesting cap. let depth = if psd_import::can_recover_layers(file) { psd_import::check_group_depth(file) } else { Ok(()) }; - let checked = depth.and_then(|()| { + let preflight_check: Result = (|| { + depth?; let est = psd_budget::estimate(file)?; - let snapshot = memory::MemorySnapshot::current(); - let limit_opt = (caller_limit > 0).then_some(caller_limit); - let budget = memory::resolve_budget(snapshot, limit_opt); - match budget.decide(est.total_bytes) { - memory::BudgetDecision::Automatic => Ok(()), - memory::BudgetDecision::RequiresApproval if high_memory_approved => Ok(()), - memory::BudgetDecision::RequiresApproval => Err(IoError::PsdApprovalRequired { - required: est.total_bytes, - soft_limit: budget.soft_limit, - hard_limit: budget.hard_limit, - available_ram: budget.available_ram, - }), - memory::BudgetDecision::Refused => Err(IoError::PsdImportBudget { required: est.total_bytes, limit: budget.hard_limit }), + + if psd_gate::is_holding_admission() { + // Nested import: count against shared remaining allowance, never reset parent on nested import + psd_gate::consume_attempt_allowance(est.total_bytes)?; + let guard = psd_gate::acquire_decode_admission(ctl)?; + *admission_guard.borrow_mut() = Some(guard); + return Ok(psd_import::merged_needed(file)); + } + + // 1. Initial admission check BEFORE waiting on or acquiring the gate. + // Invalid or unapproved files fail fast without blocking other decodes or acquiring gate. + memory::evaluate_psd_admission( + est.total_bytes, + opts.psd_max_pixel_bytes, + opts.psd_high_memory_approved, + opts.psd_approved_estimate, + memory::MemorySnapshot::current(), + )?; + + // 2. Cancellation-aware gate acquisition BEFORE any merged or layer pixel decoding/inflation. + let guard = psd_gate::acquire_decode_admission(ctl)?; + + // 3. Re-evaluate adaptive budget immediately after gate acquisition. + // If available memory dropped while waiting for gate, this returns Err, + // guard is dropped (releasing gate immediately), and error is returned before prompting. + let outcome = memory::evaluate_psd_admission( + est.total_bytes, + opts.psd_max_pixel_bytes, + opts.psd_high_memory_approved, + opts.psd_approved_estimate, + memory::MemorySnapshot::current(), + )?; + + // Initialize enclosing attempt allowance for any nested decodes. + psd_gate::set_active_attempt_budget(outcome.authorized_total.saturating_sub(est.total_bytes)); + + // Retain guard across parse and conversion + *admission_guard.borrow_mut() = Some(guard); + Ok(psd_import::merged_needed(file)) + })(); + + match preflight_check { + Ok(want_merged) => Ok(want_merged), + Err(error) => { + *preflight_error.borrow_mut() = Some(error); + Err(PsdError::LimitExceeded("PSD import preflight refused the file")) } - }); - if let Err(error) = checked { - *preflight_error.borrow_mut() = Some(error); - return Err(PsdError::LimitExceeded("PSD import preflight refused the file")); } - Ok(psd_import::merged_needed(file)) }, &psd_import::can_recover_layers, ); + if let Some(error) = preflight_error.into_inner() { return Err(error); } @@ -462,30 +494,6 @@ fn import_psd( ctl.check().map_err(|_| IoError::Cancelled)?; ctl.progress(0.05); - // Acquire process-wide admission gate to prevent concurrent decodes spending the same headroom - let _admission = psd_gate::acquire_decode_admission(ctl)?; - - // Recheck memory availability immediately before decoding - let snapshot_recheck = memory::MemorySnapshot::current(); - let limit_opt = (caller_limit > 0).then_some(caller_limit); - let budget_recheck = memory::resolve_budget(snapshot_recheck, limit_opt); - let est = psd_budget::estimate(&file)?; - match budget_recheck.decide(est.total_bytes) { - memory::BudgetDecision::Automatic => {} - memory::BudgetDecision::RequiresApproval if high_memory_approved => {} - memory::BudgetDecision::RequiresApproval => { - return Err(IoError::PsdApprovalRequired { - required: est.total_bytes, - soft_limit: budget_recheck.soft_limit, - hard_limit: budget_recheck.hard_limit, - available_ram: budget_recheck.available_ram, - }); - } - memory::BudgetDecision::Refused => { - return Err(IoError::PsdImportBudget { required: est.total_bytes, limit: budget_recheck.hard_limit }); - } - } - // Read before the conversion, which moves the global blocks into the document. let txt2 = file.global_blocks.iter().find(|b| &b.key == b"Txt2").and_then(|b| photocraft_text::psd::parse_txt2(&b.data)); let (mut document, warnings, psd_damaged, fatal_error) = psd_import::psd_to_document_owned(file, ctl, merged).ok_or(IoError::Cancelled)?; @@ -521,29 +529,37 @@ pub fn import_file_for_open_with( let bytes = photocraft_format::read_file(path).map_err(read_failed)?; return import_for_open_with(name, &bytes, opts, ctl); } - import_source_with_limit(name, photocraft_psd::Source::new(source), ctl, opts.psd_max_pixel_bytes, opts.psd_high_memory_approved) + import_source_with_options(name, photocraft_psd::Source::new(source), ctl, opts) } /// [`import_file_for_open_with`] for a PSD/PSB in any [`photocraft_psd::ReadAt`] source. pub fn import_source_for_open_with(name: &str, source: photocraft_psd::Source, ctl: &photocraft_raster::Interrupt) -> Result<(ImportResult, bool), IoError> { - import_source_with_limit(name, source, ctl, 0, false) + import_source_with_options(name, source, ctl, &ImportOptions::default()) } -fn import_source_with_limit( +/// [`import_source_for_open_with`] with custom import options. +pub fn import_source_with_options( + name: &str, + source: photocraft_psd::Source, + ctl: &photocraft_raster::Interrupt, + opts: &ImportOptions, +) -> Result<(ImportResult, bool), IoError> { + ctl.check().map_err(|_| IoError::Cancelled)?; + let mut damaged = false; + let r = import_psd(name, ctl, &mut damaged, opts, |want, recover| PsdFile::from_source_and_merged_preflight(source, want, recover))?; + ctl.check().map_err(|_| IoError::Cancelled)?; + ctl.progress(1.0); + Ok((r, damaged)) +} + +pub(crate) fn import_source_with_limit( name: &str, source: photocraft_psd::Source, ctl: &photocraft_raster::Interrupt, pixel_limit: u64, - high_memory_approved: bool, ) -> Result<(ImportResult, bool), IoError> { - ctl.check().map_err(|_| IoError::Cancelled)?; - let mut damaged = false; - let r = import_psd(name, ctl, &mut damaged, pixel_limit, high_memory_approved, |want, recover| { - PsdFile::from_source_and_merged_preflight(source, want, recover) - })?; - ctl.check().map_err(|_| IoError::Cancelled)?; - ctl.progress(1.0); - Ok((r, damaged)) + let opts = ImportOptions { psd_max_pixel_bytes: pixel_limit, ..Default::default() }; + import_source_with_options(name, source, ctl, &opts) } /// [`import_file_for_open_with`] without the damage flag. @@ -563,9 +579,7 @@ fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, o // Magic first: an Affinity file renamed .psd is still Affinity (#5258 corpus // preview_never_saves_back_to_its_native_or_renamed_source). if is_psd(bytes) { - return import_psd(name, ctl, damaged, opts.psd_max_pixel_bytes, opts.psd_high_memory_approved, |want, recover| { - PsdFile::from_bytes_and_merged_preflight(bytes, want, recover) - }); + return import_psd(name, ctl, damaged, opts, |want, recover| PsdFile::from_bytes_and_merged_preflight(bytes, want, recover)); } if affinity::is_affinity(bytes) || affinity::has_extension(name) { return affinity::import(name, bytes); @@ -598,9 +612,7 @@ fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt, o // A `.psd`/`.psb`/`.psdt` with no raster signature keeps the PSD error instead of // `codec: unrecognized image format` (#5258). Magic already returned above. if is_psd_input(name, bytes) { - return import_psd(name, ctl, damaged, opts.psd_max_pixel_bytes, opts.psd_high_memory_approved, |want, recover| { - PsdFile::from_bytes_and_merged_preflight(bytes, want, recover) - }); + return import_psd(name, ctl, damaged, opts, |want, recover| PsdFile::from_bytes_and_merged_preflight(bytes, want, recover)); } flat::import_flat_with_limit(name, bytes, opts.psd_max_pixel_bytes) } diff --git a/crates/io/src/memory.rs b/crates/io/src/memory.rs index 6c49e5cb1d..68eacc3b61 100644 --- a/crates/io/src/memory.rs +++ b/crates/io/src/memory.rs @@ -32,6 +32,11 @@ pub struct MemorySnapshot { pub commit_headroom: Option, } +#[cfg(any(test, feature = "testgen"))] +thread_local! { + static MOCK_SNAPSHOT: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + impl MemorySnapshot { /// Unknown memory measurement. pub const UNKNOWN: Self = Self { available_ram: None, swap_free: None, commit_headroom: None }; @@ -39,8 +44,10 @@ impl MemorySnapshot { /// Obtains the current system memory snapshot from platform providers. pub fn current() -> Self { #[cfg(any(test, feature = "testgen"))] - if let Some(mock) = MOCK_SNAPSHOT.with(|m| *m.borrow()) { - return mock; + { + if let Some(mock) = MOCK_SNAPSHOT.with(|m| *m.borrow()) { + return mock; + } } #[cfg(target_os = "linux")] @@ -96,10 +103,10 @@ impl MemoryBudget { /// Resolves the adaptive hard and soft import budgets from a snapshot and an optional caller limit. /// /// Policy: -/// - Hard H = min(75% A, saturating A - 1 GiB, C - reserve if known, platform/address-space limits) +/// - Hard H = min(floor(3*A/4), saturating A - 1 GiB, C - reserve if known, platform/address-space limits) /// - Soft S = min(50% A, 8 GiB, H) /// - <= S: automatic; S < E <= H: explicit approval; > H: refuse, no unlimited override. -/// - Unknown native fallback: 2 GiB, no override (S = H = 2 GiB). +/// - Unknown native fallback: 2 GiB bounded by C - reserve if known (S = H). /// - Browser/wasm: fixed 1 GiB (S = H = 1 GiB). /// - Explicit caller limits may lower admission, never bypass the hard boundary. pub fn resolve_budget(snapshot: MemorySnapshot, caller_limit: Option) -> MemoryBudget { @@ -116,7 +123,7 @@ pub fn resolve_budget(snapshot: MemorySnapshot, caller_limit: Option) -> Me let (mut hard, mut soft) = match snapshot.available_ram { Some(a) => { - let h_pct = a.checked_mul(3).map_or(u64::MAX, |v| v / 4); + let h_pct = ((a as u128 * 3) / 4) as u64; let h_reserve = a.saturating_sub(1 << 30); let mut h = h_pct.min(h_reserve); @@ -132,7 +139,11 @@ pub fn resolve_budget(snapshot: MemorySnapshot, caller_limit: Option) -> Me (h, s) } None => { - let limit = NATIVE_FALLBACK_BUDGET.min(address_space_cap); + let mut limit = NATIVE_FALLBACK_BUDGET.min(address_space_cap); + if let Some(c) = snapshot.commit_headroom { + let c_room = c.saturating_sub(COMMIT_RESERVE); + limit = limit.min(c_room); + } (limit, limit) } }; @@ -145,6 +156,85 @@ pub fn resolve_budget(snapshot: MemorySnapshot, caller_limit: Option) -> Me MemoryBudget { soft_limit: soft, hard_limit: hard, available_ram: snapshot.available_ram } } +/// Central evaluation of PSD admission against adaptive budgets and options. +/// +/// Refuses before decoding if: +/// - `required > hard_limit` (regardless of approvals: hard ceiling cannot be overridden); +/// - `required > soft_limit` and high memory is not approved; +/// - high memory is approved, but `approved_estimate` is specified and `required > approved_estimate` +/// (preventing unbounded approval for altered/enlarged files). +/// Result of evaluating an import admission request. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct AdmissionOutcome { + pub budget: MemoryBudget, + /// Total authorized memory allowance for the entire attempt (top-level + nested decodes): + /// `min(S if automatic else H if approved, caller cap if any, approved_estimate if present)`. + pub authorized_total: u64, +} + +pub(crate) fn evaluate_psd_admission( + required: u64, + caller_limit: u64, + high_memory_approved: bool, + approved_estimate: Option, + snapshot: MemorySnapshot, +) -> Result { + let limit_opt = (caller_limit > 0).then_some(caller_limit); + let budget = resolve_budget(snapshot, limit_opt); + + let authorized_total = match budget.decide(required) { + BudgetDecision::Automatic => { + let mut cap = budget.soft_limit; + if let Some(caller) = limit_opt { + cap = cap.min(caller); + } + if let Some(appr) = approved_estimate { + cap = cap.min(appr); + } + cap + } + BudgetDecision::RequiresApproval => { + if !high_memory_approved { + return Err(IoError::PsdApprovalRequired { + required, + soft_limit: budget.soft_limit, + hard_limit: budget.hard_limit, + available_ram: budget.available_ram, + }); + } + if let Some(approved) = approved_estimate { + if required > approved { + return Err(IoError::PsdApprovalRequired { + required, + soft_limit: budget.soft_limit, + hard_limit: budget.hard_limit, + available_ram: budget.available_ram, + }); + } + } + let mut cap = budget.hard_limit; + if let Some(caller) = limit_opt { + cap = cap.min(caller); + } + if let Some(appr) = approved_estimate { + cap = cap.min(appr); + } + cap + } + BudgetDecision::Refused => return Err(IoError::PsdImportBudget { required, limit: budget.hard_limit }), + }; + + if required > authorized_total { + return Err(IoError::PsdApprovalRequired { + required, + soft_limit: budget.soft_limit, + hard_limit: budget.hard_limit, + available_ram: budget.available_ram, + }); + } + Ok(AdmissionOutcome { budget, authorized_total }) +} + /// Bytes this process can still use without running out, or `None` where that isn't known. On /// Linux: the free RAM the kernel can hand out (`MemAvailable`, capped by the process's cgroup /// v2 `memory.max` and those above it) plus free swap (capped by the cgroup's `memory.swap.max` and those above it). @@ -176,31 +266,101 @@ pub(crate) fn check_fits(w: u32, h: u32, needed: u64, available: Option) -> ))) } -#[cfg(any(test, feature = "testgen"))] -thread_local! { - static MOCK_SNAPSHOT: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; -} - -/// Sets a mock memory snapshot for testing policy and import admission. +/// Sets a thread-local mock memory snapshot for testing policy and import admission. #[cfg(any(test, feature = "testgen"))] pub fn set_mock_memory(snapshot: Option) { MOCK_SNAPSHOT.with(|m| *m.borrow_mut() = snapshot); } -/// Runs a closure with a temporarily injected mock memory snapshot. +/// Runs a closure with a temporarily injected mock memory snapshot on the current thread. +/// +/// Restores the previous snapshot upon return or panic, supporting nested invocations. #[cfg(any(test, feature = "testgen"))] pub fn with_mock_memory(snapshot: MemorySnapshot, f: impl FnOnce() -> R) -> R { - struct Reset; + let prev = MOCK_SNAPSHOT.with(|m| { + let old = *m.borrow(); + *m.borrow_mut() = Some(snapshot); + old + }); + + struct Reset { + prev: Option, + } impl Drop for Reset { fn drop(&mut self) { - set_mock_memory(None); + MOCK_SNAPSHOT.with(|m| *m.borrow_mut() = self.prev); } } - set_mock_memory(Some(snapshot)); - let _reset = Reset; + + let _reset = Reset { prev }; f() } +/// Explicit test-support capture/scope object to propagate a thread-local mock +/// snapshot across worker threads without modifying global process state. +/// +/// In production, this is an inert zero-overhead type. +#[derive(Clone, Copy, Debug, Default)] +pub struct TestMemoryScope { + #[cfg(any(test, feature = "testgen"))] + mock: Option, +} + +/// RAII guard that restores the previous thread-local mock memory upon drop. +pub struct TestMemoryGuard { + #[cfg(any(test, feature = "testgen"))] + prev: Option, +} + +#[cfg(any(test, feature = "testgen"))] +impl Drop for TestMemoryGuard { + fn drop(&mut self) { + MOCK_SNAPSHOT.with(|m| *m.borrow_mut() = self.prev); + } +} + +impl TestMemoryScope { + /// Captures the current thread's mock memory snapshot, if any. + /// + /// Never captures actual system RAM as a permanent snapshot so that + /// production memory rechecks remain fresh. + pub fn capture() -> Self { + #[cfg(any(test, feature = "testgen"))] + { + let mock = MOCK_SNAPSHOT.with(|m| *m.borrow()); + Self { mock } + } + #[cfg(not(any(test, feature = "testgen")))] + { + Self {} + } + } + + /// Enters this captured mock memory scope, returning a RAII guard that + /// restores the thread's previous mock state on drop. + pub fn enter(self) -> TestMemoryGuard { + #[cfg(any(test, feature = "testgen"))] + { + let prev = MOCK_SNAPSHOT.with(|m| { + let old = *m.borrow(); + *m.borrow_mut() = self.mock; + old + }); + TestMemoryGuard { prev } + } + #[cfg(not(any(test, feature = "testgen")))] + { + TestMemoryGuard {} + } + } + + /// Executes a closure within this captured mock memory scope. + pub fn run(self, f: impl FnOnce() -> R) -> R { + let _guard = self.enter(); + f() + } +} + #[cfg(target_os = "linux")] pub(super) mod linux { use super::MemorySnapshot; @@ -252,9 +412,12 @@ pub(super) mod linux { (ram, swap) } - /// A `memory.stat` field (` ` per line). - fn stat(stat: &str, field: &str) -> Option { - stat.lines().find_map(|l| l.strip_prefix(field)?.strip_prefix(' '))?.trim().parse().ok() + fn stat(s: &str, field: &str) -> Option { + s.lines().find_map(|l| { + let mut parts = l.split_whitespace(); + let key = parts.next()?; + if key == field { parts.next()?.parse().ok() } else { None } + }) } } @@ -274,6 +437,11 @@ mod windows_mem { mod fallback_mem { use super::MemorySnapshot; + /// Fallback provider for platforms without a validated memory-availability provider (e.g. macOS). + /// + /// Available memory is reported as unknown (`None`), which applies the safe native fallback + /// budget (2 GiB) without allowing an unverified memory override. macOS dynamic paging makes + /// physical RAM a poor indicator of allocation capacity without platform-specific Mach VM APIs. pub(super) fn snapshot() -> MemorySnapshot { MemorySnapshot::UNKNOWN } @@ -365,14 +533,81 @@ mod tests { assert_eq!(b_unknown.decide(NATIVE_FALLBACK_BUDGET + 1), BudgetDecision::Refused); } + #[test] + fn unknown_ram_with_known_zero_commit_bounds_admission() { + let snap = MemorySnapshot { available_ram: None, swap_free: None, commit_headroom: Some(0) }; + let b = resolve_budget(snap, None); + assert_eq!(b.hard_limit, 0); + assert_eq!(b.soft_limit, 0); + assert_eq!(b.decide(1), BudgetDecision::Refused); + + let snap_room = MemorySnapshot { available_ram: None, swap_free: None, commit_headroom: Some(1 << 30) }; + let b_room = resolve_budget(snap_room, None); + assert_eq!(b_room.hard_limit, (1 << 30) - COMMIT_RESERVE); + assert_eq!(b_room.soft_limit, (1 << 30) - COMMIT_RESERVE); + } + #[test] fn arithmetic_overflow_safety() { let snap_huge = MemorySnapshot { available_ram: Some(u64::MAX), swap_free: Some(u64::MAX), commit_headroom: Some(u64::MAX) }; let b = resolve_budget(snap_huge, None); - assert!(b.hard_limit <= u64::MAX); + let expected_hard = ((u64::MAX as u128 * 3) / 4) as u64; + let expected_hard = if cfg!(target_pointer_width = "32") { 2 << 30 } else { expected_hard }; + assert_eq!(b.hard_limit, expected_hard); assert_eq!(b.soft_limit, MAX_SOFT_BUDGET); } + #[test] + fn nested_mock_memory_restores_previous() { + let snap1 = MemorySnapshot { available_ram: Some(100), swap_free: None, commit_headroom: None }; + let snap2 = MemorySnapshot { available_ram: Some(200), swap_free: None, commit_headroom: None }; + with_mock_memory(MemorySnapshot::UNKNOWN, || { + assert_eq!(MemorySnapshot::current(), MemorySnapshot::UNKNOWN); + with_mock_memory(snap1, || { + assert_eq!(MemorySnapshot::current().available_ram, Some(100)); + with_mock_memory(snap2, || { + assert_eq!(MemorySnapshot::current().available_ram, Some(200)); + }); + assert_eq!(MemorySnapshot::current().available_ram, Some(100)); + }); + assert_eq!(MemorySnapshot::current(), MemorySnapshot::UNKNOWN); + }); + } + + #[test] + fn central_admission_evaluation_enforces_bounds() { + if cfg!(any(target_arch = "wasm32", target_pointer_width = "32")) { + return; + } + let gb = 1u64 << 30; + let snap = MemorySnapshot { available_ram: Some(12 * gb), swap_free: None, commit_headroom: None }; + // S = 6 GiB, H = 9 GiB + + // Below S: automatic, authorized_total = S (6 GiB) + let out = evaluate_psd_admission(5 * gb, 0, false, None, snap).unwrap(); + assert_eq!(out.authorized_total, 6 * gb); + + // In [S, H]: requires approval + let err = evaluate_psd_admission(7 * gb, 0, false, None, snap).unwrap_err(); + assert!(matches!(err, IoError::PsdApprovalRequired { required, .. } if required == 7 * gb)); + + // In [S, H] with approval and no approved_estimate bound: admitted, authorized_total = H (9 GiB) + let out = evaluate_psd_admission(7 * gb, 0, true, None, snap).unwrap(); + assert_eq!(out.authorized_total, 9 * gb); + + // In [S, H] with approval but required exceeds approved_estimate: requires fresh approval + let err = evaluate_psd_admission(7 * gb, 0, true, Some(6 * gb), snap).unwrap_err(); + assert!(matches!(err, IoError::PsdApprovalRequired { .. })); + + // In [S, H] with approval and required within approved_estimate: admitted, authorized_total = approved_estimate (7 GiB) + let out = evaluate_psd_admission(7 * gb, 0, true, Some(7 * gb), snap).unwrap(); + assert_eq!(out.authorized_total, 7 * gb); + + // Exceeding H: refused even if high_memory_approved is true + let err = evaluate_psd_admission(10 * gb, 0, true, Some(10 * gb), snap).unwrap_err(); + assert!(matches!(err, IoError::PsdImportBudget { .. })); + } + #[cfg(target_os = "linux")] #[test] fn linux_memory_is_read_from_meminfo_and_the_cgroup() { @@ -411,7 +646,6 @@ mod tests { write(&leaf, "memory.stat", "anon 268435456\n"); assert_eq!(linux::cgroup_room(&leaf).0, Some(0), "no inactive_file: memory.current is all in use"); std::fs::remove_dir_all(&root).unwrap(); - assert!(available().is_some()); } #[cfg(target_os = "linux")] diff --git a/crates/io/src/psd_budget/tests.rs b/crates/io/src/psd_budget/tests.rs index 06692773c8..432441eee9 100644 --- a/crates/io/src/psd_budget/tests.rs +++ b/crates/io/src/psd_budget/tests.rs @@ -55,9 +55,11 @@ fn large_off_canvas_layer_is_rejected_without_decoding_its_tiny_data() { // section. No enormous decoded plane is ever constructed by this test. let mut bytes = file.to_bytes().unwrap(); bytes.truncate(bytes.len() - file.image_data.data.len() - 2); - assert!(matches!(crate::import("huge.psd", &bytes), Err(IoError::PsdImportBudget { .. }))); - let source = photocraft_psd::Source::new(bytes); - assert!(matches!(crate::import_source_for_open_with("huge.psd", source, &photocraft_raster::Interrupt::NONE), Err(IoError::PsdImportBudget { .. }))); + crate::memory::with_mock_memory(crate::memory::MemorySnapshot::UNKNOWN, || { + assert!(matches!(crate::import("huge.psd", &bytes), Err(IoError::PsdImportBudget { .. }))); + let source = photocraft_psd::Source::new(bytes); + assert!(matches!(crate::import_source_for_open_with("huge.psd", source, &photocraft_raster::Interrupt::NONE), Err(IoError::PsdImportBudget { .. }))); + }); } #[test] @@ -119,9 +121,12 @@ fn accepted_off_canvas_pixels_and_depths_are_preserved() { fn legacy_conversion_reports_a_rejected_import_instead_of_decoding_it() { let mut file = testgen::small(Version::Psd, Compression::Zip); file.layers_mut()[0].rect = Rect::from_xywh(0, 0, 20000, 20000); - let (doc, warnings) = crate::psd_to_document(&file); - assert!(doc.layers.is_empty()); - assert!(warnings.iter().any(|warning| warning.contains("pixel memory"))); + // Use fallback snapshot to ensure test does not depend on host available RAM + crate::memory::with_mock_memory(crate::memory::MemorySnapshot::UNKNOWN, || { + let (doc, warnings) = crate::psd_to_document(&file); + assert!(doc.layers.is_empty()); + assert!(warnings.iter().any(|warning| warning.contains("pixel memory"))); + }); } fn pattern_block(mode: u32, depth: u16, width: u32, height: u32) -> photocraft_psd::TaggedBlock { @@ -271,3 +276,132 @@ fn zero_available_ram_refuses_admission() { assert!(matches!(res, Err(IoError::PsdImportBudget { .. }))); }); } + +#[test] +fn preflight_rejection_and_approval_files_release_gate() { + if cfg!(any(target_arch = "wasm32", target_pointer_width = "32")) { + return; + } + let mut file = testgen::small(Version::Psd, Compression::Zip); + file.header.width = 1; + file.header.height = 1; + file.layers_mut()[0].rect = Rect::from_xywh(0, 0, 30_000, 30_000); + let bytes = file.to_bytes().unwrap(); + + let gb = 1u64 << 30; + // Set RAM such that this large layer exceeds hard limit + let snap = crate::memory::MemorySnapshot { available_ram: Some(4 * gb), swap_free: None, commit_headroom: None }; + crate::memory::with_mock_memory(snap, || { + assert!(!crate::psd_gate::is_holding_admission()); + let res = crate::import_with_options("huge.psd", &bytes, &crate::ImportOptions::default()); + assert!(matches!(res, Err(IoError::PsdImportBudget { .. }))); + // Gate must not be held after rejection + assert!(!crate::psd_gate::is_holding_admission()); + }); + + // Set RAM such that file falls in confirmation range + let est = estimate(&file); + let snap_mid = crate::memory::MemorySnapshot { available_ram: Some(est * 2), swap_free: None, commit_headroom: None }; + crate::memory::with_mock_memory(snap_mid, || { + assert!(!crate::psd_gate::is_holding_admission()); + let res = crate::import_with_options("mid.psd", &bytes, &crate::ImportOptions::default()); + assert!(matches!(res, Err(IoError::PsdApprovalRequired { .. }))); + // Gate must not be held when requiring approval + assert!(!crate::psd_gate::is_holding_admission()); + }); +} + +#[test] +fn retry_estimate_cap_rejects_altered_or_enlarged_file() { + if cfg!(any(target_arch = "wasm32", target_pointer_width = "32")) { + return; + } + let gb = 1u64 << 30; + let snap = crate::memory::MemorySnapshot { available_ram: Some(12 * gb), swap_free: None, commit_headroom: None }; + // S = 6 GiB, H = 9 GiB + + // 1. Within approved_estimate: passes + let res = crate::memory::evaluate_psd_admission(7 * gb, 0, true, Some(7 * gb), snap); + assert!(res.is_ok()); + + // 2. Fresh requirement exceeds approved_estimate: requires fresh approval + let res = crate::memory::evaluate_psd_admission(8 * gb, 0, true, Some(7 * gb), snap); + assert!(matches!(res, Err(IoError::PsdApprovalRequired { required, .. }) if required == 8 * gb)); + + // 3. Exceeds hard limit: refused completely regardless of approval + let res = crate::memory::evaluate_psd_admission(10 * gb, 0, true, Some(10 * gb), snap); + assert!(matches!(res, Err(IoError::PsdImportBudget { required, limit }) if required == 10 * gb && limit == 9 * gb)); +} + +#[test] +fn caller_zero_and_lower_caps_cannot_bypass_hard_boundary() { + if cfg!(any(target_arch = "wasm32", target_pointer_width = "32")) { + return; + } + let gb = 1u64 << 30; + let snap = crate::memory::MemorySnapshot { available_ram: Some(8 * gb), swap_free: None, commit_headroom: None }; + // S = 4 GiB, H = 6 GiB + + // 0 uses adaptive budget + let b_zero = crate::memory::resolve_budget(snap, Some(0)); + assert_eq!(b_zero.hard_limit, 6 * gb); + assert_eq!(b_zero.soft_limit, 4 * gb); + + // Lower cap lowers both hard and soft + let b_lower = crate::memory::resolve_budget(snap, Some(3 * gb)); + assert_eq!(b_lower.hard_limit, 3 * gb); + assert_eq!(b_lower.soft_limit, 3 * gb); + + // Higher cap cannot raise above hard limit + let b_higher = crate::memory::resolve_budget(snap, Some(20 * gb)); + assert_eq!(b_higher.hard_limit, 6 * gb); + assert_eq!(b_higher.soft_limit, 4 * gb); +} + +#[test] +fn test_memory_scope_propagates_to_worker_thread() { + let gb = 1u64 << 30; + let mock = crate::memory::MemorySnapshot { available_ram: Some(4 * gb), swap_free: None, commit_headroom: None }; + crate::memory::with_mock_memory(mock, || { + let scope = crate::memory::TestMemoryScope::capture(); + let handle = std::thread::spawn(move || { + scope.run(|| { + assert_eq!(crate::memory::MemorySnapshot::current().available_ram, Some(4 * gb)); + }); + }); + handle.join().unwrap(); + }); +} + +#[test] +fn nested_imports_consume_from_shared_allowance_and_do_not_reset_parent() { + let gb = 1u64 << 30; + let ctl = photocraft_raster::Interrupt::NONE; + let _guard = crate::psd_gate::acquire_decode_admission(&ctl).unwrap(); + // Simulate top-level attempt authorized total of 5 GB with 2 GB remaining allowance + crate::psd_gate::set_active_attempt_budget(2 * gb); + + // First nested consume fits within 2 GB + assert!(crate::psd_gate::consume_attempt_allowance(1 * gb).is_ok()); + + // Second nested consume exceeds remaining 1 GB + let err = crate::psd_gate::consume_attempt_allowance(2 * gb).unwrap_err(); + assert!(matches!(err, IoError::PsdImportBudget { required, limit } if required == 2 * gb && limit == 1 * gb)); + + // Allowance is still 1 GB (failed attempt does not reset or corrupt parent) + assert!(crate::psd_gate::consume_attempt_allowance(1 * gb).is_ok()); + assert!(crate::psd_gate::consume_attempt_allowance(1).is_err()); +} + +#[test] +fn nested_tiff_layer_import_consumes_composite_and_estimate_without_resetting_parent() { + let gb = 1u64 << 30; + let ctl = photocraft_raster::Interrupt::NONE; + let _guard = crate::psd_gate::acquire_decode_admission(&ctl).unwrap(); + crate::psd_gate::set_active_attempt_budget(3 * gb); + + assert!(crate::psd_gate::is_holding_admission()); + assert!(crate::psd_gate::consume_attempt_allowance(1 * gb).is_ok()); + assert!(crate::psd_gate::consume_attempt_allowance(2 * gb).is_ok()); + assert!(crate::psd_gate::consume_attempt_allowance(1).is_err()); +} diff --git a/crates/io/src/psd_gate.rs b/crates/io/src/psd_gate.rs index d2a4535eb2..cc71e2e6c6 100644 --- a/crates/io/src/psd_gate.rs +++ b/crates/io/src/psd_gate.rs @@ -6,6 +6,7 @@ //! budget. Approval prompts never hold this lock. use std::cell::Cell; +use std::marker::PhantomData; use std::sync::{Condvar, Mutex, OnceLock}; use std::thread::ThreadId; use std::time::Duration; @@ -25,49 +26,84 @@ fn get_gate() -> &'static (Mutex, Condvar) { thread_local! { static NESTED_DEPTH: Cell = const { Cell::new(0) }; + static ATTEMPT_ALLOWANCE: Cell> = const { Cell::new(None) }; } /// RAII guard releasing decode admission when dropped. -pub struct AdmissionGuard { - is_top_level: bool, +/// Non-Send and non-Sync to prevent cross-thread leakage or premature release. +pub(crate) struct AdmissionGuard { + _marker: PhantomData<*const ()>, } impl Drop for AdmissionGuard { fn drop(&mut self) { - if self.is_top_level { + let depth = NESTED_DEPTH.with(|d| { + let val = d.get().saturating_sub(1); + d.set(val); + val + }); + if depth == 0 { + ATTEMPT_ALLOWANCE.with(|a| a.set(None)); let (mutex, cvar) = get_gate(); let mut state = mutex.lock().unwrap_or_else(std::sync::PoisonError::into_inner); state.active = false; state.owner = None; cvar.notify_one(); - } else { - NESTED_DEPTH.with(|d| d.set(d.get().saturating_sub(1))); } } } +/// Returns whether the current thread currently holds decode admission. +pub(crate) fn is_holding_admission() -> bool { + NESTED_DEPTH.with(|d| d.get() > 0) +} + +/// Sets the remaining memory allowance for the active import attempt on the current thread. +pub(crate) fn set_active_attempt_budget(allowance: u64) { + ATTEMPT_ALLOWANCE.with(|a| a.set(Some(allowance))); +} + +/// Consumes `bytes` from the enclosing attempt's remaining allowance, or returns +/// [`IoError::PsdImportBudget`] if the required amount exceeds what remains. +pub(crate) fn consume_attempt_allowance(bytes: u64) -> Result<(), IoError> { + ATTEMPT_ALLOWANCE.with(|a| match a.get() { + Some(remaining) => { + if bytes > remaining { + return Err(IoError::PsdImportBudget { required: bytes, limit: remaining }); + } + a.set(Some(remaining - bytes)); + Ok(()) + } + None => { + // Unknown allowance during reentrant gate must fail closed. + Err(IoError::PsdImportBudget { required: bytes, limit: 0 }) + } + }) +} + /// Acquires process-wide admission to decode PSD pixels, or awaits completion of an active decode. /// /// If the current thread already holds admission (a nested/reentrant decode), it is admitted /// immediately without reacquiring the mutex or waiting on the condvar. Otherwise, it polls /// `ctl.check()` every 50 ms while waiting so cancellation halts the wait immediately. -pub fn acquire_decode_admission(ctl: &photocraft_raster::Interrupt) -> Result { +pub(crate) fn acquire_decode_admission(ctl: &photocraft_raster::Interrupt) -> Result { let current_thread = std::thread::current().id(); - - let is_reentrant = { - let (mutex, _) = get_gate(); - let state = mutex.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - state.active && state.owner == Some(current_thread) - }; - - if is_reentrant { - NESTED_DEPTH.with(|d| d.set(d.get() + 1)); - return Ok(AdmissionGuard { is_top_level: false }); - } - let (mutex, cvar) = get_gate(); let mut state = mutex.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if state.active && state.owner == Some(current_thread) { + ctl.check().map_err(|_| IoError::Cancelled)?; + NESTED_DEPTH.with(|d| d.set(d.get().saturating_add(1))); + return Ok(AdmissionGuard { _marker: PhantomData }); + } + + #[cfg(target_arch = "wasm32")] + if state.active { + // Stateless wasm is single-threaded: contention cannot be resolved by waiting on Condvar. + return Err(IoError::Unsupported("concurrent PSD decoding is not supported on wasm".into())); + } + + #[cfg(not(target_arch = "wasm32"))] while state.active { ctl.check().map_err(|_| IoError::Cancelled)?; let (next_state, _) = cvar.wait_timeout(state, Duration::from_millis(50)).unwrap_or_else(std::sync::PoisonError::into_inner); @@ -77,29 +113,119 @@ pub fn acquire_decode_admission(ctl: &photocraft_raster::Interrupt) -> Result e, + Err(error) => { + let message = error.to_string(); + let doc = Document::new("Untitled", Size::new(1, 1), ColorMode::Rgb, SampleType::U8); + return Some((doc, vec![message], true, Some(error))); + } + }; + + if crate::psd_gate::is_holding_admission() { + // Nested conversion: consume from enclosing attempt allowance without fresh budget or deadlocks + if let Err(error) = crate::psd_gate::consume_attempt_allowance(est.total_bytes) { + let message = error.to_string(); + let doc = Document::new("Untitled", Size::new(1, 1), ColorMode::Rgb, SampleType::U8); + return Some((doc, vec![message], true, Some(error))); + } + match crate::psd_gate::acquire_decode_admission(ctl) { + Ok(g) => _guard = Some(g), + Err(error) => { + let message = error.to_string(); + let doc = Document::new("Untitled", Size::new(1, 1), ColorMode::Rgb, SampleType::U8); + return Some((doc, vec![message], true, Some(error))); + } + } + } else { + // Standalone legacy conversion: acquire admission gate and check adaptive budget + match crate::psd_gate::acquire_decode_admission(ctl) { + Ok(g) => _guard = Some(g), + Err(error) => { + let message = error.to_string(); + let doc = Document::new("Untitled", Size::new(1, 1), ColorMode::Rgb, SampleType::U8); + return Some((doc, vec![message], true, Some(error))); + } + } + let snapshot = crate::memory::MemorySnapshot::current(); + // Legacy standalone is unconfirmed: cannot silently auto allow > S. + match crate::memory::evaluate_psd_admission(est.total_bytes, 0, false, None, snapshot) { + Ok(outcome) => { + crate::psd_gate::set_active_attempt_budget(outcome.authorized_total.saturating_sub(est.total_bytes)); + } + Err(error) => { + let message = error.to_string(); + let doc = Document::new("Untitled", Size::new(1, 1), ColorMode::Rgb, SampleType::U8); + return Some((doc, vec![message], true, Some(error))); + } + } + } + } else if !crate::psd_gate::is_holding_admission() { + // Fallback for callers passing preflighted=true without holding admission: + // acquire admission gate and initialize allowance safely. + match crate::psd_gate::acquire_decode_admission(ctl) { + Ok(g) => _guard = Some(g), + Err(error) => { + let message = error.to_string(); + let doc = Document::new("Untitled", Size::new(1, 1), ColorMode::Rgb, SampleType::U8); + return Some((doc, vec![message], true, Some(error))); + } + } + let est = match crate::psd_budget::estimate(file) { + Ok(e) => e, + Err(error) => { + let message = error.to_string(); + let doc = Document::new("Untitled", Size::new(1, 1), ColorMode::Rgb, SampleType::U8); + return Some((doc, vec![message], true, Some(error))); + } + }; + let snapshot = crate::memory::MemorySnapshot::current(); + match crate::memory::evaluate_psd_admission(est.total_bytes, 0, false, None, snapshot) { + Ok(outcome) => { + crate::psd_gate::set_active_attempt_budget(outcome.authorized_total.saturating_sub(est.total_bytes)); + } + Err(error) => { + let message = error.to_string(); + let doc = Document::new("Untitled", Size::new(1, 1), ColorMode::Rgb, SampleType::U8); + return Some((doc, vec![message], true, Some(error))); + } + } } let (mode, layered, multichannel, depth) = import_format(file); let h = &file.header; diff --git a/crates/io/src/tiff_layers.rs b/crates/io/src/tiff_layers.rs index 664355ef5b..2ca338f07e 100644 --- a/crates/io/src/tiff_layers.rs +++ b/crates/io/src/tiff_layers.rs @@ -124,7 +124,18 @@ pub(crate) fn import_layered(name: &str, img: &Image, layers: &[u8], pixel_limit if composite > pixel_limit { return Err(photocraft_psd::PsdError::LimitExceeded("the TIFF composite exceeds the import allowance").into()); } - crate::psd_budget::check(&file, pixel_limit - composite)?; + let remaining_limit = pixel_limit - composite; + let est = crate::psd_budget::check(&file, remaining_limit)?; + let nested = crate::psd_gate::is_holding_admission(); + if nested { + crate::psd_gate::consume_attempt_allowance( + est.total_bytes.checked_add(composite).ok_or_else(|| IoError::Unsupported("TIFF import estimate overflow".into()))?, + )?; + } + let _guard = crate::psd_gate::acquire_decode_admission(&photocraft_raster::Interrupt::NONE)?; + if !nested { + crate::psd_gate::set_active_attempt_budget(remaining_limit.saturating_sub(est.total_bytes)); + } let img = if img.sample_type() == CSample::F16 { warnings.push("16-bit float samples are stored as 32-bit float".to_string()); std::borrow::Cow::Owned(img.convert(img.layout(), CSample::F32)) diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 326e6bf7a7..9fccf05de1 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -57,6 +57,7 @@ sys-locale = "=0.3.2" winsafe = { version = "=0.0.29", default-features = false, features = ["kernel", "dxgi", "advapi"] } [dev-dependencies] +photocraft-io = { workspace = true, features = ["testgen"] } # egui's own default fonts in tests: the oracle for egui_fonts.rs, and contexts made with # `Context::default()` (no install_fonts) can lay out text. egui = { workspace = true, features = ["default_fonts", "monochrome_emoji_fonts"] } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 3e7d2aa906..ef17287407 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -193,6 +193,7 @@ impl PhotocraftApp { dds_options: None, held_opens: Default::default(), held_memory_prompts: Default::default(), + prompt_order: Default::default(), held_preset_import: None, allow_close: false, stylus: Default::default(), diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 2fee62f41e..789cf42aa1 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -73,7 +73,14 @@ impl PhotocraftApp { let (mut doc, warnings, damaged) = if photocraft_io::is_psd(bytes) { // Read PSD damage as structured information in the same decode, not by // retrying an error or matching the text of a compatibility warning. - let (r, damaged) = photocraft_io::import_for_open(name, bytes, &opts).map_err(|e| e.to_string())?; + let (r, damaged) = match photocraft_io::import_for_open(name, bytes, &opts) { + Ok(result) => result, + Err(photocraft_io::IoError::PsdApprovalRequired { .. }) => { + jobs_ui::start_open(self, name, path.map(str::to_string), jobs_ui::bytes(bytes))?; + return Ok(Vec::new()); + } + Err(error) => return Err(error.to_string()), + }; (r.document, r.warnings, damaged) } else { let (doc, warnings) = import(name, bytes, &opts)?; @@ -112,13 +119,17 @@ impl PhotocraftApp { /// Returns the import warnings (also shown to the user). Brush and gradient /// files go to the preset libraries, as for interactive opens. pub fn open_automation_bytes(&mut self, name: &str, bytes: &[u8]) -> Result, String> { + self.open_automation_bytes_with_approval(name, bytes, false) + } + + pub fn open_automation_bytes_with_approval(&mut self, name: &str, bytes: &[u8], approved: bool) -> Result, String> { let events_enabled = self.session.prefs().script_events.enabled; if events_enabled { self.session.edit_prefs(|prefs| prefs.script_events.enabled = false); } let result = match preset_files_ui::open(self, name, bytes) { Some(r) => r.map(|()| Vec::new()), - None => self.import_automation_document(name, bytes), + None => self.import_automation_document(name, bytes, approved), }; if events_enabled { self.session.edit_prefs(|prefs| prefs.script_events.enabled = true); @@ -128,9 +139,10 @@ impl PhotocraftApp { /// The document half of [`open_automation_bytes`](Self::open_automation_bytes): no script /// events and no Color Settings policy (which may read user-configured profile paths). - fn import_automation_document(&mut self, name: &str, bytes: &[u8]) -> Result, String> { + fn import_automation_document(&mut self, name: &str, bytes: &[u8], approved: bool) -> Result, String> { let import = self.services.import.as_ref().ok_or("no importer configured")?; - let opts = photocraft_engine::jobs::import_options(self.session.prefs()); + let mut opts = photocraft_engine::jobs::import_options(self.session.prefs()); + opts.psd_high_memory_approved = approved; let (mut doc, warnings) = import(name, bytes, &opts)?; photocraft_engine::file_cmds::raw_defaults(&self.session, &warnings, &mut doc); // The caller records the path it read from. diff --git a/crates/ui-egui/src/control/dispatch.rs b/crates/ui-egui/src/control/dispatch.rs index 3c7b22dda0..31ad74a4c8 100644 --- a/crates/ui-egui/src/control/dispatch.rs +++ b/crates/ui-egui/src/control/dispatch.rs @@ -1369,7 +1369,11 @@ fn app_methods(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlReques let p = &req.params; Some(match req.method.as_str() { "app.open" => match str_param(p, "path") { - Some(path) => app_open(app, path), + Some(path) => match p.get("approveHighMemory") { + None | Some(Value::Null) => app_open(app, path, false), + Some(Value::Bool(approved)) => app_open(app, path, *approved), + Some(_) => err("expected boolean for `approveHighMemory`"), + }, None => err("missing `path`"), }, "app.save" => match crate::FormatChoices::from_params(p, "app.save") { @@ -1388,7 +1392,7 @@ fn app_methods(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlReques }) } -fn app_open(app: &mut PhotocraftApp, path: &str) -> Outcome { +fn app_open(app: &mut PhotocraftApp, path: &str, approved: bool) -> Outcome { if let Some(outcome) = open_pcraft_directory(app, path) { return outcome; } @@ -1398,7 +1402,7 @@ fn app_open(app: &mut PhotocraftApp, path: &str) -> Outcome { }; wrap(opened.and_then(|(name, bytes)| { let name = app.open_name(&name); - let warnings = app.open_automation_bytes(&name, &bytes)?; + let warnings = app.open_automation_bytes_with_approval(&name, &bytes, approved)?; // Brushes/gradients go to the preset libraries: no document, no Open Recent entry. if !crate::preset_files_ui::is_preset_file(&name) { app.opened_from(path); diff --git a/crates/ui-egui/src/dialogs/open_prompt.rs b/crates/ui-egui/src/dialogs/open_prompt.rs index 0c0f0fe845..02b2276cfb 100644 --- a/crates/ui-egui/src/dialogs/open_prompt.rs +++ b/crates/ui-egui/src/dialogs/open_prompt.rs @@ -44,7 +44,15 @@ pub struct Held { /// Dialog field for the high-memory confirmation prompt. pub const MEMORY_FIELD: &str = "__psdMemoryOpen"; +/// Item kind in the arrival-ordered open prompt queue. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum PromptKind { + Memory, + Open, +} + /// An un-decoded PSD file whose preflight estimate requires user approval. +#[derive(Clone)] pub struct MemoryPrompt { pub id: u64, pub name: String, @@ -63,27 +71,55 @@ pub fn waiting(app: &PhotocraftApp) -> bool { /// Opens `held` now, or queues it behind the file whose prompt is up. pub fn arrive(app: &mut PhotocraftApp, held: Held) { app.held_opens.push_back(held); + app.prompt_order.push_back(PromptKind::Open); advance(app); } +pub fn has_open_dialog(app: &PhotocraftApp) -> bool { + app.ui.dialogs.iter().any(|d| owns(&d.fields) || owns_damage(&d.fields) || owns_memory(&d.fields)) +} + /// Opens queued files in order until one needs its prompt, which is shown if it isn't yet. -fn advance(app: &mut PhotocraftApp) { - while let Some(front) = app.held_opens.front() { - if front.damage_pending { - if !app.ui.dialogs.iter().any(|d| owns_damage(&d.fields)) { - show_damage(app); +pub fn advance(app: &mut PhotocraftApp) { + // Reconcile legacy callers that populated held queues directly. + if app.prompt_order.is_empty() { + app.prompt_order.extend(std::iter::repeat_n(PromptKind::Open, app.held_opens.len())); + app.prompt_order.extend(std::iter::repeat_n(PromptKind::Memory, app.held_memory_prompts.len())); + } + if has_open_dialog(app) { + return; + } + loop { + match app.prompt_order.front() { + None => return, + Some(PromptKind::Memory) => { + if let Some(front) = app.held_memory_prompts.front().cloned() { + show_memory(app, &front); + return; + } else { + app.prompt_order.pop_front(); + } } - return; - } - if front.question.is_some() { - if !app.ui.dialogs.iter().any(|d| d.fields.contains_key(FIELD)) { - show(app); + Some(PromptKind::Open) => { + let Some(front) = app.held_opens.front() else { + app.prompt_order.pop_front(); + continue; + }; + if front.damage_pending { + show_damage(app); + return; + } + if front.question.is_some() { + show(app); + return; + } + let held = app.held_opens.pop_front().unwrap(); + app.prompt_order.pop_front(); + let _ = open(app, held, None); + if has_open_dialog(app) { + return; + } } - return; - } - if let Some(held) = app.held_opens.pop_front() { - // A failure is shown to the user (`open_failed`); the next file still opens. - let _ = open(app, held, None); } } } @@ -143,17 +179,28 @@ pub fn answer(app: &mut PhotocraftApp, action: Option<&str>) -> Result>() { app.session.cancel_job(job); } + app.jobs.opens.clear(); + app.jobs.batches.clear(); + app.ui.dialogs.retain(|d| !owns(&d.fields) && !owns_damage(&d.fields) && !owns_memory(&d.fields)); app.ui.status = crate::i18n::fmt(tl!("Cancelled opening {name}"), &[("name", &name)]); app.ui.status_error = false; return Ok(json!({"cancelled": dropped})); }; let Some(held) = app.held_opens.pop_front() else { return Err("no file is waiting to open".into()) }; + if let Some(pos) = app.prompt_order.iter().position(|p| *p == PromptKind::Open) { + app.prompt_order.remove(pos); + } let r = open(app, held, Some(action)); advance(app); r @@ -178,9 +225,13 @@ pub fn answer_remembering(app: &mut PhotocraftApp, action: &str) -> Result Result) -> Result, ) { app.held_memory_prompts.push_back(MemoryPrompt { id, name, path, slot, order, estimated, available }); + app.prompt_order.push_back(PromptKind::Memory); advance_memory(app); } @@ -305,22 +361,19 @@ pub(crate) fn memory_body(ui: &mut egui::Ui, fields: &serde_json::Map format!("{:.1} GB", a as f64 / (1u64 << 30) as f64), + Some(a) => format!("{:.1} GiB", a as f64 / (1u64 << 30) as f64), None => "unknown".to_string(), }; let message = format!( "{}\n\n{}", crate::i18n::fmt( - tl!("Opening “{name}” requires an estimated {est:.1} GB of memory ({avail} available)."), + tl!("Opening “{name}” requires an estimated {est} GiB of memory ({avail} available)."), &[("name", &prompt.name), ("est", &format!("{est_gb:.1}")), ("avail", &avail_str)], ), tl!("Opening this document uses more memory and may slow down your computer or other running applications."), @@ -343,30 +396,50 @@ fn show_memory(app: &mut PhotocraftApp, prompt: &MemoryPrompt) { pub(crate) fn answer_memory(app: &mut PhotocraftApp, accept: bool) -> Result { let Some(front) = app.held_memory_prompts.pop_front() else { + advance(app); return Err("no high-memory PSD is waiting for confirmation".into()); }; + if let Some(pos) = app.prompt_order.iter().position(|p| *p == PromptKind::Memory) { + app.prompt_order.remove(pos); + } let id = front.id; let name = front.name.clone(); - let r = app.run("file.approveMemory", json!({"id": id, "approve": accept})).map_err(|e| format!("{}: {e}", name))?; + let path = front.path.clone(); + let slot = front.slot; + let order = front.order; - if accept { - if let Some(job) = r.get("job").and_then(Value::as_u64) { - app.jobs.opens.push(crate::jobs_ui::OpenTab { - job: photocraft_engine::jobs::JobId(job), - name: name.clone(), - path: front.path, - slot: front.slot, - order: front.order, - }); - app.jobs.focus = Some(photocraft_engine::jobs::JobId(job)); - app.ui.chrome.home = None; - app.ui.status = crate::i18n::fmt(tl!("Opening {name}…"), &[("name", &name)]); - app.ui.status_error = false; + let res = app.run("file.approveMemory", json!({"id": id, "approve": accept, "background": app.background_jobs})).map_err(|e| format!("{}: {e}", name)); + + match res { + Ok(r) => { + if accept { + if let Some(job) = r.get("job").and_then(Value::as_u64) { + app.jobs.opens.push(crate::jobs_ui::OpenTab { job: photocraft_engine::jobs::JobId(job), name: name.clone(), path, slot, order }); + app.jobs.focus = Some(photocraft_engine::jobs::JobId(job)); + app.ui.chrome.home = None; + app.ui.status = crate::i18n::fmt(tl!("Opening {name}…"), &[("name", &name)]); + app.ui.status_error = false; + } else if let Some(result) = r.get("result") { + let tab = crate::jobs_ui::OpenTab { job: photocraft_engine::jobs::JobId(0), name: name.clone(), path: path.clone(), slot, order }; + if let Err(e) = crate::jobs_ui::finish_open_tab(app, &tab, result) { + app.ui.status = e; + app.ui.status_error = true; + } + } + } else { + app.ui.status = crate::i18n::fmt(tl!("Cancelled opening {name}"), &[("name", &name)]); + app.ui.status_error = false; + crate::jobs_ui::end_batch(&mut app.jobs, &app.held_memory_prompts); + } + advance(app); + Ok(r) + } + Err(err) => { + app.ui.status = err.clone(); + app.ui.status_error = true; + crate::jobs_ui::end_batch(&mut app.jobs, &app.held_memory_prompts); + advance(app); + Err(err) } - } else { - app.ui.status = crate::i18n::fmt(tl!("Cancelled opening {name}"), &[("name", &name)]); - app.ui.status_error = false; } - advance_memory(app); - Ok(r) } diff --git a/crates/ui-egui/src/file_open.rs b/crates/ui-egui/src/file_open.rs index 65c1fb5758..39e55aa3e0 100644 --- a/crates/ui-egui/src/file_open.rs +++ b/crates/ui-egui/src/file_open.rs @@ -182,7 +182,7 @@ impl PhotocraftApp { Err(e) => self.open_failed(&display_name(abs), &e), } } - crate::jobs_ui::end_batch(&mut self.jobs); + crate::jobs_ui::end_batch(&mut self.jobs, &self.held_memory_prompts); opened } diff --git a/crates/ui-egui/src/file_open/tests.rs b/crates/ui-egui/src/file_open/tests.rs index c0323da9a1..5fdece7f71 100644 --- a/crates/ui-egui/src/file_open/tests.rs +++ b/crates/ui-egui/src/file_open/tests.rs @@ -885,7 +885,7 @@ fn a_set_of_background_opens_keeps_its_order_however_they_finish() { let index = app.session.add_document(Document::new("f1.psd", Size::new(4, 4), ColorMode::Rgb, SampleType::U8), None); assert_eq!(index, 1); jobs_ui::opened_in_order(&mut app.jobs, OpenOrder { batch, seq: 1 }); - jobs_ui::end_batch(&mut app.jobs); + jobs_ui::end_batch(&mut app.jobs, &app.held_memory_prompts); assert_eq!(app.jobs.batches.len(), 1, "kept while members are opening"); // The rest finish out of order: last, first, third. for seq in [3usize, 0, 2] { diff --git a/crates/ui-egui/src/jobs_ui.rs b/crates/ui-egui/src/jobs_ui.rs index 584a4cad8c..9dc391169f 100644 --- a/crates/ui-egui/src/jobs_ui.rs +++ b/crates/ui-egui/src/jobs_ui.rs @@ -200,7 +200,7 @@ pub fn run(app: &mut PhotocraftApp, id: &str, params: Value) -> Result, source: OpenSource) -> Result<(), String> { let name = &app.open_name(name); - match app.session.start_open_for_user(name, source).map_err(|e| e.to_string())? { + match app.session.start_open_for_user_with_background(name, source, app.background_jobs).map_err(|e| e.to_string())? { // Inline (wasm): finish now, like a background open that ended at once. Started::Done(v) => finish_open(app, name, path.as_deref(), &v, None), Started::Job(job) => { @@ -233,9 +233,11 @@ pub(crate) fn opened_in_order(jobs: &mut JobsUi, order: OpenOrder) { } /// Every member of the set has been started: forget it unless some are still opening. -pub(crate) fn end_batch(jobs: &mut JobsUi) { +pub(crate) fn end_batch(jobs: &mut JobsUi, held_memory_prompts: &std::collections::VecDeque) { let opens = &jobs.opens; - jobs.batches.retain(|b| opens.iter().any(|o| o.order.is_some_and(|x| x.batch == b.id))); + jobs.batches.retain(|b| { + opens.iter().any(|o| o.order.is_some_and(|x| x.batch == b.id)) || held_memory_prompts.iter().any(|m| m.order.is_some_and(|x| x.batch == b.id)) + }); } /// The tab position for a member of a set that just opened: after the members before it that @@ -258,7 +260,7 @@ pub(crate) fn finish_open_tab(app: &mut PhotocraftApp, tab: &OpenTab, v: &Value) } let slot = tab.slot.or_else(|| tab.order.and_then(|o| batch_slot(&mut app.jobs, o))); let r = finish_open(app, &tab.name, tab.path.as_deref(), v, slot); - end_batch(&mut app.jobs); + end_batch(&mut app.jobs, &app.held_memory_prompts); r } @@ -513,7 +515,7 @@ fn on_event(app: &mut PhotocraftApp, ctx: &egui::Context, e: JobEvent) { app.ui.status_error = false; } } - end_batch(&mut app.jobs); + end_batch(&mut app.jobs, &app.held_memory_prompts); return; } match e.outcome { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 2a7af1fc7b..d94a408d91 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -689,6 +689,7 @@ pub struct PhotocraftApp { pub(crate) held_opens: std::collections::VecDeque, /// PSD files whose memory preflight requires user approval before pixel decoding (see `open_prompt`). pub(crate) held_memory_prompts: std::collections::VecDeque, + pub(crate) prompt_order: std::collections::VecDeque, /// A brush or gradient file waiting on the group-name prompt (see `preset_group_prompt`). pub(crate) held_preset_import: Option, /// Set once the user has agreed to quit, so the resulting close request goes through. diff --git a/crates/ui-egui/src/psd_open_tests.rs b/crates/ui-egui/src/psd_open_tests.rs index 728817a4fe..0765f65229 100644 --- a/crates/ui-egui/src/psd_open_tests.rs +++ b/crates/ui-egui/src/psd_open_tests.rs @@ -203,26 +203,443 @@ fn memory_confirmation_dialog_and_cancel_lifecycle() { let mut app = app(); let gb = 1u64 << 30; - // Simulate memory prompt arrival: - let preflight_id = app.session.store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { - id: 0, - name: "high_mem.psd".into(), - source: photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 16])), - fingerprint: photocraft_engine::jobs::SourceFingerprint::of(&photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 16]))).unwrap(), - required: 7 * gb, - soft_limit: 4 * gb, - hard_limit: 8 * gb, - available_ram: Some(10 * gb), - confirm_damage: true, - }); + let preflight_id = app + .session + .store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { + id: 0, + name: "high_mem.psd".into(), + source: photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 16])), + fingerprint: photocraft_engine::jobs::SourceFingerprint::of(&photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 16]))).unwrap(), + required: 7 * gb, + soft_limit: 4 * gb, + hard_limit: 8 * gb, + available_ram: Some(10 * gb), + confirm_damage: true, + }) + .unwrap(); crate::open_prompt::arrive_memory(&mut app, preflight_id, "high_mem.psd".into(), None, None, None, 7 * gb, Some(10 * gb)); assert_eq!(app.ui.dialogs.len(), 1); assert!(crate::open_prompt::owns_memory(&app.ui.dialogs[0].fields)); let dlg_id = app.ui.dialogs[0].id; - // Cancel via dialog cancel: assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": dlg_id}))["ok"], true); assert!(app.ui.dialogs.is_empty()); assert!(app.session.take_pending_preflight(preflight_id).is_none(), "pending preflight dropped on cancel"); + assert!(app.held_memory_prompts.is_empty()); + assert!(app.prompt_order.is_empty()); +} + +#[test] +fn memory_confirmation_resume_inline_success() { + let mut app = app(); + app.background_jobs = false; + let psd = recovery_psd::make_psd(false); + let (file, _) = photocraft_psd::PsdFile::from_bytes_and_merged(&psd, |_| false).unwrap(); + let est = photocraft_io::psd_budget::estimate(&file).unwrap().total_bytes; + let bytes = std::sync::Arc::new(psd); + let fp = photocraft_engine::jobs::SourceFingerprint::of(&photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::clone(&bytes))).unwrap(); + + let snap = photocraft_io::memory::MemorySnapshot { available_ram: Some((4 * est).max(4 << 30)), swap_free: None, commit_headroom: None }; + photocraft_io::memory::with_mock_memory(snap, || { + let budget = photocraft_io::memory::resolve_budget(snap, None); + let preflight_id = app + .session + .store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { + id: 0, + name: "inline_resume.psd".into(), + source: photocraft_engine::jobs::OpenSource::Bytes(bytes), + fingerprint: fp, + required: est, + soft_limit: budget.soft_limit, + hard_limit: budget.hard_limit, + available_ram: budget.available_ram, + confirm_damage: true, + }) + .unwrap(); + + crate::open_prompt::arrive_memory( + &mut app, + preflight_id, + "inline_resume.psd".into(), + Some("/test/inline_resume.psd".into()), + None, + None, + est, + budget.available_ram, + ); + assert_eq!(app.ui.dialogs.len(), 1); + let dlg_id = app.ui.dialogs[0].id; + + let res = call(&mut app, "ui.dialog.confirm", json!({"dialog": dlg_id})); + assert_eq!(res["ok"], true); + assert!(app.ui.dialogs.is_empty(), "dialog dismissed after inline resume"); + assert_eq!(app.session.documents().len(), 1, "document opened via inline resume"); + assert_eq!(app.session.documents()[0].doc.name, "inline_resume.psd"); + assert_eq!(app.session.documents()[0].path.as_deref(), Some("/test/inline_resume.psd")); + assert!(app.held_memory_prompts.is_empty()); + assert!(app.held_opens.is_empty()); + assert!(app.prompt_order.is_empty()); + assert!(app.jobs.opens.is_empty()); + }); +} + +#[test] +fn memory_confirmation_resume_background_success() { + let mut app = app(); + app.background_jobs = true; + let psd = recovery_psd::make_psd(false); + let (file, _) = photocraft_psd::PsdFile::from_bytes_and_merged(&psd, |_| false).unwrap(); + let est = photocraft_io::psd_budget::estimate(&file).unwrap().total_bytes; + let bytes = std::sync::Arc::new(psd); + let fp = photocraft_engine::jobs::SourceFingerprint::of(&photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::clone(&bytes))).unwrap(); + + let snap = photocraft_io::memory::MemorySnapshot { available_ram: Some((4 * est).max(4 << 30)), swap_free: None, commit_headroom: None }; + photocraft_io::memory::with_mock_memory(snap, || { + let budget = photocraft_io::memory::resolve_budget(snap, None); + let preflight_id = app + .session + .store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { + id: 0, + name: "bg_resume.psd".into(), + source: photocraft_engine::jobs::OpenSource::Bytes(bytes), + fingerprint: fp, + required: est, + soft_limit: budget.soft_limit, + hard_limit: budget.hard_limit, + available_ram: budget.available_ram, + confirm_damage: true, + }) + .unwrap(); + + crate::open_prompt::arrive_memory( + &mut app, + preflight_id, + "bg_resume.psd".into(), + Some("/test/bg_resume.psd".into()), + None, + None, + est, + budget.available_ram, + ); + assert_eq!(app.ui.dialogs.len(), 1); + let dlg_id = app.ui.dialogs[0].id; + + let res = call(&mut app, "ui.dialog.confirm", json!({"dialog": dlg_id})); + assert_eq!(res["ok"], true); + assert_eq!(app.jobs.opens.len(), 1, "background open job registered in jobs.opens"); + + let jobs: Vec<_> = app.session.jobs().iter().map(|j| j.id).collect(); + for id in jobs { + app.session.wait_job(id).unwrap(); + } + crate::jobs_ui::tick(&mut app, &egui::Context::default()); + assert_eq!(app.session.documents().len(), 1, "document opened via background resume"); + assert_eq!(app.session.documents()[0].doc.name, "bg_resume.psd"); + assert_eq!(app.session.documents()[0].path.as_deref(), Some("/test/bg_resume.psd")); + assert!(app.ui.dialogs.is_empty()); + assert!(app.held_memory_prompts.is_empty()); + assert!(app.held_opens.is_empty()); + assert!(app.prompt_order.is_empty()); + assert!(app.jobs.opens.is_empty()); + }); +} + +#[test] +fn memory_confirmation_refuses_when_source_changed_inline() { + let mut app = app(); + app.background_jobs = false; + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("changed.psd"); + std::fs::write(&path, b"initial file contents").unwrap(); + + let src = photocraft_engine::jobs::OpenSource::Path(path.to_string_lossy().to_string()); + let fp = photocraft_engine::jobs::SourceFingerprint::of(&src).unwrap(); + + let preflight_id = app + .session + .store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { + id: 0, + name: "changed.psd".into(), + source: src, + fingerprint: fp, + required: 1000, + soft_limit: 500, + hard_limit: 50_000, + available_ram: Some(100_000), + confirm_damage: true, + }) + .unwrap(); + + crate::open_prompt::arrive_memory(&mut app, preflight_id, "changed.psd".into(), Some(path.to_string_lossy().to_string()), None, None, 1000, Some(100_000)); + assert_eq!(app.ui.dialogs.len(), 1); + let dlg_id = app.ui.dialogs[0].id; + + // Mutate file before confirming: + std::fs::write(&path, b"modified file contents longer").unwrap(); + + let res = call(&mut app, "ui.dialog.confirm", json!({"dialog": dlg_id})); + assert_eq!(res["ok"], false, "confirming changed file inline must fail"); + assert!(app.session.documents().is_empty()); + assert!(app.held_memory_prompts.is_empty()); +} + +#[test] +fn memory_confirmation_refuses_when_source_changed_async() { + let mut app = app(); + app.background_jobs = true; + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("changed_async.psd"); + std::fs::write(&path, b"initial file contents").unwrap(); + + let src = photocraft_engine::jobs::OpenSource::Path(path.to_string_lossy().to_string()); + let fp = photocraft_engine::jobs::SourceFingerprint::of(&src).unwrap(); + + let preflight_id = app + .session + .store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { + id: 0, + name: "changed_async.psd".into(), + source: src, + fingerprint: fp, + required: 1000, + soft_limit: 500, + hard_limit: 50_000, + available_ram: Some(100_000), + confirm_damage: true, + }) + .unwrap(); + + crate::open_prompt::arrive_memory( + &mut app, + preflight_id, + "changed_async.psd".into(), + Some(path.to_string_lossy().to_string()), + None, + None, + 1000, + Some(100_000), + ); + assert_eq!(app.ui.dialogs.len(), 1); + let dlg_id = app.ui.dialogs[0].id; + + // Mutate file before confirming: + std::fs::write(&path, b"modified file contents longer").unwrap(); + + let res = call(&mut app, "ui.dialog.confirm", json!({"dialog": dlg_id})); + assert_eq!(res["ok"], true, "confirmation kicks off background job"); + assert_eq!(app.jobs.opens.len(), 1); + + // Run the job to completion and observe async failure: + let jobs: Vec<_> = app.session.jobs().iter().map(|j| j.id).collect(); + for id in jobs { + let _ = app.session.wait_job(id); + } + crate::jobs_ui::tick(&mut app, &egui::Context::default()); + + assert!(app.session.documents().is_empty(), "no document opened on changed file failure"); + assert!(app.jobs.opens.is_empty(), "opens cleared on job failure"); + assert!(app.ui.status_error, "error recorded in UI status"); +} + +#[test] +fn memory_decline_advances_queue_and_cleans_batch() { + let mut app = app(); + let batch_id = crate::jobs_ui::begin_batch(&mut app); + let order = crate::jobs_ui::OpenOrder { batch: batch_id, seq: 0 }; + + let preflight_id = app + .session + .store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { + id: 0, + name: "declined.psd".into(), + source: photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 16])), + fingerprint: photocraft_engine::jobs::SourceFingerprint::of(&photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 16]))).unwrap(), + required: 1000, + soft_limit: 500, + hard_limit: 2000, + available_ram: Some(4000), + confirm_damage: true, + }) + .unwrap(); + + crate::open_prompt::arrive_memory(&mut app, preflight_id, "declined.psd".into(), None, None, Some(order), 1000, Some(4000)); + assert_eq!(app.ui.dialogs.len(), 1); + let dlg_id = app.ui.dialogs[0].id; + + let res = call(&mut app, "ui.dialog.cancel", json!({"dialog": dlg_id})); + assert_eq!(res["ok"], true); + assert!(app.ui.dialogs.is_empty()); + assert!(app.session.take_pending_preflight(preflight_id).is_none()); + assert!(app.jobs.batches.is_empty(), "batch cleaned up on decline"); + assert!(app.prompt_order.is_empty()); +} + +#[test] +fn batch_single_file_cancel_preserves_other_held_memory_orders() { + let mut app = app(); + let batch_id = crate::jobs_ui::begin_batch(&mut app); + let order0 = crate::jobs_ui::OpenOrder { batch: batch_id, seq: 0 }; + let order1 = crate::jobs_ui::OpenOrder { batch: batch_id, seq: 1 }; + + let p0 = app + .session + .store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { + id: 0, + name: "first.psd".into(), + source: photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 4])), + fingerprint: photocraft_engine::jobs::SourceFingerprint::of(&photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 4]))).unwrap(), + required: 1000, + soft_limit: 500, + hard_limit: 2000, + available_ram: Some(4000), + confirm_damage: true, + }) + .unwrap(); + + let p1 = app + .session + .store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { + id: 0, + name: "second.psd".into(), + source: photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 4])), + fingerprint: photocraft_engine::jobs::SourceFingerprint::of(&photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 4]))).unwrap(), + required: 1000, + soft_limit: 500, + hard_limit: 2000, + available_ram: Some(4000), + confirm_damage: true, + }) + .unwrap(); + + crate::open_prompt::arrive_memory(&mut app, p0, "first.psd".into(), None, None, Some(order0), 1000, Some(4000)); + crate::open_prompt::arrive_memory(&mut app, p1, "second.psd".into(), None, None, Some(order1), 1000, Some(4000)); + + // Cancel first file: + let dlg0 = app.ui.dialogs[0].id; + assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": dlg0}))["ok"], true); + + // Batch must be preserved because second file is still waiting: + assert_eq!(app.jobs.batches.len(), 1, "batch preserved while second file is waiting"); + assert_eq!(app.held_memory_prompts.len(), 1); + + // Now cancel second file: + let dlg1 = app.ui.dialogs[0].id; + assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": dlg1}))["ok"], true); + assert!(app.jobs.batches.is_empty(), "batch cleaned after all members cancelled"); + assert!(app.prompt_order.is_empty()); +} + +#[test] +fn profile_cancel_cancels_whole_queue_including_memory_prompts() { + let mut app = app(); + let gb = 1u64 << 30; + + let preflight_id = app + .session + .store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { + id: 0, + name: "high_mem.psd".into(), + source: photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 16])), + fingerprint: photocraft_engine::jobs::SourceFingerprint::of(&photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 16]))).unwrap(), + required: 7 * gb, + soft_limit: 4 * gb, + hard_limit: 8 * gb, + available_ram: Some(10 * gb), + confirm_damage: true, + }) + .unwrap(); + + crate::open_prompt::arrive_memory(&mut app, preflight_id, "high_mem.psd".into(), None, None, None, 7 * gb, Some(10 * gb)); + + crate::open_prompt::arrive( + &mut app, + crate::open_prompt::Held { + doc: photocraft_doc::Document::new("test", photocraft_geom::Size::new(4, 4), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8), + read_only: false, + damage_pending: false, + name: "profile.psd".into(), + path: None, + warnings: vec![], + bytes: None, + slot: None, + question: Some(json!({"missing": false, "working": "sRGB", "embedded": "Adobe RGB"})), + policy_applied: false, + }, + ); + + let r = crate::open_prompt::answer(&mut app, None).unwrap(); + assert_eq!(r["cancelled"], 2, "both held open and memory prompt dropped"); + assert!(app.held_opens.is_empty()); + assert!(app.held_memory_prompts.is_empty()); + assert!(app.prompt_order.is_empty()); + assert!(app.session.take_pending_preflight(preflight_id).is_none(), "pending preflight cancelled"); +} + +#[test] +fn mixed_prompts_follow_arrival_order_fifo() { + let mut app = app(); + let gb = 1u64 << 30; + + // 1. Arrive damage prompt first + crate::open_prompt::arrive( + &mut app, + crate::open_prompt::Held { + doc: photocraft_doc::Document::new("test", photocraft_geom::Size::new(4, 4), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8), + read_only: false, + damage_pending: true, + name: "first_damage.psd".into(), + path: None, + warnings: vec!["damaged data".into()], + bytes: None, + slot: None, + question: None, + policy_applied: false, + }, + ); + + // 2. Arrive memory prompt second + let preflight_id = app + .session + .store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { + id: 0, + name: "second_mem.psd".into(), + source: photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 16])), + fingerprint: photocraft_engine::jobs::SourceFingerprint::of(&photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(vec![0; 16]))).unwrap(), + required: 7 * gb, + soft_limit: 4 * gb, + hard_limit: 8 * gb, + available_ram: Some(10 * gb), + confirm_damage: true, + }) + .unwrap(); + crate::open_prompt::arrive_memory(&mut app, preflight_id, "second_mem.psd".into(), None, None, None, 7 * gb, Some(10 * gb)); + + // First prompt shown must be damage (since it arrived first)! + assert_eq!(app.ui.dialogs.len(), 1); + assert!(crate::open_prompt::owns_damage(&app.ui.dialogs[0].fields)); + + // Cancel damage prompt: + let dlg_id = app.ui.dialogs[0].id; + assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": dlg_id}))["ok"], true); + + // Now memory prompt must be shown! + assert_eq!(app.ui.dialogs.len(), 1); + assert!(crate::open_prompt::owns_memory(&app.ui.dialogs[0].fields)); + let dlg_mem = app.ui.dialogs[0].id; + assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": dlg_mem}))["ok"], true); + assert!(app.ui.dialogs.is_empty()); +} + +#[test] +fn normal_image_open_does_not_require_timestamps_or_preflight_fingerprints() { + let mut app = app(); + // A synthetic 4x4 PNG/raw/flat image opens without timestamp or preflight checks + let bytes = std::sync::Arc::new(vec![0u8; 32]); + let src = photocraft_engine::jobs::OpenSource::Bytes(bytes); + // SourceFingerprint matches on same Bytes Arc without re-reading + let fp1 = photocraft_engine::jobs::SourceFingerprint::of(&src).unwrap(); + let fp2 = photocraft_engine::jobs::SourceFingerprint::of(&src).unwrap(); + assert_eq!(fp1, fp2); + assert!(fp1.matches(&fp2)); } diff --git a/docs/development.md b/docs/development.md index 7a2744eccc..286b235eca 100644 --- a/docs/development.md +++ b/docs/development.md @@ -670,12 +670,19 @@ physical RAM (excluding swap) and system commit headroom: - **Hard budget (H)**: $\min(75\% ext{ RAM}, ext{RAM} - 1 ext{ GiB}, ext{commit headroom} - 512 ext{ MiB}, ext{address-space limits})$. - **Soft budget (S)**: $\min(50\% ext{ RAM}, 8 ext{ GiB}, H)$. - Files requiring $\le S$ are admitted automatically. -- Files requiring $S < E \le H$ prompt for explicit one-shot user confirmation ("Open anyway") in the UI or require `approveHighMemory: true` for headless callers. +- Files requiring $S < E \le H$ prompt for explicit one-shot user confirmation ("Open anyway") in the UI. Headless callers default to no interactive dialog and require explicit per-invocation opt-in: + - Engine commands: `file.openAs` and `file.placeEmbedded` take `approveHighMemory: bool` (default `false`); `file.approveMemory` takes `{"id": u64, "approve": bool = true}`. + - Headless RPC / control protocol: `doc.open` and `doc.place` take `approveHighMemory: bool`. + - MCP: `doc_open` takes `approve_high_memory: bool`. + - CLI: `convert`, `info`, `run`, and `batch` take `--approve-high-memory`. + - Explicit approval authorizes imports within $(S, H]$ but never bypasses the hard memory budget $H$. - Files requiring $> H$ are refused and cannot be overridden. -- Fallback allowance when usable memory is unknown is 2 GiB with no confirmation override; WebAssembly uses a fixed 1 GiB limit. +- Fallback allowance when usable memory is unknown is 2 GiB with no confirmation override; this currently applies on macOS. Adaptive memory detection is available on Linux and Windows. WebAssembly uses a fixed 1 GiB limit. - Applications can lower the admission threshold with `ImportOptions::psd_max_pixel_bytes`; explicit caller limits may lower admission, never bypass the hard boundary. - Concurrent PSD decodes are serialized using a process-wide, cancellation-aware admission gate, with nested decodes sharing the enclosing allowance. +Headless RPC and MCP report structured memory errors with byte counts (`required`, `softLimit`, `hardLimit`, and `availableRam` when known). GUI automation imports currently cross a service boundary that returns string errors. + An import exceeding the hard budget returns `IoError::PsdImportBudget` with the estimated and allowed byte counts; imports requiring confirmation return `IoError::PsdApprovalRequired` when unapproved. Damaged-file recovery never bypasses these memory guards. The legacy