From 6352916c338d7516443b040845ee9e0466f4cab4 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 16 Nov 2026 14:06:13 -0800 Subject: [PATCH 01/19] Show unreadable-file failures in modal alerts --- crates/ui-egui/src/file_open.rs | 26 ++- .../src/file_open/unreadable_alert_tests.rs | 154 ++++++++++++++++++ 2 files changed, 174 insertions(+), 6 deletions(-) create mode 100644 crates/ui-egui/src/file_open/unreadable_alert_tests.rs diff --git a/crates/ui-egui/src/file_open.rs b/crates/ui-egui/src/file_open.rs index 1ae2be2003..e577c2d451 100644 --- a/crates/ui-egui/src/file_open.rs +++ b/crates/ui-egui/src/file_open.rs @@ -327,7 +327,7 @@ impl PhotocraftApp { // prompt that is answered later all place the file at its place in the set. match self.open_path_placed(abs, None, Some(order)) { Ok(_) => opened += 1, - Err(e) => self.open_failed(&display_name(abs), &e), + Err(e) => self.open_failed(abs, &e), } } crate::jobs_ui::end_batch(self); @@ -361,12 +361,23 @@ impl PhotocraftApp { true } - /// Show "Couldn't open : " as an error (status bar + notice). - pub fn open_failed(&mut self, name: &str, err: &str) { - self.failed({ + /// Report one failed open in an OK alert, naming its source file once. Pass the source path + /// when available so its exact prefix can be removed from filesystem read errors too. + pub fn open_failed(&mut self, source: &str, err: &str) { + let name = display_name(source); + let source_prefix = format!("{source}: "); + let name_prefix = format!("{name}: "); + let reason = err.strip_prefix(&source_prefix).or_else(|| err.strip_prefix(&name_prefix)).unwrap_or(err); + let msg = if reason == "codec: unrecognized image format" { + crate::i18n::fmt(tl!("Could not open \"{name}\" because PhotoCraft does not recognize this type of file."), &[("name", &name)]) + } else { let template = "Couldn't open {name}: {error}"; - crate::i18n::fmt(tl!(template), &[("name", name), ("error", err)]) - }); + crate::i18n::fmt(tl!(template), &[("name", &name), ("error", reason)]) + }; + log::warn!("{msg}"); + self.ui.status = msg.clone(); + self.ui.status_error = true; + self.ui.open_dialog(crate::state::DialogKind::Error, serde_json::json!({"message": msg}).as_object().cloned().unwrap_or_default()); } /// Show "Couldn't place : " as an error (status bar + notice). @@ -712,3 +723,6 @@ fn same_file(p: &str, path: &str, canon: Option<&std::path::Path>) -> bool { mod dialog_order_tests; #[cfg(test)] mod tests; + +#[cfg(test)] +mod unreadable_alert_tests; diff --git a/crates/ui-egui/src/file_open/unreadable_alert_tests.rs b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs new file mode 100644 index 0000000000..2268c819a1 --- /dev/null +++ b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs @@ -0,0 +1,154 @@ +//! #14059: unreadable File > Open inputs use one modal alert per file, while callers that +//! request an error result still receive it. + +use super::*; +use crate::control::{ControlRequest, Outcome, handle}; +use crate::file_dialog::{self, FileDialogAnswer}; +use crate::state::DialogKind; +use crate::{Services, menus}; +use egui_kittest::kittest::Queryable; +use serde_json::json; + +fn app_with(answer: Option) -> PhotocraftApp { + let services = Services { file_dialog: Some(file_dialog::fake(vec![answer]).0), ..Default::default() }; + PhotocraftApp::new(photocraft_engine::Session::new(), services) +} + +fn pick(app: &mut PhotocraftApp) { + menus::invoke(app, &egui::Context::default(), "file.open", json!({})).unwrap(); + app.poll_file_dialog(&egui::Context::default(), None); +} + +fn messages(app: &PhotocraftApp) -> Vec<&str> { + app.ui.dialogs.iter().filter(|d| d.kind == DialogKind::Error).map(|d| d.fields["message"].as_str().unwrap()).collect() +} + +fn expected(name: &str) -> String { + format!("Could not open \"{name}\" because PhotoCraft does not recognize this type of file.") +} + +fn png() -> Vec { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 2, "height": 2, "background": "white"})).unwrap(); + photocraft_io::export(&s.active().unwrap().doc, "valid.png", &Default::default()).unwrap().bytes +} + +#[test] +fn unrecognized_and_mislabeled_files_show_the_exact_alert_without_opening_documents() { + for (name, bytes) in [("notes.txt", b"ordinary text".to_vec()), ("broken.png", b"ordinary text".to_vec()), ("zz-bad.png", (1..=17).collect())] { + let mut app = app_with(Some(FileDialogAnswer::Contents(name.into(), bytes))); + pick(&mut app); + assert_eq!(messages(&app), [expected(name)]); + assert!(app.session.documents().is_empty()); + assert!(app.ui.recent_files.is_empty()); + assert!(app.ui.notices.is_empty(), "the modal replaces the corner notice"); + assert!(app.ui.status_error); + assert_eq!(app.ui.status, expected(name)); + assert_eq!(app.ui.status.matches(name).count(), 1); + } +} + +#[test] +fn an_open_failure_alert_has_one_ok_button_and_closes_when_clicked() { + let mut app = app_with(None); + app.open_failed("notes.txt", "notes.txt: codec: unrecognized image format"); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 600.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(3); + assert!(h.query_by_label(&expected("notes.txt")).is_some()); + assert!(h.query_by_label("Cancel").is_none()); + h.get_by_label("OK").click(); + h.run_steps(3); + assert!(h.state().ui.dialogs.is_empty()); + assert!(h.state().session.documents().is_empty()); +} + +#[test] +fn other_read_errors_keep_their_reason_and_only_exact_leading_source_prefixes_are_removed() { + let source = std::path::Path::new("pictures").join("missing.png").to_string_lossy().into_owned(); + for err in [format!("{source}: file not found"), "missing.png: permission denied".into(), "the directory is missing.png: keep this reason".into()] { + let mut app = app_with(None); + app.open_failed(&source, &err); + let reason = if err.starts_with(&source) { + "file not found" + } else if err.starts_with("missing.png: ") { + "permission denied" + } else { + &err + }; + assert_eq!(messages(&app), [format!("Couldn't open missing.png: {reason}")]); + assert!(app.ui.notices.is_empty()); + } +} + +#[test] +fn several_failed_files_each_get_one_alert_and_valid_files_still_open() { + let files = vec![("a.txt".into(), b"text".to_vec()), ("b.png".into(), png()), ("c.png".into(), b"text".to_vec()), ("d.png".into(), png())]; + let mut app = app_with(Some(FileDialogAnswer::ContentsMany(files))); + pick(&mut app); + assert_eq!(messages(&app), [expected("a.txt"), expected("c.png")]); + assert_eq!(app.session.documents().iter().map(|d| d.doc.name.as_str()).collect::>(), ["b.png", "d.png"]); + assert!(app.ui.notices.iter().all(|n| !n.error)); + let first = app.ui.dialogs[0].id; + crate::dialogs::confirm(&mut app, first).unwrap(); + assert_eq!(messages(&app), [expected("c.png")]); + let second = app.ui.dialogs[0].id; + crate::dialogs::confirm(&mut app, second).unwrap(); + assert!(messages(&app).is_empty()); + assert_eq!(app.session.documents().len(), 2); +} + +#[test] +fn background_open_failures_are_reported_once_when_the_jobs_finish() { + let mut app = app_with(None); + app.background_jobs = true; + app.open_bytes("first.txt", b"text").unwrap(); + app.open_bytes("second.png", b"text").unwrap(); + app.open_bytes("valid.png", &png()).unwrap(); + let ctx = egui::Context::default(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + while !app.jobs.opens.is_empty() { + assert!(std::time::Instant::now() < deadline, "open jobs did not finish"); + crate::jobs_ui::tick(&mut app, &ctx); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + let mut actual = messages(&app).into_iter().map(str::to_owned).collect::>(); + actual.sort(); + let mut wanted = vec![expected("first.txt"), expected("second.png")]; + wanted.sort(); + assert_eq!(actual, wanted); + assert_eq!(app.session.documents().iter().map(|d| d.doc.name.as_str()).collect::>(), ["valid.png"]); + crate::jobs_ui::tick(&mut app, &ctx); + assert_eq!(messages(&app).len(), 2, "a consumed failure event cannot show twice"); + assert!(app.ui.notices.iter().all(|n| !n.error)); +} + +#[test] +fn cancelling_file_open_does_not_show_an_error() { + let mut app = app_with(None); + pick(&mut app); + assert!(!app.file_dialog_open()); + assert!(app.session.documents().is_empty()); + assert!(app.ui.dialogs.is_empty()); + assert!(app.ui.notices.is_empty()); + assert!(!app.ui.status_error); +} + +#[test] +fn automation_and_control_open_still_return_the_original_error() { + let mut app = app_with(None); + app.services.import = Some(Box::new(|name, bytes, opts| { + photocraft_io::import_with_options(name, bytes, opts).map(|r| (r.document, r.warnings)).map_err(|e| format!("{name}: {e}")) + })); + let err = app.open_automation_bytes("notes.txt", b"text").unwrap_err(); + assert_eq!(err, "notes.txt: codec: unrecognized image format"); + assert!(app.ui.dialogs.is_empty()); + app.services.automation_read = Some(Box::new(|_| Ok(crate::AutomationReadResult { name: "notes.txt".into(), bytes: b"text".to_vec(), save_path: None }))); + let (request, _rx) = ControlRequest::new("app.open", json!({"path": "notes.txt"})); + let Outcome::Done(reply) = handle(&mut app, &egui::Context::default(), &request) else { panic!("open should return immediately") }; + assert_eq!(reply["ok"], false); + assert_eq!(reply["error"], err); + assert!(app.session.documents().is_empty()); + assert!(app.ui.dialogs.is_empty()); + assert!(app.ui.notices.is_empty()); +} From 065abdffc68f6736301f33cb11637f7f2771b4ac Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 16 Nov 2026 14:38:50 -0800 Subject: [PATCH 02/19] Configure real imports and fonts in unreadable-alert tests --- .../src/file_open/unreadable_alert_tests.rs | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/file_open/unreadable_alert_tests.rs b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs index 2268c819a1..8251221539 100644 --- a/crates/ui-egui/src/file_open/unreadable_alert_tests.rs +++ b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs @@ -10,7 +10,13 @@ use egui_kittest::kittest::Queryable; use serde_json::json; fn app_with(answer: Option) -> PhotocraftApp { - let services = Services { file_dialog: Some(file_dialog::fake(vec![answer]).0), ..Default::default() }; + let services = Services { + file_dialog: Some(file_dialog::fake(vec![answer]).0), + import: Some(Box::new(|name, bytes, opts| { + photocraft_io::import_with_options(name, bytes, opts).map(|r| (r.document, r.warnings)).map_err(|e| format!("{name}: {e}")) + })), + ..Default::default() + }; PhotocraftApp::new(photocraft_engine::Session::new(), services) } @@ -52,8 +58,10 @@ fn unrecognized_and_mislabeled_files_show_the_exact_alert_without_opening_docume fn an_open_failure_alert_has_one_ok_button_and_closes_when_clicked() { let mut app = app_with(None); app.open_failed("notes.txt", "notes.txt: codec: unrecognized image format"); - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 600.0)).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); - PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + let mut h = egui_kittest::Harness::builder() + .with_size(egui::vec2(900.0, 600.0)) + .with_context_setup(|ctx| PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ALL[0])) + .build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app); h.run_steps(3); assert!(h.query_by_label(&expected("notes.txt")).is_some()); assert!(h.query_by_label("Cancel").is_none()); From c10e7f277db16b3a41006969f2c39248beae931c Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 16 Nov 2026 18:22:05 -0800 Subject: [PATCH 03/19] Update Open failure tests for modal unreadable-file alerts --- crates/ui-egui/src/file_open/tests.rs | 37 +++++++++++++++++++-------- 1 file changed, 26 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/file_open/tests.rs b/crates/ui-egui/src/file_open/tests.rs index 6f015aad0b..26f71e3652 100644 --- a/crates/ui-egui/src/file_open/tests.rs +++ b/crates/ui-egui/src/file_open/tests.rs @@ -170,7 +170,7 @@ fn the_web_opens_every_selected_file() { // Each good file is its own tab; the broken one is reported without stopping the rest. let names: Vec<_> = app.session.documents().iter().map(|st| st.doc.name.as_str()).collect(); assert_eq!(names, ["one.png", "two.jpg"]); - assert!(app.ui.notices.iter().any(|n| n.error && n.title.contains("broken.png")), "{:?}", app.ui.notices); + assert!(open_error_messages(&app).iter().any(|message| message.contains("broken.png")), "{:?}", app.ui.dialogs); } /// #5749: the web shell reads dropped files itself, so it asks where they landed: image files @@ -401,7 +401,7 @@ fn open_failures_are_errors_and_leave_no_document() { assert!(app.ui.recent_files.is_empty()); assert!(app.ui.status_error); assert!(app.ui.status.starts_with("Couldn't open broken.psd"), "{}", app.ui.status); - assert!(app.ui.notices.last().is_some_and(|n| n.error)); + assert_eq!(open_error_messages(&app).len(), 1); let _ = std::fs::remove_dir_all(&dir); } @@ -414,8 +414,11 @@ fn a_picked_file_that_cannot_be_read_is_reported_like_any_open_failure() { answer(&mut app); assert!(app.session.documents().is_empty()); assert!(app.ui.status_error); - let notice = app.ui.notices.last().unwrap(); - assert!(notice.error && notice.title.starts_with("Couldn't open big.psb: "), "{}", notice.title); + let messages = open_error_messages(&app); + assert_eq!(messages.len(), 1); + assert!(messages[0].starts_with("Couldn't open big.psb: "), "{}", messages[0]); + let alert = app.ui.dialogs.last().unwrap().id; + crate::dialogs::confirm(&mut app, alert).unwrap(); // Commands that read a picked file (scripts, notes, Place) fail with the file's name. app.ui.status_error = false; app.pick_file_bytes(|_, _, _| Err("read".into())).unwrap(); @@ -436,7 +439,8 @@ fn open_paths_reports_each_failure_without_panicking() { assert_eq!(n, 0); assert!(app.session.documents().is_empty()); assert!(app.ui.status_error); - assert_eq!(app.ui.notices.len(), notices::MAX_NOTICES); + assert_eq!(open_error_messages(&app).len(), 4, "every failing path has its own alert"); + assert!(app.ui.notices.is_empty()); // Bad control params error instead of panicking. let ctx = egui::Context::default(); assert!(menus::invoke(&mut app, &ctx, "file.open", json!({ "path": "" })).is_err()); @@ -545,7 +549,7 @@ fn dropped_files_open_with_path_and_recent() { assert_eq!(app.session.documents()[1].path, None); assert_eq!(app.ui.recent_files, vec![abs_s]); assert!(app.ui.status_error); - assert_eq!(app.ui.notices.iter().filter(|n| n.error).count(), 2); + assert_eq!(open_error_messages(&app).len(), 2); let _ = std::fs::remove_dir_all(&dir); } @@ -1860,6 +1864,10 @@ fn error_titles(app: &PhotocraftApp) -> Vec { app.ui.notices.iter().filter(|n| n.error).map(|n| n.title.clone()).collect() } +fn open_error_messages(app: &PhotocraftApp) -> Vec { + app.ui.dialogs.iter().filter(|d| d.kind == crate::state::DialogKind::Error).map(|d| d.fields["message"].as_str().unwrap().to_owned()).collect() +} + /// The Home screen (no document open) is where a first drop lands: every file opens as its own /// document, in drop order, whatever the type, and nothing is placed. #[test] @@ -1882,6 +1890,7 @@ fn files_dropped_with_no_document_open_all_open() { assert_eq!(doc_names(&app), names); assert!(app.drop_places.is_empty()); assert!(error_titles(&app).is_empty(), "{:?}", app.ui.notices); + assert!(open_error_messages(&app).is_empty(), "{:?}", app.ui.dialogs); let _ = std::fs::remove_dir_all(&dir); } @@ -1899,7 +1908,7 @@ fn a_dropped_folder_is_refused_with_a_clear_message() { let (mut app, _) = app_with(Vec::new()); app.open_dropped(&ctx, vec![dropped(folder.clone(), Err("read from the path".into())), dropped(file, Err("read from the path".into()))], None); assert_eq!(doc_names(&app), ["ok.psd"]); - let errors = error_titles(&app); + let errors = open_error_messages(&app); assert_eq!(errors.len(), 1, "{errors:?}"); assert!(errors[0].starts_with("Couldn't open Holiday photos: ") && errors[0].contains("folder"), "{errors:?}"); // On the canvas: not queued for placing, and the layers stay as they were. @@ -1927,7 +1936,7 @@ fn a_dropped_file_that_is_not_an_image_reports_why() { app.open_dropped(&ctx, vec![dropped(file.clone(), Err("read from the path".into()))], None); assert!(app.session.documents().is_empty()); assert!(app.ui.status_error); - assert!(error_titles(&app).iter().any(|t| t.starts_with("Couldn't open notes.txt: ")), "{:?}", app.ui.notices); + assert!(open_error_messages(&app).iter().any(|t| t.starts_with("Couldn't open notes.txt: ")), "{:?}", app.ui.dialogs); let mut app = app_with_canvas(); let layers = layer_count(&app); app.open_dropped(&ctx, vec![dropped(file, Err("read from the path".into()))], Some(egui::pos2(300.0, 300.0))); @@ -1962,7 +1971,7 @@ fn several_files_dropped_on_the_canvas_are_queued_in_order() { }) .collect(); assert_eq!(queued, ["one.png", "two.jpg"]); - assert!(error_titles(&app).iter().any(|t| t.starts_with("Couldn't open set.abr: ")), "{:?}", app.ui.notices); + assert!(open_error_messages(&app).iter().any(|t| t.starts_with("Couldn't open set.abr: ")), "{:?}", app.ui.dialogs); } #[test] @@ -1997,7 +2006,10 @@ fn open_as_smart_object_dialog_opens_one_document_per_selected_file() { assert_eq!(app.session.documents().iter().map(|d| d.doc.name.as_str()).collect::>(), ["one-1", "two-1"]); assert!(app.session.documents().iter().all(|d| d.path.is_none() && d.doc.layers.len() == 1)); - assert!(app.ui.notices.iter().any(|n| n.error && n.title.starts_with("Couldn't open bad.png")), "the unreadable file is reported"); + assert!( + open_error_messages(&app).iter().any(|message| message == "Could not open \"bad.png\" because PhotoCraft does not recognize this type of file."), + "the unreadable file is reported" + ); let _ = std::fs::remove_dir_all(&dir); } @@ -2019,7 +2031,10 @@ fn open_as_smart_object_opens_in_the_background_in_name_order() { tick_until(&mut app, &ctx, |app| app.jobs.opens.is_empty()); assert_eq!(app.session.documents().iter().map(|d| d.doc.name.as_str()).collect::>(), ["one-1", "two-1"]); assert!(app.session.documents().iter().all(|d| d.path.is_none() && d.doc.layers.len() == 1)); - assert!(app.ui.notices.iter().any(|n| n.error && n.title.starts_with("Couldn't open bad.png")), "the unreadable file is reported"); + assert!( + open_error_messages(&app).iter().any(|message| message == "Could not open \"bad.png\" because PhotoCraft does not recognize this type of file."), + "the unreadable file is reported" + ); let _ = std::fs::remove_dir_all(&dir); } From 16d9a0dc13f94959e54fb809b22622301cda06b4 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Mon, 16 Nov 2026 19:57:55 -0800 Subject: [PATCH 04/19] Preserve read sources in unreadable-file alerts --- crates/ui-egui/src/app/files.rs | 7 +- .../ui-egui/src/canvas/scroll_all_windows.rs | 2 +- crates/ui-egui/src/dialogs/open_prompt.rs | 18 +- crates/ui-egui/src/file_dialog.rs | 2 +- crates/ui-egui/src/file_open.rs | 14 +- crates/ui-egui/src/file_open/tests.rs | 13 +- .../src/file_open/unreadable_alert_tests.rs | 230 ++++++++++++++++-- crates/ui-egui/src/home_recent_ui.rs | 2 +- crates/ui-egui/src/jobs_ui.rs | 20 +- crates/ui-egui/src/jobs_ui/tests.rs | 2 +- crates/ui-egui/src/psd_open_tests.rs | 7 +- 11 files changed, 274 insertions(+), 43 deletions(-) diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 1fa6b5ec16..dbeb45ceb0 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -82,7 +82,6 @@ impl PhotocraftApp { if let Some(r) = preset_files_ui::open(self, name, bytes) { return r.map(|()| Vec::new()); } - let name = &self.open_name(name); // Decoded on a worker: a tab with progress appears now, the document when it's ready // (warnings are shown then). if self.background_jobs { @@ -117,6 +116,12 @@ impl PhotocraftApp { let (doc, warnings) = import(name, bytes, &opts)?; (doc, warnings, false) }; + // Decode under the source name; only a successfully opened template becomes untitled. + let opened_name = self.open_name(name); + if opened_name != name { + doc.name = opened_name.clone(); + } + let name = &opened_name; // Preferences › Raw Defaults › Resolution, as the engine's open applies it. photocraft_engine::file_cmds::raw_defaults(&self.session, &warnings, &mut doc); // Edit › Color Settings policies apply on open; Ask When Opening holds the file back diff --git a/crates/ui-egui/src/canvas/scroll_all_windows.rs b/crates/ui-egui/src/canvas/scroll_all_windows.rs index 34d15b4897..b27519f50e 100644 --- a/crates/ui-egui/src/canvas/scroll_all_windows.rs +++ b/crates/ui-egui/src/canvas/scroll_all_windows.rs @@ -272,7 +272,7 @@ mod tests { app.ui.chrome.home = Some(app.session.documents().len()); } else { let job = photocraft_engine::jobs::JobId(9); - app.jobs.opens.push(crate::jobs_ui::OpenTab { job, name: "opening.psd".into(), path: None, slot: None, order: None }); + app.jobs.opens.push(crate::jobs_ui::OpenTab { job, name: "opening.psd".into(), path: None, error_source: None, slot: None, order: None }); app.jobs.focus = Some(job); } diff --git a/crates/ui-egui/src/dialogs/open_prompt.rs b/crates/ui-egui/src/dialogs/open_prompt.rs index 4c7c49618f..e48418505d 100644 --- a/crates/ui-egui/src/dialogs/open_prompt.rs +++ b/crates/ui-egui/src/dialogs/open_prompt.rs @@ -466,13 +466,27 @@ pub(crate) fn answer_memory(app: &mut PhotocraftApp, accept: bool) -> Result { 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.opens.push(crate::jobs_ui::OpenTab { + job: photocraft_engine::jobs::JobId(job), + name: name.clone(), + path, + error_source: None, + 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 }; + let tab = crate::jobs_ui::OpenTab { + job: photocraft_engine::jobs::JobId(0), + name: name.clone(), + path: path.clone(), + error_source: None, + slot, + order, + }; if let Err(e) = crate::jobs_ui::finish_open_tab(app, &tab, result) { app.ui.status = e; app.ui.status_error = true; diff --git a/crates/ui-egui/src/file_dialog.rs b/crates/ui-egui/src/file_dialog.rs index aabff48324..a7829f735c 100644 --- a/crates/ui-egui/src/file_dialog.rs +++ b/crates/ui-egui/src/file_dialog.rs @@ -312,7 +312,7 @@ impl PhotocraftApp { for (seq, path) in paths.iter().enumerate() { let order = crate::jobs_ui::OpenOrder { batch, seq }; if let Err(e) = crate::jobs_ui::start_open_as_smart_object(app, path, Some(order)) { - app.open_failed(&crate::file_open::display_name(path), &e); + app.open_failed(path, &e); } } crate::jobs_ui::end_batch(app); diff --git a/crates/ui-egui/src/file_open.rs b/crates/ui-egui/src/file_open.rs index e577c2d451..7ed8f34a17 100644 --- a/crates/ui-egui/src/file_open.rs +++ b/crates/ui-egui/src/file_open.rs @@ -367,7 +367,14 @@ impl PhotocraftApp { let name = display_name(source); let source_prefix = format!("{source}: "); let name_prefix = format!("{name}: "); - let reason = err.strip_prefix(&source_prefix).or_else(|| err.strip_prefix(&name_prefix)).unwrap_or(err); + // The native background importer wraps its path-prefixed read error in the file name. + let wrapped_source_prefix = format!("{name}: {source}: "); + let reason = (source != name) + .then(|| err.strip_prefix(&wrapped_source_prefix)) + .flatten() + .or_else(|| err.strip_prefix(&source_prefix)) + .or_else(|| err.strip_prefix(&name_prefix)) + .unwrap_or(err); let msg = if reason == "codec: unrecognized image format" { crate::i18n::fmt(tl!("Could not open \"{name}\" because PhotoCraft does not recognize this type of file."), &[("name", &name)]) } else { @@ -429,7 +436,10 @@ impl PhotocraftApp { match self.open_dropped_file(&f, &name, slot) { Ok(true) => slot = slot.map(|s| s + 1), Ok(false) => {} - Err(e) => self.open_failed(&name, &e), + Err(e) => { + let source = if f.path().is_absolute() { f.path().to_string_lossy().into_owned() } else { name.clone() }; + self.open_failed(&source, &e); + } } } } diff --git a/crates/ui-egui/src/file_open/tests.rs b/crates/ui-egui/src/file_open/tests.rs index 26f71e3652..9cb1c6b28f 100644 --- a/crates/ui-egui/src/file_open/tests.rs +++ b/crates/ui-egui/src/file_open/tests.rs @@ -1552,7 +1552,14 @@ fn a_set_of_background_opens_keeps_its_order_however_they_finish() { let (mut app, _) = app_with(Vec::new()); app.open_bytes("existing.psd", b"x").unwrap(); let batch = jobs_ui::begin_batch(&mut app); - let tab = |seq: usize| OpenTab { job: JobId(100 + seq as u64), name: format!("f{seq}.psd"), path: None, slot: None, order: Some(OpenOrder { batch, seq }) }; + let tab = |seq: usize| OpenTab { + job: JobId(100 + seq as u64), + name: format!("f{seq}.psd"), + path: None, + error_source: None, + slot: None, + order: Some(OpenOrder { batch, seq }), + }; app.jobs.opens.extend((0..4).map(tab)); // f1 opened at once (a preset file, say, or background jobs off for it). app.jobs.opens.remove(1); @@ -1574,11 +1581,11 @@ fn a_set_of_background_opens_keeps_its_order_however_they_finish() { assert_eq!(app.ui.views.len(), 5, "views follow their documents"); assert!(app.jobs.batches.is_empty(), "forgotten once every member opened"); // A tab with a slot (dropped on the tabs) keeps it; one from a forgotten set goes to the end. - let dropped = OpenTab { job: JobId(200), name: "dropped.psd".into(), path: None, slot: Some(0), order: None }; + let dropped = OpenTab { job: JobId(200), name: "dropped.psd".into(), path: None, error_source: None, slot: Some(0), order: None }; let index = app.session.add_document(Document::new("dropped.psd", Size::new(4, 4), ColorMode::Rgb, SampleType::U8), None); let id = app.session.documents()[index].doc.id; jobs_ui::finish_open_tab(&mut app, &dropped, &json!({"document": index, "docId": id.0})).unwrap(); - let late = OpenTab { job: JobId(201), name: "late.psd".into(), path: None, slot: None, order: Some(OpenOrder { batch: 999, seq: 0 }) }; + let late = OpenTab { job: JobId(201), name: "late.psd".into(), path: None, error_source: None, slot: None, order: Some(OpenOrder { batch: 999, seq: 0 }) }; let index = app.session.add_document(Document::new("late.psd", Size::new(4, 4), ColorMode::Rgb, SampleType::U8), None); let id = app.session.documents()[index].doc.id; jobs_ui::finish_open_tab(&mut app, &late, &json!({"document": index, "docId": id.0})).unwrap(); diff --git a/crates/ui-egui/src/file_open/unreadable_alert_tests.rs b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs index 8251221539..561c8eba5c 100644 --- a/crates/ui-egui/src/file_open/unreadable_alert_tests.rs +++ b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs @@ -41,17 +41,46 @@ fn png() -> Vec { #[test] fn unrecognized_and_mislabeled_files_show_the_exact_alert_without_opening_documents() { - for (name, bytes) in [("notes.txt", b"ordinary text".to_vec()), ("broken.png", b"ordinary text".to_vec()), ("zz-bad.png", (1..=17).collect())] { + for (name, bytes) in [ + ("notes.txt", b"ordinary text".to_vec()), + ("broken.png", b"ordinary text".to_vec()), + ("zz-bad.png", (1..=17).collect()), + ("unknown.psdt", b"ordinary text".to_vec()), + ] { let mut app = app_with(Some(FileDialogAnswer::Contents(name.into(), bytes))); pick(&mut app); - assert_eq!(messages(&app), [expected(name)]); + let wanted = + if name == "unknown.psdt" { format!("Couldn't open {name}: PSD: invalid signature [111, 114, 100, 105], expected 8BPS") } else { expected(name) }; + assert_eq!(messages(&app), [wanted.as_str()]); assert!(app.session.documents().is_empty()); assert!(app.ui.recent_files.is_empty()); assert!(app.ui.notices.is_empty(), "the modal replaces the corner notice"); assert!(app.ui.status_error); - assert_eq!(app.ui.status, expected(name)); + assert_eq!(app.ui.status, wanted); assert_eq!(app.ui.status.matches(name).count(), 1); } + // Interactive foreground errors now retain the source name instead of a generated Untitled-N. + let mut interactive = app_with(None); + assert_eq!( + interactive.open_bytes("unknown.psdt", b"ordinary text").unwrap_err(), + "unknown.psdt: PSD: invalid signature [111, 114, 100, 105], expected 8BPS" + ); + assert!(interactive.ui.dialogs.is_empty(), "the caller owns presentation of a returned error"); + + #[cfg(not(target_arch = "wasm32"))] + { + let mut app = app_with(Some(FileDialogAnswer::Contents("unknown.psdt".into(), b"ordinary text".to_vec()))); + app.background_jobs = true; + pick(&mut app); + assert_eq!(app.jobs.opens.len(), 1); + let tab = &app.jobs.opens[0]; + assert_eq!(tab.name, "Untitled-1"); + assert!(tab.path.is_none()); + assert_eq!(tab.error_source.as_deref(), Some("unknown.psdt")); + let worker_error = format!("{}: codec: unrecognized image format", tab.name); + finish_read_failure(&mut app, "unknown.psdt", "codec: unrecognized image format", &worker_error); + assert!(app.ui.recent_files.is_empty()); + } } #[test] @@ -74,16 +103,15 @@ fn an_open_failure_alert_has_one_ok_button_and_closes_when_clicked() { #[test] fn other_read_errors_keep_their_reason_and_only_exact_leading_source_prefixes_are_removed() { let source = std::path::Path::new("pictures").join("missing.png").to_string_lossy().into_owned(); - for err in [format!("{source}: file not found"), "missing.png: permission denied".into(), "the directory is missing.png: keep this reason".into()] { + for (err, reason) in [ + (format!("{source}: file not found"), "file not found"), + ("missing.png: permission denied".into(), "permission denied"), + (format!("missing.png: {source}: file not found"), "file not found"), + ("missing.png: elsewhere/missing.png: keep this reason".into(), "elsewhere/missing.png: keep this reason"), + ("the directory is missing.png: keep this reason".into(), "the directory is missing.png: keep this reason"), + ] { let mut app = app_with(None); app.open_failed(&source, &err); - let reason = if err.starts_with(&source) { - "file not found" - } else if err.starts_with("missing.png: ") { - "permission denied" - } else { - &err - }; assert_eq!(messages(&app), [format!("Couldn't open missing.png: {reason}")]); assert!(app.ui.notices.is_empty()); } @@ -144,19 +172,173 @@ fn cancelling_file_open_does_not_show_an_error() { #[test] fn automation_and_control_open_still_return_the_original_error() { - let mut app = app_with(None); - app.services.import = Some(Box::new(|name, bytes, opts| { - photocraft_io::import_with_options(name, bytes, opts).map(|r| (r.document, r.warnings)).map_err(|e| format!("{name}: {e}")) - })); - let err = app.open_automation_bytes("notes.txt", b"text").unwrap_err(); - assert_eq!(err, "notes.txt: codec: unrecognized image format"); - assert!(app.ui.dialogs.is_empty()); - app.services.automation_read = Some(Box::new(|_| Ok(crate::AutomationReadResult { name: "notes.txt".into(), bytes: b"text".to_vec(), save_path: None }))); - let (request, _rx) = ControlRequest::new("app.open", json!({"path": "notes.txt"})); - let Outcome::Done(reply) = handle(&mut app, &egui::Context::default(), &request) else { panic!("open should return immediately") }; - assert_eq!(reply["ok"], false); - assert_eq!(reply["error"], err); + // app.open reserves the template's untitled name before its separate automation decode. + for (name, expected_error, expected_control_error) in [ + ("notes.txt", "notes.txt: codec: unrecognized image format", "notes.txt: codec: unrecognized image format"), + ("unknown.psdt", "unknown.psdt: PSD: invalid signature [116, 101, 120, 116], expected 8BPS", "Untitled-1: codec: unrecognized image format"), + ] { + let mut app = app_with(None); + let err = app.open_automation_bytes(name, b"text").unwrap_err(); + assert_eq!(err, expected_error); + assert!(app.ui.dialogs.is_empty()); + let read_name = name.to_string(); + app.services.automation_read = + Some(Box::new(move |_| Ok(crate::AutomationReadResult { name: read_name.clone(), bytes: b"text".to_vec(), save_path: None }))); + let (request, _rx) = ControlRequest::new("app.open", json!({"path": name})); + let Outcome::Done(reply) = handle(&mut app, &egui::Context::default(), &request) else { panic!("open should return immediately") }; + assert_eq!(reply["ok"], false); + assert_eq!(reply["error"], expected_control_error); + assert!(app.session.documents().is_empty()); + assert!(app.ui.dialogs.is_empty()); + assert!(app.ui.notices.is_empty()); + } +} + +/// This path must remain absent: both the foreground and worker open really fail to read it. +#[cfg(not(target_arch = "wasm32"))] +fn missing_source(tag: &str, name: &str) -> (std::path::PathBuf, String, String) { + let path = std::env::temp_dir().join(format!("photocraft-unreadable-{tag}-{}", std::process::id())).join(name); + assert!(!path.exists()); + let reason = photocraft_format::read_file(&path).unwrap_err().to_string(); + let source = path.to_string_lossy().into_owned(); + (path, source, reason) +} + +#[cfg(not(target_arch = "wasm32"))] +#[derive(Debug)] +struct UnreadableNativeDrop(std::path::PathBuf); + +#[cfg(not(target_arch = "wasm32"))] +impl egui::DroppedFile for UnreadableNativeDrop { + fn path(&self) -> &std::path::Path { + &self.0 + } + fn bytes(&self) -> Result, String> { + panic!("a native absolute-path drop must read from disk") + } +} + +/// Apply actual worker events and check the unmodified error sent to a waiting control client. +#[cfg(not(target_arch = "wasm32"))] +fn finish_read_failure(app: &mut PhotocraftApp, source: &str, reason: &str, worker_error: &str) { + let job = app.jobs.opens.first().map(|tab| tab.job); + let reply = job.map(|job| { + let (tx, rx) = std::sync::mpsc::channel(); + app.jobs.waiters.push((job, tx)); + rx + }); + let ctx = egui::Context::default(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); + while !app.jobs.opens.is_empty() { + assert!(std::time::Instant::now() < deadline, "open job did not finish"); + crate::jobs_ui::tick(app, &ctx); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + if let Some(reply) = reply { + assert_eq!(reply.try_recv().unwrap(), json!({"ok": false, "error": worker_error})); + } + let name = display_name(source); + let wanted = if reason == "codec: unrecognized image format" { expected(&name) } else { format!("Couldn't open {name}: {reason}") }; + assert_eq!(messages(app), [wanted]); + assert_eq!(app.ui.status, messages(app)[0]); + assert_eq!(app.ui.status.matches(name.as_str()).count(), 1); assert!(app.session.documents().is_empty()); - assert!(app.ui.dialogs.is_empty()); assert!(app.ui.notices.is_empty()); + crate::jobs_ui::tick(app, &ctx); + assert_eq!(messages(app).len(), 1, "the finished event is consumed once"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn native_drop_read_failures_name_the_source_once_in_foreground_and_background() { + for name in ["missing.psd", "missing.psdt"] { + let (path, source, reason) = missing_source("drop", name); + for background in [false, true] { + let mut app = app_with(None); + app.background_jobs = background; + app.open_dropped(&egui::Context::default(), vec![std::sync::Arc::new(UnreadableNativeDrop(path.clone()))], None); + assert_eq!(app.jobs.opens.len(), usize::from(background), "exercise the actual selected execution route"); + let worker_name = app.jobs.opens.first().map(|tab| tab.name.as_str()).unwrap_or(name); + if background { + assert_eq!(worker_name, if name == "missing.psdt" { "Untitled-1" } else { name }); + } + let worker_error = format!("{worker_name}: {source}: {reason}"); + finish_read_failure(&mut app, &source, &reason, &worker_error); + assert!(app.ui.recent_files.is_empty()); + } + } + + // The public path-plus-bytes API retains the source while the actual template worker is untitled. + let (_, source, _) = missing_source("template-codec", "unknown.psdt"); + let mut app = app_with(None); + app.background_jobs = true; + app.open_file(&source, b"ordinary text").unwrap(); + assert_eq!(app.jobs.opens.len(), 1); + let tab = &app.jobs.opens[0]; + assert_eq!(tab.name, "Untitled-1"); + assert_eq!(tab.path.as_deref(), Some(source.as_str())); + let worker_error = format!("{}: codec: unrecognized image format", tab.name); + finish_read_failure(&mut app, &source, "codec: unrecognized image format", &worker_error); + assert!(app.ui.recent_files.is_empty()); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn recent_grid_and_list_read_failures_keep_the_reason_without_repeating_the_path() { + let (_, source, reason) = missing_source("recent", "missing.psd"); + for grid in [false, true] { + let mut app = app_with(None); + app.background_jobs = false; + app.ui.chrome.home_recent_grid = grid; + app.push_recent(&source); + let mut h = egui_kittest::Harness::builder() + .with_size(egui::vec2(900.0, 760.0)) + .with_context_setup(|ctx| PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ALL[0])) + .build_ui_state( + |ui, app: &mut PhotocraftApp| { + let recent = app.ui.recent_files.clone(); + crate::home_recent_ui::show_home_recent(app, ui, &recent, 600.0); + }, + app, + ); + h.run_steps(3); + h.get_by_label("missing.psd").click(); + h.run_steps(3); + finish_read_failure(h.state_mut(), &source, &reason, "no worker in this foreground control"); + assert_eq!(h.state().ui.recent_files.as_slice(), std::slice::from_ref(&source)); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn os_open_read_failures_keep_the_existing_full_source_route() { + let (_, source, reason) = missing_source("os", "missing.psd"); + for background in [false, true] { + let mut app = app_with(None); + app.background_jobs = background; + let mut events = vec![OsEvent::Open(vec![source.clone()])]; + app.services.os_events = Some(Box::new(move || std::mem::take(&mut events))); + app.drain_os_events(&egui::Context::default()); + assert_eq!(app.jobs.opens.len(), usize::from(background), "exercise the actual selected execution route"); + let worker_error = format!("{}: {source}: {reason}", display_name(&source)); + finish_read_failure(&mut app, &source, &reason, &worker_error); + assert!(app.ui.recent_files.is_empty()); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn smart_object_open_read_failures_retain_the_read_source_without_a_save_or_recent_path() { + let (_, source, reason) = missing_source("smart-object", "missing.psd"); + for background in [false, true] { + let mut app = app_with(Some(FileDialogAnswer::Paths(vec![source.clone()]))); + app.background_jobs = background; + app.open_dialog_as_smart_object().unwrap(); + app.poll_file_dialog(&egui::Context::default(), None); + assert_eq!(app.jobs.opens.len(), usize::from(background), "exercise the actual selected execution route"); + assert!(app.jobs.opens.iter().all(|tab| tab.path.is_none()), "a Smart Object remains untitled"); + assert!(app.jobs.opens.iter().all(|tab| tab.error_source.as_deref() == Some(source.as_str()))); + finish_read_failure(&mut app, &source, &reason, &format!("{source}: {reason}")); + assert!(app.ui.recent_files.is_empty()); + } } diff --git a/crates/ui-egui/src/home_recent_ui.rs b/crates/ui-egui/src/home_recent_ui.rs index e8f25a1e72..24cffe4a6e 100644 --- a/crates/ui-egui/src/home_recent_ui.rs +++ b/crates/ui-egui/src/home_recent_ui.rs @@ -877,7 +877,7 @@ pub(crate) fn show_home_recent(app: &mut PhotocraftApp, ui: &mut Ui, recent: &[S match action { RecentAction::Open(path) => { if let Err(e) = open_recent_gate(app, &path).and_then(|()| app.open_path(&path)) { - app.open_failed(&crate::file_open::display_name(&path), &e); + app.open_failed(&path, &e); } } RecentAction::Remove(path) => { diff --git a/crates/ui-egui/src/jobs_ui.rs b/crates/ui-egui/src/jobs_ui.rs index d636067b3b..b3b2cb486e 100644 --- a/crates/ui-egui/src/jobs_ui.rs +++ b/crates/ui-egui/src/jobs_ui.rs @@ -42,6 +42,8 @@ pub struct OpenTab { pub name: String, /// Where it was read from (File › Save writes back there; added to Open Recent). pub path: Option, + /// Actual read source when it differs from the save/recent path (an untitled Smart Object). + pub error_source: Option, /// The tab position it goes to when it opens (a file dropped on the tabs); `None`: the end. pub slot: Option, /// Its place in a set of files opened together, when it is one of several (see [`OpenOrder`]). @@ -281,13 +283,15 @@ pub fn start_open( slot: Option, order: Option, ) -> Result<(), String> { - let name = &app.open_name(name); + let source_name = name; + let name = &app.open_name(source_name); + let error_source = (path.is_none() && name.as_str() != source_name).then(|| source_name.to_string()); match app.session.start_open_for_user_with_background(name, source, app.background_jobs).map_err(|e| e.to_string())? { // Inline (wasm, or background jobs off): finish now, like a background open that ended at // once. A preflight keeps the slot and set order in its memory prompt. Started::Done(v) => finish_open(app, name, path.as_deref(), &v, slot, order), Started::Job(job) => { - track_open(app, OpenTab { job, name: name.to_string(), path, slot, order }); + track_open(app, OpenTab { job, name: name.to_string(), path, error_source, slot, order }); Ok(()) } } @@ -318,7 +322,7 @@ pub(crate) fn start_open_as_smart_object(app: &mut PhotocraftApp, path: &str, or match started { Started::Done(v) => finish_open(app, &name, None, &v, None, order), Started::Job(job) => { - track_open(app, OpenTab { job, name, path: None, slot: None, order }); + track_open(app, OpenTab { job, name, path: None, error_source: Some(path.to_string()), slot: None, order }); Ok(()) } } @@ -640,13 +644,19 @@ fn on_event(app: &mut PhotocraftApp, ctx: &egui::Context, e: JobEvent) { if e.command == OPEN_JOB || app.jobs.opens.iter().any(|o| o.job == e.id) { let Some(i) = app.jobs.opens.iter().position(|o| o.job == e.id) else { return }; let tab = app.jobs.opens.remove(i); + let source = tab.error_source.as_deref().or(tab.path.as_deref()).unwrap_or(&tab.name); match e.outcome { JobOutcome::Done(v) => { if let Err(err) = finish_open_tab(app, &tab, &v) { - app.open_failed(&tab.name, &err); + app.open_failed(source, &err); } } - JobOutcome::Failed(err) => app.open_failed(&tab.name, &err), + JobOutcome::Failed(err) => { + // A template's worker name is Untitled-N, while its alert names the read source. + let reason = + if tab.name != crate::file_open::display_name(source) { err.strip_prefix(&format!("{}: ", tab.name)).unwrap_or(&err) } else { &err }; + app.open_failed(source, reason); + } JobOutcome::Cancelled => { app.ui.status = crate::i18n::fmt(tl!("Canceled opening {name}"), &[("name", &tab.name)]); app.ui.status_error = false; diff --git a/crates/ui-egui/src/jobs_ui/tests.rs b/crates/ui-egui/src/jobs_ui/tests.rs index 8cc19bdcf8..b7193b12db 100644 --- a/crates/ui-egui/src/jobs_ui/tests.rs +++ b/crates/ui-egui/src/jobs_ui/tests.rs @@ -343,7 +343,7 @@ fn the_opening_card_keeps_a_long_name_and_cancel_inside() { let long = "a7rv-test_2024_02_17_shot_30_3705_with_an_even_longer_suffix_that_never_ends.psb"; for name in ["short.psd", long] { h.state_mut().jobs.opens.clear(); - h.state_mut().jobs.opens.push(crate::jobs_ui::OpenTab { job, name: name.to_string(), path: None, slot: None, order: None }); + h.state_mut().jobs.opens.push(crate::jobs_ui::OpenTab { job, name: name.to_string(), path: None, error_source: None, slot: None, order: None }); h.state_mut().jobs.focus = Some(job); h.run_steps(4); let r = crate::jobs_ui::open_card_rects(&h.ctx).expect("the opening card was drawn"); diff --git a/crates/ui-egui/src/psd_open_tests.rs b/crates/ui-egui/src/psd_open_tests.rs index 61ad40a919..287db29b58 100644 --- a/crates/ui-egui/src/psd_open_tests.rs +++ b/crates/ui-egui/src/psd_open_tests.rs @@ -718,6 +718,7 @@ fn memory_prompt_states_unknown_capacity_and_the_eight_gib_warning() { job: photocraft_engine::jobs::JobId(1), name: "unknown.psd".into(), path: Some("/pics/unknown.psd".into()), + error_source: None, slot: None, order: None, }; @@ -742,7 +743,8 @@ fn memory_prompt_states_unknown_capacity_and_the_eight_gib_warning() { // A measured capacity shows the number and drops the uncertainty warning. let id = store_preflight(&mut app, "known.psd", 3 * gb, Some(5 * gb)); - let tab = crate::jobs_ui::OpenTab { job: photocraft_engine::jobs::JobId(2), name: "known.psd".into(), path: None, slot: None, order: None }; + let tab = + crate::jobs_ui::OpenTab { job: photocraft_engine::jobs::JobId(2), name: "known.psd".into(), path: None, error_source: None, slot: None, order: None }; crate::jobs_ui::finish_open_tab( &mut app, &tab, @@ -768,7 +770,8 @@ fn memory_prompt_warns_when_little_memory_would_be_left() { let mut app = app(); let available = 3 * gb + gb / 2; let id = store_preflight(&mut app, "tight.psd", 3 * gb, Some(available)); - let tab = crate::jobs_ui::OpenTab { job: photocraft_engine::jobs::JobId(3), name: "tight.psd".into(), path: None, slot: None, order: None }; + let tab = + crate::jobs_ui::OpenTab { job: photocraft_engine::jobs::JobId(3), name: "tight.psd".into(), path: None, error_source: None, slot: None, order: None }; crate::jobs_ui::finish_open_tab( &mut app, &tab, From 3e768fe6e66e2bf764871402dc7a3c00945a239d Mon Sep 17 00:00:00 2001 From: yoriswind Date: Tue, 17 Nov 2026 01:36:07 -0800 Subject: [PATCH 05/19] Preserve unreadable alert behavior for templates and approved opens --- crates/ui-egui/src/dialogs/open_prompt.rs | 9 ++- crates/ui-egui/src/file_open.rs | 25 ++++++- .../src/file_open/unreadable_alert_tests.rs | 36 +++++++++- crates/ui-egui/src/psd_open_tests.rs | 66 +++++++++++++++++++ 4 files changed, 131 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/dialogs/open_prompt.rs b/crates/ui-egui/src/dialogs/open_prompt.rs index e48418505d..1b770f99ce 100644 --- a/crates/ui-egui/src/dialogs/open_prompt.rs +++ b/crates/ui-egui/src/dialogs/open_prompt.rs @@ -502,8 +502,13 @@ pub(crate) fn answer_memory(app: &mut PhotocraftApp, accept: bool) -> Result { - app.ui.status = err.clone(); - app.ui.status_error = true; + let source = path.as_deref().unwrap_or(&name); + // A template may have reserved an Untitled name; presentation names its read source, + // while the returned error keeps the approval command's original wrapper. + let prefix = format!("{name}: "); + let error = err.strip_prefix(&prefix).unwrap_or(&err); + let reason = if name != crate::file_open::display_name(source) { error.strip_prefix(&prefix).unwrap_or(error) } else { error }; + app.open_failed(source, reason); crate::jobs_ui::end_batch(app); advance(app); crate::jobs_ui::end_batch(app); diff --git a/crates/ui-egui/src/file_open.rs b/crates/ui-egui/src/file_open.rs index 7ed8f34a17..c888251e1b 100644 --- a/crates/ui-egui/src/file_open.rs +++ b/crates/ui-egui/src/file_open.rs @@ -205,6 +205,29 @@ pub fn display_name(path: &str) -> String { std::path::Path::new(path).file_name().map(|n| n.to_string_lossy().to_string()).filter(|n| !n.is_empty()).unwrap_or_else(|| path.to_string()) } +// Named PSD/PSB/templates deliberately keep the PSD parser's errors for direct callers. Only +// its missing file-header signature means unrecognized content; damaged internal signatures +// (8BIM, etc.) and a recognized 8BPS file's other parse errors must retain their reasons. +fn unrecognized_open_reason(reason: &str) -> bool { + if reason == "codec: unrecognized image format" { + return true; + } + let Some(signature) = reason.strip_prefix("PSD: invalid signature [").and_then(|s| s.strip_suffix("], expected 8BPS")) else { + return false; + }; + let mut values = signature.split(", "); + let mut found = [0u8; 4]; + for byte in &mut found { + let Some(text) = values.next() else { return false }; + let Ok(value) = text.parse::() else { return false }; + if text != value.to_string() { + return false; + } + *byte = value; + } + values.next().is_none() && &found != b"8BPS" +} + impl PhotocraftApp { /// Open `bytes` read from the file at `path`: the document is named after the file, keeps /// `path` for File › Save unless it is a derivative preview, and `path` goes to the top of Open Recent. Returns the import @@ -375,7 +398,7 @@ impl PhotocraftApp { .or_else(|| err.strip_prefix(&source_prefix)) .or_else(|| err.strip_prefix(&name_prefix)) .unwrap_or(err); - let msg = if reason == "codec: unrecognized image format" { + let msg = if unrecognized_open_reason(reason) { crate::i18n::fmt(tl!("Could not open \"{name}\" because PhotoCraft does not recognize this type of file."), &[("name", &name)]) } else { let template = "Couldn't open {name}: {error}"; diff --git a/crates/ui-egui/src/file_open/unreadable_alert_tests.rs b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs index 561c8eba5c..a46004fec0 100644 --- a/crates/ui-egui/src/file_open/unreadable_alert_tests.rs +++ b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs @@ -45,12 +45,13 @@ fn unrecognized_and_mislabeled_files_show_the_exact_alert_without_opening_docume ("notes.txt", b"ordinary text".to_vec()), ("broken.png", b"ordinary text".to_vec()), ("zz-bad.png", (1..=17).collect()), + ("unknown.psd", b"ordinary text".to_vec()), + ("unknown.psb", b"ordinary text".to_vec()), ("unknown.psdt", b"ordinary text".to_vec()), ] { let mut app = app_with(Some(FileDialogAnswer::Contents(name.into(), bytes))); pick(&mut app); - let wanted = - if name == "unknown.psdt" { format!("Couldn't open {name}: PSD: invalid signature [111, 114, 100, 105], expected 8BPS") } else { expected(name) }; + let wanted = expected(name); assert_eq!(messages(&app), [wanted.as_str()]); assert!(app.session.documents().is_empty()); assert!(app.ui.recent_files.is_empty()); @@ -342,3 +343,34 @@ fn smart_object_open_read_failures_retain_the_read_source_without_a_save_or_rece assert!(app.ui.recent_files.is_empty()); } } + +#[test] +fn recognized_psd_header_failures_keep_their_diagnostic_and_raw_error() { + // The file signature is recognized: a bad version is a PSD error, not a codec miss. + let bytes = b"8BPS\0\0".to_vec(); + let mut app = app_with(Some(FileDialogAnswer::Contents("corrupt.psdt".into(), bytes.clone()))); + pick(&mut app); + assert_eq!(messages(&app), ["Couldn't open corrupt.psdt: PSD: unsupported file version 0"]); + assert!(app.session.documents().is_empty()); + assert!(app.ui.recent_files.is_empty()); + assert!(app.ui.notices.is_empty()); + let mut direct = app_with(None); + assert_eq!(direct.open_bytes("corrupt.psdt", &bytes).unwrap_err(), "corrupt.psdt: PSD: unsupported file version 0"); + assert!(direct.ui.dialogs.is_empty()); + + // A damaged internal block or an unrelated/malformed diagnostic retains its reason. + for reason in [ + "PSD: invalid signature [0, 0, 0, 0], expected 8BIM (layer blend mode)", + "PSD: invalid signature [56, 66, 80, 83], expected 8BPS", + "PSD: invalid signature [0, 0, 0], expected 8BPS", + "PSD: invalid signature [256, 0, 0, 0], expected 8BPS", + "PSD: invalid signature [+1, 0, 0, 0], expected 8BPS", + "PSD: invalid signature [00, 0, 0, 0], expected 8BPS", + "PSD: invalid signature [0, 0, 0, 0], expected 8BPS; keep this detail", + "embedded PSD: invalid signature [0, 0, 0, 0], expected 8BPS", + ] { + let mut app = app_with(None); + app.open_failed("corrupt.psdt", reason); + assert_eq!(messages(&app), [format!("Couldn't open corrupt.psdt: {reason}")]); + } +} diff --git a/crates/ui-egui/src/psd_open_tests.rs b/crates/ui-egui/src/psd_open_tests.rs index 287db29b58..eb64397069 100644 --- a/crates/ui-egui/src/psd_open_tests.rs +++ b/crates/ui-egui/src/psd_open_tests.rs @@ -1010,3 +1010,69 @@ fn confirmed_damaged_smart_object_opens_are_admitted_as_smart_objects_with_disti } let _ = std::fs::remove_dir_all(&dir); } + +/// A real inline decode after consent fails on a tiny recognized PSD header. Its raw control +/// reply is unchanged, its one alert names the source, and the next prompt retains its batch. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn failed_inline_memory_approval_alerts_once_and_preserves_the_next_prompt_and_error_reply() { + for (name, file_name) in [("failed.psd", None), ("failed.psd", Some("failed.psd")), ("Untitled-1", Some("template.psdt"))] { + let mut app = app(); + let temp = tempfile::tempdir().unwrap(); + let path = file_name.map(|file| { + let path = temp.path().join(file); + std::fs::write(&path, b"8BPS\0\0").unwrap(); + path.to_string_lossy().into_owned() + }); + let source = path.as_ref().map_or_else( + || photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(b"8BPS\0\0".to_vec())), + |path| photocraft_engine::jobs::OpenSource::Path(path.clone()), + ); + let fingerprint = photocraft_engine::jobs::SourceFingerprint::of(&source).unwrap(); + let first = app.session.store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { + id: 0, name: name.into(), source, fingerprint, + required: 1000, soft_limit: 500, hard_limit: 2000, available_ram: Some(4000), confirm_damage: true, + }).unwrap(); + let second = store_preflight(&mut app, "next.psd", 1000, Some(4000)); + let batch = crate::jobs_ui::begin_batch(&mut app); + let first_order = crate::jobs_ui::OpenOrder { batch, seq: 0 }; + let second_order = crate::jobs_ui::OpenOrder { batch, seq: 1 }; + crate::open_prompt::arrive_memory(&mut app, first, name.into(), path.clone(), None, Some(first_order), 1000, Some(4000), false, false); + crate::open_prompt::arrive_memory(&mut app, second, "next.psd".into(), None, None, Some(second_order), 1000, Some(4000), false, false); + let dialog = app.ui.dialogs[0].id; + let reply = call(&mut app, "ui.dialog.confirm", json!({"dialog": dialog})); + assert_eq!(reply["ok"], false); + assert_eq!(reply["error"], format!("{name}: {name}: PSD: unsupported file version 0"), "keep the approval's original error reply"); + let source_name = file_name.unwrap_or(name); + let wanted = format!("Couldn't open {source_name}: PSD: unsupported file version 0"); + let errors: Vec<_> = app.ui.dialogs.iter().filter(|d| d.kind == crate::state::DialogKind::Error).collect(); + assert_eq!(errors.len(), 1); + assert_eq!(errors[0].fields["message"], wanted); + let error_id = errors[0].id; + assert_eq!(app.ui.status, wanted); + assert_eq!(app.ui.status.matches(source_name).count(), 1); + if name != source_name { assert!(!app.ui.status.contains(name)); } + assert!(app.ui.status_error); + assert!(app.ui.notices.is_empty()); + assert!(app.session.documents().is_empty()); + assert!(app.ui.recent_files.is_empty()); + assert!(app.jobs.opens.is_empty()); + assert!(app.session.take_pending_preflight(first).is_none()); + assert_eq!(app.held_memory_prompts.len(), 1); + assert_eq!(app.held_memory_prompts[0].id, second); + assert_eq!(app.prompt_order.len(), 1); + assert_eq!(app.jobs.batches.len(), 1, "the waiting successor still owns this batch"); + let next = app.ui.dialogs.iter().find(|d| crate::open_prompt::owns_memory(&d.fields)).unwrap().id; + crate::open_prompt::advance_memory(&mut app); + assert_eq!(app.ui.dialogs.len(), 2, "neither the alert nor the successor prompt is duplicated"); + assert_eq!(call(&mut app, "ui.dialog.confirm", json!({"dialog": error_id}))["ok"], true); + assert_eq!(app.ui.dialogs.len(), 1); + assert_eq!(app.ui.dialogs[0].id, next); + assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": next}))["ok"], true); + assert!(app.session.take_pending_preflight(second).is_none()); + assert!(app.ui.dialogs.is_empty()); + assert!(app.held_memory_prompts.is_empty()); + assert!(app.prompt_order.is_empty()); + assert!(app.jobs.batches.is_empty()); + } +} From 9db3e586d9a1dae1ffd18ceb7c66d050c4051d98 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Tue, 17 Nov 2026 01:58:18 -0800 Subject: [PATCH 06/19] Format template and memory approval alert regressions --- crates/ui-egui/src/psd_open_tests.rs | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/psd_open_tests.rs b/crates/ui-egui/src/psd_open_tests.rs index eb64397069..1861659c33 100644 --- a/crates/ui-egui/src/psd_open_tests.rs +++ b/crates/ui-egui/src/psd_open_tests.rs @@ -1029,10 +1029,20 @@ fn failed_inline_memory_approval_alerts_once_and_preserves_the_next_prompt_and_e |path| photocraft_engine::jobs::OpenSource::Path(path.clone()), ); let fingerprint = photocraft_engine::jobs::SourceFingerprint::of(&source).unwrap(); - let first = app.session.store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { - id: 0, name: name.into(), source, fingerprint, - required: 1000, soft_limit: 500, hard_limit: 2000, available_ram: Some(4000), confirm_damage: true, - }).unwrap(); + let first = app + .session + .store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { + id: 0, + name: name.into(), + source, + fingerprint, + required: 1000, + soft_limit: 500, + hard_limit: 2000, + available_ram: Some(4000), + confirm_damage: true, + }) + .unwrap(); let second = store_preflight(&mut app, "next.psd", 1000, Some(4000)); let batch = crate::jobs_ui::begin_batch(&mut app); let first_order = crate::jobs_ui::OpenOrder { batch, seq: 0 }; @@ -1051,7 +1061,9 @@ fn failed_inline_memory_approval_alerts_once_and_preserves_the_next_prompt_and_e let error_id = errors[0].id; assert_eq!(app.ui.status, wanted); assert_eq!(app.ui.status.matches(source_name).count(), 1); - if name != source_name { assert!(!app.ui.status.contains(name)); } + if name != source_name { + assert!(!app.ui.status.contains(name)); + } assert!(app.ui.status_error); assert!(app.ui.notices.is_empty()); assert!(app.session.documents().is_empty()); From 85e5ec2b9862b27a1352cf6065b236f6a21e9d6f Mon Sep 17 00:00:00 2001 From: yoriswind Date: Tue, 17 Nov 2026 02:11:15 -0800 Subject: [PATCH 07/19] Correct PSD alert test oracle and approved-open header fixture --- .../src/file_open/unreadable_alert_tests.rs | 3 ++- crates/ui-egui/src/psd_open_tests.rs | 16 ++++++++++++++-- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/file_open/unreadable_alert_tests.rs b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs index a46004fec0..4cbfe98561 100644 --- a/crates/ui-egui/src/file_open/unreadable_alert_tests.rs +++ b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs @@ -355,7 +355,8 @@ fn recognized_psd_header_failures_keep_their_diagnostic_and_raw_error() { assert!(app.ui.recent_files.is_empty()); assert!(app.ui.notices.is_empty()); let mut direct = app_with(None); - assert_eq!(direct.open_bytes("corrupt.psdt", &bytes).unwrap_err(), "corrupt.psdt: PSD: unsupported file version 0"); + // The typed PSD path returns its raw IO error without adding a source-name prefix. + assert_eq!(direct.open_bytes("corrupt.psdt", &bytes).unwrap_err(), "PSD: unsupported file version 0"); assert!(direct.ui.dialogs.is_empty()); // A damaged internal block or an unrelated/malformed diagnostic retains its reason. diff --git a/crates/ui-egui/src/psd_open_tests.rs b/crates/ui-egui/src/psd_open_tests.rs index 1861659c33..fe3af29274 100644 --- a/crates/ui-egui/src/psd_open_tests.rs +++ b/crates/ui-egui/src/psd_open_tests.rs @@ -1016,16 +1016,28 @@ fn confirmed_damaged_smart_object_opens_are_admitted_as_smart_objects_with_disti #[cfg(not(target_arch = "wasm32"))] #[test] fn failed_inline_memory_approval_alerts_once_and_preserves_the_next_prompt_and_error_reply() { + // File-backed decoding reads the complete 26-byte header before parsing it. Give both + // routes that same header so the unsupported version, rather than EOF, is the failure. + let header = [ + b'8', b'B', b'P', b'S', + 0, 0, // unsupported version + 0, 0, 0, 0, 0, 0, // reserved + 0, 3, // channels + 0, 0, 0, 1, // height + 0, 0, 0, 1, // width + 0, 8, // depth + 0, 3, // RGB + ]; for (name, file_name) in [("failed.psd", None), ("failed.psd", Some("failed.psd")), ("Untitled-1", Some("template.psdt"))] { let mut app = app(); let temp = tempfile::tempdir().unwrap(); let path = file_name.map(|file| { let path = temp.path().join(file); - std::fs::write(&path, b"8BPS\0\0").unwrap(); + std::fs::write(&path, header).unwrap(); path.to_string_lossy().into_owned() }); let source = path.as_ref().map_or_else( - || photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(b"8BPS\0\0".to_vec())), + || photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(header.to_vec())), |path| photocraft_engine::jobs::OpenSource::Path(path.clone()), ); let fingerprint = photocraft_engine::jobs::SourceFingerprint::of(&source).unwrap(); From edc838a573989966c254652bbda5f2d355cee9f0 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Tue, 17 Nov 2026 02:15:01 -0800 Subject: [PATCH 08/19] Format the complete PSD approval fixture --- crates/ui-egui/src/psd_open_tests.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/ui-egui/src/psd_open_tests.rs b/crates/ui-egui/src/psd_open_tests.rs index fe3af29274..03aa0c6734 100644 --- a/crates/ui-egui/src/psd_open_tests.rs +++ b/crates/ui-egui/src/psd_open_tests.rs @@ -1019,8 +1019,7 @@ fn failed_inline_memory_approval_alerts_once_and_preserves_the_next_prompt_and_e // File-backed decoding reads the complete 26-byte header before parsing it. Give both // routes that same header so the unsupported version, rather than EOF, is the failure. let header = [ - b'8', b'B', b'P', b'S', - 0, 0, // unsupported version + b'8', b'B', b'P', b'S', 0, 0, // unsupported version 0, 0, 0, 0, 0, 0, // reserved 0, 3, // channels 0, 0, 0, 1, // height From d8c1efec890f71bc4b0347a76d31a98c6ae44f72 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Tue, 17 Nov 2026 03:14:18 -0800 Subject: [PATCH 09/19] Preserve byte-template source through memory approval Carry read-source metadata through high-memory prompts and approval completions while retaining worker names, save paths, and raw error replies. Add real byte-template preflight approval/cancel controls and inline/background approval decoder failure regressions. Native validation remains Root-owned and unrun for this commit. --- crates/ui-egui/src/dialogs/open_prompt.rs | 12 +- .../src/file_open/unreadable_alert_tests.rs | 147 ++++++++++++++++++ crates/ui-egui/src/jobs_ui.rs | 11 +- crates/ui-egui/src/psd_open_tests.rs | 22 +-- 4 files changed, 173 insertions(+), 19 deletions(-) diff --git a/crates/ui-egui/src/dialogs/open_prompt.rs b/crates/ui-egui/src/dialogs/open_prompt.rs index 1b770f99ce..3d0dcb2a38 100644 --- a/crates/ui-egui/src/dialogs/open_prompt.rs +++ b/crates/ui-egui/src/dialogs/open_prompt.rs @@ -64,6 +64,8 @@ pub struct MemoryPrompt { pub id: u64, pub name: String, pub path: Option, + /// Original read source when an untitled open has no save/recent path. + pub error_source: Option, pub slot: Option, pub order: Option, pub estimated: u64, @@ -370,6 +372,7 @@ pub fn arrive_memory( id: u64, name: String, path: Option, + error_source: Option, slot: Option, order: Option, estimated: u64, @@ -377,7 +380,7 @@ pub fn arrive_memory( capacity_unknown: bool, uncertain_capacity_warning: bool, ) { - app.held_memory_prompts.push_back(MemoryPrompt { id, name, path, slot, order, estimated, available, capacity_unknown, uncertain_capacity_warning }); + app.held_memory_prompts.push_back(MemoryPrompt { id, name, path, error_source, slot, order, estimated, available, capacity_unknown, uncertain_capacity_warning }); app.prompt_order.push_back(PromptKind::Memory); advance_memory(app); } @@ -457,6 +460,7 @@ pub(crate) fn answer_memory(app: &mut PhotocraftApp, accept: bool) -> Result Result Result Result { - let source = path.as_deref().unwrap_or(&name); + let source = path.as_deref().or(error_source.as_deref()).unwrap_or(&name); // A template may have reserved an Untitled name; presentation names its read source, // while the returned error keeps the approval command's original wrapper. let prefix = format!("{name}: "); diff --git a/crates/ui-egui/src/file_open/unreadable_alert_tests.rs b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs index 4cbfe98561..a5c38e4485 100644 --- a/crates/ui-egui/src/file_open/unreadable_alert_tests.rs +++ b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs @@ -375,3 +375,150 @@ fn recognized_psd_header_failures_keep_their_diagnostic_and_raw_error() { assert_eq!(messages(&app), [format!("Couldn't open corrupt.psdt: {reason}")]); } } + + +#[cfg(not(target_arch = "wasm32"))] +fn template_psd_for_memory_prompt() -> Vec { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 4, "height": 3, "background": "white"})).unwrap(); + photocraft_io::export(&s.active().unwrap().doc, "small.psd", &Default::default()).unwrap().bytes +} + +#[cfg(not(target_arch = "wasm32"))] +fn memory_dialog_reply(app: &mut PhotocraftApp, dialog: u64, accept: bool) -> serde_json::Value { + let method = if accept { "ui.dialog.confirm" } else { "ui.dialog.cancel" }; + let (request, _rx) = ControlRequest::new(method, json!({"dialog": dialog})); + let Outcome::Done(reply) = handle(app, &egui::Context::default(), &request) else { panic!("memory prompt reply is immediate") }; + reply +} + +#[cfg(not(target_arch = "wasm32"))] +fn finish_successful_template_jobs(app: &mut PhotocraftApp) { + let jobs: Vec<_> = app.jobs.opens.iter().map(|tab| tab.job).collect(); + for job in jobs { + app.session.wait_job(job).unwrap(); + } + crate::jobs_ui::tick(app, &egui::Context::default()); +} + +/// A real picked byte template reaches preflight through both immediate and worker completion. +/// Its original source is metadata only: approval still opens Untitled-1 without a save path. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn byte_template_memory_prompt_keeps_the_source_through_real_open_approve_and_cancel() { + if cfg!(target_pointer_width = "32") { + return; // The scoped 3 GiB estimate charge exceeds the 32-bit product cap. + } + let gb = 1u64 << 30; + let psd = template_psd_for_memory_prompt(); + let memory = photocraft_io::memory::MemorySnapshot { available_ram: Some(5 * gb), swap_free: None, commit_headroom: None }; + for background in [false, true] { + for accept in [false, true] { + let mut app = app_with(Some(FileDialogAnswer::Contents("card.psdt".into(), psd.clone()))); + app.background_jobs = background; + photocraft_io::psd_budget::with_test_estimate_charge(3 * gb, || { + photocraft_io::memory::with_mock_memory(memory, || { + pick(&mut app); + assert_eq!(app.jobs.opens.len(), usize::from(background)); + if background { + finish_successful_template_jobs(&mut app); + } + assert!(app.session.documents().is_empty()); + assert_eq!(app.held_memory_prompts.len(), 1, "use the real high-memory preflight"); + let prompt = &app.held_memory_prompts[0]; + assert_eq!(prompt.name, "Untitled-1"); + assert!(prompt.path.is_none()); + assert_eq!(prompt.error_source.as_deref(), Some("card.psdt")); + assert!(prompt.estimated > 3 * gb); + let preflight = prompt.id; + let dialog = app.ui.dialogs[0].id; + assert!(crate::open_prompt::owns_memory(&app.ui.dialogs[0].fields)); + let reply = memory_dialog_reply(&mut app, dialog, accept); + assert_eq!(reply["ok"], true, "{reply}"); + if background && accept { + let tab = app.jobs.opens.first().unwrap(); + assert_eq!(tab.name, "Untitled-1"); + assert!(tab.path.is_none()); + assert_eq!(tab.error_source.as_deref(), Some("card.psdt")); + finish_successful_template_jobs(&mut app); + } + assert_eq!(app.session.documents().len(), usize::from(accept)); + if accept { + let opened = &app.session.documents()[0]; + assert_eq!(opened.doc.name, "Untitled-1"); + assert!(opened.path.is_none(), "error source is never a save destination"); + } + assert!(app.ui.recent_files.is_empty(), "byte input does not acquire a Recent path"); + assert!(app.ui.dialogs.is_empty()); + assert!(app.held_memory_prompts.is_empty()); + assert!(app.prompt_order.is_empty()); + assert!(app.jobs.opens.is_empty()); + assert!(app.jobs.batches.is_empty()); + assert!(app.session.take_pending_preflight(preflight).is_none()); + assert_eq!(app.session.pending_preflight_bytes().unwrap(), 0); + assert!(!app.ui.status_error); + }); + }); + } + } +} + +/// A stored byte preflight with a valid identity but invalid PSD version drives the real +/// approval decoder, so both the immediate error and the later worker failure keep raw replies. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn byte_template_memory_approval_decode_failures_name_the_source_and_keep_raw_replies() { + let header = vec![ + b'8', b'B', b'P', b'S', 0, 0, // unsupported version + 0, 0, 0, 0, 0, 0, // reserved + 0, 3, // channels + 0, 0, 0, 1, // height + 0, 0, 0, 1, // width + 0, 8, // depth + 0, 3, // RGB + ]; + for background in [false, true] { + let mut app = app_with(None); + app.background_jobs = background; + let source = photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(header.clone())); + let fingerprint = photocraft_engine::jobs::SourceFingerprint::of(&source).unwrap(); + let preflight = app.session.store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { + id: 0, name: "Untitled-1".into(), source, fingerprint, + required: 1000, soft_limit: 500, hard_limit: 2000, available_ram: Some(4000), confirm_damage: true, + }).unwrap(); + crate::open_prompt::arrive_memory( + &mut app, preflight, "Untitled-1".into(), None, Some("card.psdt".into()), None, None, 1000, Some(4000), false, false, + ); + let dialog = app.ui.dialogs[0].id; + let reply = memory_dialog_reply(&mut app, dialog, true); + let reason = "PSD: unsupported file version 0"; + if background { + assert_eq!(reply["ok"], true, "the actual approval starts a worker: {reply}"); + let tab = app.jobs.opens.first().unwrap(); + assert_eq!(tab.name, "Untitled-1"); + assert!(tab.path.is_none()); + assert_eq!(tab.error_source.as_deref(), Some("card.psdt")); + finish_read_failure(&mut app, "card.psdt", reason, &format!("Untitled-1: {reason}")); + } else { + assert_eq!(reply["ok"], false); + assert_eq!(reply["error"], format!("Untitled-1: Untitled-1: {reason}"), "preserve the approval's original wrapper"); + assert_eq!(messages(&app), [format!("Couldn't open card.psdt: {reason}")]); + } + assert_eq!(app.ui.status, format!("Couldn't open card.psdt: {reason}")); + assert_eq!(app.ui.status.matches("card.psdt").count(), 1); + assert!(!app.ui.status.contains("Untitled-1")); + assert!(app.ui.status_error); + assert!(app.ui.notices.is_empty()); + assert!(app.session.documents().is_empty()); + assert!(app.ui.recent_files.is_empty()); + assert!(app.jobs.opens.is_empty()); + assert!(app.held_memory_prompts.is_empty()); + assert!(app.prompt_order.is_empty()); + assert!(app.jobs.batches.is_empty()); + assert_eq!(app.session.pending_preflight_bytes().unwrap(), 0); + assert!(app.session.take_pending_preflight(preflight).is_none()); + let alert = app.ui.dialogs[0].id; + crate::dialogs::confirm(&mut app, alert).unwrap(); + assert!(app.ui.dialogs.is_empty(), "the one error alert closes normally"); + } +} diff --git a/crates/ui-egui/src/jobs_ui.rs b/crates/ui-egui/src/jobs_ui.rs index b3b2cb486e..abdc53ae7c 100644 --- a/crates/ui-egui/src/jobs_ui.rs +++ b/crates/ui-egui/src/jobs_ui.rs @@ -42,7 +42,7 @@ pub struct OpenTab { pub name: String, /// Where it was read from (File › Save writes back there; added to Open Recent). pub path: Option, - /// Actual read source when it differs from the save/recent path (an untitled Smart Object). + /// Actual read source when it differs from the save/recent path (an untitled Smart Object or byte-backed template). pub error_source: Option, /// The tab position it goes to when it opens (a file dropped on the tabs); `None`: the end. pub slot: Option, @@ -289,7 +289,7 @@ pub fn start_open( match app.session.start_open_for_user_with_background(name, source, app.background_jobs).map_err(|e| e.to_string())? { // Inline (wasm, or background jobs off): finish now, like a background open that ended at // once. A preflight keeps the slot and set order in its memory prompt. - Started::Done(v) => finish_open(app, name, path.as_deref(), &v, slot, order), + Started::Done(v) => finish_open(app, name, path.as_deref(), error_source.as_deref(), &v, slot, order), Started::Job(job) => { track_open(app, OpenTab { job, name: name.to_string(), path, error_source, slot, order }); Ok(()) @@ -320,7 +320,7 @@ pub(crate) fn start_open_as_smart_object(app: &mut PhotocraftApp, path: &str, or Started::Done(app.session.execute("file.openAsSmartObject", params).map_err(|e| e.to_string())?) }; match started { - Started::Done(v) => finish_open(app, &name, None, &v, None, order), + Started::Done(v) => finish_open(app, &name, None, Some(path), &v, None, order), Started::Job(job) => { track_open(app, OpenTab { job, name, path: None, error_source: Some(path.to_string()), slot: None, order }); Ok(()) @@ -376,7 +376,7 @@ pub(crate) fn tab_slot(app: &mut PhotocraftApp, slot: Option, order: Opti /// [`JobsUi::opens`]: the document goes to the tab's slot, or to its place in its set. A memory /// preflight keeps both in its prompt. pub(crate) fn finish_open_tab(app: &mut PhotocraftApp, tab: &OpenTab, v: &Value) -> Result<(), String> { - let r = finish_open(app, &tab.name, tab.path.as_deref(), v, tab.slot, tab.order); + let r = finish_open(app, &tab.name, tab.path.as_deref(), tab.error_source.as_deref(), v, tab.slot, tab.order); end_batch(app); r } @@ -708,7 +708,7 @@ fn on_event(app: &mut PhotocraftApp, ctx: &egui::Context, e: JobEvent) { /// (`{document, docId, warnings, color}` or `{held, …}`). `slot` and `order` are the tab position /// and set place the file keeps: through a memory prompt, a profile/damage prompt and the final /// document, so an inline completion lands where a background tab would. -fn finish_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>, v: &Value, slot: Option, order: Option) -> Result<(), String> { +fn finish_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>, error_source: Option<&str>, v: &Value, slot: Option, order: Option) -> Result<(), String> { if let Some(preflight_id) = v.get("pendingPreflight").and_then(Value::as_u64) { let estimated = v.get("estimated").and_then(Value::as_u64).unwrap_or(0); let available = v.get("availableRam").and_then(Value::as_u64); @@ -719,6 +719,7 @@ fn finish_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>, v: &Valu preflight_id, name.to_string(), path.map(str::to_string), + error_source.map(str::to_string), slot, order, estimated, diff --git a/crates/ui-egui/src/psd_open_tests.rs b/crates/ui-egui/src/psd_open_tests.rs index 03aa0c6734..2e7ce2058a 100644 --- a/crates/ui-egui/src/psd_open_tests.rs +++ b/crates/ui-egui/src/psd_open_tests.rs @@ -218,7 +218,7 @@ fn memory_confirmation_dialog_and_cancel_lifecycle() { }) .unwrap(); - crate::open_prompt::arrive_memory(&mut app, preflight_id, "high_mem.psd".into(), None, None, None, 7 * gb, Some(10 * gb), false, false); + crate::open_prompt::arrive_memory(&mut app, preflight_id, "high_mem.psd".into(), None, None, None, None, 7 * gb, Some(10 * gb), false, false); 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; @@ -365,6 +365,7 @@ fn memory_confirmation_refuses_when_source_changed_inline() { Some(path.to_string_lossy().to_string()), None, None, + None, 1000, Some(100_000), false, @@ -417,6 +418,7 @@ fn memory_confirmation_refuses_when_source_changed_async() { Some(path.to_string_lossy().to_string()), None, None, + None, 1000, Some(100_000), false, @@ -466,7 +468,7 @@ fn memory_decline_advances_queue_and_cleans_batch() { }) .unwrap(); - crate::open_prompt::arrive_memory(&mut app, preflight_id, "declined.psd".into(), None, None, Some(order), 1000, Some(4000), false, false); + crate::open_prompt::arrive_memory(&mut app, preflight_id, "declined.psd".into(), None, None, None, Some(order), 1000, Some(4000), false, false); assert_eq!(app.ui.dialogs.len(), 1); let dlg_id = app.ui.dialogs[0].id; @@ -515,8 +517,8 @@ fn batch_single_file_cancel_preserves_other_held_memory_orders() { }) .unwrap(); - crate::open_prompt::arrive_memory(&mut app, p0, "first.psd".into(), None, None, Some(order0), 1000, Some(4000), false, false); - crate::open_prompt::arrive_memory(&mut app, p1, "second.psd".into(), None, None, Some(order1), 1000, Some(4000), false, false); + crate::open_prompt::arrive_memory(&mut app, p0, "first.psd".into(), None, None, None, Some(order0), 1000, Some(4000), false, false); + crate::open_prompt::arrive_memory(&mut app, p1, "second.psd".into(), None, None, None, Some(order1), 1000, Some(4000), false, false); // Cancel first file: let dlg0 = app.ui.dialogs[0].id; @@ -553,7 +555,7 @@ fn profile_cancel_cancels_whole_queue_including_memory_prompts() { }) .unwrap(); - crate::open_prompt::arrive_memory(&mut app, preflight_id, "high_mem.psd".into(), None, None, None, 7 * gb, Some(10 * gb), false, false); + crate::open_prompt::arrive_memory(&mut app, preflight_id, "high_mem.psd".into(), None, None, None, None, 7 * gb, Some(10 * gb), false, false); crate::open_prompt::arrive( &mut app, @@ -620,7 +622,7 @@ fn mixed_prompts_follow_arrival_order_fifo() { 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), false, false); + crate::open_prompt::arrive_memory(&mut app, preflight_id, "second_mem.psd".into(), None, None, None, None, 7 * gb, Some(10 * gb), false, false); // First prompt shown must be damage (since it arrived first)! assert_eq!(app.ui.dialogs.len(), 1); @@ -792,7 +794,7 @@ fn reopening_a_file_whose_memory_prompt_waits_does_not_queue_a_duplicate() { let gb = 1u64 << 30; let mut app = app(); let id = store_preflight(&mut app, "slow.psd", 3 * gb, Some(5 * gb)); - crate::open_prompt::arrive_memory(&mut app, id, "slow.psd".into(), Some("/pics/slow.psd".into()), None, None, 3 * gb, Some(5 * gb), false, false); + crate::open_prompt::arrive_memory(&mut app, id, "slow.psd".into(), Some("/pics/slow.psd".into()), None, None, None, 3 * gb, Some(5 * gb), false, false); assert_eq!(app.held_memory_prompts.len(), 1); assert_eq!(app.ui.dialogs.len(), 1); assert!(app.show_if_open("/pics/slow.psd"), "the waiting prompt is shown"); @@ -801,7 +803,7 @@ fn reopening_a_file_whose_memory_prompt_waits_does_not_queue_a_duplicate() { // The template exception: a repeat open still creates another Untitled. let id = store_preflight(&mut app, "card.psdt", 3 * gb, Some(5 * gb)); - crate::open_prompt::arrive_memory(&mut app, id, "card.psdt".into(), Some("/pics/card.psdt".into()), None, None, 3 * gb, Some(5 * gb), false, false); + crate::open_prompt::arrive_memory(&mut app, id, "card.psdt".into(), Some("/pics/card.psdt".into()), None, None, None, 3 * gb, Some(5 * gb), false, false); assert_eq!(app.held_memory_prompts.len(), 2); assert!(!app.show_if_open("/pics/card.psdt"), "a template reopens instead of reusing the waiting prompt"); assert_eq!(app.held_memory_prompts.len(), 2); @@ -1058,8 +1060,8 @@ fn failed_inline_memory_approval_alerts_once_and_preserves_the_next_prompt_and_e let batch = crate::jobs_ui::begin_batch(&mut app); let first_order = crate::jobs_ui::OpenOrder { batch, seq: 0 }; let second_order = crate::jobs_ui::OpenOrder { batch, seq: 1 }; - crate::open_prompt::arrive_memory(&mut app, first, name.into(), path.clone(), None, Some(first_order), 1000, Some(4000), false, false); - crate::open_prompt::arrive_memory(&mut app, second, "next.psd".into(), None, None, Some(second_order), 1000, Some(4000), false, false); + crate::open_prompt::arrive_memory(&mut app, first, name.into(), path.clone(), None, None, Some(first_order), 1000, Some(4000), false, false); + crate::open_prompt::arrive_memory(&mut app, second, "next.psd".into(), None, None, None, Some(second_order), 1000, Some(4000), false, false); let dialog = app.ui.dialogs[0].id; let reply = call(&mut app, "ui.dialog.confirm", json!({"dialog": dialog})); assert_eq!(reply["ok"], false); From eb76800acbad9f9f664bd259db355771a7f2a054 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Tue, 17 Nov 2026 03:23:52 -0800 Subject: [PATCH 10/19] Format byte-template memory prompt source retention --- crates/ui-egui/src/dialogs/open_prompt.rs | 13 ++++++++++- .../src/file_open/unreadable_alert_tests.rs | 23 ++++++++++++------- crates/ui-egui/src/jobs_ui.rs | 10 +++++++- 3 files changed, 36 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/dialogs/open_prompt.rs b/crates/ui-egui/src/dialogs/open_prompt.rs index 3d0dcb2a38..2d81b58729 100644 --- a/crates/ui-egui/src/dialogs/open_prompt.rs +++ b/crates/ui-egui/src/dialogs/open_prompt.rs @@ -380,7 +380,18 @@ pub fn arrive_memory( capacity_unknown: bool, uncertain_capacity_warning: bool, ) { - app.held_memory_prompts.push_back(MemoryPrompt { id, name, path, error_source, slot, order, estimated, available, capacity_unknown, uncertain_capacity_warning }); + app.held_memory_prompts.push_back(MemoryPrompt { + id, + name, + path, + error_source, + slot, + order, + estimated, + available, + capacity_unknown, + uncertain_capacity_warning, + }); app.prompt_order.push_back(PromptKind::Memory); advance_memory(app); } diff --git a/crates/ui-egui/src/file_open/unreadable_alert_tests.rs b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs index a5c38e4485..a9729a9f96 100644 --- a/crates/ui-egui/src/file_open/unreadable_alert_tests.rs +++ b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs @@ -376,7 +376,6 @@ fn recognized_psd_header_failures_keep_their_diagnostic_and_raw_error() { } } - #[cfg(not(target_arch = "wasm32"))] fn template_psd_for_memory_prompt() -> Vec { let mut s = photocraft_engine::Session::new(); @@ -482,13 +481,21 @@ fn byte_template_memory_approval_decode_failures_name_the_source_and_keep_raw_re app.background_jobs = background; let source = photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(header.clone())); let fingerprint = photocraft_engine::jobs::SourceFingerprint::of(&source).unwrap(); - let preflight = app.session.store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { - id: 0, name: "Untitled-1".into(), source, fingerprint, - required: 1000, soft_limit: 500, hard_limit: 2000, available_ram: Some(4000), confirm_damage: true, - }).unwrap(); - crate::open_prompt::arrive_memory( - &mut app, preflight, "Untitled-1".into(), None, Some("card.psdt".into()), None, None, 1000, Some(4000), false, false, - ); + let preflight = app + .session + .store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { + id: 0, + name: "Untitled-1".into(), + source, + fingerprint, + required: 1000, + soft_limit: 500, + hard_limit: 2000, + available_ram: Some(4000), + confirm_damage: true, + }) + .unwrap(); + crate::open_prompt::arrive_memory(&mut app, preflight, "Untitled-1".into(), None, Some("card.psdt".into()), None, None, 1000, Some(4000), false, false); let dialog = app.ui.dialogs[0].id; let reply = memory_dialog_reply(&mut app, dialog, true); let reason = "PSD: unsupported file version 0"; diff --git a/crates/ui-egui/src/jobs_ui.rs b/crates/ui-egui/src/jobs_ui.rs index abdc53ae7c..bf07b69a89 100644 --- a/crates/ui-egui/src/jobs_ui.rs +++ b/crates/ui-egui/src/jobs_ui.rs @@ -708,7 +708,15 @@ fn on_event(app: &mut PhotocraftApp, ctx: &egui::Context, e: JobEvent) { /// (`{document, docId, warnings, color}` or `{held, …}`). `slot` and `order` are the tab position /// and set place the file keeps: through a memory prompt, a profile/damage prompt and the final /// document, so an inline completion lands where a background tab would. -fn finish_open(app: &mut PhotocraftApp, name: &str, path: Option<&str>, error_source: Option<&str>, v: &Value, slot: Option, order: Option) -> Result<(), String> { +fn finish_open( + app: &mut PhotocraftApp, + name: &str, + path: Option<&str>, + error_source: Option<&str>, + v: &Value, + slot: Option, + order: Option, +) -> Result<(), String> { if let Some(preflight_id) = v.get("pendingPreflight").and_then(Value::as_u64) { let estimated = v.get("estimated").and_then(Value::as_u64).unwrap_or(0); let available = v.get("availableRam").and_then(Value::as_u64); From 94219e012266e009e58ec1e0a0f140866ade8134 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Tue, 17 Nov 2026 03:29:47 -0800 Subject: [PATCH 11/19] Update open completion fixtures for optional source metadata --- crates/ui-egui/src/jobs_ui/tests.rs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/jobs_ui/tests.rs b/crates/ui-egui/src/jobs_ui/tests.rs index b7193b12db..27fa1fe304 100644 --- a/crates/ui-egui/src/jobs_ui/tests.rs +++ b/crates/ui-egui/src/jobs_ui/tests.rs @@ -1127,7 +1127,7 @@ fn background_open_warns_about_missing_fonts() { // What the open job leaves behind: the decoded document in the session, then its result. let (index, _) = app.session.open_document(doc, None); let id = app.session.documents()[index].doc.id; - super::finish_open(&mut app, "poster.psd", None, &json!({"document": index, "docId": id.0, "warnings": []}), None, None).unwrap(); + super::finish_open(&mut app, "poster.psd", None, None, &json!({"document": index, "docId": id.0, "warnings": []}), None, None).unwrap(); let want = vec!["font 'NoSuchFamily4559' is not installed; text may render using a fallback face".to_string()]; assert!(app.ui.notices.last().is_some_and(|n| n.title.contains("poster.psd") && n.lines == want), "{:?}", app.ui.notices); } @@ -1209,7 +1209,7 @@ fn open_identity_survives_tab_reordering() { let old_index = result["document"].as_u64().unwrap() as usize; app.session.move_document(old_index, 0).unwrap(); assert_eq!(app.session.documents()[old_index].doc.id, control.doc.id); - super::finish_open(&mut app, "imported.png", Some("imported.png"), &result, None, None).unwrap(); + super::finish_open(&mut app, "imported.png", Some("imported.png"), None, &result, None, None).unwrap(); control.assert_untouched(&app); assert_eq!(app.session.active().unwrap().doc.id, imported); assert_eq!(app.session.active().unwrap().path.as_deref(), Some("imported.png")); @@ -1224,7 +1224,7 @@ fn open_identity_survives_an_earlier_tab_closing() { let (result, imported) = identified_result(&app, result); app.session.close(1).unwrap(); app.session.set_active(0); - super::finish_open(&mut app, "imported.png", Some("imported.png"), &result, Some(0), None).unwrap(); + super::finish_open(&mut app, "imported.png", Some("imported.png"), None, &result, Some(0), None).unwrap(); control.assert_untouched(&app); assert_eq!(app.session.active().unwrap().doc.id, imported); assert_eq!(app.session.documents()[0].doc.id, imported, "the requested destination slot applies to the correct document"); @@ -1246,13 +1246,13 @@ fn open_identity_rejects_closed_missing_and_invalid_identities() { } Some(value) => result["docId"] = value, } - assert!(super::finish_open(&mut app, "closed.png", Some("closed.png"), &result, Some(0), None).is_err(), "invalid identity was accepted: {result}"); + assert!(super::finish_open(&mut app, "closed.png", Some("closed.png"), None, &result, Some(0), None).is_err(), "invalid identity was accepted: {result}"); control.assert_untouched(&app); assert_eq!(app.session.active().unwrap().doc.id, control.doc.id); assert_eq!(app.session.documents().len(), 1); result["docId"] = json!(imported.0); assert!( - super::finish_open(&mut app, "closed.png", Some("closed.png"), &result, None, None).is_err(), + super::finish_open(&mut app, "closed.png", Some("closed.png"), None, &result, None, None).is_err(), "a closed identity must not fall back to the old tab index" ); control.assert_untouched(&app); @@ -1273,9 +1273,9 @@ fn open_identity_keeps_same_poll_results_in_the_profile_queue() { let (second, second_id) = identified_result(&app, second); // All engine applies have finished. Handling the first ordinary result removes its tab, // shifting the second result before its UI callback runs. - super::finish_open(&mut app, "profile.png", Some("profile.png"), &prompt, None, None).unwrap(); - super::finish_open(&mut app, "first.png", Some("first.png"), &first, None, None).unwrap(); - super::finish_open(&mut app, "second.png", Some("second.png"), &second, None, None).unwrap(); + super::finish_open(&mut app, "profile.png", Some("profile.png"), None, &prompt, None, None).unwrap(); + super::finish_open(&mut app, "first.png", Some("first.png"), None, &first, None, None).unwrap(); + super::finish_open(&mut app, "second.png", Some("second.png"), None, &second, None, None).unwrap(); assert_eq!(app.held_opens.iter().map(|held| held.name.as_str()).collect::>(), ["profile.png", "first.png", "second.png"]); assert_eq!(app.held_opens.iter().skip(1).map(|held| held.doc.id).collect::>(), [first_id, second_id]); assert_eq!(app.session.documents().len(), 1, "both completed imports wait behind the profile prompt"); From ee4cfc0a087da1cc9346ce95772ffa743b547747 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Tue, 17 Nov 2026 03:33:44 -0800 Subject: [PATCH 12/19] Format open fixture source argument calls --- crates/ui-egui/src/jobs_ui/tests.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/jobs_ui/tests.rs b/crates/ui-egui/src/jobs_ui/tests.rs index 27fa1fe304..6d33028859 100644 --- a/crates/ui-egui/src/jobs_ui/tests.rs +++ b/crates/ui-egui/src/jobs_ui/tests.rs @@ -1246,7 +1246,10 @@ fn open_identity_rejects_closed_missing_and_invalid_identities() { } Some(value) => result["docId"] = value, } - assert!(super::finish_open(&mut app, "closed.png", Some("closed.png"), None, &result, Some(0), None).is_err(), "invalid identity was accepted: {result}"); + assert!( + super::finish_open(&mut app, "closed.png", Some("closed.png"), None, &result, Some(0), None).is_err(), + "invalid identity was accepted: {result}" + ); control.assert_untouched(&app); assert_eq!(app.session.active().unwrap().doc.id, control.doc.id); assert_eq!(app.session.documents().len(), 1); From 2b336ac9efb7250d4861f9d3ce2690e924e3f8d5 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Thu, 26 Nov 2026 17:15:30 -0800 Subject: [PATCH 13/19] Format unreadable-file alert integration --- crates/ui-egui/src/file_open.rs | 20 +- crates/ui-egui/src/file_open/tests.rs | 20 +- .../src/file_open/unreadable_alert_tests.rs | 41 ++-- crates/ui-egui/src/psd_open_tests.rs | 178 ++++++++++-------- 4 files changed, 150 insertions(+), 109 deletions(-) diff --git a/crates/ui-egui/src/file_open.rs b/crates/ui-egui/src/file_open.rs index cef9b21b27..a9c878bb48 100644 --- a/crates/ui-egui/src/file_open.rs +++ b/crates/ui-egui/src/file_open.rs @@ -240,11 +240,21 @@ struct OpenFailureAlert { impl StackDialog for OpenFailureAlert { type Result = (); - fn id(&self) -> DialogId { self.id } - fn instance(&self) -> Option { Some(self.id) } - fn key(&self) -> Option<&str> { self.alert.key() } - fn json_fields(&self) -> Option { self.alert.json_fields() } - fn confirm(&mut self, ctx: &egui::Context) -> Option<()> { self.alert.confirm(ctx) } + fn id(&self) -> DialogId { + self.id + } + fn instance(&self) -> Option { + Some(self.id) + } + fn key(&self) -> Option<&str> { + self.alert.key() + } + fn json_fields(&self) -> Option { + self.alert.json_fields() + } + fn confirm(&mut self, ctx: &egui::Context) -> Option<()> { + self.alert.confirm(ctx) + } fn show(&mut self, ui: &mut egui::Ui, stack: &DialogStack) -> Option> { ui.push_id(self.id, |ui| self.alert.show(ui, stack)).inner } diff --git a/crates/ui-egui/src/file_open/tests.rs b/crates/ui-egui/src/file_open/tests.rs index 93888515ed..a6274bd038 100644 --- a/crates/ui-egui/src/file_open/tests.rs +++ b/crates/ui-egui/src/file_open/tests.rs @@ -1704,11 +1704,15 @@ fn error_titles(app: &PhotocraftApp) -> Vec { } fn open_error_messages(app: &PhotocraftApp) -> Vec { - app.framework.dialogs.open_dialogs().into_iter().filter(|d| d.key.as_deref() == Some("alert")) - .filter_map(|d| d.fields.and_then(|f| f.get("message").and_then(serde_json::Value::as_str).map(str::to_owned))).collect() + app.framework + .dialogs + .open_dialogs() + .into_iter() + .filter(|d| d.key.as_deref() == Some("alert")) + .filter_map(|d| d.fields.and_then(|f| f.get("message").and_then(serde_json::Value::as_str).map(str::to_owned))) + .collect() } - /// The Home screen (no document open) is where a first drop lands: every file opens as its own /// document, in drop order, whatever the type, and nothing is placed. #[test] @@ -1852,10 +1856,7 @@ fn open_as_smart_object_dialog_opens_one_document_per_selected_file() { assert_eq!(app.session.documents().iter().map(|d| d.doc.name.as_str()).collect::>(), ["one-1", "two-1"]); assert!(app.session.documents().iter().all(|d| d.path.is_none() && d.doc.layers.len() == 1)); - assert!( - open_error_messages(&app).iter().any(|message| message.starts_with("Couldn't open bad.png")), - "the unreadable file is reported" - ); + assert!(open_error_messages(&app).iter().any(|message| message.starts_with("Couldn't open bad.png")), "the unreadable file is reported"); let _ = std::fs::remove_dir_all(&dir); } @@ -1877,10 +1878,7 @@ fn open_as_smart_object_opens_in_the_background_in_name_order() { tick_until(&mut app, &ctx, |app| app.jobs.opens.is_empty()); assert_eq!(app.session.documents().iter().map(|d| d.doc.name.as_str()).collect::>(), ["one-1", "two-1"]); assert!(app.session.documents().iter().all(|d| d.path.is_none() && d.doc.layers.len() == 1)); - assert!( - open_error_messages(&app).iter().any(|message| message.starts_with("Couldn't open bad.png")), - "the unreadable file is reported" - ); + assert!(open_error_messages(&app).iter().any(|message| message.starts_with("Couldn't open bad.png")), "the unreadable file is reported"); let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/ui-egui/src/file_open/unreadable_alert_tests.rs b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs index 5230e74655..6286de7cdc 100644 --- a/crates/ui-egui/src/file_open/unreadable_alert_tests.rs +++ b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs @@ -3,13 +3,13 @@ use super::*; use crate::control::{ControlRequest, Reply, handle}; +use crate::{Services, menus}; use craft::host::{Picked, ScriptedFiles}; use craft::ui::dialog::{DialogId, OpenDialog}; use craft::ui::runtime::drag::OsFile; -use std::sync::Arc; -use crate::{Services, menus}; use egui_kittest::kittest::Queryable; use serde_json::json; +use std::sync::Arc; fn app_with(answer: Option) -> Box { let services = Services { @@ -36,7 +36,9 @@ fn messages(app: &PhotocraftApp) -> Vec { error_dialogs(app).into_iter().map(|d| d.fields.unwrap()["message"].as_str().unwrap().to_owned()).collect() } -fn no_dialogs(app: &PhotocraftApp) -> bool { app.framework.dialogs.open_dialogs().is_empty() } +fn no_dialogs(app: &PhotocraftApp) -> bool { + app.framework.dialogs.open_dialogs().is_empty() +} fn memory_id(app: &PhotocraftApp) -> DialogId { crate::dialogs::alerts::prompt_tagged::(app).unwrap() @@ -303,15 +305,12 @@ fn recent_grid_and_list_read_failures_keep_the_reason_without_repeating_the_path app.background_jobs = false; app.ui.chrome.home_recent_view = if grid { craft::ui::shell::RecentView::Grid } else { craft::ui::shell::RecentView::List }; app.push_recent(&source); - let mut h = egui_kittest::Harness::builder() - .with_size(egui::vec2(900.0, 760.0)) - .with_context(app.ctx().clone()) - .build_ui_state( - |ui, app: &mut Box| { - egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| crate::canvas::document_area(app, ui)); - }, - app, - ); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 760.0)).with_context(app.ctx().clone()).build_ui_state( + |ui, app: &mut Box| { + egui::CentralPanel::default().frame(egui::Frame::NONE).show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + app, + ); h.run_steps(3); h.get_by_label("missing.psd").click(); h.run_steps(3); @@ -495,10 +494,20 @@ fn byte_template_memory_approval_decode_failures_name_the_source_and_keep_raw_re direct.background_jobs = false; let source = photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(header.clone())); let fingerprint = photocraft_engine::jobs::SourceFingerprint::of(&source).unwrap(); - let id = direct.session.store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { - id: 0, name: "Untitled-1".into(), source, fingerprint, required: 1000, soft_limit: 500, - hard_limit: 2000, available_ram: Some(4000), confirm_damage: true, - }).unwrap(); + let id = direct + .session + .store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { + id: 0, + name: "Untitled-1".into(), + source, + fingerprint, + required: 1000, + soft_limit: 500, + hard_limit: 2000, + available_ram: Some(4000), + confirm_damage: true, + }) + .unwrap(); crate::open_prompt::arrive_memory(&mut direct, id, "Untitled-1".into(), None, Some("card.psdt".into()), None, None, 1000, Some(4000), false, false); let error = crate::open_prompt::answer_memory(&mut direct, true).unwrap_err(); assert_eq!(error, "Untitled-1: Untitled-1: PSD: unsupported file version 0", "preserve the approval's original wrapper"); diff --git a/crates/ui-egui/src/psd_open_tests.rs b/crates/ui-egui/src/psd_open_tests.rs index f9b0593a10..2ab637fc0d 100644 --- a/crates/ui-egui/src/psd_open_tests.rs +++ b/crates/ui-egui/src/psd_open_tests.rs @@ -383,7 +383,19 @@ fn memory_confirmation_refuses_when_source_changed_inline() { }) .unwrap(); - crate::open_prompt::arrive_memory(&mut app, preflight_id, "changed.psd".into(), Some(path.to_string_lossy().to_string()), None, None, None, 1000, Some(100_000), false, false); + crate::open_prompt::arrive_memory( + &mut app, + preflight_id, + "changed.psd".into(), + Some(path.to_string_lossy().to_string()), + None, + None, + None, + 1000, + Some(100_000), + false, + false, + ); let dlg_id = memory_dialog(&mut app); // Mutate file before confirming: @@ -423,7 +435,19 @@ fn memory_confirmation_refuses_when_source_changed_async() { }) .unwrap(); - crate::open_prompt::arrive_memory(&mut app, preflight_id, "changed_async.psd".into(), Some(path.to_string_lossy().to_string()), None, None, None, 1000, Some(100_000), false, false); + crate::open_prompt::arrive_memory( + &mut app, + preflight_id, + "changed_async.psd".into(), + Some(path.to_string_lossy().to_string()), + None, + None, + None, + 1000, + Some(100_000), + false, + false, + ); let dlg_id = memory_dialog(&mut app); // Mutate file before confirming: @@ -1025,81 +1049,81 @@ fn failed_inline_memory_approval_alerts_once_and_preserves_the_next_prompt_and_e ]; for (name, file_name) in [("failed.psd", None), ("failed.psd", Some("failed.psd")), ("Untitled-1", Some("template.psdt"))] { for typed in [false, true] { - let mut app = app(); - let temp = tempfile::tempdir().unwrap(); - let path = file_name.map(|file| { - let path = temp.path().join(file); - std::fs::write(&path, header).unwrap(); - path.to_string_lossy().into_owned() - }); - let source = path.as_ref().map_or_else( - || photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(header.to_vec())), - |path| photocraft_engine::jobs::OpenSource::Path(path.clone()), - ); - let fingerprint = photocraft_engine::jobs::SourceFingerprint::of(&source).unwrap(); - let first = app - .session - .store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { - id: 0, - name: name.into(), - source, - fingerprint, - required: 1000, - soft_limit: 500, - hard_limit: 2000, - available_ram: Some(4000), - confirm_damage: true, - }) - .unwrap(); - let second = store_preflight(&mut app, "next.psd", 1000, Some(4000)); - let batch = crate::jobs_ui::begin_batch(&mut app); - let first_order = crate::jobs_ui::OpenOrder { batch, seq: 0 }; - let second_order = crate::jobs_ui::OpenOrder { batch, seq: 1 }; - crate::open_prompt::arrive_memory(&mut app, first, name.into(), path.clone(), None, None, Some(first_order), 1000, Some(4000), false, false); - crate::open_prompt::arrive_memory(&mut app, second, "next.psd".into(), None, None, None, Some(second_order), 1000, Some(4000), false, false); - let dialog = alerts::prompt_tagged::(&app).unwrap(); - if typed { - let reply = call(&mut app, "ui.dialog.confirm", json!({"dialog": dialog.value()})); - assert_eq!(reply["ok"], true, "typed confirmation acknowledges delivery; the real consumer presents the approval failure"); - } else { - let error = crate::open_prompt::answer_memory(&mut app, true).unwrap_err(); - assert_eq!(error, format!("{name}: {name}: PSD: unsupported file version 0"), "keep the approval's original raw error"); - let ctx = app.ctx().clone(); - ctx.run_ui(Default::default(), |ui| crate::dialogs::run(&mut app, ui)).textures_delta.clear(); - } - let source_name = file_name.unwrap_or(name); - let wanted = format!("Couldn't open {source_name}: PSD: unsupported file version 0"); - let errors: Vec<_> = app.framework.dialogs.open_dialogs().into_iter().filter(|d| d.key.as_deref() == Some("alert")).collect(); - assert_eq!(errors.len(), 1); - assert_eq!(errors[0].fields.as_ref().unwrap()["message"], wanted); - let error_id = errors[0].id; - assert_eq!(app.ui.status, wanted); - assert_eq!(app.ui.status.matches(source_name).count(), 1); - if name != source_name { - assert!(!app.ui.status.contains(name)); - } - assert!(app.ui.status_error); - assert!(app.ui.notices.is_empty()); - assert!(app.session.documents().is_empty()); - assert!(app.ui.recent_files.is_empty()); - assert!(app.jobs.opens.is_empty()); - assert!(app.session.take_pending_preflight(first).is_none()); - assert_eq!(app.held_memory_prompts.len(), 1); - assert_eq!(app.held_memory_prompts[0].id, second); - assert_eq!(app.prompt_order.len(), 1); - assert_eq!(app.jobs.batches.len(), 1, "the waiting successor still owns this batch"); - let next = alerts::prompt_tagged::(&app).unwrap(); - crate::open_prompt::advance_memory(&mut app); - assert_eq!(app.framework.dialogs.open_dialogs().len(), 2, "neither the alert nor the successor prompt is duplicated"); - assert_eq!(call(&mut app, "ui.dialog.confirm", json!({"dialog": error_id.value()}))["ok"], true); - assert_eq!(app.framework.dialogs.open_dialogs().len(), 1); - assert_eq!(app.framework.dialogs.open_dialogs()[0].id, next); - assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": next.value()}))["ok"], true); - assert!(app.session.take_pending_preflight(second).is_none()); - assert!(app.framework.dialogs.open_dialogs().is_empty()); - assert!(app.held_memory_prompts.is_empty()); - assert!(app.prompt_order.is_empty()); - assert!(app.jobs.batches.is_empty()); + let mut app = app(); + let temp = tempfile::tempdir().unwrap(); + let path = file_name.map(|file| { + let path = temp.path().join(file); + std::fs::write(&path, header).unwrap(); + path.to_string_lossy().into_owned() + }); + let source = path.as_ref().map_or_else( + || photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(header.to_vec())), + |path| photocraft_engine::jobs::OpenSource::Path(path.clone()), + ); + let fingerprint = photocraft_engine::jobs::SourceFingerprint::of(&source).unwrap(); + let first = app + .session + .store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { + id: 0, + name: name.into(), + source, + fingerprint, + required: 1000, + soft_limit: 500, + hard_limit: 2000, + available_ram: Some(4000), + confirm_damage: true, + }) + .unwrap(); + let second = store_preflight(&mut app, "next.psd", 1000, Some(4000)); + let batch = crate::jobs_ui::begin_batch(&mut app); + let first_order = crate::jobs_ui::OpenOrder { batch, seq: 0 }; + let second_order = crate::jobs_ui::OpenOrder { batch, seq: 1 }; + crate::open_prompt::arrive_memory(&mut app, first, name.into(), path.clone(), None, None, Some(first_order), 1000, Some(4000), false, false); + crate::open_prompt::arrive_memory(&mut app, second, "next.psd".into(), None, None, None, Some(second_order), 1000, Some(4000), false, false); + let dialog = alerts::prompt_tagged::(&app).unwrap(); + if typed { + let reply = call(&mut app, "ui.dialog.confirm", json!({"dialog": dialog.value()})); + assert_eq!(reply["ok"], true, "typed confirmation acknowledges delivery; the real consumer presents the approval failure"); + } else { + let error = crate::open_prompt::answer_memory(&mut app, true).unwrap_err(); + assert_eq!(error, format!("{name}: {name}: PSD: unsupported file version 0"), "keep the approval's original raw error"); + let ctx = app.ctx().clone(); + ctx.run_ui(Default::default(), |ui| crate::dialogs::run(&mut app, ui)).textures_delta.clear(); + } + let source_name = file_name.unwrap_or(name); + let wanted = format!("Couldn't open {source_name}: PSD: unsupported file version 0"); + let errors: Vec<_> = app.framework.dialogs.open_dialogs().into_iter().filter(|d| d.key.as_deref() == Some("alert")).collect(); + assert_eq!(errors.len(), 1); + assert_eq!(errors[0].fields.as_ref().unwrap()["message"], wanted); + let error_id = errors[0].id; + assert_eq!(app.ui.status, wanted); + assert_eq!(app.ui.status.matches(source_name).count(), 1); + if name != source_name { + assert!(!app.ui.status.contains(name)); + } + assert!(app.ui.status_error); + assert!(app.ui.notices.is_empty()); + assert!(app.session.documents().is_empty()); + assert!(app.ui.recent_files.is_empty()); + assert!(app.jobs.opens.is_empty()); + assert!(app.session.take_pending_preflight(first).is_none()); + assert_eq!(app.held_memory_prompts.len(), 1); + assert_eq!(app.held_memory_prompts[0].id, second); + assert_eq!(app.prompt_order.len(), 1); + assert_eq!(app.jobs.batches.len(), 1, "the waiting successor still owns this batch"); + let next = alerts::prompt_tagged::(&app).unwrap(); + crate::open_prompt::advance_memory(&mut app); + assert_eq!(app.framework.dialogs.open_dialogs().len(), 2, "neither the alert nor the successor prompt is duplicated"); + assert_eq!(call(&mut app, "ui.dialog.confirm", json!({"dialog": error_id.value()}))["ok"], true); + assert_eq!(app.framework.dialogs.open_dialogs().len(), 1); + assert_eq!(app.framework.dialogs.open_dialogs()[0].id, next); + assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": next.value()}))["ok"], true); + assert!(app.session.take_pending_preflight(second).is_none()); + assert!(app.framework.dialogs.open_dialogs().is_empty()); + assert!(app.held_memory_prompts.is_empty()); + assert!(app.prompt_order.is_empty()); + assert!(app.jobs.batches.is_empty()); } } } From d29315ea7dae77b53ba8ff12374456ff2d1a649b Mon Sep 17 00:00:00 2001 From: yoriswind Date: Thu, 26 Nov 2026 17:52:23 -0800 Subject: [PATCH 14/19] Drain per-file alert acknowledgements by instance-aware dialog type --- crates/ui-egui/src/file_open.rs | 2 +- .../src/file_open/unreadable_alert_tests.rs | 14 +++++++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/file_open.rs b/crates/ui-egui/src/file_open.rs index a9c878bb48..c40cb777e5 100644 --- a/crates/ui-egui/src/file_open.rs +++ b/crates/ui-egui/src/file_open.rs @@ -262,7 +262,7 @@ impl StackDialog for OpenFailureAlert { /// Acknowledgements contain no command; drain every completed occurrence without reopening it. pub(crate) fn take_open_alerts(app: &mut PhotocraftApp, _ctx: &egui::Context) { - while app.framework.dialogs.take::().is_some() {} + while app.framework.dialogs.take_keyed::().is_some() {} } impl PhotocraftApp { diff --git a/crates/ui-egui/src/file_open/unreadable_alert_tests.rs b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs index 6286de7cdc..dedc0e59c1 100644 --- a/crates/ui-egui/src/file_open/unreadable_alert_tests.rs +++ b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs @@ -146,9 +146,21 @@ fn several_failed_files_each_get_one_alert_and_valid_files_still_open() { crate::dialogs::confirm(&mut app, &app_ctx, first).unwrap(); assert_eq!(messages(&app), [expected("c.png")]); let second = error_dialogs(&app)[0].id; - crate::dialogs::confirm(&mut app, &app_ctx, second).unwrap(); + assert_ne!(first, second, "each failed file has its own instance"); + let (request, _rx) = ControlRequest::new("ui.dialog.confirm", json!({"dialog": second.value()})); + let Reply::Done(reply) = handle(&mut app, &app_ctx, &request) else { panic!("alert confirmation is immediate") }; + assert_eq!(reply["ok"], true); + app_ctx.run_ui(Default::default(), |ui| crate::dialogs::run(&mut app, ui)).textures_delta.clear(); assert!(messages(&app).is_empty()); assert_eq!(app.session.documents().len(), 2); + assert!(app.framework.dialogs.take_keyed::().is_none(), "the consumer drains both instance-bound acknowledgements"); + + // The per-file consumer owns only its wrapper, even though a plain alert also answers (). + let plain = app.framework.dialogs.open(HostedAlert::new(Alert::new("PhotoCraft", "unrelated alert"))); + assert!(app.framework.dialogs.confirm_by_id(&app_ctx, plain)); + take_open_alerts(&mut app, &app_ctx); + assert!(matches!(app.framework.dialogs.take::(), Some(DialogResult::Ok(())))); + assert!(app.framework.dialogs.take_keyed::().is_none()); } #[test] From 8a216ae142a85f8e381858d8f1d262eec5c9abc0 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Thu, 26 Nov 2026 19:09:37 -0800 Subject: [PATCH 15/19] Use current control replies in unreadable-file regressions --- crates/ui-egui/src/file_open/unreadable_alert_tests.rs | 7 ++++--- crates/ui-egui/src/psd_open_tests.rs | 6 +++--- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/file_open/unreadable_alert_tests.rs b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs index dedc0e59c1..75b4cf40bb 100644 --- a/crates/ui-egui/src/file_open/unreadable_alert_tests.rs +++ b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs @@ -249,9 +249,10 @@ fn unreadable_native_drop(path: std::path::PathBuf) -> OsFile { fn finish_read_failure(app: &mut PhotocraftApp, source: &str, reason: &str, worker_error: &str) { let job = app.jobs.opens.first().map(|tab| tab.job); let reply = job.map(|job| { - let (tx, rx) = std::sync::mpsc::channel(); - app.jobs.waiters.push((job, tx)); - rx + let (request, reply) = ControlRequest::new("engine.execute", json!({})); + let channel = app.control.get_or_insert_with(|| craft::automation::ControlChannel::new(std::sync::mpsc::channel().1)); + channel.settle(request, Reply::AfterJob(job.0), None, 0.0); + reply }); let ctx = app.ctx().clone(); let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30); diff --git a/crates/ui-egui/src/psd_open_tests.rs b/crates/ui-egui/src/psd_open_tests.rs index 2ab637fc0d..1d199542ee 100644 --- a/crates/ui-egui/src/psd_open_tests.rs +++ b/crates/ui-egui/src/psd_open_tests.rs @@ -760,7 +760,7 @@ fn memory_prompt_states_unknown_capacity_and_the_eight_gib_warning() { assert!(message.contains("could not be measured"), "{message}"); assert!(message.contains("8 GiB") && message.contains("may run out of memory"), "{message}"); assert!(!message.contains("available)"), "the unknown-capacity message claims no available figure: {message}"); - assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": dialog.value()}))["ok"], true); + assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": dialog}))["ok"], true); // A measured capacity shows the number and drops the uncertainty warning. let id = store_preflight(&mut app, "known.psd", 3 * gb, Some(5 * gb)); @@ -779,7 +779,7 @@ fn memory_prompt_states_unknown_capacity_and_the_eight_gib_warning() { let message = crate::open_prompt::memory_message(prompt); assert!(message.contains("5.0 GiB available"), "{message}"); assert!(!message.contains("could not be measured") && !message.contains("may run out of memory"), "{message}"); - assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": dialog.value()}))["ok"], true); + assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": dialog}))["ok"], true); assert!(no_dialog(&app)); } @@ -802,7 +802,7 @@ fn memory_prompt_warns_when_little_memory_would_be_left() { let dialog = memory_dialog(&mut app); let message = crate::open_prompt::memory_message(front_memory(&app)); assert!(message.contains("Little memory would be left") && message.contains("may run out of memory"), "{message}"); - assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": dialog.value()}))["ok"], true); + assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": dialog}))["ok"], true); } /// #10897: reopening an ordinary file whose high-memory prompt is already waiting shows that From afbb82c625bbbd556f28ac8c6a9ad53ad3832300 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Thu, 26 Nov 2026 19:26:49 -0800 Subject: [PATCH 16/19] Separate memory-approval regression scenarios from their assertions --- crates/ui-egui/src/psd_open_tests.rs | 161 ++++++++++++++------------- 1 file changed, 83 insertions(+), 78 deletions(-) diff --git a/crates/ui-egui/src/psd_open_tests.rs b/crates/ui-egui/src/psd_open_tests.rs index 1d199542ee..c9863af334 100644 --- a/crates/ui-egui/src/psd_open_tests.rs +++ b/crates/ui-egui/src/psd_open_tests.rs @@ -1036,6 +1036,15 @@ fn confirmed_damaged_smart_object_opens_are_admitted_as_smart_objects_with_disti #[cfg(not(target_arch = "wasm32"))] #[test] fn failed_inline_memory_approval_alerts_once_and_preserves_the_next_prompt_and_error_reply() { + for (name, file_name) in [("failed.psd", None), ("failed.psd", Some("failed.psd")), ("Untitled-1", Some("template.psdt"))] { + for typed in [false, true] { + check_failed_memory_approval_case(name, file_name, typed); + } + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn check_failed_memory_approval_case(name: &str, file_name: Option<&str>, typed: bool) { // File-backed decoding reads the complete 26-byte header before parsing it. Give both // routes that same header so the unsupported version, rather than EOF, is the failure. let header = [ @@ -1047,83 +1056,79 @@ fn failed_inline_memory_approval_alerts_once_and_preserves_the_next_prompt_and_e 0, 8, // depth 0, 3, // RGB ]; - for (name, file_name) in [("failed.psd", None), ("failed.psd", Some("failed.psd")), ("Untitled-1", Some("template.psdt"))] { - for typed in [false, true] { - let mut app = app(); - let temp = tempfile::tempdir().unwrap(); - let path = file_name.map(|file| { - let path = temp.path().join(file); - std::fs::write(&path, header).unwrap(); - path.to_string_lossy().into_owned() - }); - let source = path.as_ref().map_or_else( - || photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(header.to_vec())), - |path| photocraft_engine::jobs::OpenSource::Path(path.clone()), - ); - let fingerprint = photocraft_engine::jobs::SourceFingerprint::of(&source).unwrap(); - let first = app - .session - .store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { - id: 0, - name: name.into(), - source, - fingerprint, - required: 1000, - soft_limit: 500, - hard_limit: 2000, - available_ram: Some(4000), - confirm_damage: true, - }) - .unwrap(); - let second = store_preflight(&mut app, "next.psd", 1000, Some(4000)); - let batch = crate::jobs_ui::begin_batch(&mut app); - let first_order = crate::jobs_ui::OpenOrder { batch, seq: 0 }; - let second_order = crate::jobs_ui::OpenOrder { batch, seq: 1 }; - crate::open_prompt::arrive_memory(&mut app, first, name.into(), path.clone(), None, None, Some(first_order), 1000, Some(4000), false, false); - crate::open_prompt::arrive_memory(&mut app, second, "next.psd".into(), None, None, None, Some(second_order), 1000, Some(4000), false, false); - let dialog = alerts::prompt_tagged::(&app).unwrap(); - if typed { - let reply = call(&mut app, "ui.dialog.confirm", json!({"dialog": dialog.value()})); - assert_eq!(reply["ok"], true, "typed confirmation acknowledges delivery; the real consumer presents the approval failure"); - } else { - let error = crate::open_prompt::answer_memory(&mut app, true).unwrap_err(); - assert_eq!(error, format!("{name}: {name}: PSD: unsupported file version 0"), "keep the approval's original raw error"); - let ctx = app.ctx().clone(); - ctx.run_ui(Default::default(), |ui| crate::dialogs::run(&mut app, ui)).textures_delta.clear(); - } - let source_name = file_name.unwrap_or(name); - let wanted = format!("Couldn't open {source_name}: PSD: unsupported file version 0"); - let errors: Vec<_> = app.framework.dialogs.open_dialogs().into_iter().filter(|d| d.key.as_deref() == Some("alert")).collect(); - assert_eq!(errors.len(), 1); - assert_eq!(errors[0].fields.as_ref().unwrap()["message"], wanted); - let error_id = errors[0].id; - assert_eq!(app.ui.status, wanted); - assert_eq!(app.ui.status.matches(source_name).count(), 1); - if name != source_name { - assert!(!app.ui.status.contains(name)); - } - assert!(app.ui.status_error); - assert!(app.ui.notices.is_empty()); - assert!(app.session.documents().is_empty()); - assert!(app.ui.recent_files.is_empty()); - assert!(app.jobs.opens.is_empty()); - assert!(app.session.take_pending_preflight(first).is_none()); - assert_eq!(app.held_memory_prompts.len(), 1); - assert_eq!(app.held_memory_prompts[0].id, second); - assert_eq!(app.prompt_order.len(), 1); - assert_eq!(app.jobs.batches.len(), 1, "the waiting successor still owns this batch"); - let next = alerts::prompt_tagged::(&app).unwrap(); - crate::open_prompt::advance_memory(&mut app); - assert_eq!(app.framework.dialogs.open_dialogs().len(), 2, "neither the alert nor the successor prompt is duplicated"); - assert_eq!(call(&mut app, "ui.dialog.confirm", json!({"dialog": error_id.value()}))["ok"], true); - assert_eq!(app.framework.dialogs.open_dialogs().len(), 1); - assert_eq!(app.framework.dialogs.open_dialogs()[0].id, next); - assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": next.value()}))["ok"], true); - assert!(app.session.take_pending_preflight(second).is_none()); - assert!(app.framework.dialogs.open_dialogs().is_empty()); - assert!(app.held_memory_prompts.is_empty()); - assert!(app.prompt_order.is_empty()); - assert!(app.jobs.batches.is_empty()); - } + let mut app = app(); + let temp = tempfile::tempdir().unwrap(); + let path = file_name.map(|file| { + let path = temp.path().join(file); + std::fs::write(&path, header).unwrap(); + path.to_string_lossy().into_owned() + }); + let source = path.as_ref().map_or_else( + || photocraft_engine::jobs::OpenSource::Bytes(std::sync::Arc::new(header.to_vec())), + |path| photocraft_engine::jobs::OpenSource::Path(path.clone()), + ); + let fingerprint = photocraft_engine::jobs::SourceFingerprint::of(&source).unwrap(); + let first = app + .session + .store_pending_preflight(photocraft_engine::jobs::PendingPsdPreflight { + id: 0, + name: name.into(), + source, + fingerprint, + required: 1000, + soft_limit: 500, + hard_limit: 2000, + available_ram: Some(4000), + confirm_damage: true, + }) + .unwrap(); + let second = store_preflight(&mut app, "next.psd", 1000, Some(4000)); + let batch = crate::jobs_ui::begin_batch(&mut app); + let first_order = crate::jobs_ui::OpenOrder { batch, seq: 0 }; + let second_order = crate::jobs_ui::OpenOrder { batch, seq: 1 }; + crate::open_prompt::arrive_memory(&mut app, first, name.into(), path.clone(), None, None, Some(first_order), 1000, Some(4000), false, false); + crate::open_prompt::arrive_memory(&mut app, second, "next.psd".into(), None, None, None, Some(second_order), 1000, Some(4000), false, false); + let dialog = alerts::prompt_tagged::(&app).unwrap(); + if typed { + let reply = call(&mut app, "ui.dialog.confirm", json!({"dialog": dialog.value()})); + assert_eq!(reply["ok"], true, "typed confirmation acknowledges delivery; the real consumer presents the approval failure"); + } else { + let error = crate::open_prompt::answer_memory(&mut app, true).unwrap_err(); + assert_eq!(error, format!("{name}: {name}: PSD: unsupported file version 0"), "keep the approval's original raw error"); + let ctx = app.ctx().clone(); + ctx.run_ui(Default::default(), |ui| crate::dialogs::run(&mut app, ui)).textures_delta.clear(); } + let source_name = file_name.unwrap_or(name); + let wanted = format!("Couldn't open {source_name}: PSD: unsupported file version 0"); + let errors: Vec<_> = app.framework.dialogs.open_dialogs().into_iter().filter(|d| d.key.as_deref() == Some("alert")).collect(); + assert_eq!(errors.len(), 1); + assert_eq!(errors[0].fields.as_ref().unwrap()["message"], wanted); + let error_id = errors[0].id; + assert_eq!(app.ui.status, wanted); + assert_eq!(app.ui.status.matches(source_name).count(), 1); + if name != source_name { + assert!(!app.ui.status.contains(name)); + } + assert!(app.ui.status_error); + assert!(app.ui.notices.is_empty()); + assert!(app.session.documents().is_empty()); + assert!(app.ui.recent_files.is_empty()); + assert!(app.jobs.opens.is_empty()); + assert!(app.session.take_pending_preflight(first).is_none()); + assert_eq!(app.held_memory_prompts.len(), 1); + assert_eq!(app.held_memory_prompts[0].id, second); + assert_eq!(app.prompt_order.len(), 1); + assert_eq!(app.jobs.batches.len(), 1, "the waiting successor still owns this batch"); + let next = alerts::prompt_tagged::(&app).unwrap(); + crate::open_prompt::advance_memory(&mut app); + assert_eq!(app.framework.dialogs.open_dialogs().len(), 2, "neither the alert nor the successor prompt is duplicated"); + assert_eq!(call(&mut app, "ui.dialog.confirm", json!({"dialog": error_id.value()}))["ok"], true); + assert_eq!(app.framework.dialogs.open_dialogs().len(), 1); + assert_eq!(app.framework.dialogs.open_dialogs()[0].id, next); + assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": next.value()}))["ok"], true); + assert!(app.session.take_pending_preflight(second).is_none()); + assert!(app.framework.dialogs.open_dialogs().is_empty()); + assert!(app.held_memory_prompts.is_empty()); + assert!(app.prompt_order.is_empty()); + assert!(app.jobs.batches.is_empty()); } From 7127634bce0bf98eb7c9e0c1685baae8b78233e4 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Thu, 26 Nov 2026 21:38:01 -0800 Subject: [PATCH 17/19] test(ui): target maintained recent-file accessibility names --- crates/ui-egui/src/file_open/unreadable_alert_tests.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/file_open/unreadable_alert_tests.rs b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs index 75b4cf40bb..41580d6888 100644 --- a/crates/ui-egui/src/file_open/unreadable_alert_tests.rs +++ b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs @@ -312,7 +312,7 @@ fn native_drop_read_failures_name_the_source_once_in_foreground_and_background() #[cfg(not(target_arch = "wasm32"))] #[test] fn recent_grid_and_list_read_failures_keep_the_reason_without_repeating_the_path() { - let (_, source, reason) = missing_source("recent", "missing.psd"); + let (path, source, reason) = missing_source("recent", "missing.psd"); for grid in [false, true] { let mut app = app_with(None); app.background_jobs = false; @@ -325,7 +325,8 @@ fn recent_grid_and_list_read_failures_keep_the_reason_without_repeating_the_path app, ); h.run_steps(3); - h.get_by_label("missing.psd").click(); + let label = if grid { "missing.psd".to_owned() } else { format!("missing.psd, {}", path.parent().unwrap().display()) }; + h.get_by_role_and_label(egui::accesskit::Role::ListItem, &label).click(); h.run_steps(3); finish_read_failure(h.state_mut(), &source, &reason, "no worker in this foreground control"); assert_eq!(h.state().ui.recent_files.as_slice(), std::slice::from_ref(&source)); From fd3afcbfc0436f17c3ffc5bf96ea741c25ffa651 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Thu, 26 Nov 2026 22:16:38 -0800 Subject: [PATCH 18/19] test(ui): assert modal alerts for failed window drops --- crates/ui-egui/src/file_open/tests.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/file_open/tests.rs b/crates/ui-egui/src/file_open/tests.rs index a6274bd038..0e92c23d36 100644 --- a/crates/ui-egui/src/file_open/tests.rs +++ b/crates/ui-egui/src/file_open/tests.rs @@ -559,7 +559,9 @@ fn dropped_files_open_with_path_and_recent() { assert_eq!(app.session.documents()[1].path, None); assert_eq!(*app.ui.recent_files, vec![abs_s]); assert!(app.ui.status_error); - assert_eq!(app.ui.notices.iter().filter(|n| n.tone == craft::theme::variant::Tone::Bad).count(), 2); + assert_eq!(open_error_messages(&app), ["Couldn't open gone.psd: couldn't read the file", "Couldn't open dropped: not an image"]); + assert!(app.ui.notices.is_empty(), "open failures use modal alerts, not corner notices"); + assert_eq!(app.ui.status, "Couldn't open dropped: not an image"); let _ = std::fs::remove_dir_all(&dir); } From b187c73c7cd0d2d4ff9eae562d38dbb83e038c91 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Thu, 26 Nov 2026 22:40:02 -0800 Subject: [PATCH 19/19] test(ui): expect plain unrecognized alerts for Smart Object opens --- crates/ui-egui/src/file_open/tests.rs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/file_open/tests.rs b/crates/ui-egui/src/file_open/tests.rs index 0e92c23d36..aa14793201 100644 --- a/crates/ui-egui/src/file_open/tests.rs +++ b/crates/ui-egui/src/file_open/tests.rs @@ -1858,7 +1858,12 @@ fn open_as_smart_object_dialog_opens_one_document_per_selected_file() { assert_eq!(app.session.documents().iter().map(|d| d.doc.name.as_str()).collect::>(), ["one-1", "two-1"]); assert!(app.session.documents().iter().all(|d| d.path.is_none() && d.doc.layers.len() == 1)); - assert!(open_error_messages(&app).iter().any(|message| message.starts_with("Couldn't open bad.png")), "the unreadable file is reported"); + assert_eq!( + open_error_messages(&app), + ["Could not open \"bad.png\" because PhotoCraft does not recognize this type of file."], + "the unreadable file has one exact modal alert; status: {}", + app.ui.status + ); let _ = std::fs::remove_dir_all(&dir); } @@ -1880,7 +1885,12 @@ fn open_as_smart_object_opens_in_the_background_in_name_order() { tick_until(&mut app, &ctx, |app| app.jobs.opens.is_empty()); assert_eq!(app.session.documents().iter().map(|d| d.doc.name.as_str()).collect::>(), ["one-1", "two-1"]); assert!(app.session.documents().iter().all(|d| d.path.is_none() && d.doc.layers.len() == 1)); - assert!(open_error_messages(&app).iter().any(|message| message.starts_with("Couldn't open bad.png")), "the unreadable file is reported"); + assert_eq!( + open_error_messages(&app), + ["Could not open \"bad.png\" because PhotoCraft does not recognize this type of file."], + "the unreadable file has one exact modal alert; status: {}", + app.ui.status + ); let _ = std::fs::remove_dir_all(&dir); }