From 1e480077dcf4e00c7566eba41d74c1eed7688234 Mon Sep 17 00:00:00 2001 From: alientechsw <43017062+alientechsw@users.noreply.github.com> Date: Sat, 5 Dec 2026 10:54:13 -0800 Subject: [PATCH 1/7] Revert "fix(startup): keep welcome setup complete across updates" --- apps/notecraft/src/main.rs | 194 ++++++++++++++++++++++------ crates/store/src/settings.rs | 9 ++ crates/ui-egui/src/app.rs | 20 +-- crates/ui-egui/src/backstage.rs | 9 ++ i18n/ar-XB.tsv | 2 + i18n/ar.tsv | 2 + i18n/de.tsv | 2 + i18n/en-XA.tsv | 2 + i18n/en.tsv | 2 + i18n/es.tsv | 2 + i18n/fa.tsv | 2 + i18n/fr.tsv | 2 + i18n/he.tsv | 2 + i18n/hi.tsv | 2 + i18n/ja.tsv | 2 + i18n/ko.tsv | 2 + i18n/ru.tsv | 2 + i18n/tr.tsv | 2 + i18n/ur.tsv | 2 + i18n/zh.tsv | 2 + packaging/OSX/README.md | 2 +- packaging/installation artifacts.md | 9 +- packaging/windows/notecraft.wxs | 9 +- packaging/windows/package.ps1 | 4 +- 24 files changed, 234 insertions(+), 54 deletions(-) diff --git a/apps/notecraft/src/main.rs b/apps/notecraft/src/main.rs index 8bf1c627d..da32d4276 100644 --- a/apps/notecraft/src/main.rs +++ b/apps/notecraft/src/main.rs @@ -133,12 +133,33 @@ fn choose_demo_payload(candidates: &[PathBuf], fallback: &Path) -> PathBuf { candidates.iter().find(|path| path.is_dir()).cloned().unwrap_or_else(|| fallback.to_path_buf()) } -/// An explicit first-use request reopens setup with the user's saved preferences. -fn apply_first_use_flag(args: &[String], settings: &Settings) -> notecraft_store::Result<()> { - if args.iter().any(|arg| arg == "--first-use") { - settings.set("privacy_welcome_seen", "")?; - } - Ok(()) +/// The file the MSI leaves beside the app to ask for the first-use wizard once. +const INSTALL_MARKER: &str = "first-use.pending"; + +/// Acknowledge the installer marker in per-user settings before trying to remove it. A normal +/// user cannot necessarily delete files in the install directory. A retained marker must not +/// clear completed setup on every launch. A replaced marker can request setup again. +fn take_install_marker(install_dir: &std::path::Path, settings: &Settings) -> Result { + let marker = install_dir.join(INSTALL_MARKER); + let metadata = match std::fs::metadata(&marker) { + Ok(metadata) if metadata.is_file() => metadata, + Ok(_) => return Ok(false), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false), + Err(error) => return Err(format!("Could not read the first-use installation marker: {error}")), + }; + let modified = metadata.modified().map_err(|error| format!("Could not read the installation marker timestamp: {error}"))?; + let stamp = modified.duration_since(std::time::UNIX_EPOCH).map_err(|error| format!("Invalid installation marker timestamp: {error}"))?; + let identity = format!("{}:{}:{}", marker.display(), stamp.as_nanos(), metadata.len()); + if settings.get("first_use_install_marker").as_deref() == Some(identity.as_str()) { + return Ok(false); + } + if settings.welcome_notebook_update_prompt() { + settings.set("privacy_welcome_seen", "").map_err(|error| format!("Could not save first-use preferences: {error}"))?; + } + settings.set("first_use_install_marker", &identity).map_err(|error| format!("Could not acknowledge this installation: {error}"))?; + // Cleanup is optional once this user has acknowledged the marker. + let _ = std::fs::remove_file(&marker); + Ok(true) } fn flag_value(args: &[String], name: &str) -> Option { @@ -296,11 +317,18 @@ fn main() -> eframe::Result { let remembered = std::fs::canonicalize(&root).unwrap_or_else(|_| root.clone()); let _ = session.settings.set("last_notebooks_root", &remembered.to_string_lossy()); } + // Reset first-use flags so both current first-run prompts can be reviewed again. + if args.iter().any(|arg| arg == "--first-use") { + let _ = session.settings.set("privacy_welcome_seen", ""); + applog::info("First-use flag set: the first-use wizard will show"); + } let mut startup_alerts: Vec<(&str, String)> = Vec::new(); - if let Err(error) = apply_first_use_flag(&args, &session.settings) { - let message = format!("Could not reopen first-use setup: {error}"); - applog::line("ERROR", &message); - startup_alerts.push(("first-use", message)); + // The installer leaves a marker beside the app. Acknowledge it once for this user. + if let Some(dir) = executable.parent() + && let Err(error) = take_install_marker(dir, &session.settings) + { + applog::line("ERROR", &error); + startup_alerts.push(("install-marker", error)); } // NoteCraft draws its own title bar unless the settings say the system's is wanted. @@ -434,41 +462,133 @@ mod tests { use super::*; #[test] - fn normal_startup_preserves_completed_setup_and_saved_preferences() { - let temp = notecraft_store::testing::TempDir::new("welcome-upgrades"); - let path = temp.path().join("settings.toml"); - let settings = Settings::at(&path); + fn an_installer_marker_asks_for_the_first_use_wizard_once() { + let t = notecraft_store::testing::TempDir::new("install-marker"); + let settings = Settings::at(t.path().join("settings.toml")); + settings.set("privacy_welcome_seen", "true").expect("seen before install"); + std::fs::write(t.path().join(INSTALL_MARKER), "").expect("installer marker"); + + assert!(take_install_marker(t.path(), &settings).expect("acknowledge marker")); + assert_eq!(settings.get("privacy_welcome_seen").as_deref(), Some(""), "the wizard shows again"); + assert!(!t.path().join(INSTALL_MARKER).exists(), "the marker is used up"); + assert!(!take_install_marker(t.path(), &settings).expect("read marker"), "a second launch does not ask again"); + } + + #[test] + fn no_installer_marker_is_not_consumed() { + let t = notecraft_store::testing::TempDir::new("install-marker-absent"); + let settings = Settings::at(t.path().join("settings.toml")); + assert!(!take_install_marker(t.path(), &settings).expect("read marker")); + assert!(!t.path().join(INSTALL_MARKER).exists()); + } + + #[test] + fn welcome_update_opt_out_survives_new_install_markers() { + let t = notecraft_store::testing::TempDir::new("welcome-update-opt-out"); + let marker = t.path().join(INSTALL_MARKER); + let settings = Settings::at(t.path().join("settings.toml")); settings.set("privacy_welcome_seen", "true").expect("finish setup"); - settings.set("first_use_install_marker", "previous install").expect("save legacy installer state"); - settings.set("welcome_notebook_update_prompt", "true").expect("save legacy update choice"); - settings.set("telemetry_level", "warning").expect("save logging choice"); - settings.set_default_format(notecraft_model::PageFormat::Cmgfm).expect("save format choice"); - settings.set("theme_mode", "dark").expect("save theme"); + settings.set_welcome_notebook_update_prompt(false).expect("opt out"); + + let settings = Settings::at(settings.path()); + for contents in ["first upgrade", "next upgrade"] { + std::fs::write(&marker, contents).expect("installer marker"); + assert!(take_install_marker(t.path(), &settings).expect("acknowledge marker")); + assert!(!settings.first_use_pending(), "completed setup stays completed"); + } - let saved = std::fs::read(&path).expect("read settings"); - let reopened = Settings::at(&path); - apply_first_use_flag(&[], &reopened).expect("start after upgrade"); - assert!(!reopened.first_use_pending(), "completed setup stays completed after an upgrade"); - assert_eq!(std::fs::read(&path).expect("read settings"), saved, "startup preserves preferences"); + settings.set_welcome_notebook_update_prompt(true).expect("opt back in"); + std::fs::write(&marker, "another upgrade").expect("installer marker"); + assert!(take_install_marker(t.path(), &settings).expect("acknowledge marker")); + assert!(settings.first_use_pending(), "a later upgrade prompts after opting back in"); } #[test] - fn first_use_flag_reopens_setup_without_resetting_saved_preferences() { - let temp = notecraft_store::testing::TempDir::new("welcome-rerun"); - let path = temp.path().join("settings.toml"); - let settings = Settings::at(&path); + fn welcome_update_opt_out_keeps_pending_first_use() { + let t = notecraft_store::testing::TempDir::new("welcome-update-first-use"); + let settings = Settings::at(t.path().join("settings.toml")); + settings.set_welcome_notebook_update_prompt(false).expect("opt out"); + std::fs::write(t.path().join(INSTALL_MARKER), "").expect("installer marker"); + + assert!(take_install_marker(t.path(), &settings).expect("acknowledge marker")); + assert!(settings.first_use_pending(), "first-use setup is still pending"); + } + + #[test] + fn an_already_acknowledged_install_marker_does_not_reset_preferences() { + let t = notecraft_store::testing::TempDir::new("install-marker-retained"); + let marker = t.path().join(INSTALL_MARKER); + let settings = Settings::at(t.path().join("settings.toml")); + std::fs::write(&marker, "installed").expect("installer marker"); + let modified = std::fs::metadata(&marker).expect("metadata").modified().expect("modified"); + assert!(take_install_marker(t.path(), &settings).expect("acknowledge marker")); + settings.set("privacy_welcome_seen", "true").expect("finish setup"); + + // An installer can restore the same marker during repair. Its identity is unchanged. + std::fs::write(&marker, "installed").expect("restore installer marker"); + std::fs::File::options().write(true).open(&marker).expect("open marker").set_modified(modified).expect("restore timestamp"); + assert!(!take_install_marker(t.path(), &settings).expect("read marker"), "the same installation is acknowledged per user"); + assert_eq!(settings.get("privacy_welcome_seen").as_deref(), Some("true"), "completed preferences stay completed"); + } + + #[cfg(windows)] + #[test] + fn a_locked_install_marker_only_requests_setup_once() { + use std::os::windows::fs::OpenOptionsExt; + + let t = notecraft_store::testing::TempDir::new("install-marker-locked"); + let marker = t.path().join(INSTALL_MARKER); + let settings = Settings::at(t.path().join("settings.toml")); + std::fs::write(&marker, "installed").expect("installer marker"); + // Permit reads and writes but deny deletion, as an install directory can do. + let held = std::fs::OpenOptions::new().read(true).share_mode(3).open(&marker).expect("hold marker without delete sharing"); + let first = take_install_marker(t.path(), &settings).expect("acknowledge marker"); + assert!(marker.is_file(), "the real filesystem refuses marker cleanup"); settings.set("privacy_welcome_seen", "true").expect("finish setup"); - settings.set("telemetry_level", "warning").expect("save logging choice"); - settings.set_default_format(notecraft_model::PageFormat::Cmgfm).expect("save format choice"); - settings.set("theme_mode", "dark").expect("save theme"); + let second = take_install_marker(t.path(), &settings).expect("read marker"); + let seen = settings.get("privacy_welcome_seen"); + drop(held); + assert!(first, "first launch requests setup"); + assert!(!second, "a marker that cannot be deleted does not reset setup on every launch"); + assert_eq!(seen.as_deref(), Some("true")); + } - apply_first_use_flag(&["--first-use".to_string()], &settings).expect("request first-use setup"); + #[test] + fn a_new_install_marker_and_a_new_user_each_request_setup() { + let t = notecraft_store::testing::TempDir::new("install-marker-new-cycle"); + let marker = t.path().join(INSTALL_MARKER); + let first = Settings::at(t.path().join("first-user.toml")); + let second = Settings::at(t.path().join("second-user.toml")); + std::fs::write(&marker, "installed").expect("installer marker"); + let modified = std::fs::metadata(&marker).expect("metadata").modified().expect("modified"); + assert!(take_install_marker(t.path(), &first).expect("first user")); + first.set("privacy_welcome_seen", "true").expect("finish setup"); + std::fs::write(&marker, "installed").expect("restore marker"); + std::fs::File::options().write(true).open(&marker).expect("marker").set_modified(modified).expect("original timestamp"); + assert!(take_install_marker(t.path(), &second).expect("second user"), "acknowledgement is per user"); + assert_eq!(first.get("privacy_welcome_seen").as_deref(), Some("true")); + std::fs::write(&marker, "installed").expect("new installer marker"); + std::fs::File::options() + .write(true) + .open(&marker) + .expect("marker") + .set_modified(modified + std::time::Duration::from_secs(2)) + .expect("new installation timestamp"); + assert!(take_install_marker(t.path(), &first).expect("new installation")); + assert_eq!(first.get("privacy_welcome_seen").as_deref(), Some("")); + } - let reopened = Settings::at(&path); - assert!(reopened.first_use_pending(), "the wizard opens after an explicit request"); - assert_eq!(reopened.get("telemetry_level").as_deref(), Some("warning")); - assert_eq!(reopened.default_format(), Some(notecraft_model::PageFormat::Cmgfm)); - assert_eq!(reopened.get("theme_mode").as_deref(), Some("dark")); + #[test] + fn installer_marker_stays_when_settings_cannot_be_saved() { + let t = notecraft_store::testing::TempDir::new("install-marker-settings-failure"); + let marker = t.path().join(INSTALL_MARKER); + std::fs::write(&marker, "pending").expect("write marker"); + let settings_parent = t.path().join("settings-parent"); + std::fs::write(&settings_parent, "a file where the settings directory should be").expect("block settings directory"); + let settings = Settings::at(settings_parent.join("settings.toml")); + + assert!(take_install_marker(t.path(), &settings).is_err(), "a save failure is actionable at startup"); + assert!(marker.is_file(), "the next launch must retry the first-use wizard"); } #[test] diff --git a/crates/store/src/settings.rs b/crates/store/src/settings.rs index 8ae4e86e3..101fe96ae 100644 --- a/crates/store/src/settings.rs +++ b/crates/store/src/settings.rs @@ -159,6 +159,15 @@ impl Settings { self.get("privacy_welcome_seen").is_none_or(|value| value.trim().is_empty()) } + /// Whether to prompt again about the Welcome notebook after setup has been completed. + pub fn welcome_notebook_update_prompt(&self) -> bool { + self.get("welcome_notebook_update_prompt").is_none_or(|value| value.trim() != "false") + } + + pub fn set_welcome_notebook_update_prompt(&self, enabled: bool) -> Result<()> { + self.set("welcome_notebook_update_prompt", if enabled { "true" } else { "false" }) + } + /// Removes all saved application preferences. Missing settings are already at defaults. pub fn reset(&self) -> Result<()> { match std::fs::remove_file(&self.path) { diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 8c6971d1b..aad8eb0b1 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -7167,6 +7167,7 @@ impl NoteCraftApp { self.page_prefs, &quick_notes, self.update_check_off, + self.session.settings.welcome_notebook_update_prompt(), &update, &mut copy, &mut account, @@ -7263,6 +7264,14 @@ impl NoteCraftApp { Err(e) => self.complain(&crate::i18n::format_message_id("ui.update_check_not_saved", &[("error", &e.to_string())])), } } + backstage::Act::SetWelcomeNotebookUpdatePrompt(enabled) => { + if let Err(error) = self.session.settings.set_welcome_notebook_update_prompt(enabled) { + self.complain(&crate::i18n::format_message_id( + "ui.welcome_notebook_update_prompt_not_saved", + &[("error", &error.to_string())], + )); + } + } backstage::Act::ChooseNotebooksFolder => self.choose_default_notebooks_folder(), backstage::Act::UseDefaultNotebooksFolder => self.apply_notebooks_root_choice(None), backstage::Act::OpenTelemetryFolder(path) => { @@ -19874,19 +19883,14 @@ mod alert_tests { /// `--first-use` writes `privacy_welcome_seen = ""` and keeps every other setting. #[test] - fn first_use_flag_value_opens_setup_with_the_saved_choices() { + fn first_use_flag_value_shows_the_privacy_welcome_again() { let t = notecraft_store::testing::TempDir::new("privacy-first-use-flag"); let settings = notecraft_store::Settings::at(t.path().join("settings.toml")); settings.set("privacy_welcome_seen", "").expect("settings"); settings.set("theme_mode", "dark").expect("settings"); - settings.set("telemetry_level", "warning").expect("save logging choice"); - settings.set_default_format(PageFormat::Cmgfm).expect("save format choice"); let session = Session::new(&t.path().join("notebooks"), settings).expect("session"); let app = NoteCraftApp::new(session); - assert!( - matches!(app.dialog, Some(Dialog::FirstUseWizard { step: 0, ref level, format: PageFormat::Cmgfm, .. }) if level == "warning"), - "the reopened wizard starts with the saved logging level and format" - ); + assert!(matches!(app.dialog, Some(Dialog::FirstUseWizard { .. })), "an emptied key counts as not seen"); assert_eq!(app.session.settings.get("theme_mode").as_deref(), Some("dark"), "other settings are kept"); } @@ -19904,7 +19908,7 @@ mod alert_tests { let app1 = NoteCraftApp::new(session1); assert!(app1.dialog.is_none(), "Dialog should not show when privacy_welcome_seen is set"); - // Removing the settings file resets all preferences. + // Delete the settings file (simulates what run.cmd does with --first-use) let _ = std::fs::remove_file(&settings_path); // Create new settings from deleted file (triggers fresh initialization) diff --git a/crates/ui-egui/src/backstage.rs b/crates/ui-egui/src/backstage.rs index 24beeb0ac..359915f6d 100644 --- a/crates/ui-egui/src/backstage.rs +++ b/crates/ui-egui/src/backstage.rs @@ -101,6 +101,7 @@ pub enum Act { SetQuickNotesSection(Option), /// Don't check for updates at start up: the setting is saved, and on by default is off. SetUpdateCheckOff(bool), + SetWelcomeNotebookUpdatePrompt(bool), /// Pick the folder NoteCraft keeps new notebooks in, from the next start. ChooseNotebooksFolder, /// Go back to the default notebooks folder, from the next start. @@ -268,6 +269,7 @@ pub fn show( page_prefs: PagePrefs, quick_notes: &QuickNotes, update_check_off: bool, + welcome_notebook_update_prompt: bool, update: &crate::update::Status, copy: &mut CopyChoice, account: &mut AccountChoice, @@ -315,6 +317,7 @@ pub fn show( page_prefs, quick_notes, update_check_off, + welcome_notebook_update_prompt, update, t, &mut acts, @@ -849,6 +852,7 @@ fn options_page( page_prefs: PagePrefs, quick_notes: &QuickNotes, update_check_off: bool, + welcome_notebook_update_prompt: bool, update: &crate::update::Status, t: &Tokens, acts: &mut Vec, @@ -977,6 +981,10 @@ fn options_page( if ui.checkbox(&mut off, crate::tl_id!("ui.update_check_off_at_start")).changed() { acts.push(Act::SetUpdateCheckOff(off)); } + let mut prompt = welcome_notebook_update_prompt; + if ui.checkbox(&mut prompt, crate::tl_id!("ui.welcome_notebook_update_prompt")).changed() { + acts.push(Act::SetWelcomeNotebookUpdatePrompt(prompt)); + } ui.add_space(12.0); section_heading(ui, 3); ui.label(egui::RichText::new(crate::tl_id!("ui.privacy_is_our_top_priority_logs_and_telemetry_stay_17a34813d0")).strong().color(t.strong)); @@ -1086,6 +1094,7 @@ mod tests { PagePrefs::default(), &QuickNotes::default(), false, + true, &crate::update::Status::Idle, &mut CopyChoice::default(), &mut AccountChoice::default(), diff --git a/i18n/ar-XB.tsv b/i18n/ar-XB.tsv index 3b97c1db6..f7943f911 100644 --- a/i18n/ar-XB.tsv +++ b/i18n/ar-XB.tsv @@ -1022,6 +1022,8 @@ @id ui.check_for_updates_hint [[RLI]]$$$Checks GitHub for a newer release each time NoteCraft starts, and when you press Check for Updates. It downloads and installs only when you press Update and Restart.@@@[[PDI]] @id ui.update_check_off_at_start [[RLI]]$$$Don't check for updates at start up@@@[[PDI]] @id ui.update_check_not_saved [[RLI]]$$$The update setting could not be saved: {error}@@@[[PDI]] +@id ui.welcome_notebook_update_prompt [[RLI]]$$$Ask to update the Welcome notebook after upgrades@@@[[PDI]] +@id ui.welcome_notebook_update_prompt_not_saved [[RLI]]$$$The Welcome notebook update preference could not be saved: {error}@@@[[PDI]] @id ui.open_the_releases_page [[RLI]]$$$Open the releases page@@@[[PDI]] @id ui.update_checking [[RLI]]$$$Looking for a newer version…@@@[[PDI]] @id ui.update_up_to_date [[RLI]]$$$NoteCraft is up to date. The newest release is {version}.@@@[[PDI]] diff --git a/i18n/ar.tsv b/i18n/ar.tsv index f37f68bc0..4b3e4e656 100644 --- a/i18n/ar.tsv +++ b/i18n/ar.tsv @@ -800,6 +800,8 @@ @id ui.check_for_updates_hint يتحقق من GitHub بحثًا عن إصدار أحدث في كل مرة يبدأ فيها NoteCraft، وعند الضغط على التحقق من التحديثات. لا يُنزَّل التحديث ولا يُثبَّت إلا عند الضغط على تحديث وإعادة التشغيل. @id ui.update_check_off_at_start عدم التحقق من التحديثات عند بدء التشغيل @id ui.update_check_not_saved تعذّر حفظ إعداد التحديثات: {error} +@id ui.welcome_notebook_update_prompt السؤال عن تحديث دفتر الترحيب بعد ترقية التطبيق +@id ui.welcome_notebook_update_prompt_not_saved تعذّر حفظ تفضيل تحديث دفتر الترحيب: {error} @id ui.update_prompt.newest_available {app} {version} هو أحدث إصدار متاح. @id ui.update_prompt.by_developer بواسطة {developer} @id ui.update_prompt.version_change من v{from} إلى {to} diff --git a/i18n/de.tsv b/i18n/de.tsv index 8d9b54755..773a87047 100644 --- a/i18n/de.tsv +++ b/i18n/de.tsv @@ -797,6 +797,8 @@ @id ui.check_for_updates_hint Prüft bei jedem Start von NoteCraft und beim Drücken von Nach Updates suchen auf GitHub nach einer neueren Version. Herunterladen und Installieren erfolgen erst, wenn Sie Aktualisieren und neu starten drücken. @id ui.update_check_off_at_start Beim Start nicht nach Updates suchen @id ui.update_check_not_saved Die Update-Einstellung konnte nicht gespeichert werden: {error} +@id ui.welcome_notebook_update_prompt Nach Programmupdates nach dem Aktualisieren des Willkommensnotizbuchs fragen +@id ui.welcome_notebook_update_prompt_not_saved Die Einstellung für Updates des Willkommensnotizbuchs konnte nicht gespeichert werden: {error} @id ui.update_prompt.newest_available {app} {version} ist die neueste verfügbare Version. @id ui.update_prompt.by_developer von {developer} @id ui.update_prompt.version_change v{from} auf {to} diff --git a/i18n/en-XA.tsv b/i18n/en-XA.tsv index 2d4c4090c..ed7d6118e 100644 --- a/i18n/en-XA.tsv +++ b/i18n/en-XA.tsv @@ -1022,6 +1022,8 @@ @id ui.check_for_updates_hint $$$Checks GitHub for a newer release each time NoteCraft starts, and when you press Check for Updates. It downloads and installs only when you press Update and Restart.@@@ @id ui.update_check_off_at_start $$$Don't check for updates at start up@@@ @id ui.update_check_not_saved $$$The update setting could not be saved: {error}@@@ +@id ui.welcome_notebook_update_prompt $$$Ask to update the Welcome notebook after upgrades@@@ +@id ui.welcome_notebook_update_prompt_not_saved $$$The Welcome notebook update preference could not be saved: {error}@@@ @id ui.open_the_releases_page $$$Open the releases page@@@ @id ui.update_checking $$$Looking for a newer version…@@@ @id ui.update_up_to_date $$$NoteCraft is up to date. The newest release is {version}.@@@ diff --git a/i18n/en.tsv b/i18n/en.tsv index c9aa63c2b..74e059986 100644 --- a/i18n/en.tsv +++ b/i18n/en.tsv @@ -1022,6 +1022,8 @@ @id ui.check_for_updates_hint Checks GitHub for a newer release each time NoteCraft starts, and when you press Check for Updates. It downloads and installs only when you press Update and Restart. @id ui.update_check_off_at_start Don't check for updates at start up @id ui.update_check_not_saved The update setting could not be saved: {error} +@id ui.welcome_notebook_update_prompt Ask to update the Welcome notebook after upgrades +@id ui.welcome_notebook_update_prompt_not_saved The Welcome notebook update preference could not be saved: {error} @id ui.open_the_releases_page Open the releases page @id ui.update_checking Looking for a newer version… @id ui.update_up_to_date NoteCraft is up to date. The newest release is {version}. diff --git a/i18n/es.tsv b/i18n/es.tsv index 57c5c02f3..cbf06ed46 100644 --- a/i18n/es.tsv +++ b/i18n/es.tsv @@ -797,6 +797,8 @@ @id ui.check_for_updates_hint Consulta GitHub por una versión más reciente cada vez que se inicia NoteCraft y cuando pulsas Buscar actualizaciones. Solo se descarga e instala cuando pulsas Actualizar y reiniciar. @id ui.update_check_off_at_start No buscar actualizaciones al iniciar @id ui.update_check_not_saved No se pudo guardar el ajuste de actualizaciones: {error} +@id ui.welcome_notebook_update_prompt Preguntar si se actualiza el cuaderno de bienvenida tras actualizar la aplicación +@id ui.welcome_notebook_update_prompt_not_saved No se pudo guardar la preferencia de actualización del cuaderno de bienvenida: {error} @id ui.update_prompt.newest_available {app} {version} es la versión más reciente disponible. @id ui.update_prompt.by_developer por {developer} @id ui.update_prompt.version_change v{from} a {to} diff --git a/i18n/fa.tsv b/i18n/fa.tsv index 7e6513131..04d253663 100644 --- a/i18n/fa.tsv +++ b/i18n/fa.tsv @@ -797,6 +797,8 @@ @id ui.check_for_updates_hint هر بار که NoteCraft شروع می‌شود و هنگام فشردن بررسی به‌روزرسانی، GitHub را برای نسخه‌ی جدیدتر بررسی می‌کند. تنها پس از فشردن به‌روزرسانی و راه‌اندازی مجدد دانلود و نصب می‌شود. @id ui.update_check_off_at_start هنگام راه‌اندازی به‌روزرسانی را بررسی نکن @id ui.update_check_not_saved تنظیم به‌روزرسانی ذخیره نشد: {error} +@id ui.welcome_notebook_update_prompt پس از ارتقای برنامه، دربارهٔ به‌روزرسانی دفترچه خوش‌آمدگویی سؤال شود +@id ui.welcome_notebook_update_prompt_not_saved ترجیح به‌روزرسانی دفترچه خوش‌آمدگویی ذخیره نشد: {error} @id ui.update_prompt.newest_available {app} {version} جدیدترین نسخه‌ی موجود است. @id ui.update_prompt.by_developer توسط {developer} @id ui.update_prompt.version_change از v{from} به {to} diff --git a/i18n/fr.tsv b/i18n/fr.tsv index d84d7020a..c30ffa190 100644 --- a/i18n/fr.tsv +++ b/i18n/fr.tsv @@ -797,6 +797,8 @@ @id ui.check_for_updates_hint Vérifie GitHub pour une version plus récente à chaque démarrage de NoteCraft, et lorsque vous appuyez sur Rechercher des mises à jour. Elle ne se télécharge et ne s'installe qu'après que vous appuyez sur Mettre à jour et redémarrer. @id ui.update_check_off_at_start Ne pas rechercher les mises à jour au démarrage @id ui.update_check_not_saved Le réglage de mise à jour n'a pas pu être enregistré : {error} +@id ui.welcome_notebook_update_prompt Proposer de mettre à jour le carnet de bienvenue après une mise à jour de l'application +@id ui.welcome_notebook_update_prompt_not_saved Impossible d’enregistrer la préférence de mise à jour du carnet de bienvenue : {error} @id ui.update_prompt.newest_available {app} {version} est la version la plus récente disponible. @id ui.update_prompt.by_developer par {developer} @id ui.update_prompt.version_change v{from} vers {to} diff --git a/i18n/he.tsv b/i18n/he.tsv index 0bbdfa1b3..557599d73 100644 --- a/i18n/he.tsv +++ b/i18n/he.tsv @@ -797,6 +797,8 @@ @id ui.check_for_updates_hint בודק ב-GitHub אם יש גרסה חדשה בכל הפעלה של NoteCraft, וכשלוחצים על בדיקת עדכונים. ההורדה וההתקנה מתבצעות רק אחרי לחיצה על עדכון והפעלה מחדש. @id ui.update_check_off_at_start לא לבדוק עדכונים בהפעלה @id ui.update_check_not_saved לא ניתן לשמור את הגדרת העדכונים: {error} +@id ui.welcome_notebook_update_prompt לשאול אם לעדכן את מחברת הברוכים הבאים לאחר שדרוג היישום +@id ui.welcome_notebook_update_prompt_not_saved לא ניתן לשמור את ההעדפה לעדכון מחברת הברוכים הבאים: {error} @id ui.update_prompt.newest_available {app} {version} היא הגרסה העדכנית ביותר הזמינה. @id ui.update_prompt.by_developer מאת {developer} @id ui.update_prompt.version_change מ-v{from} ל-{to} diff --git a/i18n/hi.tsv b/i18n/hi.tsv index 689327058..a40ffa28e 100644 --- a/i18n/hi.tsv +++ b/i18n/hi.tsv @@ -797,6 +797,8 @@ @id ui.check_for_updates_hint NoteCraft शुरू होने पर और जब आप अपडेट जांचें दबाते हैं, GitHub पर नई रिलीज़ की जांच होती है। डाउनलोड और इंस्टॉल तभी होता है जब आप अपडेट करें और पुनः आरंभ करें दबाते हैं। @id ui.update_check_off_at_start शुरू होने पर अपडेट न जांचें @id ui.update_check_not_saved अपडेट सेटिंग सहेजी नहीं जा सकी: {error} +@id ui.welcome_notebook_update_prompt ऐप अपग्रेड के बाद स्वागत नोटबुक को अपडेट करने के लिए पूछें +@id ui.welcome_notebook_update_prompt_not_saved स्वागत नोटबुक अपडेट करने की प्राथमिकता सहेजी नहीं जा सकी: {error} @id ui.update_prompt.newest_available {app} {version} उपलब्ध सबसे नया संस्करण है। @id ui.update_prompt.by_developer {developer} द्वारा @id ui.update_prompt.version_change v{from} से {to} diff --git a/i18n/ja.tsv b/i18n/ja.tsv index 8b2111102..f1f512866 100644 --- a/i18n/ja.tsv +++ b/i18n/ja.tsv @@ -797,6 +797,8 @@ @id ui.check_for_updates_hint NoteCraft の起動時と「アップデートを確認」を押したときに、GitHub で新しいリリースを確認します。「アップデートして再起動」を押すまでダウンロードもインストールもしません。 @id ui.update_check_off_at_start 起動時にアップデートを確認しない @id ui.update_check_not_saved アップデートの設定を保存できませんでした: {error} +@id ui.welcome_notebook_update_prompt アプリの更新後にようこそノートブックの更新を確認する +@id ui.welcome_notebook_update_prompt_not_saved ようこそノートブックの更新設定を保存できませんでした: {error} @id ui.update_prompt.newest_available {app} {version} は利用可能な最新バージョンです。 @id ui.update_prompt.by_developer {developer} 提供 @id ui.update_prompt.version_change v{from} から {to} diff --git a/i18n/ko.tsv b/i18n/ko.tsv index 72a46c4c9..ea5ebddff 100644 --- a/i18n/ko.tsv +++ b/i18n/ko.tsv @@ -797,6 +797,8 @@ @id ui.check_for_updates_hint NoteCraft를 시작할 때마다, 그리고 업데이트 확인을 누를 때 GitHub에서 새 릴리스를 확인합니다. 업데이트 및 다시 시작을 누를 때만 다운로드하고 설치합니다. @id ui.update_check_off_at_start 시작할 때 업데이트를 확인하지 않음 @id ui.update_check_not_saved 업데이트 설정을 저장할 수 없습니다: {error} +@id ui.welcome_notebook_update_prompt 앱 업그레이드 후 환영 노트북을 업데이트할지 묻기 +@id ui.welcome_notebook_update_prompt_not_saved 환영 노트북 업데이트 설정을 저장할 수 없습니다: {error} @id ui.update_prompt.newest_available {app} {version}은(는) 사용 가능한 최신 버전입니다. @id ui.update_prompt.by_developer {developer} 제작 @id ui.update_prompt.version_change v{from} → {to} diff --git a/i18n/ru.tsv b/i18n/ru.tsv index 6207eede2..b30dffe3b 100644 --- a/i18n/ru.tsv +++ b/i18n/ru.tsv @@ -797,6 +797,8 @@ @id ui.check_for_updates_hint Проверяет GitHub на более новую версию при каждом запуске NoteCraft и при нажатии «Проверить обновления». Загрузка и установка начинаются только после нажатия «Обновить и перезапустить». @id ui.update_check_off_at_start Не проверять обновления при запуске @id ui.update_check_not_saved Не удалось сохранить настройку обновлений: {error} +@id ui.welcome_notebook_update_prompt Предлагать обновить приветственный блокнот после обновления приложения +@id ui.welcome_notebook_update_prompt_not_saved Не удалось сохранить настройку обновления приветственного блокнота: {error} @id ui.update_prompt.newest_available {app} {version} — самая новая доступная версия. @id ui.update_prompt.by_developer от {developer} @id ui.update_prompt.version_change с v{from} на {to} diff --git a/i18n/tr.tsv b/i18n/tr.tsv index e3de02bb5..cbaae8c8d 100644 --- a/i18n/tr.tsv +++ b/i18n/tr.tsv @@ -947,6 +947,8 @@ @id ui.check_for_updates_hint NoteCraft her başladığında ve Güncellemeleri denetle düğmesine bastığınızda GitHub'da daha yeni bir sürümü denetler. Yalnızca Güncelle ve yeniden başlat düğmesine basınca indirir ve kurar. @id ui.update_check_off_at_start Başlangıçta güncellemeleri denetleme @id ui.update_check_not_saved Güncelleme ayarı kaydedilemedi: {error} +@id ui.welcome_notebook_update_prompt Uygulama yükseltildikten sonra Hoş Geldiniz not defterini güncellemeyi sor +@id ui.welcome_notebook_update_prompt_not_saved Hoş Geldiniz not defterini güncelleme tercihi kaydedilemedi: {error} @id ui.update_prompt.newest_available {app} {version} mevcut en yeni sürüm. @id ui.open_the_releases_page Sürümler sayfasını aç @id ui.update_checking Daha yeni bir sürüm aranıyor… diff --git a/i18n/ur.tsv b/i18n/ur.tsv index 9beca8349..a3687c6d0 100644 --- a/i18n/ur.tsv +++ b/i18n/ur.tsv @@ -797,6 +797,8 @@ @id ui.check_for_updates_hint NoteCraft کے ہر آغاز پر، اور جب آپ اپ ڈیٹس چیک کریں دبائیں تو GitHub پر نیا ریلیز دیکھا جاتا ہے۔ ڈاؤن لوڈ اور انسٹال صرف اس وقت ہوتا ہے جب آپ اپ ڈیٹ اور دوبارہ شروع کریں دبائیں۔ @id ui.update_check_off_at_start شروع پر اپ ڈیٹس نہ چیک کریں @id ui.update_check_not_saved اپ ڈیٹ کی ترتیب محفوظ نہیں ہو سکی: {error} +@id ui.welcome_notebook_update_prompt ایپ اپ گریڈ ہونے پر پوچھیں کہ خوش آمدید نوٹ بک اپ ڈیٹ کرنی ہے یا نہیں +@id ui.welcome_notebook_update_prompt_not_saved خوش آمدید نوٹ بک کی اپ ڈیٹ کی ترجیح محفوظ نہیں ہو سکی: {error} @id ui.update_prompt.newest_available {app} {version} دستیاب سب سے نیا ورژن ہے۔ @id ui.update_prompt.by_developer {developer} کی جانب سے @id ui.update_prompt.version_change v{from} سے {to} diff --git a/i18n/zh.tsv b/i18n/zh.tsv index 31db65944..45ff4236a 100644 --- a/i18n/zh.tsv +++ b/i18n/zh.tsv @@ -800,6 +800,8 @@ @id ui.check_for_updates_hint 每次启动 NoteCraft 时,以及按下“检查更新”时,都会检查 GitHub 上是否有更新的版本。只有按下“更新并重启”后,才会下载并安装。 @id ui.update_check_off_at_start 启动时不检查更新 @id ui.update_check_not_saved 无法保存更新设置:{error} +@id ui.welcome_notebook_update_prompt 升级应用后询问是否更新欢迎笔记本 +@id ui.welcome_notebook_update_prompt_not_saved 无法保存欢迎笔记本更新偏好:{error} @id ui.update_prompt.newest_available {app} {version} 是目前可用的最新版本。 @id ui.update_prompt.by_developer 由 {developer} 提供 @id ui.update_prompt.version_change v{from} 到 {to} diff --git a/packaging/OSX/README.md b/packaging/OSX/README.md index c52f5fb61..6114bccac 100644 --- a/packaging/OSX/README.md +++ b/packaging/OSX/README.md @@ -20,7 +20,7 @@ bash packaging/OSX/test-provenance.sh ``` The DMG contains `NoteCraft.app`, an Applications link and a read-me file at its root. Drag the -app to Applications and open it. During first-use setup, NoteCraft asks whether to add +app to Applications and open it. On first launch of each version, NoteCraft asks whether to add the bundled Welcome notebook to the user's notebook folder. The default `--arch universal` builds both Apple targets and combines the GUI and CLI with diff --git a/packaging/installation artifacts.md b/packaging/installation artifacts.md index 19859fe32..bd6384bc5 100644 --- a/packaging/installation artifacts.md +++ b/packaging/installation artifacts.md @@ -2,7 +2,7 @@ Status: product contract updated by the owner on 2026-11-07. This is the single authority for installation artifact responsibilities and the User Assistance demo notebook. The application -bundles the generated notebook and asks during first-use setup before creating or replacing the +bundles the generated notebook and asks once per app version before creating or replacing the per-user Welcome notebook. ## Separate installation artifacts @@ -34,9 +34,8 @@ The running app owns the per-user copy after the user confirms: are reset. It is one dialog with five pages and Next at the bottom right: the welcome page with the brand banner; the local logging level; the page format, HTML or CommonMark + GFM, saved as the default; whether to create the demo notebook in that format; and a thank-you page with Finish. -- Upgrades preserve the first-use completion state and saved preferences. Run NoteCraft with - `--first-use` to reopen the wizard with the saved settings. The package ships the generated - editions as the wizard's source. +- The wizard does not reopen for later app versions. Installation copies nothing into the notebooks + folder; the package ships the generated editions only as the wizard's source. - On Yes on the demo page, create or completely replace only `welcome-to-notecraft` from the bundled edition for the chosen format when Finish is pressed. The edition's notebook folder becomes the managed notebook, so the notebook list finds it, and the Welcome page opens. The other format is @@ -50,7 +49,7 @@ The running app owns the per-user copy after the user confirms: Desktop apps copy the chosen edition from the installed package or app bundle into the selected user notebook root only after Yes in step 3. The desktop setup launcher installs nothing; it starts NoteCraft. Android and the browser have separate startup paths; each must -ask for confirmation before replacing a user's Welcome notebook. Android +apply the same per-version confirmation before replacing a user's Welcome notebook. Android app-specific storage follows Android's normal uninstall lifecycle. ## Platform installation contract diff --git a/packaging/windows/notecraft.wxs b/packaging/windows/notecraft.wxs index 3b3d868ab..cbfc04d71 100644 --- a/packaging/windows/notecraft.wxs +++ b/packaging/windows/notecraft.wxs @@ -10,8 +10,9 @@ Per-machine install into Program Files with a Start Menu shortcut. The installer shows the standard WiX dialogs: welcome and licence, progress, and a finish page. - The app carries both generated Welcome notebook formats for the first-use wizard. - Per-user settings record whether the wizard has been completed across upgrades. + The app carries both generated Welcome notebook formats and asks once per app version before + creating or replacing its dedicated per-user Welcome notebook. Other notebook folders remain + unchanged. UpgradeCode and the component GUIDs below belong to NoteCraft alone. Never change the UpgradeCode after the first public release: Windows Installer would stop treating a new @@ -52,6 +53,7 @@ Impersonate="yes" Return="ignore" /> + @@ -82,6 +84,9 @@ + + + diff --git a/packaging/windows/package.ps1 b/packaging/windows/package.ps1 index 1c6ffe94e..a60df3219 100644 --- a/packaging/windows/package.ps1 +++ b/packaging/windows/package.ps1 @@ -116,8 +116,10 @@ $VoiceWork = Join-Path $TargetDir 'transcription-package' Invoke-Native 'stage bundled offline transcription' { cmake "-DBIN_DIR=$VoiceStage" "-DMODEL_DIR=$VoiceStage" "-DWORK_DIR=$VoiceWork" -P (Join-Path $Root 'packaging\stage-transcription.cmake') } +# The installer leaves this marker beside the app. The first launch after installing shows the first-use wizard again. +[IO.File]::WriteAllText((Join-Path $Stage 'first-use.pending'), '') - # Bundle both generated formats for the first-use wizard. + # The app copies both generated formats into the user's notebooks folder at startup. $DemoSource = Join-Path $Root 'docs\demo\DemoNotebook' foreach ($format in 'html', 'cmgfm') { $FormatRoot = Join-Path $DemoSource $format From 9abfefb11e66766aaedb7962f223e7c6540276f9 Mon Sep 17 00:00:00 2001 From: alientechsw <43017062+alientechsw@users.noreply.github.com> Date: Sat, 5 Dec 2026 12:29:40 -0800 Subject: [PATCH 2/7] revert: undo the revert of 45c9d78 --- apps/notecraft/src/main.rs | 194 ++++++---------------------- crates/store/src/settings.rs | 9 -- crates/ui-egui/src/app.rs | 20 ++- crates/ui-egui/src/backstage.rs | 9 -- i18n/ar-XB.tsv | 2 - i18n/ar.tsv | 2 - i18n/de.tsv | 2 - i18n/en-XA.tsv | 2 - i18n/en.tsv | 2 - i18n/es.tsv | 2 - i18n/fa.tsv | 2 - i18n/fr.tsv | 2 - i18n/he.tsv | 2 - i18n/hi.tsv | 2 - i18n/ja.tsv | 2 - i18n/ko.tsv | 2 - i18n/ru.tsv | 2 - i18n/tr.tsv | 2 - i18n/ur.tsv | 2 - i18n/zh.tsv | 2 - packaging/OSX/README.md | 2 +- packaging/installation artifacts.md | 9 +- packaging/windows/notecraft.wxs | 9 +- packaging/windows/package.ps1 | 4 +- 24 files changed, 54 insertions(+), 234 deletions(-) diff --git a/apps/notecraft/src/main.rs b/apps/notecraft/src/main.rs index da32d4276..8bf1c627d 100644 --- a/apps/notecraft/src/main.rs +++ b/apps/notecraft/src/main.rs @@ -133,33 +133,12 @@ fn choose_demo_payload(candidates: &[PathBuf], fallback: &Path) -> PathBuf { candidates.iter().find(|path| path.is_dir()).cloned().unwrap_or_else(|| fallback.to_path_buf()) } -/// The file the MSI leaves beside the app to ask for the first-use wizard once. -const INSTALL_MARKER: &str = "first-use.pending"; - -/// Acknowledge the installer marker in per-user settings before trying to remove it. A normal -/// user cannot necessarily delete files in the install directory. A retained marker must not -/// clear completed setup on every launch. A replaced marker can request setup again. -fn take_install_marker(install_dir: &std::path::Path, settings: &Settings) -> Result { - let marker = install_dir.join(INSTALL_MARKER); - let metadata = match std::fs::metadata(&marker) { - Ok(metadata) if metadata.is_file() => metadata, - Ok(_) => return Ok(false), - Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false), - Err(error) => return Err(format!("Could not read the first-use installation marker: {error}")), - }; - let modified = metadata.modified().map_err(|error| format!("Could not read the installation marker timestamp: {error}"))?; - let stamp = modified.duration_since(std::time::UNIX_EPOCH).map_err(|error| format!("Invalid installation marker timestamp: {error}"))?; - let identity = format!("{}:{}:{}", marker.display(), stamp.as_nanos(), metadata.len()); - if settings.get("first_use_install_marker").as_deref() == Some(identity.as_str()) { - return Ok(false); - } - if settings.welcome_notebook_update_prompt() { - settings.set("privacy_welcome_seen", "").map_err(|error| format!("Could not save first-use preferences: {error}"))?; - } - settings.set("first_use_install_marker", &identity).map_err(|error| format!("Could not acknowledge this installation: {error}"))?; - // Cleanup is optional once this user has acknowledged the marker. - let _ = std::fs::remove_file(&marker); - Ok(true) +/// An explicit first-use request reopens setup with the user's saved preferences. +fn apply_first_use_flag(args: &[String], settings: &Settings) -> notecraft_store::Result<()> { + if args.iter().any(|arg| arg == "--first-use") { + settings.set("privacy_welcome_seen", "")?; + } + Ok(()) } fn flag_value(args: &[String], name: &str) -> Option { @@ -317,18 +296,11 @@ fn main() -> eframe::Result { let remembered = std::fs::canonicalize(&root).unwrap_or_else(|_| root.clone()); let _ = session.settings.set("last_notebooks_root", &remembered.to_string_lossy()); } - // Reset first-use flags so both current first-run prompts can be reviewed again. - if args.iter().any(|arg| arg == "--first-use") { - let _ = session.settings.set("privacy_welcome_seen", ""); - applog::info("First-use flag set: the first-use wizard will show"); - } let mut startup_alerts: Vec<(&str, String)> = Vec::new(); - // The installer leaves a marker beside the app. Acknowledge it once for this user. - if let Some(dir) = executable.parent() - && let Err(error) = take_install_marker(dir, &session.settings) - { - applog::line("ERROR", &error); - startup_alerts.push(("install-marker", error)); + if let Err(error) = apply_first_use_flag(&args, &session.settings) { + let message = format!("Could not reopen first-use setup: {error}"); + applog::line("ERROR", &message); + startup_alerts.push(("first-use", message)); } // NoteCraft draws its own title bar unless the settings say the system's is wanted. @@ -462,133 +434,41 @@ mod tests { use super::*; #[test] - fn an_installer_marker_asks_for_the_first_use_wizard_once() { - let t = notecraft_store::testing::TempDir::new("install-marker"); - let settings = Settings::at(t.path().join("settings.toml")); - settings.set("privacy_welcome_seen", "true").expect("seen before install"); - std::fs::write(t.path().join(INSTALL_MARKER), "").expect("installer marker"); - - assert!(take_install_marker(t.path(), &settings).expect("acknowledge marker")); - assert_eq!(settings.get("privacy_welcome_seen").as_deref(), Some(""), "the wizard shows again"); - assert!(!t.path().join(INSTALL_MARKER).exists(), "the marker is used up"); - assert!(!take_install_marker(t.path(), &settings).expect("read marker"), "a second launch does not ask again"); - } - - #[test] - fn no_installer_marker_is_not_consumed() { - let t = notecraft_store::testing::TempDir::new("install-marker-absent"); - let settings = Settings::at(t.path().join("settings.toml")); - assert!(!take_install_marker(t.path(), &settings).expect("read marker")); - assert!(!t.path().join(INSTALL_MARKER).exists()); - } - - #[test] - fn welcome_update_opt_out_survives_new_install_markers() { - let t = notecraft_store::testing::TempDir::new("welcome-update-opt-out"); - let marker = t.path().join(INSTALL_MARKER); - let settings = Settings::at(t.path().join("settings.toml")); + fn normal_startup_preserves_completed_setup_and_saved_preferences() { + let temp = notecraft_store::testing::TempDir::new("welcome-upgrades"); + let path = temp.path().join("settings.toml"); + let settings = Settings::at(&path); settings.set("privacy_welcome_seen", "true").expect("finish setup"); - settings.set_welcome_notebook_update_prompt(false).expect("opt out"); - - let settings = Settings::at(settings.path()); - for contents in ["first upgrade", "next upgrade"] { - std::fs::write(&marker, contents).expect("installer marker"); - assert!(take_install_marker(t.path(), &settings).expect("acknowledge marker")); - assert!(!settings.first_use_pending(), "completed setup stays completed"); - } + settings.set("first_use_install_marker", "previous install").expect("save legacy installer state"); + settings.set("welcome_notebook_update_prompt", "true").expect("save legacy update choice"); + settings.set("telemetry_level", "warning").expect("save logging choice"); + settings.set_default_format(notecraft_model::PageFormat::Cmgfm).expect("save format choice"); + settings.set("theme_mode", "dark").expect("save theme"); - settings.set_welcome_notebook_update_prompt(true).expect("opt back in"); - std::fs::write(&marker, "another upgrade").expect("installer marker"); - assert!(take_install_marker(t.path(), &settings).expect("acknowledge marker")); - assert!(settings.first_use_pending(), "a later upgrade prompts after opting back in"); + let saved = std::fs::read(&path).expect("read settings"); + let reopened = Settings::at(&path); + apply_first_use_flag(&[], &reopened).expect("start after upgrade"); + assert!(!reopened.first_use_pending(), "completed setup stays completed after an upgrade"); + assert_eq!(std::fs::read(&path).expect("read settings"), saved, "startup preserves preferences"); } #[test] - fn welcome_update_opt_out_keeps_pending_first_use() { - let t = notecraft_store::testing::TempDir::new("welcome-update-first-use"); - let settings = Settings::at(t.path().join("settings.toml")); - settings.set_welcome_notebook_update_prompt(false).expect("opt out"); - std::fs::write(t.path().join(INSTALL_MARKER), "").expect("installer marker"); - - assert!(take_install_marker(t.path(), &settings).expect("acknowledge marker")); - assert!(settings.first_use_pending(), "first-use setup is still pending"); - } - - #[test] - fn an_already_acknowledged_install_marker_does_not_reset_preferences() { - let t = notecraft_store::testing::TempDir::new("install-marker-retained"); - let marker = t.path().join(INSTALL_MARKER); - let settings = Settings::at(t.path().join("settings.toml")); - std::fs::write(&marker, "installed").expect("installer marker"); - let modified = std::fs::metadata(&marker).expect("metadata").modified().expect("modified"); - assert!(take_install_marker(t.path(), &settings).expect("acknowledge marker")); - settings.set("privacy_welcome_seen", "true").expect("finish setup"); - - // An installer can restore the same marker during repair. Its identity is unchanged. - std::fs::write(&marker, "installed").expect("restore installer marker"); - std::fs::File::options().write(true).open(&marker).expect("open marker").set_modified(modified).expect("restore timestamp"); - assert!(!take_install_marker(t.path(), &settings).expect("read marker"), "the same installation is acknowledged per user"); - assert_eq!(settings.get("privacy_welcome_seen").as_deref(), Some("true"), "completed preferences stay completed"); - } - - #[cfg(windows)] - #[test] - fn a_locked_install_marker_only_requests_setup_once() { - use std::os::windows::fs::OpenOptionsExt; - - let t = notecraft_store::testing::TempDir::new("install-marker-locked"); - let marker = t.path().join(INSTALL_MARKER); - let settings = Settings::at(t.path().join("settings.toml")); - std::fs::write(&marker, "installed").expect("installer marker"); - // Permit reads and writes but deny deletion, as an install directory can do. - let held = std::fs::OpenOptions::new().read(true).share_mode(3).open(&marker).expect("hold marker without delete sharing"); - let first = take_install_marker(t.path(), &settings).expect("acknowledge marker"); - assert!(marker.is_file(), "the real filesystem refuses marker cleanup"); + fn first_use_flag_reopens_setup_without_resetting_saved_preferences() { + let temp = notecraft_store::testing::TempDir::new("welcome-rerun"); + let path = temp.path().join("settings.toml"); + let settings = Settings::at(&path); settings.set("privacy_welcome_seen", "true").expect("finish setup"); - let second = take_install_marker(t.path(), &settings).expect("read marker"); - let seen = settings.get("privacy_welcome_seen"); - drop(held); - assert!(first, "first launch requests setup"); - assert!(!second, "a marker that cannot be deleted does not reset setup on every launch"); - assert_eq!(seen.as_deref(), Some("true")); - } + settings.set("telemetry_level", "warning").expect("save logging choice"); + settings.set_default_format(notecraft_model::PageFormat::Cmgfm).expect("save format choice"); + settings.set("theme_mode", "dark").expect("save theme"); - #[test] - fn a_new_install_marker_and_a_new_user_each_request_setup() { - let t = notecraft_store::testing::TempDir::new("install-marker-new-cycle"); - let marker = t.path().join(INSTALL_MARKER); - let first = Settings::at(t.path().join("first-user.toml")); - let second = Settings::at(t.path().join("second-user.toml")); - std::fs::write(&marker, "installed").expect("installer marker"); - let modified = std::fs::metadata(&marker).expect("metadata").modified().expect("modified"); - assert!(take_install_marker(t.path(), &first).expect("first user")); - first.set("privacy_welcome_seen", "true").expect("finish setup"); - std::fs::write(&marker, "installed").expect("restore marker"); - std::fs::File::options().write(true).open(&marker).expect("marker").set_modified(modified).expect("original timestamp"); - assert!(take_install_marker(t.path(), &second).expect("second user"), "acknowledgement is per user"); - assert_eq!(first.get("privacy_welcome_seen").as_deref(), Some("true")); - std::fs::write(&marker, "installed").expect("new installer marker"); - std::fs::File::options() - .write(true) - .open(&marker) - .expect("marker") - .set_modified(modified + std::time::Duration::from_secs(2)) - .expect("new installation timestamp"); - assert!(take_install_marker(t.path(), &first).expect("new installation")); - assert_eq!(first.get("privacy_welcome_seen").as_deref(), Some("")); - } + apply_first_use_flag(&["--first-use".to_string()], &settings).expect("request first-use setup"); - #[test] - fn installer_marker_stays_when_settings_cannot_be_saved() { - let t = notecraft_store::testing::TempDir::new("install-marker-settings-failure"); - let marker = t.path().join(INSTALL_MARKER); - std::fs::write(&marker, "pending").expect("write marker"); - let settings_parent = t.path().join("settings-parent"); - std::fs::write(&settings_parent, "a file where the settings directory should be").expect("block settings directory"); - let settings = Settings::at(settings_parent.join("settings.toml")); - - assert!(take_install_marker(t.path(), &settings).is_err(), "a save failure is actionable at startup"); - assert!(marker.is_file(), "the next launch must retry the first-use wizard"); + let reopened = Settings::at(&path); + assert!(reopened.first_use_pending(), "the wizard opens after an explicit request"); + assert_eq!(reopened.get("telemetry_level").as_deref(), Some("warning")); + assert_eq!(reopened.default_format(), Some(notecraft_model::PageFormat::Cmgfm)); + assert_eq!(reopened.get("theme_mode").as_deref(), Some("dark")); } #[test] diff --git a/crates/store/src/settings.rs b/crates/store/src/settings.rs index 101fe96ae..8ae4e86e3 100644 --- a/crates/store/src/settings.rs +++ b/crates/store/src/settings.rs @@ -159,15 +159,6 @@ impl Settings { self.get("privacy_welcome_seen").is_none_or(|value| value.trim().is_empty()) } - /// Whether to prompt again about the Welcome notebook after setup has been completed. - pub fn welcome_notebook_update_prompt(&self) -> bool { - self.get("welcome_notebook_update_prompt").is_none_or(|value| value.trim() != "false") - } - - pub fn set_welcome_notebook_update_prompt(&self, enabled: bool) -> Result<()> { - self.set("welcome_notebook_update_prompt", if enabled { "true" } else { "false" }) - } - /// Removes all saved application preferences. Missing settings are already at defaults. pub fn reset(&self) -> Result<()> { match std::fs::remove_file(&self.path) { diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index aad8eb0b1..8c6971d1b 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -7167,7 +7167,6 @@ impl NoteCraftApp { self.page_prefs, &quick_notes, self.update_check_off, - self.session.settings.welcome_notebook_update_prompt(), &update, &mut copy, &mut account, @@ -7264,14 +7263,6 @@ impl NoteCraftApp { Err(e) => self.complain(&crate::i18n::format_message_id("ui.update_check_not_saved", &[("error", &e.to_string())])), } } - backstage::Act::SetWelcomeNotebookUpdatePrompt(enabled) => { - if let Err(error) = self.session.settings.set_welcome_notebook_update_prompt(enabled) { - self.complain(&crate::i18n::format_message_id( - "ui.welcome_notebook_update_prompt_not_saved", - &[("error", &error.to_string())], - )); - } - } backstage::Act::ChooseNotebooksFolder => self.choose_default_notebooks_folder(), backstage::Act::UseDefaultNotebooksFolder => self.apply_notebooks_root_choice(None), backstage::Act::OpenTelemetryFolder(path) => { @@ -19883,14 +19874,19 @@ mod alert_tests { /// `--first-use` writes `privacy_welcome_seen = ""` and keeps every other setting. #[test] - fn first_use_flag_value_shows_the_privacy_welcome_again() { + fn first_use_flag_value_opens_setup_with_the_saved_choices() { let t = notecraft_store::testing::TempDir::new("privacy-first-use-flag"); let settings = notecraft_store::Settings::at(t.path().join("settings.toml")); settings.set("privacy_welcome_seen", "").expect("settings"); settings.set("theme_mode", "dark").expect("settings"); + settings.set("telemetry_level", "warning").expect("save logging choice"); + settings.set_default_format(PageFormat::Cmgfm).expect("save format choice"); let session = Session::new(&t.path().join("notebooks"), settings).expect("session"); let app = NoteCraftApp::new(session); - assert!(matches!(app.dialog, Some(Dialog::FirstUseWizard { .. })), "an emptied key counts as not seen"); + assert!( + matches!(app.dialog, Some(Dialog::FirstUseWizard { step: 0, ref level, format: PageFormat::Cmgfm, .. }) if level == "warning"), + "the reopened wizard starts with the saved logging level and format" + ); assert_eq!(app.session.settings.get("theme_mode").as_deref(), Some("dark"), "other settings are kept"); } @@ -19908,7 +19904,7 @@ mod alert_tests { let app1 = NoteCraftApp::new(session1); assert!(app1.dialog.is_none(), "Dialog should not show when privacy_welcome_seen is set"); - // Delete the settings file (simulates what run.cmd does with --first-use) + // Removing the settings file resets all preferences. let _ = std::fs::remove_file(&settings_path); // Create new settings from deleted file (triggers fresh initialization) diff --git a/crates/ui-egui/src/backstage.rs b/crates/ui-egui/src/backstage.rs index 359915f6d..24beeb0ac 100644 --- a/crates/ui-egui/src/backstage.rs +++ b/crates/ui-egui/src/backstage.rs @@ -101,7 +101,6 @@ pub enum Act { SetQuickNotesSection(Option), /// Don't check for updates at start up: the setting is saved, and on by default is off. SetUpdateCheckOff(bool), - SetWelcomeNotebookUpdatePrompt(bool), /// Pick the folder NoteCraft keeps new notebooks in, from the next start. ChooseNotebooksFolder, /// Go back to the default notebooks folder, from the next start. @@ -269,7 +268,6 @@ pub fn show( page_prefs: PagePrefs, quick_notes: &QuickNotes, update_check_off: bool, - welcome_notebook_update_prompt: bool, update: &crate::update::Status, copy: &mut CopyChoice, account: &mut AccountChoice, @@ -317,7 +315,6 @@ pub fn show( page_prefs, quick_notes, update_check_off, - welcome_notebook_update_prompt, update, t, &mut acts, @@ -852,7 +849,6 @@ fn options_page( page_prefs: PagePrefs, quick_notes: &QuickNotes, update_check_off: bool, - welcome_notebook_update_prompt: bool, update: &crate::update::Status, t: &Tokens, acts: &mut Vec, @@ -981,10 +977,6 @@ fn options_page( if ui.checkbox(&mut off, crate::tl_id!("ui.update_check_off_at_start")).changed() { acts.push(Act::SetUpdateCheckOff(off)); } - let mut prompt = welcome_notebook_update_prompt; - if ui.checkbox(&mut prompt, crate::tl_id!("ui.welcome_notebook_update_prompt")).changed() { - acts.push(Act::SetWelcomeNotebookUpdatePrompt(prompt)); - } ui.add_space(12.0); section_heading(ui, 3); ui.label(egui::RichText::new(crate::tl_id!("ui.privacy_is_our_top_priority_logs_and_telemetry_stay_17a34813d0")).strong().color(t.strong)); @@ -1094,7 +1086,6 @@ mod tests { PagePrefs::default(), &QuickNotes::default(), false, - true, &crate::update::Status::Idle, &mut CopyChoice::default(), &mut AccountChoice::default(), diff --git a/i18n/ar-XB.tsv b/i18n/ar-XB.tsv index f7943f911..3b97c1db6 100644 --- a/i18n/ar-XB.tsv +++ b/i18n/ar-XB.tsv @@ -1022,8 +1022,6 @@ @id ui.check_for_updates_hint [[RLI]]$$$Checks GitHub for a newer release each time NoteCraft starts, and when you press Check for Updates. It downloads and installs only when you press Update and Restart.@@@[[PDI]] @id ui.update_check_off_at_start [[RLI]]$$$Don't check for updates at start up@@@[[PDI]] @id ui.update_check_not_saved [[RLI]]$$$The update setting could not be saved: {error}@@@[[PDI]] -@id ui.welcome_notebook_update_prompt [[RLI]]$$$Ask to update the Welcome notebook after upgrades@@@[[PDI]] -@id ui.welcome_notebook_update_prompt_not_saved [[RLI]]$$$The Welcome notebook update preference could not be saved: {error}@@@[[PDI]] @id ui.open_the_releases_page [[RLI]]$$$Open the releases page@@@[[PDI]] @id ui.update_checking [[RLI]]$$$Looking for a newer version…@@@[[PDI]] @id ui.update_up_to_date [[RLI]]$$$NoteCraft is up to date. The newest release is {version}.@@@[[PDI]] diff --git a/i18n/ar.tsv b/i18n/ar.tsv index 4b3e4e656..f37f68bc0 100644 --- a/i18n/ar.tsv +++ b/i18n/ar.tsv @@ -800,8 +800,6 @@ @id ui.check_for_updates_hint يتحقق من GitHub بحثًا عن إصدار أحدث في كل مرة يبدأ فيها NoteCraft، وعند الضغط على التحقق من التحديثات. لا يُنزَّل التحديث ولا يُثبَّت إلا عند الضغط على تحديث وإعادة التشغيل. @id ui.update_check_off_at_start عدم التحقق من التحديثات عند بدء التشغيل @id ui.update_check_not_saved تعذّر حفظ إعداد التحديثات: {error} -@id ui.welcome_notebook_update_prompt السؤال عن تحديث دفتر الترحيب بعد ترقية التطبيق -@id ui.welcome_notebook_update_prompt_not_saved تعذّر حفظ تفضيل تحديث دفتر الترحيب: {error} @id ui.update_prompt.newest_available {app} {version} هو أحدث إصدار متاح. @id ui.update_prompt.by_developer بواسطة {developer} @id ui.update_prompt.version_change من v{from} إلى {to} diff --git a/i18n/de.tsv b/i18n/de.tsv index 773a87047..8d9b54755 100644 --- a/i18n/de.tsv +++ b/i18n/de.tsv @@ -797,8 +797,6 @@ @id ui.check_for_updates_hint Prüft bei jedem Start von NoteCraft und beim Drücken von Nach Updates suchen auf GitHub nach einer neueren Version. Herunterladen und Installieren erfolgen erst, wenn Sie Aktualisieren und neu starten drücken. @id ui.update_check_off_at_start Beim Start nicht nach Updates suchen @id ui.update_check_not_saved Die Update-Einstellung konnte nicht gespeichert werden: {error} -@id ui.welcome_notebook_update_prompt Nach Programmupdates nach dem Aktualisieren des Willkommensnotizbuchs fragen -@id ui.welcome_notebook_update_prompt_not_saved Die Einstellung für Updates des Willkommensnotizbuchs konnte nicht gespeichert werden: {error} @id ui.update_prompt.newest_available {app} {version} ist die neueste verfügbare Version. @id ui.update_prompt.by_developer von {developer} @id ui.update_prompt.version_change v{from} auf {to} diff --git a/i18n/en-XA.tsv b/i18n/en-XA.tsv index ed7d6118e..2d4c4090c 100644 --- a/i18n/en-XA.tsv +++ b/i18n/en-XA.tsv @@ -1022,8 +1022,6 @@ @id ui.check_for_updates_hint $$$Checks GitHub for a newer release each time NoteCraft starts, and when you press Check for Updates. It downloads and installs only when you press Update and Restart.@@@ @id ui.update_check_off_at_start $$$Don't check for updates at start up@@@ @id ui.update_check_not_saved $$$The update setting could not be saved: {error}@@@ -@id ui.welcome_notebook_update_prompt $$$Ask to update the Welcome notebook after upgrades@@@ -@id ui.welcome_notebook_update_prompt_not_saved $$$The Welcome notebook update preference could not be saved: {error}@@@ @id ui.open_the_releases_page $$$Open the releases page@@@ @id ui.update_checking $$$Looking for a newer version…@@@ @id ui.update_up_to_date $$$NoteCraft is up to date. The newest release is {version}.@@@ diff --git a/i18n/en.tsv b/i18n/en.tsv index 74e059986..c9aa63c2b 100644 --- a/i18n/en.tsv +++ b/i18n/en.tsv @@ -1022,8 +1022,6 @@ @id ui.check_for_updates_hint Checks GitHub for a newer release each time NoteCraft starts, and when you press Check for Updates. It downloads and installs only when you press Update and Restart. @id ui.update_check_off_at_start Don't check for updates at start up @id ui.update_check_not_saved The update setting could not be saved: {error} -@id ui.welcome_notebook_update_prompt Ask to update the Welcome notebook after upgrades -@id ui.welcome_notebook_update_prompt_not_saved The Welcome notebook update preference could not be saved: {error} @id ui.open_the_releases_page Open the releases page @id ui.update_checking Looking for a newer version… @id ui.update_up_to_date NoteCraft is up to date. The newest release is {version}. diff --git a/i18n/es.tsv b/i18n/es.tsv index cbf06ed46..57c5c02f3 100644 --- a/i18n/es.tsv +++ b/i18n/es.tsv @@ -797,8 +797,6 @@ @id ui.check_for_updates_hint Consulta GitHub por una versión más reciente cada vez que se inicia NoteCraft y cuando pulsas Buscar actualizaciones. Solo se descarga e instala cuando pulsas Actualizar y reiniciar. @id ui.update_check_off_at_start No buscar actualizaciones al iniciar @id ui.update_check_not_saved No se pudo guardar el ajuste de actualizaciones: {error} -@id ui.welcome_notebook_update_prompt Preguntar si se actualiza el cuaderno de bienvenida tras actualizar la aplicación -@id ui.welcome_notebook_update_prompt_not_saved No se pudo guardar la preferencia de actualización del cuaderno de bienvenida: {error} @id ui.update_prompt.newest_available {app} {version} es la versión más reciente disponible. @id ui.update_prompt.by_developer por {developer} @id ui.update_prompt.version_change v{from} a {to} diff --git a/i18n/fa.tsv b/i18n/fa.tsv index 04d253663..7e6513131 100644 --- a/i18n/fa.tsv +++ b/i18n/fa.tsv @@ -797,8 +797,6 @@ @id ui.check_for_updates_hint هر بار که NoteCraft شروع می‌شود و هنگام فشردن بررسی به‌روزرسانی، GitHub را برای نسخه‌ی جدیدتر بررسی می‌کند. تنها پس از فشردن به‌روزرسانی و راه‌اندازی مجدد دانلود و نصب می‌شود. @id ui.update_check_off_at_start هنگام راه‌اندازی به‌روزرسانی را بررسی نکن @id ui.update_check_not_saved تنظیم به‌روزرسانی ذخیره نشد: {error} -@id ui.welcome_notebook_update_prompt پس از ارتقای برنامه، دربارهٔ به‌روزرسانی دفترچه خوش‌آمدگویی سؤال شود -@id ui.welcome_notebook_update_prompt_not_saved ترجیح به‌روزرسانی دفترچه خوش‌آمدگویی ذخیره نشد: {error} @id ui.update_prompt.newest_available {app} {version} جدیدترین نسخه‌ی موجود است. @id ui.update_prompt.by_developer توسط {developer} @id ui.update_prompt.version_change از v{from} به {to} diff --git a/i18n/fr.tsv b/i18n/fr.tsv index c30ffa190..d84d7020a 100644 --- a/i18n/fr.tsv +++ b/i18n/fr.tsv @@ -797,8 +797,6 @@ @id ui.check_for_updates_hint Vérifie GitHub pour une version plus récente à chaque démarrage de NoteCraft, et lorsque vous appuyez sur Rechercher des mises à jour. Elle ne se télécharge et ne s'installe qu'après que vous appuyez sur Mettre à jour et redémarrer. @id ui.update_check_off_at_start Ne pas rechercher les mises à jour au démarrage @id ui.update_check_not_saved Le réglage de mise à jour n'a pas pu être enregistré : {error} -@id ui.welcome_notebook_update_prompt Proposer de mettre à jour le carnet de bienvenue après une mise à jour de l'application -@id ui.welcome_notebook_update_prompt_not_saved Impossible d’enregistrer la préférence de mise à jour du carnet de bienvenue : {error} @id ui.update_prompt.newest_available {app} {version} est la version la plus récente disponible. @id ui.update_prompt.by_developer par {developer} @id ui.update_prompt.version_change v{from} vers {to} diff --git a/i18n/he.tsv b/i18n/he.tsv index 557599d73..0bbdfa1b3 100644 --- a/i18n/he.tsv +++ b/i18n/he.tsv @@ -797,8 +797,6 @@ @id ui.check_for_updates_hint בודק ב-GitHub אם יש גרסה חדשה בכל הפעלה של NoteCraft, וכשלוחצים על בדיקת עדכונים. ההורדה וההתקנה מתבצעות רק אחרי לחיצה על עדכון והפעלה מחדש. @id ui.update_check_off_at_start לא לבדוק עדכונים בהפעלה @id ui.update_check_not_saved לא ניתן לשמור את הגדרת העדכונים: {error} -@id ui.welcome_notebook_update_prompt לשאול אם לעדכן את מחברת הברוכים הבאים לאחר שדרוג היישום -@id ui.welcome_notebook_update_prompt_not_saved לא ניתן לשמור את ההעדפה לעדכון מחברת הברוכים הבאים: {error} @id ui.update_prompt.newest_available {app} {version} היא הגרסה העדכנית ביותר הזמינה. @id ui.update_prompt.by_developer מאת {developer} @id ui.update_prompt.version_change מ-v{from} ל-{to} diff --git a/i18n/hi.tsv b/i18n/hi.tsv index a40ffa28e..689327058 100644 --- a/i18n/hi.tsv +++ b/i18n/hi.tsv @@ -797,8 +797,6 @@ @id ui.check_for_updates_hint NoteCraft शुरू होने पर और जब आप अपडेट जांचें दबाते हैं, GitHub पर नई रिलीज़ की जांच होती है। डाउनलोड और इंस्टॉल तभी होता है जब आप अपडेट करें और पुनः आरंभ करें दबाते हैं। @id ui.update_check_off_at_start शुरू होने पर अपडेट न जांचें @id ui.update_check_not_saved अपडेट सेटिंग सहेजी नहीं जा सकी: {error} -@id ui.welcome_notebook_update_prompt ऐप अपग्रेड के बाद स्वागत नोटबुक को अपडेट करने के लिए पूछें -@id ui.welcome_notebook_update_prompt_not_saved स्वागत नोटबुक अपडेट करने की प्राथमिकता सहेजी नहीं जा सकी: {error} @id ui.update_prompt.newest_available {app} {version} उपलब्ध सबसे नया संस्करण है। @id ui.update_prompt.by_developer {developer} द्वारा @id ui.update_prompt.version_change v{from} से {to} diff --git a/i18n/ja.tsv b/i18n/ja.tsv index f1f512866..8b2111102 100644 --- a/i18n/ja.tsv +++ b/i18n/ja.tsv @@ -797,8 +797,6 @@ @id ui.check_for_updates_hint NoteCraft の起動時と「アップデートを確認」を押したときに、GitHub で新しいリリースを確認します。「アップデートして再起動」を押すまでダウンロードもインストールもしません。 @id ui.update_check_off_at_start 起動時にアップデートを確認しない @id ui.update_check_not_saved アップデートの設定を保存できませんでした: {error} -@id ui.welcome_notebook_update_prompt アプリの更新後にようこそノートブックの更新を確認する -@id ui.welcome_notebook_update_prompt_not_saved ようこそノートブックの更新設定を保存できませんでした: {error} @id ui.update_prompt.newest_available {app} {version} は利用可能な最新バージョンです。 @id ui.update_prompt.by_developer {developer} 提供 @id ui.update_prompt.version_change v{from} から {to} diff --git a/i18n/ko.tsv b/i18n/ko.tsv index ea5ebddff..72a46c4c9 100644 --- a/i18n/ko.tsv +++ b/i18n/ko.tsv @@ -797,8 +797,6 @@ @id ui.check_for_updates_hint NoteCraft를 시작할 때마다, 그리고 업데이트 확인을 누를 때 GitHub에서 새 릴리스를 확인합니다. 업데이트 및 다시 시작을 누를 때만 다운로드하고 설치합니다. @id ui.update_check_off_at_start 시작할 때 업데이트를 확인하지 않음 @id ui.update_check_not_saved 업데이트 설정을 저장할 수 없습니다: {error} -@id ui.welcome_notebook_update_prompt 앱 업그레이드 후 환영 노트북을 업데이트할지 묻기 -@id ui.welcome_notebook_update_prompt_not_saved 환영 노트북 업데이트 설정을 저장할 수 없습니다: {error} @id ui.update_prompt.newest_available {app} {version}은(는) 사용 가능한 최신 버전입니다. @id ui.update_prompt.by_developer {developer} 제작 @id ui.update_prompt.version_change v{from} → {to} diff --git a/i18n/ru.tsv b/i18n/ru.tsv index b30dffe3b..6207eede2 100644 --- a/i18n/ru.tsv +++ b/i18n/ru.tsv @@ -797,8 +797,6 @@ @id ui.check_for_updates_hint Проверяет GitHub на более новую версию при каждом запуске NoteCraft и при нажатии «Проверить обновления». Загрузка и установка начинаются только после нажатия «Обновить и перезапустить». @id ui.update_check_off_at_start Не проверять обновления при запуске @id ui.update_check_not_saved Не удалось сохранить настройку обновлений: {error} -@id ui.welcome_notebook_update_prompt Предлагать обновить приветственный блокнот после обновления приложения -@id ui.welcome_notebook_update_prompt_not_saved Не удалось сохранить настройку обновления приветственного блокнота: {error} @id ui.update_prompt.newest_available {app} {version} — самая новая доступная версия. @id ui.update_prompt.by_developer от {developer} @id ui.update_prompt.version_change с v{from} на {to} diff --git a/i18n/tr.tsv b/i18n/tr.tsv index cbaae8c8d..e3de02bb5 100644 --- a/i18n/tr.tsv +++ b/i18n/tr.tsv @@ -947,8 +947,6 @@ @id ui.check_for_updates_hint NoteCraft her başladığında ve Güncellemeleri denetle düğmesine bastığınızda GitHub'da daha yeni bir sürümü denetler. Yalnızca Güncelle ve yeniden başlat düğmesine basınca indirir ve kurar. @id ui.update_check_off_at_start Başlangıçta güncellemeleri denetleme @id ui.update_check_not_saved Güncelleme ayarı kaydedilemedi: {error} -@id ui.welcome_notebook_update_prompt Uygulama yükseltildikten sonra Hoş Geldiniz not defterini güncellemeyi sor -@id ui.welcome_notebook_update_prompt_not_saved Hoş Geldiniz not defterini güncelleme tercihi kaydedilemedi: {error} @id ui.update_prompt.newest_available {app} {version} mevcut en yeni sürüm. @id ui.open_the_releases_page Sürümler sayfasını aç @id ui.update_checking Daha yeni bir sürüm aranıyor… diff --git a/i18n/ur.tsv b/i18n/ur.tsv index a3687c6d0..9beca8349 100644 --- a/i18n/ur.tsv +++ b/i18n/ur.tsv @@ -797,8 +797,6 @@ @id ui.check_for_updates_hint NoteCraft کے ہر آغاز پر، اور جب آپ اپ ڈیٹس چیک کریں دبائیں تو GitHub پر نیا ریلیز دیکھا جاتا ہے۔ ڈاؤن لوڈ اور انسٹال صرف اس وقت ہوتا ہے جب آپ اپ ڈیٹ اور دوبارہ شروع کریں دبائیں۔ @id ui.update_check_off_at_start شروع پر اپ ڈیٹس نہ چیک کریں @id ui.update_check_not_saved اپ ڈیٹ کی ترتیب محفوظ نہیں ہو سکی: {error} -@id ui.welcome_notebook_update_prompt ایپ اپ گریڈ ہونے پر پوچھیں کہ خوش آمدید نوٹ بک اپ ڈیٹ کرنی ہے یا نہیں -@id ui.welcome_notebook_update_prompt_not_saved خوش آمدید نوٹ بک کی اپ ڈیٹ کی ترجیح محفوظ نہیں ہو سکی: {error} @id ui.update_prompt.newest_available {app} {version} دستیاب سب سے نیا ورژن ہے۔ @id ui.update_prompt.by_developer {developer} کی جانب سے @id ui.update_prompt.version_change v{from} سے {to} diff --git a/i18n/zh.tsv b/i18n/zh.tsv index 45ff4236a..31db65944 100644 --- a/i18n/zh.tsv +++ b/i18n/zh.tsv @@ -800,8 +800,6 @@ @id ui.check_for_updates_hint 每次启动 NoteCraft 时,以及按下“检查更新”时,都会检查 GitHub 上是否有更新的版本。只有按下“更新并重启”后,才会下载并安装。 @id ui.update_check_off_at_start 启动时不检查更新 @id ui.update_check_not_saved 无法保存更新设置:{error} -@id ui.welcome_notebook_update_prompt 升级应用后询问是否更新欢迎笔记本 -@id ui.welcome_notebook_update_prompt_not_saved 无法保存欢迎笔记本更新偏好:{error} @id ui.update_prompt.newest_available {app} {version} 是目前可用的最新版本。 @id ui.update_prompt.by_developer 由 {developer} 提供 @id ui.update_prompt.version_change v{from} 到 {to} diff --git a/packaging/OSX/README.md b/packaging/OSX/README.md index 6114bccac..c52f5fb61 100644 --- a/packaging/OSX/README.md +++ b/packaging/OSX/README.md @@ -20,7 +20,7 @@ bash packaging/OSX/test-provenance.sh ``` The DMG contains `NoteCraft.app`, an Applications link and a read-me file at its root. Drag the -app to Applications and open it. On first launch of each version, NoteCraft asks whether to add +app to Applications and open it. During first-use setup, NoteCraft asks whether to add the bundled Welcome notebook to the user's notebook folder. The default `--arch universal` builds both Apple targets and combines the GUI and CLI with diff --git a/packaging/installation artifacts.md b/packaging/installation artifacts.md index bd6384bc5..19859fe32 100644 --- a/packaging/installation artifacts.md +++ b/packaging/installation artifacts.md @@ -2,7 +2,7 @@ Status: product contract updated by the owner on 2026-11-07. This is the single authority for installation artifact responsibilities and the User Assistance demo notebook. The application -bundles the generated notebook and asks once per app version before creating or replacing the +bundles the generated notebook and asks during first-use setup before creating or replacing the per-user Welcome notebook. ## Separate installation artifacts @@ -34,8 +34,9 @@ The running app owns the per-user copy after the user confirms: are reset. It is one dialog with five pages and Next at the bottom right: the welcome page with the brand banner; the local logging level; the page format, HTML or CommonMark + GFM, saved as the default; whether to create the demo notebook in that format; and a thank-you page with Finish. -- The wizard does not reopen for later app versions. Installation copies nothing into the notebooks - folder; the package ships the generated editions only as the wizard's source. +- Upgrades preserve the first-use completion state and saved preferences. Run NoteCraft with + `--first-use` to reopen the wizard with the saved settings. The package ships the generated + editions as the wizard's source. - On Yes on the demo page, create or completely replace only `welcome-to-notecraft` from the bundled edition for the chosen format when Finish is pressed. The edition's notebook folder becomes the managed notebook, so the notebook list finds it, and the Welcome page opens. The other format is @@ -49,7 +50,7 @@ The running app owns the per-user copy after the user confirms: Desktop apps copy the chosen edition from the installed package or app bundle into the selected user notebook root only after Yes in step 3. The desktop setup launcher installs nothing; it starts NoteCraft. Android and the browser have separate startup paths; each must -apply the same per-version confirmation before replacing a user's Welcome notebook. Android +ask for confirmation before replacing a user's Welcome notebook. Android app-specific storage follows Android's normal uninstall lifecycle. ## Platform installation contract diff --git a/packaging/windows/notecraft.wxs b/packaging/windows/notecraft.wxs index cbfc04d71..3b3d868ab 100644 --- a/packaging/windows/notecraft.wxs +++ b/packaging/windows/notecraft.wxs @@ -10,9 +10,8 @@ Per-machine install into Program Files with a Start Menu shortcut. The installer shows the standard WiX dialogs: welcome and licence, progress, and a finish page. - The app carries both generated Welcome notebook formats and asks once per app version before - creating or replacing its dedicated per-user Welcome notebook. Other notebook folders remain - unchanged. + The app carries both generated Welcome notebook formats for the first-use wizard. + Per-user settings record whether the wizard has been completed across upgrades. UpgradeCode and the component GUIDs below belong to NoteCraft alone. Never change the UpgradeCode after the first public release: Windows Installer would stop treating a new @@ -53,7 +52,6 @@ Impersonate="yes" Return="ignore" /> - @@ -84,9 +82,6 @@ - - - diff --git a/packaging/windows/package.ps1 b/packaging/windows/package.ps1 index a60df3219..1c6ffe94e 100644 --- a/packaging/windows/package.ps1 +++ b/packaging/windows/package.ps1 @@ -116,10 +116,8 @@ $VoiceWork = Join-Path $TargetDir 'transcription-package' Invoke-Native 'stage bundled offline transcription' { cmake "-DBIN_DIR=$VoiceStage" "-DMODEL_DIR=$VoiceStage" "-DWORK_DIR=$VoiceWork" -P (Join-Path $Root 'packaging\stage-transcription.cmake') } -# The installer leaves this marker beside the app. The first launch after installing shows the first-use wizard again. -[IO.File]::WriteAllText((Join-Path $Stage 'first-use.pending'), '') - # The app copies both generated formats into the user's notebooks folder at startup. + # Bundle both generated formats for the first-use wizard. $DemoSource = Join-Path $Root 'docs\demo\DemoNotebook' foreach ($format in 'html', 'cmgfm') { $FormatRoot = Join-Path $DemoSource $format From 21ecb83c2d4d22154b7f8447cdfb96942ff95e59 Mon Sep 17 00:00:00 2001 From: alientechsw <43017062+alientechsw@users.noreply.github.com> Date: Sat, 5 Dec 2026 12:29:56 -0800 Subject: [PATCH 3/7] feat(ui): update Welcome notebook on upgrade, wizard close button --- apps/notecraft/src/main.rs | 4 + crates/ui-egui/src/app.rs | 366 +++++++++++++++++++++++++++++++++++-- crates/ui-egui/tests/ui.rs | 46 +++++ i18n/en.tsv | 4 + 4 files changed, 408 insertions(+), 12 deletions(-) diff --git a/apps/notecraft/src/main.rs b/apps/notecraft/src/main.rs index 8bf1c627d..c60846449 100644 --- a/apps/notecraft/src/main.rs +++ b/apps/notecraft/src/main.rs @@ -345,6 +345,10 @@ fn main() -> eframe::Result { notecraft_setup::install_edition(&setup_payload, notebooks_root, format).map_err(|error| error.to_string()) }) .with_clipboard(clipboard); + // A newer bundled Welcome notebook replaces the installed copy when it is + // untouched, or asks once when it was changed. First-use setup is untouched: + // the wizard asks about the notebook itself. + app.check_welcome_notebook_update(env!("CARGO_PKG_VERSION")); for (key, message) in startup_alerts.drain(..) { app.alert(key, "NoteCraft", &message); } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 8c6971d1b..7d1330de0 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -286,6 +286,17 @@ const INDENT: f32 = 14.0; const WIZARD_SCREEN_MARGIN: f32 = 2.0 * (16.0 + 2.0 + 8.0); /// The height kept below the wizard's scrolling body for its Back, Next and Finish buttons. const WIZARD_BUTTON_ROW: f32 = 56.0; +/// The height kept above the wizard's scrolling body for its close button. +const WIZARD_CLOSE_ROW: f32 = 36.0; + +/// The folder name of the installed Welcome notebook, matching `notecraft_setup::NOTEBOOK_NAME`. +const WELCOME_NOTEBOOK_DIR: &str = "welcome-to-notecraft"; +/// Settings keys for the Welcome notebook update check: the installed edition's version, +/// a hash of its files at install time, and the version the update prompt was already +/// shown for. See `NoteCraftApp::check_welcome_notebook_update`. +const WELCOME_NOTEBOOK_VERSION_KEY: &str = "welcome_notebook_version"; +const WELCOME_NOTEBOOK_MANIFEST_KEY: &str = "welcome_notebook_manifest"; +const WELCOME_NOTEBOOK_PROMPTED_VERSION_KEY: &str = "welcome_notebook_prompted_version"; /// One result of a History search (Recent Edits, Find by Author; issue #382): the page's title as /// the link that opens it, and under it where it is and when it was last changed, so two pages @@ -1822,6 +1833,12 @@ enum Dialog { add_demo: bool, error: Option, }, + /// The bundled Welcome notebook is newer than the installed copy, and the installed + /// copy was changed: update it (replacing the person's edits) or keep it. + WelcomeNotebookUpdate { + version: String, + error: Option, + }, /// A problem told to the user in a box. /// A problem told to the user in a box. Ticking "do not alert me again" stops the box for /// this `key` for the rest of the session; the status line still says what happened. Alert { @@ -2642,17 +2659,7 @@ impl NoteCraftApp { self.session.settings.set("telemetry_level", level).map_err(|error| error.to_string())?; self.session.settings.set_default_format(format).map_err(|error| error.to_string())?; if add_demo { - self.save_now(); - if self.is_dirty() { - return Err("the current page could not be saved before replacing the Welcome notebook".to_string()); - } - let installed = { - let setup = self.welcome_notebook_setup.as_mut().ok_or_else(|| "the bundled Welcome notebook setup is unavailable".to_string())?; - setup(self.session.root(), format.id())? - }; - self.editor = None; - self.pad = None; - self.session.refresh(); + let installed = self.install_welcome_notebook(format)?; self.status_is_error = false; self.open_path(&installed.join("00-start/welcome").to_string_lossy()); if self.status_is_error { @@ -2663,6 +2670,152 @@ impl NoteCraftApp { Ok(()) } + /// Replaces the installed Welcome notebook with the bundled edition, in the given + /// format. Saves the open page first and refuses when it cannot be saved, so the + /// replacement never strands unsaved work. Records the installed version and a hash + /// of its files, so a later release can tell whether the notebook was changed since + /// it was installed; a failed record leaves it unrecorded, and the next update asks + /// instead of silently replacing. + fn install_welcome_notebook(&mut self, format: PageFormat) -> Result { + self.save_now(); + if self.is_dirty() { + return Err("the current page could not be saved before replacing the Welcome notebook".to_string()); + } + let installed = { + let setup = self.welcome_notebook_setup.as_mut().ok_or_else(|| "the bundled Welcome notebook setup is unavailable".to_string())?; + setup(self.session.root(), format.id())? + }; + self.editor = None; + self.pad = None; + self.session.refresh(); + Self::record_welcome_notebook(&self.session.settings, &installed); + Ok(installed) + } + + /// Records the installed Welcome notebook's version and manifest. Best-effort: a + /// failed record leaves the notebook unrecorded, and the next update asks instead of + /// silently replacing. + fn record_welcome_notebook(settings: ¬ecraft_store::Settings, installed: &Path) { + if settings.set(WELCOME_NOTEBOOK_VERSION_KEY, crate::backstage::VERSION).is_err() { + log::warn!("could not record the Welcome notebook version"); + return; + } + match Self::welcome_notebook_manifest(installed) { + Ok(manifest) => { + let _ = settings.set(WELCOME_NOTEBOOK_MANIFEST_KEY, &manifest); + } + Err(error) => log::warn!("could not record the Welcome notebook manifest: {error}"), + } + } + + /// Aggregate SHA-256 of a directory tree, for telling whether the installed Welcome + /// notebook was changed since it was installed. Sorted relative paths; each file + /// contributes its contents' hash, each directory and link its path, so a file the + /// person added, or a link they made, counts as a change. Contents only: times and + /// permissions do not matter. A read failure is an error, so a tree that cannot be + /// read is treated as changed, never as untouched. + fn welcome_notebook_manifest(dir: &Path) -> Result { + use sha2::Digest; + fn visit(dir: &Path, base: &Path, hasher: &mut sha2::Sha256) -> Result<(), String> { + use sha2::Digest; + let mut entries: Vec = std::fs::read_dir(dir) + .map_err(|error| format!("could not list {}: {error}", dir.display()))? + .collect::, _>>() + .map_err(|error| format!("could not list {}: {error}", dir.display()))? + .into_iter() + .map(|entry| entry.path()) + .collect(); + entries.sort(); + for path in entries { + let relative = path.strip_prefix(base).map_err(|_| format!("{} is not under {}", path.display(), base.display()))?; + let relative = relative.to_string_lossy(); + let kind = std::fs::symlink_metadata(&path).map_err(|error| format!("could not read {}: {error}", path.display()))?; + if kind.file_type().is_symlink() { + let target = std::fs::read_link(&path).map_err(|error| format!("could not read {}: {error}", path.display()))?; + hasher.update(format!("L {relative} -> {}\n", target.display())); + } else if kind.is_dir() { + hasher.update(format!("D {relative}\n")); + visit(&path, base, hasher)?; + } else { + let mut file = std::fs::File::open(&path).map_err(|error| format!("could not read {}: {error}", path.display()))?; + let mut file_hasher = sha2::Sha256::new(); + std::io::copy(&mut file, &mut file_hasher).map_err(|error| format!("could not read {}: {error}", path.display()))?; + hasher.update(format!("F {relative} {:x}\n", file_hasher.finalize())); + } + } + Ok(()) + } + let mut hasher = sha2::Sha256::new(); + visit(dir, dir, &mut hasher)?; + Ok(format!("{:x}", hasher.finalize())) + } + + /// The edition the installed Welcome notebook is in: the welcome page's file says + /// which one it is. Falls back to the saved default format when the page is gone + /// (the person deleted it, so the update asks anyway). + fn installed_welcome_format(&self) -> PageFormat { + let welcome = self.session.root().join(WELCOME_NOTEBOOK_DIR).join("00-start/welcome"); + if welcome.join("index.html").is_file() { + PageFormat::Html + } else if welcome.join("index.md").is_file() { + PageFormat::Cmgfm + } else { + self.session.settings.global_format().0 + } + } + + /// Checks whether the bundled Welcome notebook is newer than the installed one, for + /// a user whose first-use setup is already done. First-use setup is untouched: the + /// wizard asks about the notebook itself. + /// + /// When the installed copy is untouched, it is replaced silently. When it was + /// changed, or its version was never recorded, a prompt asks once for this version. + /// A missing notebook, or a bundled version that is not newer, does nothing. The + /// check runs at startup, whatever installed the app: it reads the installed + /// version from settings, never an installer marker. + pub fn check_welcome_notebook_update(&mut self, bundled_version: &str) { + if self.session.settings.first_use_pending() { + return; + } + let installed_dir = self.session.root().join(WELCOME_NOTEBOOK_DIR); + if !installed_dir.is_dir() { + if self.session.settings.get(WELCOME_NOTEBOOK_VERSION_KEY).is_some() { + let _ = self.session.settings.set(WELCOME_NOTEBOOK_VERSION_KEY, ""); + let _ = self.session.settings.set(WELCOME_NOTEBOOK_MANIFEST_KEY, ""); + } + return; + } + let Some(bundled) = crate::update::parse_version(bundled_version) else { + return; + }; + let bundled_version = bundled.to_string(); + let installed_version = self.session.settings.get(WELCOME_NOTEBOOK_VERSION_KEY).unwrap_or_default(); + if !crate::update::is_newer(&bundled, &installed_version) { + return; + } + let untouched = match self.session.settings.get(WELCOME_NOTEBOOK_MANIFEST_KEY) { + Some(stored) => Self::welcome_notebook_manifest(&installed_dir).is_ok_and(|current| current == stored), + None => false, + }; + if untouched { + if let Err(error) = self.install_welcome_notebook(self.installed_welcome_format()) { + self.alert( + "welcome-notebook-update", + "NoteCraft", + &crate::i18n::format_message_id("ui.welcome_notebook_action_failed", &[("error", &error)]), + ); + } + return; + } + if self.session.settings.get(WELCOME_NOTEBOOK_PROMPTED_VERSION_KEY).as_deref() == Some(bundled_version.as_str()) { + return; + } + let _ = self.session.settings.set(WELCOME_NOTEBOOK_PROMPTED_VERSION_KEY, &bundled_version); + if self.dialog.is_none() { + self.dialog = Some(Dialog::WelcomeNotebookUpdate { version: bundled_version, error: None }); + } + } + pub fn session(&self) -> &Session { &self.session } @@ -15782,6 +15935,7 @@ impl NoteCraftApp { let mut back = false; let mut next = false; let mut finish = false; + let mut close = false; let last_step: u8 = 4; let escape = ctx.input_mut(|input| input.consume_key(Modifiers::NONE, Key::Escape)); let backdrop = modal_backdrop(ctx, "first-use-wizard-modal-backdrop"); @@ -15806,7 +15960,7 @@ impl NoteCraftApp { let screen = ctx.content_rect(); let width = (screen.width() - WIZARD_SCREEN_MARGIN).clamp(1.0, 520.0); let banner_width = width.min(480.0); - let body_height = (screen.height() - WIZARD_SCREEN_MARGIN - WIZARD_BUTTON_ROW).max(80.0); + let body_height = (screen.height() - WIZARD_SCREEN_MARGIN - WIZARD_BUTTON_ROW - WIZARD_CLOSE_ROW).max(80.0); egui::Window::new(title.as_str()) .title_bar(false) .collapsible(false) @@ -15819,6 +15973,11 @@ impl NoteCraftApp { stay_above(ui, backdrop); ui.set_min_width(width); ui.set_max_width(width); + ui.with_layout(egui::Layout::right_to_left(egui::Align::TOP), |ui| { + if ui.button("×").clicked() { + close = true; + } + }); egui::ScrollArea::vertical().max_height(body_height).auto_shrink([false, true]).show(ui, |ui| { if *step == 0 { ui.add(egui::Image::from_bytes(banner_uri, banner_bytes).fit_to_exact_size(vec2(banner_width, banner_width / 2.0))); @@ -15899,6 +16058,62 @@ impl NoteCraftApp { Err(message) => *error = Some(message), } } + if close { + // Closing skips setup without installing the demo notebook. Marking + // setup seen keeps the wizard from opening again on the next launch. + let _ = self.session.settings.set("privacy_welcome_seen", "true"); + keep = false; + } + } + Dialog::WelcomeNotebookUpdate { version, error } => { + let mut update = false; + let mut keep_mine = false; + let escape = ctx.input_mut(|input| input.consume_key(Modifiers::NONE, Key::Escape)); + let backdrop = modal_backdrop(ctx, "welcome-notebook-update-modal-backdrop"); + egui::Window::new(crate::tl_id!("ui.welcome_notebook_update_title")) + .title_bar(false) + .collapsible(false) + .resizable(false) + .order(egui::Order::Foreground) + .anchor(Align2::CENTER_CENTER, vec2(0.0, 0.0)) + .frame(modal_frame(&self.tokens)) + .show(ctx, |ui| { + stay_above(ui, backdrop); + modal_title(ui, &self.tokens, crate::tl_id!("ui.welcome_notebook_update_title")); + let width = message_width(ctx); + ui.set_min_width(width); + ui.set_max_width(width); + ui.label(crate::i18n::format_message_id("ui.welcome_notebook_update_body", &[("version", version.as_str())])); + ui.add_space(6.0); + ui.colored_label(self.tokens.warn, crate::tl_id!("ui.welcome_notebook_replace_warning")); + if let Some(message) = error { + ui.add_space(8.0); + ui.colored_label( + self.tokens.warn, + crate::i18n::format_message_id("ui.welcome_notebook_action_failed", &[("error", message.as_str())]), + ); + } + ui.add_space(14.0); + ui.horizontal(|ui| { + if modal_button(ui, &self.tokens, crate::tl_id!("ui.welcome_notebook_keep_mine"), false).clicked() { + keep_mine = true; + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if modal_button(ui, &self.tokens, crate::tl_id!("ui.welcome_notebook_update"), true).clicked() { + update = true; + } + }); + }); + }); + if escape || keep_mine { + keep = false; + } + if update { + match self.install_welcome_notebook(self.installed_welcome_format()) { + Ok(_) => keep = false, + Err(message) => *error = Some(message), + } + } } Dialog::Alert { key, title, message, suppress, suppress_forever } => { let mut ok = false; @@ -19872,6 +20087,133 @@ mod alert_tests { assert_eq!(installed_format.borrow().as_str(), "cmgfm", "the chosen format reaches the install"); } + #[test] + fn welcome_notebook_manifest_tells_changed_files_apart() { + let t = notecraft_store::testing::TempDir::new("welcome-manifest"); + let first = t.path().join("first"); + let second = t.path().join("second"); + for root in [&first, &second] { + std::fs::create_dir_all(root.join("00-start/welcome")).expect("tree"); + std::fs::write(root.join("00-start/welcome/index.html"), "welcome").expect("page"); + std::fs::write(root.join("_node.toml"), "node").expect("node"); + } + let manifest = NoteCraftApp::welcome_notebook_manifest(&first).expect("manifest"); + assert_eq!(NoteCraftApp::welcome_notebook_manifest(&second).expect("same tree"), manifest, "identical trees share a manifest"); + std::fs::write(second.join("00-start/welcome/index.html"), "welcome, edited").expect("edit"); + assert_ne!(NoteCraftApp::welcome_notebook_manifest(&second).expect("changed tree"), manifest, "an edited page changes the manifest"); + std::fs::write(second.join("00-start/welcome/index.html"), "welcome").expect("restore"); + std::fs::write(second.join("extra.txt"), "added").expect("added file"); + assert_ne!(NoteCraftApp::welcome_notebook_manifest(&second).expect("added file"), manifest, "an added file changes the manifest"); + } + + #[test] + fn welcome_notebook_install_records_version_and_manifest() { + let t = notecraft_store::testing::TempDir::new("welcome-record-install"); + let settings = notecraft_store::Settings::at(t.path().join("settings.toml")); + let session = Session::new(&t.path().join("notebooks"), settings.clone()).expect("session"); + let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(|root, _format| { + let installed = root.join("welcome-to-notecraft"); + std::fs::create_dir_all(installed.join("00-start/welcome")).map_err(|error| error.to_string())?; + std::fs::write(installed.join("00-start/welcome/index.html"), "welcome").map_err(|error| error.to_string())?; + Ok(installed) + }); + // Opening the fake folder's page can fail; the install and its record happen first. + let _ = app.finish_first_use_wizard("none", PageFormat::Html, true); + assert_eq!(settings.get("welcome_notebook_version").as_deref(), Some(crate::backstage::VERSION), "the installed version is recorded"); + let installed = t.path().join("notebooks/welcome-to-notecraft"); + assert_eq!( + settings.get("welcome_notebook_manifest").as_deref(), + Some(NoteCraftApp::welcome_notebook_manifest(&installed).expect("manifest").as_str()), + "the manifest follows the installed tree" + ); + } + + #[test] + fn welcome_notebook_update_is_silent_when_untouched() { + let t = notecraft_store::testing::TempDir::new("welcome-update-silent"); + let settings = notecraft_store::Settings::at(t.path().join("settings.toml")); + settings.set("privacy_welcome_seen", "true").expect("settings"); + let notebooks = t.path().join("notebooks"); + let installed = notebooks.join("welcome-to-notecraft"); + std::fs::create_dir_all(installed.join("00-start/welcome")).expect("installed tree"); + std::fs::write(installed.join("00-start/welcome/index.html"), "old welcome").expect("old page"); + let manifest = NoteCraftApp::welcome_notebook_manifest(&installed).expect("manifest"); + settings.set("welcome_notebook_version", "0.0.29").expect("old version"); + settings.set("welcome_notebook_manifest", &manifest).expect("manifest"); + let session = Session::new(¬ebooks, settings.clone()).expect("session"); + let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(move |root, _format| { + let installed = root.join("welcome-to-notecraft"); + std::fs::create_dir_all(installed.join("00-start/welcome")).map_err(|error| error.to_string())?; + std::fs::write(installed.join("00-start/welcome/index.html"), "new welcome").map_err(|error| error.to_string())?; + Ok(installed) + }); + app.check_welcome_notebook_update("0.0.30"); + assert!(app.dialog.is_none(), "an untouched notebook updates without asking"); + assert_eq!(settings.get("welcome_notebook_version").as_deref(), Some(crate::backstage::VERSION), "the installed version is recorded"); + assert_eq!(std::fs::read_to_string(installed.join("00-start/welcome/index.html")).expect("new page"), "new welcome"); + assert_eq!( + settings.get("welcome_notebook_manifest").as_deref(), + Some(NoteCraftApp::welcome_notebook_manifest(&installed).expect("new manifest").as_str()), + "the manifest follows the new edition" + ); + } + + #[test] + fn welcome_notebook_update_prompts_when_edited() { + let t = notecraft_store::testing::TempDir::new("welcome-update-prompt"); + let settings = notecraft_store::Settings::at(t.path().join("settings.toml")); + settings.set("privacy_welcome_seen", "true").expect("settings"); + let notebooks = t.path().join("notebooks"); + let installed = notebooks.join("welcome-to-notecraft"); + std::fs::create_dir_all(installed.join("00-start/welcome")).expect("installed tree"); + std::fs::write(installed.join("00-start/welcome/index.html"), "old welcome").expect("old page"); + let manifest = NoteCraftApp::welcome_notebook_manifest(&installed).expect("manifest"); + settings.set("welcome_notebook_version", "0.0.29").expect("old version"); + settings.set("welcome_notebook_manifest", &manifest).expect("manifest"); + std::fs::write(installed.join("00-start/welcome/index.html"), "my notes").expect("edit"); + let called = std::rc::Rc::new(std::cell::Cell::new(false)); + let called_flag = called.clone(); + let session = Session::new(¬ebooks, settings.clone()).expect("session"); + let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(move |_, _| { + called_flag.set(true); + Err("must not install".to_string()) + }); + app.check_welcome_notebook_update("0.0.30"); + assert!(matches!(app.dialog, Some(Dialog::WelcomeNotebookUpdate { ref version, .. }) if version == "0.0.30"), "an edited notebook asks once"); + assert!(!called.get(), "asking does not install"); + assert_eq!(settings.get("welcome_notebook_prompted_version").as_deref(), Some("0.0.30"), "asking records the version"); + assert_eq!( + std::fs::read_to_string(installed.join("00-start/welcome/index.html")).expect("kept page"), + "my notes", + "asking does not replace the notebook" + ); + } + + #[test] + fn welcome_notebook_update_asks_once_per_version() { + let t = notecraft_store::testing::TempDir::new("welcome-update-once"); + let settings = notecraft_store::Settings::at(t.path().join("settings.toml")); + settings.set("privacy_welcome_seen", "true").expect("settings"); + let notebooks = t.path().join("notebooks"); + let installed = notebooks.join("welcome-to-notecraft"); + std::fs::create_dir_all(installed.join("00-start/welcome")).expect("installed tree"); + std::fs::write(installed.join("00-start/welcome/index.html"), "old welcome").expect("old page"); + settings.set("welcome_notebook_version", "0.0.29").expect("old version"); + settings.set("welcome_notebook_manifest", "stale").expect("stale manifest"); + let session = Session::new(¬ebooks, settings.clone()).expect("session"); + let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(|_, _| Err("must not install".to_string())); + app.check_welcome_notebook_update("0.0.30"); + assert!(matches!(app.dialog, Some(Dialog::WelcomeNotebookUpdate { .. })), "asks the first time"); + app.dialog = None; + app.check_welcome_notebook_update("0.0.30"); + assert!(app.dialog.is_none(), "does not ask again for the same version"); + app.check_welcome_notebook_update("0.0.31"); + assert!( + matches!(app.dialog, Some(Dialog::WelcomeNotebookUpdate { ref version, .. }) if version == "0.0.31"), + "asks again for a newer version" + ); + } + /// `--first-use` writes `privacy_welcome_seen = ""` and keeps every other setting. #[test] fn first_use_flag_value_opens_setup_with_the_saved_choices() { diff --git a/crates/ui-egui/tests/ui.rs b/crates/ui-egui/tests/ui.rs index c09961380..72d016914 100644 --- a/crates/ui-egui/tests/ui.rs +++ b/crates/ui-egui/tests/ui.rs @@ -2606,6 +2606,52 @@ fn failed_welcome_notebook_generation_keeps_the_prompt_open() { assert!(!t.path().join("notebooks/welcome-to-notecraft").exists(), "a failed copy creates no partial notebook"); } +#[test] +fn first_use_wizard_close_button_skips_setup_without_installing_the_demo() { + let t = TempDir::new("ui-welcome-wizard-close"); + let s = session(&t); + s.settings.set("ui_language", "en").expect("English UI setting"); + s.settings.set("privacy_welcome_seen", "").expect("first use: the wizard opens"); + let installed = std::rc::Rc::new(std::cell::Cell::new(false)); + let installed_flag = installed.clone(); + let app = NoteCraftApp::new(s).with_welcome_notebook_setup(move |_, _| { + installed_flag.set(true); + Err("must not install".to_string()) + }); + let mut h = harness(app, LIGHT); + h.get_by_label("×").click(); + settle(&mut h); + assert_eq!(h.query_all_by_label("Finish").count(), 0, "closing dismisses the wizard"); + assert_eq!(h.state().session().settings.get("privacy_welcome_seen").as_deref(), Some("true"), "closing marks setup seen"); + assert!(!installed.get(), "closing does not install the demo notebook"); + assert!(!t.path().join("notebooks/welcome-to-notecraft").exists(), "closing creates no notebook"); +} + +#[test] +fn welcome_notebook_update_prompt_keep_mine_asks_once_per_version() { + let t = TempDir::new("ui-welcome-update-prompt"); + let s = session(&t); + s.settings.set("ui_language", "en").expect("English UI setting"); + let notebooks = t.path().join("notebooks"); + let installed = notebooks.join("welcome-to-notecraft"); + std::fs::create_dir_all(installed.join("00-start/welcome")).expect("installed tree"); + std::fs::write(installed.join("00-start/welcome/index.html"), "my notes").expect("edited page"); + s.settings.set("welcome_notebook_version", "0.0.29").expect("old version"); + s.settings.set("welcome_notebook_manifest", "stale").expect("stale manifest"); + let mut app = NoteCraftApp::new(s).with_welcome_notebook_setup(|_, _| Err("must not install".to_string())); + app.check_welcome_notebook_update("0.0.30"); + let mut h = harness(app, LIGHT); + h.get_by_label("Keep mine").click(); + settle(&mut h); + assert_eq!(h.query_all_by_label("Keep mine").count(), 0, "Keep mine closes the prompt"); + assert_eq!(h.state().session().settings.get("welcome_notebook_prompted_version").as_deref(), Some("0.0.30"), "keeping records the version"); + assert_eq!( + std::fs::read_to_string(installed.join("00-start/welcome/index.html")).expect("kept page"), + "my notes", + "keeping does not replace the notebook" + ); +} + #[test] fn an_empty_notebooks_folder_stays_empty_when_the_app_opens() { let t = TempDir::new("ui-empty-notebooks"); diff --git a/i18n/en.tsv b/i18n/en.tsv index c9aa63c2b..22b5d994f 100644 --- a/i18n/en.tsv +++ b/i18n/en.tsv @@ -952,6 +952,10 @@ @id ui.welcome_notebook_add_yes Yes, add it @id ui.welcome_notebook_add_no No, not now @id ui.welcome_notebook_action_failed Could not update the Welcome notebook: {error} +@id ui.welcome_notebook_update_title Update the Welcome notebook? +@id ui.welcome_notebook_update_body A new Welcome notebook is available in this release (version {version}). Your copy was changed, so updating will replace it. +@id ui.welcome_notebook_update Update +@id ui.welcome_notebook_keep_mine Keep mine @id ui.welcome_wizard_back Back @id ui.welcome_wizard_finish Finish @id ui.welcome_wizard_done_title Thank you From d262fe3f2361eb0cae4fa2f2ba058157a655142b Mon Sep 17 00:00:00 2001 From: alientechsw <43017062+alientechsw@users.noreply.github.com> Date: Sat, 5 Dec 2026 13:56:47 -0800 Subject: [PATCH 4/7] fix(ui): guard Welcome update, retry failure, real installer tests --- android/src/activity.rs | 6 +- apps/notecraft-setup/src/lib.rs | 263 ++++++++++++++++++++++++++++++-- apps/notecraft/src/main.rs | 6 +- crates/store/src/lib.rs | 2 + crates/store/src/tree_hash.rs | 157 +++++++++++++++++++ crates/ui-egui/Cargo.toml | 2 + crates/ui-egui/src/app.rs | 179 +++++++++++++--------- crates/ui-egui/tests/ui.rs | 28 ++-- 8 files changed, 545 insertions(+), 98 deletions(-) create mode 100644 crates/store/src/tree_hash.rs diff --git a/android/src/activity.rs b/android/src/activity.rs index 3ad0a1973..21e65dae3 100644 --- a/android/src/activity.rs +++ b/android/src/activity.rs @@ -71,8 +71,10 @@ fn run(app: AndroidApp) -> Result<(), String> { let setup_payload: PathBuf = payload.clone(); let mut app = NoteCraftApp::new(session) .with_default_notebooks_root(layout.notebooks) - .with_welcome_notebook_setup(move |notebooks_root, format| { - notecraft_setup::install_edition(&setup_payload, notebooks_root, format).map_err(|error| error.to_string()) + .with_welcome_notebook_setup(move |notebooks_root, format, expected_manifest| match expected_manifest { + Some(expected) => notecraft_setup::install_edition_if_unchanged(&setup_payload, notebooks_root, format, expected) + .map_err(|error| error.to_string()), + None => notecraft_setup::install_edition(&setup_payload, notebooks_root, format).map(Some).map_err(|error| error.to_string()), }) .with_clipboard(clipboard); for (key, message) in alerts.drain(..) { diff --git a/apps/notecraft-setup/src/lib.rs b/apps/notecraft-setup/src/lib.rs index a3b9ab614..db3ca9e58 100644 --- a/apps/notecraft-setup/src/lib.rs +++ b/apps/notecraft-setup/src/lib.rs @@ -1,3 +1,4 @@ +use notecraft_store::{TreeSnapshot, file_hash, snapshot_tree, tree_manifest}; use std::io; use std::path::{Path, PathBuf}; @@ -15,6 +16,39 @@ pub fn macos_dmg_payload(executable: &Path) -> Option { /// notebook folder, so the notebook list finds it. Other notebooks in `notebooks_root` are never /// visited or changed. Returns the installed notebook folder. pub fn install_edition(payload: &Path, notebooks_root: &Path, format: &str) -> io::Result { + match install_guarded(payload, notebooks_root, format, None)? { + Some(installed) => Ok(installed), + None => Err(io::Error::new(io::ErrorKind::Other, "the install reported no replacement")), + } +} + +/// Installs one generated edition, but only when the installed tree still matches +/// `expected_manifest`, the manifest recorded when it was installed. A note that landed +/// in the tree while the new edition was staged is never silently replaced: the install +/// reports no replacement and the installed tree is left as it was, so the caller can +/// ask the person instead. Returns the installed notebook folder, or `None` when the +/// tree changed. +pub fn install_edition_if_unchanged( + payload: &Path, + notebooks_root: &Path, + format: &str, + expected_manifest: &str, +) -> io::Result> { + install_guarded(payload, notebooks_root, format, Some(expected_manifest)) +} + +/// The shared install: stages the new edition, then swaps it in for the installed +/// tree. With an expected manifest, the installed tree must still match it when the +/// swap happens. The tree is checked once the staging copy is done, and the displaced +/// tree is checked again after the swap, before its backup is deleted: a write that +/// landed between the first check and the swap is caught by the second check, and the +/// previous tree is restored. A tree that cannot be read counts as changed. +fn install_guarded( + payload: &Path, + notebooks_root: &Path, + format: &str, + expected_manifest: Option<&str>, +) -> io::Result> { validate_edition(payload, format)?; let destination = notebooks_root.join(NOTEBOOK_NAME); if std::fs::symlink_metadata(&destination).is_ok_and(|metadata| metadata.file_type().is_symlink()) { @@ -29,6 +63,13 @@ pub fn install_edition(payload: &Path, notebooks_root: &Path, format: &str) -> i return Err(error); } let had_previous = destination.exists(); + if had_previous && let Some(expected) = expected_manifest { + let unchanged = tree_manifest(&destination).is_ok_and(|current| current == expected); + if !unchanged { + remove_tree_if_present(&staging); + return Ok(None); + } + } if had_previous && let Err(error) = rename_with_retry(&destination, &backup) { // On Windows a folder cannot be moved while a file under it is open, by NoteCraft // itself, a virus scanner, a search indexer or a sync client: "Access is denied" @@ -38,9 +79,19 @@ pub fn install_edition(payload: &Path, notebooks_root: &Path, format: &str) -> i remove_tree_if_present(&staging); return Err(error); } - let replaced = replace_in_place(&staging, &destination); + let snapshot = match expected_manifest { + Some(_) => match snapshot_tree(&destination) { + Ok(snapshot) => Some(snapshot), + Err(_) => { + remove_tree_if_present(&staging); + return Ok(None); + } + }, + None => None, + }; + let replaced = replace_in_place(&staging, &destination, snapshot.as_ref())?; remove_tree_if_present(&staging); - return replaced.map(|()| destination); + return Ok(replaced.then_some(destination)); } if let Err(error) = rename_with_retry(&staging, &destination) { if had_previous { @@ -49,8 +100,38 @@ pub fn install_edition(payload: &Path, notebooks_root: &Path, format: &str) -> i remove_tree_if_present(&staging); return Err(error); } - remove_tree_if_present(&backup); - Ok(destination) + if had_previous { + match expected_manifest { + Some(expected) => { + let unchanged = tree_manifest(&backup).is_ok_and(|current| current == expected); + if unchanged { + remove_tree_if_present(&backup); + } else { + restore_displaced(&destination, &backup, notebooks_root)?; + return Ok(None); + } + } + None => remove_tree_if_present(&backup), + } + } + Ok(Some(destination)) +} + +/// Moves the displaced tree back over a replacement that must not stand: the new +/// tree goes aside first, the displaced tree moves back, then the new tree is +/// dropped. When a move fails the displaced tree is left in place for recovery +/// and the failure is reported instead of deleting anything. +fn restore_displaced(destination: &Path, backup: &Path, notebooks_root: &Path) -> io::Result<()> { + let discarded = notebooks_root.join(format!(".{NOTEBOOK_NAME}-discarded-{}", unique_suffix())); + if rename_with_retry(destination, &discarded).is_err() || rename_with_retry(backup, destination).is_err() { + let _ = rename_with_retry(&discarded, destination); + return Err(io::Error::new( + io::ErrorKind::Other, + "the Welcome notebook changed while the update was prepared and the previous copy could not be restored; the previous copy is kept beside the notebooks folder", + )); + } + remove_tree_if_present(&discarded); + Ok(()) } /// Renames, trying again for a few seconds while the system refuses with "Access is denied". @@ -75,25 +156,48 @@ fn rename_with_retry(from: &Path, to: &Path) -> io::Result<()> { /// Makes `destination` hold exactly what `staging` holds, without moving `destination` itself: /// every staged file is written over its counterpart, and what the new edition no longer has is /// removed. A file that cannot be removed is left; a file that cannot be written fails the install. -fn replace_in_place(staging: &Path, destination: &Path) -> io::Result<()> { +/// +/// With a snapshot, the destination is checked before each file is written over, before a +/// directory or file is removed to make way for the other kind, and before the new edition's +/// leftovers are removed: a note that landed while the new edition was staged stops the +/// replacement at once instead of being overwritten or removed. The tree is then left partly +/// replaced, so the caller can ask the person instead of silently finishing. Returns false +/// in that case. +fn replace_in_place(staging: &Path, destination: &Path, snapshot: Option<&TreeSnapshot>) -> io::Result { + replace_dir(staging, destination, Path::new(""), snapshot) +} + +fn replace_dir(staging: &Path, destination: &Path, relative: &Path, snapshot: Option<&TreeSnapshot>) -> io::Result { let mut wanted = std::collections::HashSet::new(); for entry in std::fs::read_dir(staging)? { let entry = entry?; let name = entry.file_name(); let target = destination.join(&name); + let entry_relative = relative.join(&name); wanted.insert(name); if entry.file_type()?.is_dir() { if target.is_file() { + if snapshot.is_some_and(|guard| !target_still_matches(guard, &target, &entry_relative)) { + return Ok(false); + } std::fs::remove_file(&target)?; } if !target.is_dir() { std::fs::create_dir(&target)?; } - replace_in_place(&entry.path(), &target)?; + if !replace_dir(&entry.path(), &target, &entry_relative, snapshot)? { + return Ok(false); + } } else { if target.is_dir() { + if snapshot.is_some_and(|guard| !subtree_still_matches(guard, &target, &entry_relative)) { + return Ok(false); + } std::fs::remove_dir_all(&target)?; } + if target.exists() && snapshot.is_some_and(|guard| !target_still_matches(guard, &target, &entry_relative)) { + return Ok(false); + } make_writable(&target); write_over(&entry.path(), &target)?; } @@ -103,10 +207,64 @@ fn replace_in_place(staging: &Path, destination: &Path) -> io::Result<()> { if wanted.contains(&entry.file_name()) { continue; } + let entry_relative = relative.join(entry.file_name()); + if let Some(snapshot) = snapshot { + if !snapshot.contains(&entry_relative) { + continue; + } + let path = entry.path(); + if entry.file_type().is_ok_and(|kind| kind.is_dir()) { + if !subtree_still_matches(snapshot, &path, &entry_relative) { + return Ok(false); + } + } else if entry.file_type().is_ok_and(|kind| kind.is_file()) && !target_still_matches(snapshot, &path, &entry_relative) { + return Ok(false); + } + } let path = entry.path(); let _ = if entry.file_type().is_ok_and(|kind| kind.is_dir()) { std::fs::remove_dir_all(&path) } else { std::fs::remove_file(&path) }; } - Ok(()) + Ok(true) +} + +/// Whether the file at `target` still holds what the snapshot recorded for +/// `relative`: it must be there, be a regular file, and hash the same. +/// Anything else, a new file, a changed file, a file that cannot be read, +/// counts as changed, never as untouched. +fn target_still_matches(snapshot: &TreeSnapshot, target: &Path, relative: &Path) -> bool { + let Some(expected) = snapshot.file_hash(relative) else { + return false; + }; + file_hash(target).is_ok_and(|current| current == expected) +} + +/// Whether everything under `dir` still holds what the snapshot recorded for +/// `relative`: every file hashes the same and nothing was added. A directory +/// that cannot be listed counts as changed. +fn subtree_still_matches(snapshot: &TreeSnapshot, dir: &Path, relative: &Path) -> bool { + let Ok(entries) = std::fs::read_dir(dir) else { + return false; + }; + for entry in entries { + let Ok(entry) = entry else { + return false; + }; + let entry_relative = relative.join(entry.file_name()); + if !snapshot.contains(&entry_relative) { + return false; + } + let Ok(kind) = entry.file_type() else { + return false; + }; + if kind.is_dir() { + if !subtree_still_matches(snapshot, &entry.path(), &entry_relative) { + return false; + } + } else if kind.is_file() && !target_still_matches(snapshot, &entry.path(), &entry_relative) { + return false; + } + } + true } /// Writes `source` over `target` through the file's own contents, never by deleting or replacing @@ -325,7 +483,7 @@ mod tests { copy_tree(&source.join("html"), &staging).expect("stage the new edition"); fs::write(staging.join("00-start/welcome/index.html"), "new welcome").expect("the new welcome page"); - replace_in_place(&staging, &destination).expect("replace in place"); + assert!(replace_in_place(&staging, &destination, None).expect("replace in place"), "an unguarded replacement replaces the tree"); assert_eq!(fs::read(destination.join("00-start/welcome/index.html")).expect("welcome page"), b"new welcome"); assert!(destination.join("_node.toml").is_file()); @@ -347,7 +505,7 @@ mod tests { copy_tree(&source.join("html"), &staging).expect("stage the new edition"); fs::write(staging.join("00-start/welcome/index.html"), "new welcome").expect("the new welcome page"); - replace_in_place(&staging, &destination).expect("replace in place"); + assert!(replace_in_place(&staging, &destination, None).expect("replace in place"), "an unguarded replacement replaces the tree"); assert_eq!(fs::read(&page).expect("welcome page"), b"new welcome"); } @@ -418,4 +576,91 @@ mod tests { assert_eq!(install_edition(&source, ¬ebooks, "docx").expect_err("reject unknown format").kind(), io::ErrorKind::InvalidInput); assert!(!notebooks.join(NOTEBOOK_NAME).exists()); } + + fn assert_no_leftovers(notebooks: &Path) { + let leftovers: Vec<_> = fs::read_dir(notebooks) + .expect("notebooks folder") + .filter_map(Result::ok) + .filter(|entry| entry.file_name().to_string_lossy().starts_with('.')) + .collect(); + assert!(leftovers.is_empty(), "no staging or backup folder is left behind: {leftovers:?}"); + } + + #[test] + fn guarded_install_replaces_a_matching_tree() { + let (_temp, source, notebooks) = fixture(); + let destination = install_edition(&source, ¬ebooks, "html").expect("initial install"); + fs::write(source.join("html/00-start/welcome/index.html"), "updated HTML").expect("update payload"); + let manifest = notecraft_store::tree_manifest(&destination).expect("manifest"); + + assert_eq!( + install_edition_if_unchanged(&source, ¬ebooks, "html", &manifest).expect("guarded install"), + Some(destination.clone()), + "a tree that still matches its manifest is replaced" + ); + assert_eq!(fs::read(destination.join("00-start/welcome/index.html")).expect("new page"), b"updated HTML"); + assert_no_leftovers(¬ebooks); + } + + #[test] + fn guarded_install_refuses_a_changed_tree_and_keeps_it() { + let (_temp, source, notebooks) = fixture(); + let destination = install_edition(&source, ¬ebooks, "html").expect("initial install"); + let manifest = notecraft_store::tree_manifest(&destination).expect("manifest"); + fs::write(destination.join("00-start/welcome/index.html"), "my notes").expect("edit"); + fs::write(source.join("html/00-start/welcome/index.html"), "updated HTML").expect("update payload"); + + assert_eq!( + install_edition_if_unchanged(&source, ¬ebooks, "html", &manifest).expect("guarded install"), + None, + "a tree that changed since its manifest was recorded is not replaced" + ); + assert_eq!(fs::read(destination.join("00-start/welcome/index.html")).expect("kept page"), b"my notes"); + assert_no_leftovers(¬ebooks); + } + + #[test] + fn guarded_install_refuses_a_tree_with_an_added_file() { + let (_temp, source, notebooks) = fixture(); + let destination = install_edition(&source, ¬ebooks, "html").expect("initial install"); + let manifest = notecraft_store::tree_manifest(&destination).expect("manifest"); + fs::write(destination.join("my-note.txt"), "my note").expect("added file"); + + assert_eq!( + install_edition_if_unchanged(&source, ¬ebooks, "html", &manifest).expect("guarded install"), + None, + "an added file changes the tree, so it is not replaced" + ); + assert_eq!(fs::read(destination.join("my-note.txt")).expect("kept note"), b"my note"); + assert_no_leftovers(¬ebooks); + } + + #[test] + fn guarded_in_place_replacement_stops_when_a_file_changes() { + let (_temp, source, notebooks) = fixture(); + let destination = install_edition(&source, ¬ebooks, "html").expect("initial install"); + let staging = notebooks.join("staged"); + fs::create_dir_all(&staging).expect("staging folder"); + copy_tree(&source.join("html"), &staging).expect("stage the new edition"); + fs::write(staging.join("00-start/welcome/index.html"), "new welcome").expect("the new welcome page"); + let snapshot = notecraft_store::snapshot_tree(&destination).expect("snapshot"); + fs::write(destination.join("00-start/welcome/index.html"), "my notes").expect("a note that lands during staging"); + + assert!(!replace_in_place(&staging, &destination, Some(&snapshot)).expect("guarded replacement"), "a changed file stops the replacement"); + assert_eq!(fs::read(destination.join("00-start/welcome/index.html")).expect("kept page"), b"my notes"); + } + + #[test] + fn guarded_in_place_replacement_replaces_an_unchanged_tree() { + let (_temp, source, notebooks) = fixture(); + let destination = install_edition(&source, ¬ebooks, "html").expect("initial install"); + let staging = notebooks.join("staged"); + fs::create_dir_all(&staging).expect("staging folder"); + copy_tree(&source.join("html"), &staging).expect("stage the new edition"); + fs::write(staging.join("00-start/welcome/index.html"), "new welcome").expect("the new welcome page"); + let snapshot = notecraft_store::snapshot_tree(&destination).expect("snapshot"); + + assert!(replace_in_place(&staging, &destination, Some(&snapshot)).expect("guarded replacement"), "an unchanged tree is replaced"); + assert_eq!(fs::read(destination.join("00-start/welcome/index.html")).expect("new page"), b"new welcome"); + } } diff --git a/apps/notecraft/src/main.rs b/apps/notecraft/src/main.rs index c60846449..3b7c6d853 100644 --- a/apps/notecraft/src/main.rs +++ b/apps/notecraft/src/main.rs @@ -341,8 +341,10 @@ fn main() -> eframe::Result { Box::new(move |cc| { let setup_payload = payload.clone(); let mut app = NoteCraftApp::new(session) - .with_welcome_notebook_setup(move |notebooks_root, format| { - notecraft_setup::install_edition(&setup_payload, notebooks_root, format).map_err(|error| error.to_string()) + .with_welcome_notebook_setup(move |notebooks_root, format, expected_manifest| match expected_manifest { + Some(expected) => notecraft_setup::install_edition_if_unchanged(&setup_payload, notebooks_root, format, expected) + .map_err(|error| error.to_string()), + None => notecraft_setup::install_edition(&setup_payload, notebooks_root, format).map(Some).map_err(|error| error.to_string()), }) .with_clipboard(clipboard); // A newer bundled Welcome notebook replaces the installed copy when it is diff --git a/crates/store/src/lib.rs b/crates/store/src/lib.rs index 4c6f61bdc..ac2bd16b4 100644 --- a/crates/store/src/lib.rs +++ b/crates/store/src/lib.rs @@ -32,10 +32,12 @@ pub mod spoken; pub mod tags; pub mod testing; pub mod tree; +pub mod tree_hash; pub use error::{Result, StoreError}; pub use notecraft_model::{NodeKind, PageFormat}; pub use settings::{FormatSource, Settings}; pub use tree::{Node, NodeInfo}; +pub use tree_hash::{TreeSnapshot, file_hash, snapshot_tree, tree_manifest}; pub mod coordination; diff --git a/crates/store/src/tree_hash.rs b/crates/store/src/tree_hash.rs new file mode 100644 index 000000000..47be6dc7f --- /dev/null +++ b/crates/store/src/tree_hash.rs @@ -0,0 +1,157 @@ +//! A hash of a directory tree, for telling whether the tree changed since it +//! was recorded. The Welcome notebook update uses it: the manifest recorded +//! when the notebook was installed is compared with the installed tree, so +//! an untouched notebook updates silently and an edited one asks first. +//! +//! Sorted relative paths; each file contributes its contents' hash, each +//! directory and link its path, so a file the person added, or a link they +//! made, counts as a change. Contents only: times and permissions do not +//! matter. A read failure is an error, so a tree that cannot be read is +//! treated as changed, never as untouched. + +use std::io; +use std::path::{Path, PathBuf}; + +/// What one entry of a directory tree holds: a regular file's contents hash, +/// a directory, or a link's target. +#[derive(Debug, Clone, PartialEq, Eq)] +enum Entry { + File(String), + Dir, + Link(PathBuf), +} + +/// The state of a directory tree: every entry in traversal order (depth-first, +/// entries sorted in each directory), so the aggregate hash is stable. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TreeSnapshot { + entries: Vec<(PathBuf, Entry)>, +} + +impl TreeSnapshot { + /// The aggregate SHA-256 of the recorded tree: each file contributes a + /// line with its contents' hash, each directory and link a line with its + /// path, in traversal order. + pub fn manifest(&self) -> String { + use sha2::Digest; + let mut hasher = sha2::Sha256::new(); + for (relative, entry) in &self.entries { + let relative = relative.to_string_lossy(); + match entry { + Entry::File(hash) => hasher.update(format!("F {relative} {hash}\n")), + Entry::Dir => hasher.update(format!("D {relative}\n")), + Entry::Link(target) => hasher.update(format!("L {relative} -> {}\n", target.display())), + } + } + format!("{:x}", hasher.finalize()) + } + + /// The recorded contents hash of one regular file, if the snapshot holds it. + pub fn file_hash(&self, relative: &Path) -> Option<&str> { + self.entries.iter().find_map(|(path, entry)| match entry { + Entry::File(hash) if path == relative => Some(hash.as_str()), + _ => None, + }) + } + + /// Whether the snapshot holds any entry at this relative path. + pub fn contains(&self, relative: &Path) -> bool { + self.entries.iter().any(|(path, _)| path == relative) + } +} + +/// Reads a directory tree into a snapshot. See the module docs for what counts. +pub fn snapshot_tree(dir: &Path) -> io::Result { + let mut entries = Vec::new(); + visit(dir, dir, &mut entries)?; + Ok(TreeSnapshot { entries }) +} + +/// The aggregate SHA-256 of a directory tree, for telling whether it changed. +/// See the module docs; a read failure is an error. +pub fn tree_manifest(dir: &Path) -> io::Result { + Ok(snapshot_tree(dir)?.manifest()) +} + +/// The SHA-256 of one file's contents. +pub fn file_hash(path: &Path) -> io::Result { + use sha2::Digest; + let mut file = std::fs::File::open(path).map_err(|error| io::Error::new(error.kind(), format!("could not read {}: {error}", path.display())))?; + let mut hasher = sha2::Sha256::new(); + std::io::copy(&mut file, &mut hasher).map_err(|error| io::Error::new(error.kind(), format!("could not read {}: {error}", path.display())))?; + Ok(format!("{:x}", hasher.finalize())) +} + +fn visit(dir: &Path, base: &Path, entries: &mut Vec<(PathBuf, Entry)>) -> io::Result<()> { + let mut paths: Vec = std::fs::read_dir(dir) + .map_err(|error| io::Error::new(error.kind(), format!("could not list {}: {error}", dir.display())))? + .collect::>>() + .map_err(|error| io::Error::new(error.kind(), format!("could not list {}: {error}", dir.display())))? + .into_iter() + .map(|entry| entry.path()) + .collect(); + paths.sort(); + for path in paths { + let relative = path + .strip_prefix(base) + .map_err(|_| io::Error::new(io::ErrorKind::Other, format!("{} is not under {}", path.display(), base.display())))? + .to_path_buf(); + let kind = std::fs::symlink_metadata(&path) + .map_err(|error| io::Error::new(error.kind(), format!("could not read {}: {error}", path.display())))?; + if kind.file_type().is_symlink() { + let target = std::fs::read_link(&path) + .map_err(|error| io::Error::new(error.kind(), format!("could not read {}: {error}", path.display())))?; + entries.push((relative, Entry::Link(target))); + } else if kind.is_dir() { + entries.push((relative, Entry::Dir)); + visit(&path, base, entries)?; + } else { + entries.push((relative, Entry::File(file_hash(&path)?))); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testing::TempDir; + use std::fs; + + fn tree(dir: &Path) { + fs::create_dir_all(dir.join("00-start/welcome")).expect("tree"); + fs::write(dir.join("00-start/welcome/index.html"), "welcome").expect("page"); + fs::write(dir.join("_node.toml"), "node").expect("node"); + } + + #[test] + fn a_manifest_tells_changed_files_apart() { + let temp = TempDir::new("tree-hash-manifest"); + let first = temp.path().join("first"); + let second = temp.path().join("second"); + tree(&first); + tree(&second); + let manifest = tree_manifest(&first).expect("manifest"); + assert_eq!(tree_manifest(&second).expect("same tree"), manifest, "identical trees share a manifest"); + fs::write(second.join("00-start/welcome/index.html"), "welcome, edited").expect("edit"); + assert_ne!(tree_manifest(&second).expect("changed tree"), manifest, "an edited page changes the manifest"); + fs::write(second.join("00-start/welcome/index.html"), "welcome").expect("restore"); + fs::write(second.join("extra.txt"), "added").expect("added file"); + assert_ne!(tree_manifest(&second).expect("added file"), manifest, "an added file changes the manifest"); + } + + #[test] + fn a_snapshot_records_each_file_and_its_paths() { + let temp = TempDir::new("tree-hash-snapshot"); + let dir = temp.path().join("tree"); + tree(&dir); + let snapshot = snapshot_tree(&dir).expect("snapshot"); + let page = Path::new("00-start/welcome/index.html"); + let recorded = file_hash(&dir.join(page)).expect("file hash"); + assert_eq!(snapshot.file_hash(page), Some(recorded.as_str()), "a file's recorded hash matches its contents"); + assert_eq!(snapshot.file_hash(Path::new("missing.txt")), None, "a missing file has no recorded hash"); + assert!(snapshot.contains(Path::new("00-start/welcome")), "a directory is recorded"); + assert!(!snapshot.contains(Path::new("missing")), "a missing path is not recorded"); + assert_eq!(snapshot.manifest(), tree_manifest(&dir).expect("manifest"), "the snapshot and the tree share a manifest"); + } +} diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index c8951003f..47cfa7eba 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -90,6 +90,8 @@ notecraft-ocr = { workspace = true } egui-wgpu = "0.37" # Live captions' tests script what the recogniser says (issue #300). craft-voice-core = { workspace = true } +# The Welcome notebook tests install the real bundled edition instead of stubbing the installer. +notecraft-setup = { path = "../../apps/notecraft-setup" } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 7d1330de0..dd2b2ace0 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -2346,7 +2346,7 @@ pub struct NoteCraftApp { #[cfg(all(not(target_arch = "wasm32"), not(target_os = "android")))] playback: Option, open_attachment_warning_suppressed: bool, - welcome_notebook_setup: Option Result>>, + welcome_notebook_setup: Option) -> Result, String>>>, } impl NoteCraftApp { @@ -2633,10 +2633,15 @@ impl NoteCraftApp { } /// Installs the application-owned action behind the Welcome notebook step of the first-use - /// wizard. The callback gets the notebooks folder and the chosen format id, and returns the - /// installed notebook folder. The wizard opens once: on the first launch after installation, or + /// wizard. The callback gets the notebooks folder, the chosen format id, and, for an + /// upgrade, the manifest recorded when the notebook was installed; it returns the + /// installed notebook folder, or nothing when the guarded upgrade found the tree + /// changed and replaced nothing. The wizard opens once: on the first launch after installation, or /// after the preferences are reset. It does not reopen for later versions. - pub fn with_welcome_notebook_setup(mut self, setup: impl FnMut(&Path, &str) -> Result + 'static) -> Self { + pub fn with_welcome_notebook_setup( + mut self, + setup: impl FnMut(&Path, &str, Option<&str>) -> Result, String> + 'static, + ) -> Self { self.welcome_notebook_setup = Some(Box::new(setup)); self } @@ -2677,19 +2682,44 @@ impl NoteCraftApp { /// it was installed; a failed record leaves it unrecorded, and the next update asks /// instead of silently replacing. fn install_welcome_notebook(&mut self, format: PageFormat) -> Result { + let installed = self + .run_welcome_notebook_setup(format, None)? + .ok_or_else(|| "the bundled Welcome notebook setup reported no install".to_string())?; + self.finish_welcome_notebook_install(&installed); + Ok(installed) + } + + /// Replaces the installed Welcome notebook only when it still matches the + /// manifest recorded when it was installed. Returns `None` when the tree + /// changed while the new edition was staged: nothing was replaced, so the + /// caller can ask the person instead of silently replacing their work. + fn update_welcome_notebook(&mut self, format: PageFormat, expected_manifest: &str) -> Result, String> { + let installed = self.run_welcome_notebook_setup(format, Some(expected_manifest))?; + if let Some(installed) = &installed { + self.finish_welcome_notebook_install(installed); + } + Ok(installed) + } + + /// Runs the bundled Welcome notebook setup for one format, after saving the + /// open page. The expected manifest guards an upgrade: with one, the setup + /// replaces nothing when the installed tree changed since it was recorded. + fn run_welcome_notebook_setup(&mut self, format: PageFormat, expected_manifest: Option<&str>) -> Result, String> { self.save_now(); if self.is_dirty() { return Err("the current page could not be saved before replacing the Welcome notebook".to_string()); } - let installed = { - let setup = self.welcome_notebook_setup.as_mut().ok_or_else(|| "the bundled Welcome notebook setup is unavailable".to_string())?; - setup(self.session.root(), format.id())? - }; + let setup = self.welcome_notebook_setup.as_mut().ok_or_else(|| "the bundled Welcome notebook setup is unavailable".to_string())?; + setup(self.session.root(), format.id(), expected_manifest) + } + + /// Clears the editor after a Welcome notebook install and records the + /// installed version and manifest. + fn finish_welcome_notebook_install(&mut self, installed: &Path) { self.editor = None; self.pad = None; self.session.refresh(); - Self::record_welcome_notebook(&self.session.settings, &installed); - Ok(installed) + Self::record_welcome_notebook(&self.session.settings, installed); } /// Records the installed Welcome notebook's version and manifest. Best-effort: a @@ -2709,45 +2739,11 @@ impl NoteCraftApp { } /// Aggregate SHA-256 of a directory tree, for telling whether the installed Welcome - /// notebook was changed since it was installed. Sorted relative paths; each file - /// contributes its contents' hash, each directory and link its path, so a file the - /// person added, or a link they made, counts as a change. Contents only: times and - /// permissions do not matter. A read failure is an error, so a tree that cannot be - /// read is treated as changed, never as untouched. + /// notebook was changed since it was installed. See `notecraft_store::tree_manifest`: + /// a read failure is an error, so a tree that cannot be read is treated as changed, + /// never as untouched. fn welcome_notebook_manifest(dir: &Path) -> Result { - use sha2::Digest; - fn visit(dir: &Path, base: &Path, hasher: &mut sha2::Sha256) -> Result<(), String> { - use sha2::Digest; - let mut entries: Vec = std::fs::read_dir(dir) - .map_err(|error| format!("could not list {}: {error}", dir.display()))? - .collect::, _>>() - .map_err(|error| format!("could not list {}: {error}", dir.display()))? - .into_iter() - .map(|entry| entry.path()) - .collect(); - entries.sort(); - for path in entries { - let relative = path.strip_prefix(base).map_err(|_| format!("{} is not under {}", path.display(), base.display()))?; - let relative = relative.to_string_lossy(); - let kind = std::fs::symlink_metadata(&path).map_err(|error| format!("could not read {}: {error}", path.display()))?; - if kind.file_type().is_symlink() { - let target = std::fs::read_link(&path).map_err(|error| format!("could not read {}: {error}", path.display()))?; - hasher.update(format!("L {relative} -> {}\n", target.display())); - } else if kind.is_dir() { - hasher.update(format!("D {relative}\n")); - visit(&path, base, hasher)?; - } else { - let mut file = std::fs::File::open(&path).map_err(|error| format!("could not read {}: {error}", path.display()))?; - let mut file_hasher = sha2::Sha256::new(); - std::io::copy(&mut file, &mut file_hasher).map_err(|error| format!("could not read {}: {error}", path.display()))?; - hasher.update(format!("F {relative} {:x}\n", file_hasher.finalize())); - } - } - Ok(()) - } - let mut hasher = sha2::Sha256::new(); - visit(dir, dir, &mut hasher)?; - Ok(format!("{:x}", hasher.finalize())) + notecraft_store::tree_manifest(dir).map_err(|error| error.to_string()) } /// The edition the installed Welcome notebook is in: the welcome page's file says @@ -2770,6 +2766,8 @@ impl NoteCraftApp { /// /// When the installed copy is untouched, it is replaced silently. When it was /// changed, or its version was never recorded, a prompt asks once for this version. + /// A change that lands while the new edition is staged is caught the same way: + /// the replacement is refused and the prompt asks instead. /// A missing notebook, or a bundled version that is not newer, does nothing. The /// check runs at startup, whatever installed the app: it reads the installed /// version from settings, never an installer marker. @@ -2793,19 +2791,29 @@ impl NoteCraftApp { if !crate::update::is_newer(&bundled, &installed_version) { return; } - let untouched = match self.session.settings.get(WELCOME_NOTEBOOK_MANIFEST_KEY) { - Some(stored) => Self::welcome_notebook_manifest(&installed_dir).is_ok_and(|current| current == stored), + let stored_manifest = self.session.settings.get(WELCOME_NOTEBOOK_MANIFEST_KEY); + let untouched = match &stored_manifest { + Some(stored) => Self::welcome_notebook_manifest(&installed_dir).is_ok_and(|current| current == *stored), None => false, }; if untouched { - if let Err(error) = self.install_welcome_notebook(self.installed_welcome_format()) { - self.alert( - "welcome-notebook-update", - "NoteCraft", - &crate::i18n::format_message_id("ui.welcome_notebook_action_failed", &[("error", &error)]), - ); + if let Some(expected) = stored_manifest.as_deref() { + match self.update_welcome_notebook(self.installed_welcome_format(), expected) { + Ok(Some(_)) => return, + Ok(None) => { + // The tree changed while the new edition was staged: fall + // through and ask instead of silently replacing it. + } + Err(error) => { + self.alert( + "welcome-notebook-update", + "NoteCraft", + &crate::i18n::format_message_id("ui.welcome_notebook_action_failed", &[("error", &error)]), + ); + return; + } + } } - return; } if self.session.settings.get(WELCOME_NOTEBOOK_PROMPTED_VERSION_KEY).as_deref() == Some(bundled_version.as_str()) { return; @@ -16111,7 +16119,13 @@ impl NoteCraftApp { if update { match self.install_welcome_notebook(self.installed_welcome_format()) { Ok(_) => keep = false, - Err(message) => *error = Some(message), + Err(message) => { + // A failed Update is offered again after restart: clear the + // asked-for-this-version marker instead of suppressing it. + // Keep mine still records the version, so it is not asked again. + let _ = self.session.settings.set(WELCOME_NOTEBOOK_PROMPTED_VERSION_KEY, ""); + *error = Some(message); + } } } } @@ -20014,19 +20028,20 @@ mod alert_tests { let settings = notecraft_store::Settings::at(t.path().join("settings.toml")); settings.set("privacy_welcome_seen", "true").expect("settings"); let upgraded = Session::new(&t.path().join("notebooks"), settings.clone()).expect("upgraded session"); - let upgraded = NoteCraftApp::new(upgraded).with_welcome_notebook_setup(|root, _format| Ok(root.join("welcome-to-notecraft"))); + let upgraded = NoteCraftApp::new(upgraded) + .with_welcome_notebook_setup(|root, _format, _expected| Ok(Some(root.join("welcome-to-notecraft")))); assert!(upgraded.dialog.is_none(), "an existing user is not shown the wizard again for a later version"); // A fresh install opens the wizard at the welcome page; finishing it saves every answer. let fresh = notecraft_store::Settings::at(t.path().join("fresh.toml")); let session = Session::new(&t.path().join("fresh-notebooks"), fresh.clone()).expect("fresh session"); - let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(|root, _format| Ok(root.join("welcome-to-notecraft"))); + let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(|root, _format, _expected| Ok(Some(root.join("welcome-to-notecraft")))); assert!(matches!(app.dialog, Some(Dialog::FirstUseWizard { step: 0, .. })), "a fresh install starts at the welcome page"); assert!(app.finish_first_use_wizard("none", PageFormat::Html, false).is_ok()); assert_eq!(fresh.get("privacy_welcome_seen").as_deref(), Some("true")); let again = Session::new(&t.path().join("fresh-notebooks"), fresh).expect("reopened session"); - let again = NoteCraftApp::new(again).with_welcome_notebook_setup(|root, _format| Ok(root.join("welcome-to-notecraft"))); + let again = NoteCraftApp::new(again).with_welcome_notebook_setup(|root, _format, _expected| Ok(Some(root.join("welcome-to-notecraft")))); assert!(again.dialog.is_none(), "a finished wizard does not open again"); } @@ -20035,7 +20050,7 @@ mod alert_tests { let t = notecraft_store::testing::TempDir::new("welcome-prompt-after-privacy"); let settings = notecraft_store::Settings::at(t.path().join("settings.toml")); let session = Session::new(&t.path().join("notebooks"), settings).expect("session"); - let app = NoteCraftApp::new(session).with_welcome_notebook_setup(|root, _format| Ok(root.join("welcome-to-notecraft"))); + let app = NoteCraftApp::new(session).with_welcome_notebook_setup(|root, _format, _expected| Ok(Some(root.join("welcome-to-notecraft")))); assert!(matches!(app.dialog, Some(Dialog::FirstUseWizard { step: 0, .. })), "the wizard opens at the logging step"); assert!(app.queued_alerts.is_empty(), "the wizard is one window, so nothing waits behind it"); @@ -20059,7 +20074,7 @@ mod alert_tests { let settings = notecraft_store::Settings::at(t.path().join("settings.toml")); settings.set("privacy_welcome_seen", "true").expect("settings"); let session = Session::new(&t.path().join("notebooks"), settings.clone()).expect("session"); - let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(|_, _| Err("copy failed".to_string())); + let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(|_, _, _| Err("copy failed".to_string())); assert!(app.finish_first_use_wizard("none", PageFormat::Cmgfm, true).is_err()); @@ -20074,11 +20089,11 @@ mod alert_tests { let session = Session::new(&t.path().join("notebooks"), settings.clone()).expect("session"); let installed_format = std::rc::Rc::new(std::cell::RefCell::new(String::new())); let recorder = installed_format.clone(); - let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(move |root, format| { + let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(move |root, format, _expected| { *recorder.borrow_mut() = format.to_string(); let installed = root.join("welcome-to-notecraft"); std::fs::create_dir_all(installed.join("00-start/welcome")).map_err(|error| error.to_string())?; - Ok(installed) + Ok(Some(installed)) }); // Opening the fake folder's page can fail; the full install and open path is covered by the UI test. @@ -20111,11 +20126,11 @@ mod alert_tests { let t = notecraft_store::testing::TempDir::new("welcome-record-install"); let settings = notecraft_store::Settings::at(t.path().join("settings.toml")); let session = Session::new(&t.path().join("notebooks"), settings.clone()).expect("session"); - let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(|root, _format| { + let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(|root, _format, _expected| { let installed = root.join("welcome-to-notecraft"); std::fs::create_dir_all(installed.join("00-start/welcome")).map_err(|error| error.to_string())?; std::fs::write(installed.join("00-start/welcome/index.html"), "welcome").map_err(|error| error.to_string())?; - Ok(installed) + Ok(Some(installed)) }); // Opening the fake folder's page can fail; the install and its record happen first. let _ = app.finish_first_use_wizard("none", PageFormat::Html, true); @@ -20141,11 +20156,11 @@ mod alert_tests { settings.set("welcome_notebook_version", "0.0.29").expect("old version"); settings.set("welcome_notebook_manifest", &manifest).expect("manifest"); let session = Session::new(¬ebooks, settings.clone()).expect("session"); - let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(move |root, _format| { + let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(move |root, _format, _expected| { let installed = root.join("welcome-to-notecraft"); std::fs::create_dir_all(installed.join("00-start/welcome")).map_err(|error| error.to_string())?; std::fs::write(installed.join("00-start/welcome/index.html"), "new welcome").map_err(|error| error.to_string())?; - Ok(installed) + Ok(Some(installed)) }); app.check_welcome_notebook_update("0.0.30"); assert!(app.dialog.is_none(), "an untouched notebook updates without asking"); @@ -20174,7 +20189,7 @@ mod alert_tests { let called = std::rc::Rc::new(std::cell::Cell::new(false)); let called_flag = called.clone(); let session = Session::new(¬ebooks, settings.clone()).expect("session"); - let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(move |_, _| { + let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(move |_, _, _| { called_flag.set(true); Err("must not install".to_string()) }); @@ -20201,7 +20216,7 @@ mod alert_tests { settings.set("welcome_notebook_version", "0.0.29").expect("old version"); settings.set("welcome_notebook_manifest", "stale").expect("stale manifest"); let session = Session::new(¬ebooks, settings.clone()).expect("session"); - let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(|_, _| Err("must not install".to_string())); + let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(|_, _, _| Err("must not install".to_string())); app.check_welcome_notebook_update("0.0.30"); assert!(matches!(app.dialog, Some(Dialog::WelcomeNotebookUpdate { .. })), "asks the first time"); app.dialog = None; @@ -20214,6 +20229,28 @@ mod alert_tests { ); } + #[test] + fn welcome_notebook_update_asks_when_the_tree_changed_during_staging() { + let t = notecraft_store::testing::TempDir::new("welcome-update-changed"); + let settings = notecraft_store::Settings::at(t.path().join("settings.toml")); + settings.set("privacy_welcome_seen", "true").expect("settings"); + let notebooks = t.path().join("notebooks"); + let installed = notebooks.join("welcome-to-notecraft"); + std::fs::create_dir_all(installed.join("00-start/welcome")).expect("installed tree"); + std::fs::write(installed.join("00-start/welcome/index.html"), "old welcome").expect("old page"); + let manifest = NoteCraftApp::welcome_notebook_manifest(&installed).expect("manifest"); + settings.set("welcome_notebook_version", "0.0.29").expect("old version"); + settings.set("welcome_notebook_manifest", &manifest).expect("manifest"); + let session = Session::new(¬ebooks, settings.clone()).expect("session"); + let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(|_, _, _| Ok(None)); + app.check_welcome_notebook_update("0.0.30"); + assert!( + matches!(app.dialog, Some(Dialog::WelcomeNotebookUpdate { ref version, .. }) if version == "0.0.30"), + "a tree that changed during staging asks instead of silently replacing" + ); + assert_eq!(std::fs::read_to_string(installed.join("00-start/welcome/index.html")).expect("kept page"), "old welcome"); + } + /// `--first-use` writes `privacy_welcome_seen = ""` and keeps every other setting. #[test] fn first_use_flag_value_opens_setup_with_the_saved_choices() { diff --git a/crates/ui-egui/tests/ui.rs b/crates/ui-egui/tests/ui.rs index 72d016914..63da7f46b 100644 --- a/crates/ui-egui/tests/ui.rs +++ b/crates/ui-egui/tests/ui.rs @@ -2448,7 +2448,7 @@ fn the_first_use_wizard_fits_a_phone_and_every_step_can_be_reached() { let s = session(&t); s.settings.set("ui_language", "en").expect("English UI setting"); s.settings.set("privacy_welcome_seen", "").expect("first use: the wizard opens"); - let app = NoteCraftApp::new(s).with_welcome_notebook_setup(|root, _format| Ok(root.join("welcome-to-notecraft"))); + let app = NoteCraftApp::new(s).with_welcome_notebook_setup(|root, _format, _expected| Ok(Some(root.join("welcome-to-notecraft")))); let size = egui::vec2(360.0, 740.0); let mut h = sized_harness(app, LIGHT, size); settle(&mut h); @@ -2481,13 +2481,13 @@ fn welcome_notebook_prompt_can_replace_and_open_the_release_copy() { let destination = notebooks.join("welcome-to-notecraft"); std::fs::create_dir_all(&destination).expect("old Welcome notebook"); std::fs::write(destination.join("old-user-edit.txt"), "replace this managed copy").expect("old Welcome edit"); - let app = NoteCraftApp::new(s).with_welcome_notebook_setup(move |root, format| { + let app = NoteCraftApp::new(s).with_welcome_notebook_setup(move |root, format, _expected| { let destination = root.join("welcome-to-notecraft"); if destination.exists() { std::fs::remove_dir_all(&destination).map_err(|error| error.to_string())?; } copy_tree(&source.join(format), &destination); - Ok(destination) + Ok(Some(destination)) }); let mut h = harness(app, LIGHT); // Welcome, logging, format, demo, thank you. @@ -2525,10 +2525,10 @@ fn declining_the_welcome_notebook_prompt_does_not_create_it() { let s = session(&t); s.settings.set("ui_language", "en").expect("English UI setting"); s.settings.set("privacy_welcome_seen", "").expect("first use: the wizard opens"); - let app = NoteCraftApp::new(s).with_welcome_notebook_setup(|root, _format| { + let app = NoteCraftApp::new(s).with_welcome_notebook_setup(|root, _format, _expected| { let destination = root.join("welcome-to-notecraft"); std::fs::create_dir_all(&destination).map_err(|error| error.to_string())?; - Ok(destination) + Ok(Some(destination)) }); let mut h = harness(app, LIGHT); h.get_by_label("Next").click(); @@ -2555,7 +2555,7 @@ fn clicking_outside_the_first_use_wizard_keeps_its_buttons_working() { let s = session(&t); s.settings.set("ui_language", "en").expect("English UI setting"); s.settings.set("privacy_welcome_seen", "").expect("first use: the wizard opens"); - let app = NoteCraftApp::new(s).with_welcome_notebook_setup(|root, _format| Ok(root.join("welcome-to-notecraft"))); + let app = NoteCraftApp::new(s).with_welcome_notebook_setup(|root, _format, _expected| Ok(Some(root.join("welcome-to-notecraft")))); let mut h = harness(app, LIGHT); settle(&mut h); @@ -2587,7 +2587,7 @@ fn failed_welcome_notebook_generation_keeps_the_prompt_open() { let s = session(&t); s.settings.set("ui_language", "en").expect("English UI setting"); s.settings.set("privacy_welcome_seen", "").expect("first use: the wizard opens"); - let app = NoteCraftApp::new(s).with_welcome_notebook_setup(|_, _| Err("permission denied".to_string())); + let app = NoteCraftApp::new(s).with_welcome_notebook_setup(|_, _, _| Err("permission denied".to_string())); let mut h = harness(app, LIGHT); h.get_by_label("Next").click(); settle(&mut h); @@ -2612,18 +2612,15 @@ fn first_use_wizard_close_button_skips_setup_without_installing_the_demo() { let s = session(&t); s.settings.set("ui_language", "en").expect("English UI setting"); s.settings.set("privacy_welcome_seen", "").expect("first use: the wizard opens"); - let installed = std::rc::Rc::new(std::cell::Cell::new(false)); - let installed_flag = installed.clone(); - let app = NoteCraftApp::new(s).with_welcome_notebook_setup(move |_, _| { - installed_flag.set(true); - Err("must not install".to_string()) + let payload = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../docs/demo/DemoNotebook"); + let app = NoteCraftApp::new(s).with_welcome_notebook_setup(move |root, format, _expected| { + notecraft_setup::install_edition(&payload, root, format).map(Some).map_err(|error| error.to_string()) }); let mut h = harness(app, LIGHT); h.get_by_label("×").click(); settle(&mut h); assert_eq!(h.query_all_by_label("Finish").count(), 0, "closing dismisses the wizard"); assert_eq!(h.state().session().settings.get("privacy_welcome_seen").as_deref(), Some("true"), "closing marks setup seen"); - assert!(!installed.get(), "closing does not install the demo notebook"); assert!(!t.path().join("notebooks/welcome-to-notecraft").exists(), "closing creates no notebook"); } @@ -2638,7 +2635,10 @@ fn welcome_notebook_update_prompt_keep_mine_asks_once_per_version() { std::fs::write(installed.join("00-start/welcome/index.html"), "my notes").expect("edited page"); s.settings.set("welcome_notebook_version", "0.0.29").expect("old version"); s.settings.set("welcome_notebook_manifest", "stale").expect("stale manifest"); - let mut app = NoteCraftApp::new(s).with_welcome_notebook_setup(|_, _| Err("must not install".to_string())); + let payload = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../docs/demo/DemoNotebook"); + let mut app = NoteCraftApp::new(s).with_welcome_notebook_setup(move |root, format, _expected| { + notecraft_setup::install_edition(&payload, root, format).map(Some).map_err(|error| error.to_string()) + }); app.check_welcome_notebook_update("0.0.30"); let mut h = harness(app, LIGHT); h.get_by_label("Keep mine").click(); From f2d0b722c42e255d4f52b239ff1986440518f531 Mon Sep 17 00:00:00 2001 From: alientechsw <43017062+alientechsw@users.noreply.github.com> Date: Sat, 5 Dec 2026 14:03:37 -0800 Subject: [PATCH 5/7] style: apply rustfmt to the Welcome update fixes --- apps/notecraft-setup/src/lib.rs | 14 ++------------ crates/store/src/tree_hash.rs | 8 ++++---- crates/ui-egui/src/app.rs | 14 +++++--------- 3 files changed, 11 insertions(+), 25 deletions(-) diff --git a/apps/notecraft-setup/src/lib.rs b/apps/notecraft-setup/src/lib.rs index db3ca9e58..3aa1d5ea7 100644 --- a/apps/notecraft-setup/src/lib.rs +++ b/apps/notecraft-setup/src/lib.rs @@ -28,12 +28,7 @@ pub fn install_edition(payload: &Path, notebooks_root: &Path, format: &str) -> i /// reports no replacement and the installed tree is left as it was, so the caller can /// ask the person instead. Returns the installed notebook folder, or `None` when the /// tree changed. -pub fn install_edition_if_unchanged( - payload: &Path, - notebooks_root: &Path, - format: &str, - expected_manifest: &str, -) -> io::Result> { +pub fn install_edition_if_unchanged(payload: &Path, notebooks_root: &Path, format: &str, expected_manifest: &str) -> io::Result> { install_guarded(payload, notebooks_root, format, Some(expected_manifest)) } @@ -43,12 +38,7 @@ pub fn install_edition_if_unchanged( /// tree is checked again after the swap, before its backup is deleted: a write that /// landed between the first check and the swap is caught by the second check, and the /// previous tree is restored. A tree that cannot be read counts as changed. -fn install_guarded( - payload: &Path, - notebooks_root: &Path, - format: &str, - expected_manifest: Option<&str>, -) -> io::Result> { +fn install_guarded(payload: &Path, notebooks_root: &Path, format: &str, expected_manifest: Option<&str>) -> io::Result> { validate_edition(payload, format)?; let destination = notebooks_root.join(NOTEBOOK_NAME); if std::fs::symlink_metadata(&destination).is_ok_and(|metadata| metadata.file_type().is_symlink()) { diff --git a/crates/store/src/tree_hash.rs b/crates/store/src/tree_hash.rs index 47be6dc7f..3f6f9bbb8 100644 --- a/crates/store/src/tree_hash.rs +++ b/crates/store/src/tree_hash.rs @@ -96,11 +96,11 @@ fn visit(dir: &Path, base: &Path, entries: &mut Vec<(PathBuf, Entry)>) -> io::Re .strip_prefix(base) .map_err(|_| io::Error::new(io::ErrorKind::Other, format!("{} is not under {}", path.display(), base.display())))? .to_path_buf(); - let kind = std::fs::symlink_metadata(&path) - .map_err(|error| io::Error::new(error.kind(), format!("could not read {}: {error}", path.display())))?; + let kind = + std::fs::symlink_metadata(&path).map_err(|error| io::Error::new(error.kind(), format!("could not read {}: {error}", path.display())))?; if kind.file_type().is_symlink() { - let target = std::fs::read_link(&path) - .map_err(|error| io::Error::new(error.kind(), format!("could not read {}: {error}", path.display())))?; + let target = + std::fs::read_link(&path).map_err(|error| io::Error::new(error.kind(), format!("could not read {}: {error}", path.display())))?; entries.push((relative, Entry::Link(target))); } else if kind.is_dir() { entries.push((relative, Entry::Dir)); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index dd2b2ace0..6ac6dbd4d 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -2638,10 +2638,7 @@ impl NoteCraftApp { /// installed notebook folder, or nothing when the guarded upgrade found the tree /// changed and replaced nothing. The wizard opens once: on the first launch after installation, or /// after the preferences are reset. It does not reopen for later versions. - pub fn with_welcome_notebook_setup( - mut self, - setup: impl FnMut(&Path, &str, Option<&str>) -> Result, String> + 'static, - ) -> Self { + pub fn with_welcome_notebook_setup(mut self, setup: impl FnMut(&Path, &str, Option<&str>) -> Result, String> + 'static) -> Self { self.welcome_notebook_setup = Some(Box::new(setup)); self } @@ -2682,9 +2679,8 @@ impl NoteCraftApp { /// it was installed; a failed record leaves it unrecorded, and the next update asks /// instead of silently replacing. fn install_welcome_notebook(&mut self, format: PageFormat) -> Result { - let installed = self - .run_welcome_notebook_setup(format, None)? - .ok_or_else(|| "the bundled Welcome notebook setup reported no install".to_string())?; + let installed = + self.run_welcome_notebook_setup(format, None)?.ok_or_else(|| "the bundled Welcome notebook setup reported no install".to_string())?; self.finish_welcome_notebook_install(&installed); Ok(installed) } @@ -20028,8 +20024,8 @@ mod alert_tests { let settings = notecraft_store::Settings::at(t.path().join("settings.toml")); settings.set("privacy_welcome_seen", "true").expect("settings"); let upgraded = Session::new(&t.path().join("notebooks"), settings.clone()).expect("upgraded session"); - let upgraded = NoteCraftApp::new(upgraded) - .with_welcome_notebook_setup(|root, _format, _expected| Ok(Some(root.join("welcome-to-notecraft")))); + let upgraded = + NoteCraftApp::new(upgraded).with_welcome_notebook_setup(|root, _format, _expected| Ok(Some(root.join("welcome-to-notecraft")))); assert!(upgraded.dialog.is_none(), "an existing user is not shown the wizard again for a later version"); // A fresh install opens the wizard at the welcome page; finishing it saves every answer. From 5c2049fb53e955de3889a366fc15d9c257eeb556 Mon Sep 17 00:00:00 2001 From: alientechsw <43017062+alientechsw@users.noreply.github.com> Date: Sat, 5 Dec 2026 14:21:14 -0800 Subject: [PATCH 6/7] fix(deps): sync Cargo.lock with the ui-egui dev-dependency --- Cargo.lock | 1 + 1 file changed, 1 insertion(+) diff --git a/Cargo.lock b/Cargo.lock index 2832e6491..215c612c0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4003,6 +4003,7 @@ dependencies = [ "notecraft-model", "notecraft-ocr", "notecraft-proofing", + "notecraft-setup", "notecraft-store", "notecraft-text", "rfd", From 294a43be590a1137ec6bbe1976256c4e5874d0ea Mon Sep 17 00:00:00 2001 From: alientechsw <43017062+alientechsw@users.noreply.github.com> Date: Sat, 5 Dec 2026 14:21:30 -0800 Subject: [PATCH 7/7] fix(web): pass the manifest argument to the Welcome setup closure --- .github/web-build/test_bundle_demo.py | 2 +- .github/web-build/web.diff | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/web-build/test_bundle_demo.py b/.github/web-build/test_bundle_demo.py index c47b5f7e4..1539b1e49 100644 --- a/.github/web-build/test_bundle_demo.py +++ b/.github/web-build/test_bundle_demo.py @@ -47,7 +47,7 @@ def test_rejects_a_demo_generated_for_a_different_release(self) -> None: def test_first_run_installs_only_the_html_edition_at_the_notebook_root(self) -> None: patch = (self.root / ".github" / "web-build" / "web.diff").read_text(encoding="utf-8") - self.assertIn("with_welcome_notebook_setup(|_root, format| install_edition(format))", patch) + self.assertIn("with_welcome_notebook_setup(|_root, format, _expected| install_edition(format))", patch) self.assertIn('session.settings.set("privacy_welcome_seen", "true")', patch) self.assertIn('relative.strip_prefix(format)', patch) self.assertIn("Ok(Some(notebook.to_string_lossy().into_owned()))", patch) diff --git a/.github/web-build/web.diff b/.github/web-build/web.diff index a2ae9af0f..02af23c1c 100644 --- a/.github/web-build/web.diff +++ b/.github/web-build/web.diff @@ -594,7 +594,7 @@ index 0000000..f4394fb + let session = Session::new(Path::new(ROOT), Settings::at(SETTINGS)).map_err(|e| e.to_string())?; + // The web demo has no first-use wizard: mark it seen, so it never opens here. + session.settings.set("privacy_welcome_seen", "true").map_err(|e| e.to_string())?; -+ let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(|_root, format| install_edition(format)); ++ let mut app = NoteCraftApp::new(session).with_welcome_notebook_setup(|_root, format, _expected| install_edition(format)); + if !persist { + app = app.with_session_only_storage(); + }