diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 4c16e24817..312bae9034 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -87,7 +87,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 { @@ -122,6 +121,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 2d77f4da00..50209b1495 100644 --- a/crates/ui-egui/src/canvas/scroll_all_windows.rs +++ b/crates/ui-egui/src/canvas/scroll_all_windows.rs @@ -281,7 +281,7 @@ mod tests { Hidden::Home => app.ui.chrome.home = Some(app.session.documents().len()), Hidden::Card => { 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.rs b/crates/ui-egui/src/dialogs.rs index 2d0fc804bf..7522447e65 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -446,6 +446,7 @@ pub(crate) fn prompts_take(app: &mut PhotocraftApp, ctx: &egui::Context) { /// The families that take their own results (one `take(app, ctx)` each), in order. pub(crate) const TAKERS: &[fn(&mut PhotocraftApp, &egui::Context)] = &[ alerts::take, + crate::file_open::take_open_alerts, discard_ui::take, open_prompt::take, credits::take, diff --git a/crates/ui-egui/src/dialogs/open_prompt.rs b/crates/ui-egui/src/dialogs/open_prompt.rs index 1bb022d47d..d5173f383b 100644 --- a/crates/ui-egui/src/dialogs/open_prompt.rs +++ b/crates/ui-egui/src/dialogs/open_prompt.rs @@ -70,6 +70,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, @@ -406,6 +408,7 @@ pub fn arrive_memory( id: u64, name: String, path: Option, + error_source: Option, slot: Option, order: Option, estimated: u64, @@ -413,7 +416,18 @@ 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); } @@ -480,6 +494,7 @@ pub(crate) fn answer_memory(app: &mut PhotocraftApp, accept: bool) -> Result 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: error_source.clone(), + 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: error_source.clone(), + slot, + order, + }; if let Err(e) = crate::jobs_ui::finish_open_tab(app, &tab, result) { app.ui.status = e; app.ui.status_error = true; @@ -511,8 +540,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().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}: "); + 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_dialog.rs b/crates/ui-egui/src/file_dialog.rs index 4fe5c16ae2..40f69e60c4 100644 --- a/crates/ui-egui/src/file_dialog.rs +++ b/crates/ui-egui/src/file_dialog.rs @@ -379,7 +379,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 84b63dbf2f..c40cb777e5 100644 --- a/crates/ui-egui/src/file_open.rs +++ b/crates/ui-egui/src/file_open.rs @@ -3,9 +3,10 @@ //! and the OS's "open these documents" requests (macOS Finder double-click, Open With, drops on the //! Dock icon) all go through [`PhotocraftApp::open_file`], so each one names the document after the //! file, remembers its path (File › Save writes back to it) and adds it to Open Recent. Failures -//! are shown as errors (status bar + notice); import warnings as a notice. +//! are shown as modal alerts and in the status bar; import warnings as a notice. use crate::{PhotocraftApp, notices}; +use craft::ui::dialog::{Alert, DialogId, DialogResult, DialogStack, HostedAlert, StackDialog}; use craft::ui::runtime::drag::OsFile; use craft::ui::runtime::windows::{WindowAction, WindowHost}; use photocraft_doc::DocId; @@ -206,6 +207,64 @@ 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" +} + +/// One failed file, rendered by the shared alert. Distinct instances keep a multi-file open's +/// errors separate; a plain HostedAlert has one fixed identity and would replace the earlier file. +struct OpenFailureAlert { + id: DialogId, + alert: HostedAlert, +} + +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 show(&mut self, ui: &mut egui::Ui, stack: &DialogStack) -> Option> { + ui.push_id(self.id, |ui| self.alert.show(ui, stack)).inner + } +} + +/// 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_keyed::().is_some() {} +} + 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 @@ -337,7 +396,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); @@ -371,12 +430,31 @@ 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}: "); + // 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 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}"; - 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; + let id = crate::jobs_ui::open_failure_id(self); + self.framework.dialogs.open(OpenFailureAlert { id, alert: HostedAlert::new(Alert::new("PhotoCraft", msg)) }); } /// Show "Couldn't place : " as an error (status bar + notice). @@ -417,11 +495,13 @@ impl PhotocraftApp { } for f in files { let name = dropped_name(&f); + let source = f.path.as_deref().filter(|path| path.is_absolute()).map(|path| path.to_string_lossy().into_owned()).unwrap_or_else(|| name.clone()); let route = to.route(&name); + if let Some(why) = f.path.as_deref().and_then(folder_error) { match route { DropRoute::Place => self.failed(crate::i18n::fmt(tl!("Couldn't place {name}: {error}"), &[("name", &name), ("error", &why)])), - DropRoute::Open => self.open_failed(&name, &why), + DropRoute::Open => self.open_failed(&source, &why), } continue; } @@ -434,7 +514,7 @@ 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) => self.open_failed(&source, &e), } } } @@ -804,3 +884,6 @@ mod dialog_order_tests; mod place_multiple_files_tests; #[cfg(test)] mod tests; + +#[cfg(test)] +mod unreadable_alert_tests; diff --git a/crates/ui-egui/src/file_open/tests.rs b/crates/ui-egui/src/file_open/tests.rs index 974dfff68e..aa14793201 100644 --- a/crates/ui-egui/src/file_open/tests.rs +++ b/crates/ui-egui/src/file_open/tests.rs @@ -186,7 +186,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.tone == craft::theme::variant::Tone::Bad && n.title.contains("broken.png")), "{:?}", app.ui.notices); + assert!(open_error_messages(&app).iter().any(|message| message.contains("broken.png")), "{:?}", app.ui.notices); } /// #5749: the web shell reads dropped files itself, so it asks where they landed: image files @@ -417,7 +417,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.tone == craft::theme::variant::Tone::Bad)); + assert_eq!(open_error_messages(&app).len(), 1); let _ = std::fs::remove_dir_all(&dir); } @@ -430,8 +430,9 @@ 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.tone == craft::theme::variant::Tone::Bad && 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]); // 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(); @@ -452,7 +453,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(), 4, "one notice per failure"); + assert_eq!(open_error_messages(&app).len(), 4, "one modal alert per failure"); + 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()); @@ -557,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); } @@ -1397,7 +1401,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); @@ -1419,11 +1430,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(); @@ -1691,7 +1702,17 @@ fn scratch(tag: &str) -> std::path::PathBuf { } fn error_titles(app: &PhotocraftApp) -> Vec { - app.ui.notices.iter().filter(|n| n.tone == craft::theme::variant::Tone::Bad).map(|n| n.title.clone()).collect() + app.ui.notices.iter().filter(|n| n.tone == craft::theme::variant::Tone::Bad).map(|n| n.title.clone()).chain(open_error_messages(app)).collect() +} + +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() } /// The Home screen (no document open) is where a first drop lands: every file opens as its own @@ -1717,6 +1738,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.framework.dialogs.open_dialogs()); let _ = std::fs::remove_dir_all(&dir); } @@ -1799,7 +1821,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.framework.dialogs.open_dialogs()); } #[test] @@ -1836,9 +1858,11 @@ 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.tone == craft::theme::variant::Tone::Bad && n.title.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); } @@ -1861,9 +1885,11 @@ 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.tone == craft::theme::variant::Tone::Bad && n.title.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); } 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..41580d6888 --- /dev/null +++ b/crates/ui-egui/src/file_open/unreadable_alert_tests.rs @@ -0,0 +1,581 @@ +//! #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, Reply, handle}; +use crate::{Services, menus}; +use craft::host::{Picked, ScriptedFiles}; +use craft::ui::dialog::{DialogId, OpenDialog}; +use craft::ui::runtime::drag::OsFile; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use std::sync::Arc; + +fn app_with(answer: Option) -> Box { + let services = Services { + files: Some(Arc::new(ScriptedFiles::answering(vec![answer.unwrap_or(Picked::Cancelled)]))), + 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) +} + +fn pick(app: &mut PhotocraftApp) { + let ctx = app.ctx().clone(); + menus::invoke(app, &ctx, "file.open", json!({})).unwrap(); + app.poll_file_dialog(); +} + +fn error_dialogs(app: &PhotocraftApp) -> Vec { + app.framework.dialogs.open_dialogs().into_iter().filter(|d| d.key.as_deref() == Some("alert")).collect() +} + +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 memory_id(app: &PhotocraftApp) -> DialogId { + crate::dialogs::alerts::prompt_tagged::(app).unwrap() +} + +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()), + ("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(Picked::Contents(vec![(name.into(), bytes)]))); + pick(&mut app); + let wanted = 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, 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!(no_dialogs(&interactive), "the caller owns presentation of a returned error"); + + #[cfg(not(target_arch = "wasm32"))] + { + let mut app = app_with(Some(Picked::Contents(vec![("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] +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)) + .with_context(app.ctx().clone()) + .build_ui_state(|ui, app| crate::dialogs::run(app, ui), app); + 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!(no_dialogs(h.state())); + 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, 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); + 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(Picked::Contents(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.tone != craft::theme::variant::Tone::Bad)); + let app_ctx = app.ctx().clone(); + let first = error_dialogs(&app)[0].id; + crate::dialogs::confirm(&mut app, &app_ctx, first).unwrap(); + assert_eq!(messages(&app), [expected("c.png")]); + let second = error_dialogs(&app)[0].id; + 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] +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 = app.ctx().clone(); + 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); + 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.tone != craft::theme::variant::Tone::Bad)); +} + +#[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!(no_dialogs(&app)); + assert!(app.ui.notices.is_empty()); + assert!(!app.ui.status_error); +} + +#[test] +fn automation_and_control_open_still_return_the_original_error() { + // 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!(no_dialogs(&app)); + 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 Reply::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!(no_dialogs(&app)); + 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) +} + +/// A native path plus tempting valid bytes: choosing bytes instead of reading the path would +/// open a document and fail the original missing-file and raw-error assertions below. +#[cfg(not(target_arch = "wasm32"))] +fn unreadable_native_drop(path: std::path::PathBuf) -> OsFile { + let mut file = OsFile::default(); + file.name = display_name(&path.to_string_lossy()); + file.path = Some(path); + file.bytes = Some(png().into()); + file +} + +/// 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 (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); + 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.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![unreadable_native_drop(path.clone())], crate::file_open::DropTo::Window); + 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 (path, 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_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, + ); + h.run_steps(3); + 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)); + } +} + +#[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(Picked::Paths(vec![source.clone().into()]))); + app.background_jobs = background; + app.open_dialog_as_smart_object().unwrap(); + app.poll_file_dialog(); + 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()); + } +} + +#[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(Picked::Contents(vec![("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); + // 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!(no_dialogs(&direct)); + + // 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}")]); + } +} + +#[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: DialogId, 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.value()})); + let ctx = app.ctx().clone(); + let Reply::Done(reply) = handle(app, &ctx, &request) else { panic!("memory prompt reply is immediate") }; + ctx.run_ui(Default::default(), |ui| crate::dialogs::run(app, ui)).textures_delta.clear(); + 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(Picked::Contents(vec![("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 = memory_id(&app); + assert!(crate::dialogs::alerts::prompt_tag::(&app).is_some()); + 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!(no_dialogs(&app)); + 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 + ]; + // The typed UI confirmation is an acknowledgement. The underlying approval result keeps + // its original raw wrapper, checked independently through the same real stored preflight. + { + let mut direct = app_with(None); + 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(); + 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"); + } + 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 = memory_id(&app); + 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"], true, "typed confirmation acknowledges its receipt; the approval error is presented by the real prompt consumer: {reply}"); + 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 = error_dialogs(&app)[0].id; + let ctx = app.ctx().clone(); + crate::dialogs::confirm(&mut app, &ctx, alert).unwrap(); + assert!(no_dialogs(&app), "the one error alert closes normally"); + } +} diff --git a/crates/ui-egui/src/home_recent_ui.rs b/crates/ui-egui/src/home_recent_ui.rs index 02470d1340..73bf196644 100644 --- a/crates/ui-egui/src/home_recent_ui.rs +++ b/crates/ui-egui/src/home_recent_ui.rs @@ -210,7 +210,7 @@ pub(crate) fn act(app: &mut PhotocraftApp, action: &StartAction) -> bool { StartAction::OpenRecent(path) => { let path = path.to_string_lossy(); 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); } true } diff --git a/crates/ui-egui/src/jobs_ui.rs b/crates/ui-egui/src/jobs_ui.rs index f01e730403..3349c99cdb 100644 --- a/crates/ui-egui/src/jobs_ui.rs +++ b/crates/ui-egui/src/jobs_ui.rs @@ -48,6 +48,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 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, /// Its place in a set of files opened together, when it is one of several (see [`OpenOrder`]). @@ -172,6 +174,8 @@ pub struct JobsUi { pub(crate) batches: Vec, /// The id of the next set. next_batch: u64, + /// Identity of the next per-file failure alert (never a document/save identity). + next_open_failure: u64, /// Background saves. pub saves: Vec, /// The window was asked to close while a save was writing: close it once none is left. @@ -187,6 +191,13 @@ pub struct JobsUi { pub(crate) caf_settings: Vec<(JobId, Value)>, } +/// A fresh identity for one failed file. Kept with the window's open bookkeeping, not persisted. +pub(crate) fn open_failure_id(app: &mut PhotocraftApp) -> craft::ui::dialog::DialogId { + let serial = app.jobs.next_open_failure; + app.jobs.next_open_failure = serial.wrapping_add(1); + craft::ui::dialog::dialog_id(("file-open-failure", serial)) +} + /// Run command `id`: in the background when background jobs are on and the command is a job /// (the result is then `{"job": id, "pending": true}` and the edit lands when [`tick`] applies /// it), else synchronously like [`photocraft_engine::Session::execute`]. @@ -285,13 +296,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::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, slot, order }); + track_open(app, OpenTab { job, name: name.to_string(), path, error_source, slot, order }); Ok(()) } } @@ -320,9 +333,9 @@ 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, slot: None, order }); + track_open(app, OpenTab { job, name, path: None, error_source: Some(path.to_string()), slot: None, order }); Ok(()) } } @@ -376,7 +389,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 } @@ -639,13 +652,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.path.as_deref().or(tab.error_source.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; @@ -707,7 +726,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>, 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); @@ -718,6 +745,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/jobs_ui/tests.rs b/crates/ui-egui/src/jobs_ui/tests.rs index 0a235c97c5..f931c57c8c 100644 --- a/crates/ui-egui/src/jobs_ui/tests.rs +++ b/crates/ui-egui/src/jobs_ui/tests.rs @@ -1040,7 +1040,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); } @@ -1122,7 +1122,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")); @@ -1137,7 +1137,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"); @@ -1159,13 +1159,16 @@ 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); @@ -1186,9 +1189,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"); diff --git a/crates/ui-egui/src/psd_open_tests.rs b/crates/ui-egui/src/psd_open_tests.rs index 8ccafccb5d..c9863af334 100644 --- a/crates/ui-egui/src/psd_open_tests.rs +++ b/crates/ui-egui/src/psd_open_tests.rs @@ -247,7 +247,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); let dlg_id = memory_dialog(&mut app); assert_eq!(call(&mut app, "ui.dialog.cancel", json!({"dialog": dlg_id}))["ok"], true); @@ -390,6 +390,7 @@ fn memory_confirmation_refuses_when_source_changed_inline() { Some(path.to_string_lossy().to_string()), None, None, + None, 1000, Some(100_000), false, @@ -441,6 +442,7 @@ fn memory_confirmation_refuses_when_source_changed_async() { Some(path.to_string_lossy().to_string()), None, None, + None, 1000, Some(100_000), false, @@ -490,7 +492,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); let dlg_id = memory_dialog(&mut app); let res = call(&mut app, "ui.dialog.cancel", json!({"dialog": dlg_id})); @@ -538,8 +540,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 = memory_dialog(&mut app); @@ -578,7 +580,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, @@ -645,7 +647,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)! let dlg_id = damage_dialog(&mut app); @@ -739,6 +741,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, }; @@ -761,7 +764,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, @@ -787,7 +791,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, @@ -808,7 +813,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!(alerts::prompt_tagged::(&app).is_some()); assert!(app.show_if_open("/pics/slow.psd"), "the waiting prompt is shown"); @@ -817,7 +822,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); @@ -1024,3 +1029,106 @@ 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 approval +/// error is unchanged; typed UI confirmation acknowledges delivery. The 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"))] { + 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 = [ + 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 + ]; + 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()); +}