diff --git a/src/instance/content/manifest.rs b/src/instance/content/manifest.rs index 24ae03b..7bff553 100644 --- a/src/instance/content/manifest.rs +++ b/src/instance/content/manifest.rs @@ -93,7 +93,10 @@ impl ContentLock { if current.version != previous.version || current.files != previous.files { return Err(ManifestError::Changed(self.path.clone())); } - self.save(manifest) + if manifest.version != previous.version || manifest.files != previous.files { + self.save(manifest)?; + } + Ok(()) } } diff --git a/src/instance/content/reconcile.rs b/src/instance/content/reconcile.rs index f2a7f5b..4fe9f45 100644 --- a/src/instance/content/reconcile.rs +++ b/src/instance/content/reconcile.rs @@ -200,9 +200,17 @@ pub(crate) async fn reconcile( ) .await }; - task.set_action("Validating content files"); - task.set_sub_action("Rechecking local files"); - task.set_progress(0, inventory.manifest.files.len() as u64); + let changed = inventory + .manifest + .files + .iter() + .filter(|record| inventory.previous.record(&record.relative_path) != Some(record)) + .count(); + if changed > 0 { + task.set_action("Validating content files"); + task.set_sub_action("Rechecking changed files"); + task.set_progress(0, changed as u64); + } publish(ReconcileResult { instance_name: instance_name.clone(), instance_created, @@ -298,6 +306,11 @@ fn save_reconciled_manifest( previous: &ContentManifest, task: &impl InventoryProgress, ) -> Result { + let records = reconciled + .files + .into_iter() + .filter(|record| previous.record(&record.relative_path) != Some(record)) + .collect::>(); ContentManifest::update(manifest_path, |current| { for record in current.files.clone() { relative_path(minecraft_dir, &minecraft_dir.join(&record.relative_path))?; @@ -309,9 +322,9 @@ fn save_reconciled_manifest( Err(error) => return Err(error.into()), } } - let total = reconciled.files.len() as u64; + let total = records.len() as u64; task.set_progress(0, total); - for (index, mut record) in reconciled.files.into_iter().enumerate() { + for (index, mut record) in records.into_iter().enumerate() { task.set_sub_action(record.relative_path.to_string_lossy().as_ref()); task.set_progress(index as u64, total); let path = minecraft_dir.join(&record.relative_path); diff --git a/src/instance/content/updates.rs b/src/instance/content/updates.rs index 327d53a..f872c38 100644 --- a/src/instance/content/updates.rs +++ b/src/instance/content/updates.rs @@ -298,6 +298,10 @@ pub(super) async fn scan_with_registry( previous: Option<&UpdateSnapshot>, mut publish: impl FnMut(&UpdateSnapshot), ) -> UpdateSnapshot { + let previous = previous.filter(|snapshot| snapshot.applies_to(instance)); + let now = chrono::Utc::now().timestamp(); + let reusable = + previous.filter(|snapshot| now.saturating_sub(snapshot.checked_at) < RECHECK_AFTER_SECONDS); let mut projects = manifest .files .iter() @@ -355,8 +359,19 @@ pub(super) async fn scan_with_registry( .collect(), failures: Vec::new(), }; + projects.retain(|(installed, _)| { + reusable.is_none_or(|snapshot| { + !snapshot.inventory.contains(installed) + || snapshot + .failures + .iter() + .any(|failure| &failure.installed == installed) + }) + }); + // Reusing old results must not extend their freshness on each inventory change. + let checked_at = reusable.map_or(now, |snapshot| snapshot.checked_at); if projects.is_empty() { - snapshot.checked_at = chrono::Utc::now().timestamp(); + snapshot.checked_at = checked_at; return snapshot; } let total = projects.len() as u64; @@ -437,7 +452,7 @@ pub(super) async fn scan_with_registry( publish(&snapshot); } sort_updates(&mut snapshot.updates); - snapshot.checked_at = chrono::Utc::now().timestamp(); + snapshot.checked_at = checked_at; snapshot } diff --git a/src/instance/tests/content/dependencies.rs b/src/instance/tests/content/dependencies.rs index 3dc0eaa..f52cc34 100644 --- a/src/instance/tests/content/dependencies.rs +++ b/src/instance/tests/content/dependencies.rs @@ -510,12 +510,14 @@ fn update_checks_prioritize_list_rows_and_publish_before_the_rest_finish() { }, ) .await; + let mut expired = complete.clone(); + expired.checked_at = 0; let offline = scan_with_registry( &instance(), &manifest, &priority, std::sync::Arc::new(ProviderRegistry::new(Vec::new())), - Some(&complete), + Some(&expired), |_| {}, ) .await; @@ -583,6 +585,168 @@ fn update_checks_prioritize_list_rows_and_publish_before_the_rest_finish() { }); } +#[test] +fn update_checks_reuse_fresh_results_only_for_unchanged_installed_versions() { + use crate::instance::content::updates::{UpdateCheckFailure, scan_with_registry}; + let _guard = crate::tests::TEST_LOCK + .lock() + .unwrap_or_else(|error| error.into_inner()); + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap() + .block_on(async { + let versions = ["alpha", "bravo", "charlie"] + .into_iter() + .flat_map(|project| { + [ + ("old", "2026-01-01T00:00:00Z"), + ("new", "2026-02-01T00:00:00Z"), + ] + .into_iter() + .map(move |(suffix, date)| { + version( + &format!("{project}-{suffix}"), + project, + VersionType::Release, + date, + Vec::new(), + ) + }) + }) + .collect(); + let (started, mut requests) = tokio::sync::mpsc::unbounded_channel(); + let registry = std::sync::Arc::new(controlled_update_registry( + versions, + started, + HashMap::new(), + )); + let instance = instance(); + let mut manifest = ContentManifest::default(); + for project in ["alpha", "bravo"] { + manifest.upsert(installed_record(project, &format!("{project}-old"), true)); + } + let mut previous = + scan_with_registry(&instance, &manifest, &[], registry.clone(), None, |_| {}).await; + assert_eq!(std::iter::from_fn(|| requests.try_recv().ok()).count(), 2); + previous.checked_at -= 60; + let original_checked_at = previous.checked_at; + + manifest.upsert(installed_record("charlie", "charlie-old", true)); + let mut snapshot = scan_with_registry( + &instance, + &manifest, + &[], + registry.clone(), + Some(&previous), + |_| {}, + ) + .await; + assert_eq!(requests.try_recv().unwrap(), "charlie"); + assert!(requests.try_recv().is_err()); + assert_eq!(snapshot.updates.len(), 3); + assert_eq!(snapshot.checked_at, original_checked_at); + + manifest.remove(Path::new("mods/alpha.jar")); + snapshot = scan_with_registry( + &instance, + &manifest, + &[], + registry.clone(), + Some(&snapshot), + |_| {}, + ) + .await; + assert!( + requests.try_recv().is_err(), + "Removal must not rescan the remaining projects" + ); + assert_eq!(snapshot.updates.len(), 2); + assert!(snapshot.matches_manifest(&manifest)); + + manifest.upsert(installed_record("bravo", "bravo-new", true)); + snapshot = scan_with_registry( + &instance, + &manifest, + &[], + registry.clone(), + Some(&snapshot), + |_| {}, + ) + .await; + assert_eq!(requests.try_recv().unwrap(), "bravo"); + assert!(requests.try_recv().is_err()); + assert_eq!(snapshot.updates.len(), 1); + assert_eq!(snapshot.updates[0].installed.project_id, "charlie"); + assert_eq!( + snapshot.checked_at, original_checked_at, + "Inventory changes must not prolong cached results" + ); + + snapshot.failures.push(UpdateCheckFailure { + installed: manifest + .files + .last() + .unwrap() + .resolved_project() + .unwrap() + .clone(), + kind: ContentKind::Mod, + reason: "offline".to_owned(), + }); + snapshot = scan_with_registry( + &instance, + &manifest, + &[], + registry.clone(), + Some(&snapshot), + |_| {}, + ) + .await; + assert_eq!(requests.try_recv().unwrap(), "charlie"); + assert!(requests.try_recv().is_err()); + assert!(snapshot.failures.is_empty()); + + snapshot.checked_at = 0; + snapshot = scan_with_registry( + &instance, + &manifest, + &[], + registry.clone(), + Some(&snapshot), + |_| {}, + ) + .await; + assert_eq!( + std::iter::from_fn(|| requests.try_recv().ok()).count(), + 2, + "Expired results must be refreshed" + ); + let mut changed_instance = instance.clone(); + changed_instance.game_version = "1.21.2".to_owned(); + scan_with_registry( + &changed_instance, + &manifest, + &[], + registry.clone(), + Some(&snapshot), + |_| {}, + ) + .await; + assert_eq!( + std::iter::from_fn(|| requests.try_recv().ok()).count(), + 2, + "Changing compatibility invalidates cached results" + ); + scan_with_registry(&instance, &manifest, &[], registry, None, |_| {}).await; + assert_eq!( + std::iter::from_fn(|| requests.try_recv().ok()).count(), + 2, + "An explicit scan must still check everything" + ); + }); +} + #[tokio::test] async fn datapack_dependencies_are_routed_to_the_world_or_instance_by_kind() { let temp = tempfile::tempdir().unwrap(); diff --git a/src/instance/tests/content/manifest.rs b/src/instance/tests/content/manifest.rs index d58305d..08ae471 100644 --- a/src/instance/tests/content/manifest.rs +++ b/src/instance/tests/content/manifest.rs @@ -102,6 +102,25 @@ fn loading_rejects_duplicate_and_escaping_ownership_paths() { } } +#[test] +fn unchanged_manifest_updates_do_not_rewrite_the_saved_index() { + let temp = tempfile::tempdir().unwrap(); + let path = temp.path().join("manifest.json"); + ContentManifest::default().save(&path).unwrap(); + std::fs::File::options() + .write(true) + .open(&path) + .unwrap() + .set_times(std::fs::FileTimes::new().set_modified(UNIX_EPOCH)) + .unwrap(); + let before = std::fs::metadata(&path).unwrap().modified().unwrap(); + ContentManifest::update(&path, |_| Ok(())).unwrap(); + assert_eq!( + std::fs::metadata(&path).unwrap().modified().unwrap(), + before + ); +} + #[test] fn curseforge_fingerprint_ignores_whitespace() { let temp = tempfile::tempdir().unwrap(); diff --git a/src/instance/tests/content/reconcile.rs b/src/instance/tests/content/reconcile.rs index e4bb784..f314c06 100644 --- a/src/instance/tests/content/reconcile.rs +++ b/src/instance/tests/content/reconcile.rs @@ -46,7 +46,7 @@ impl InventoryProgress for NoopProgress { } #[test] -fn saving_an_identified_inventory_reports_progress_for_the_actual_files() { +fn saving_an_identified_inventory_only_revalidates_changed_records() { #[derive(Default)] struct Counts(std::cell::RefCell>); impl InventoryProgress for Counts { @@ -84,9 +84,24 @@ fn saving_an_identified_inventory_reports_progress_for_the_actual_files() { .unwrap(); assert_eq!(saved.files, previous.files); let reported = counts.0.borrow(); - assert_eq!(reported.first(), Some(&(0, 2))); - assert!(reported.contains(&(1, 2))); - assert_eq!(reported.last(), Some(&(2, 2))); + assert_eq!(reported.as_slice(), &[(0, 0), (0, 0)]); + drop(reported); + + std::fs::write(minecraft.join("mods/charlie.jar"), b"new").unwrap(); + let mut inventory = reconcile_inventory(&manifest_path, &minecraft, 24, 512, &counts).unwrap(); + assert_eq!(inventory.queries.len(), 1); + inventory.manifest.files.last_mut().unwrap().resolution = resolved_record().resolution; + counts.0.borrow_mut().clear(); + let saved = save_reconciled_manifest( + &manifest_path, + &minecraft, + inventory.manifest, + &inventory.previous, + &counts, + ) + .unwrap(); + assert_eq!(saved.files.len(), 3); + assert_eq!(counts.0.borrow().as_slice(), &[(0, 1), (0, 1), (1, 1)]); } fn resolved_record() -> ContentFileRecord { diff --git a/src/tui/event.rs b/src/tui/event.rs index 5a81831..599c65d 100644 --- a/src/tui/event.rs +++ b/src/tui/event.rs @@ -510,7 +510,7 @@ impl App { self.content_update_check_pending && !(active.is_scanning() && active.entries.is_empty()) } - fn apply_cached_content_manifest(&mut self) { + pub(super) fn apply_cached_content_manifest(&mut self) { let Some((instance_name, manifest)) = &self.content_manifest else { return; }; @@ -542,6 +542,14 @@ impl App { &minecraft_dir, crate::instance::ContentKind::DataPack, ); + for discovery in [ + &mut self.mods_discovery_state, + &mut self.resource_packs_discovery_state, + &mut self.shaders_discovery_state, + &mut self.datapacks_discovery_state, + ] { + discovery.refresh_installed_manifest(manifest, &minecraft_dir); + } self.apply_content_update_snapshot(); } diff --git a/src/tui/input.rs b/src/tui/input.rs index 1b2bf84..6519b78 100644 --- a/src/tui/input.rs +++ b/src/tui/input.rs @@ -2274,6 +2274,7 @@ impl App { orphan_only, )?; self.content_manifest = Some((name, manifest)); + self.apply_cached_content_manifest(); Ok(orphaned) } @@ -2303,11 +2304,6 @@ impl App { self.worlds_state.remove_path(path); self.screenshots_state.remove_path(path); self.logs_state.remove_path(path); - self.mods_discovery_state.clear_installed_path(path); - self.resource_packs_discovery_state - .clear_installed_path(path); - self.shaders_discovery_state.clear_installed_path(path); - self.datapacks_discovery_state.clear_installed_path(path); if path .parent() .and_then(std::path::Path::file_name) diff --git a/src/tui/tests/event.rs b/src/tui/tests/event.rs index f0aa413..becca50 100644 --- a/src/tui/tests/event.rs +++ b/src/tui/tests/event.rs @@ -486,7 +486,8 @@ fn update_badges_stream_while_the_content_index_is_still_being_saved() { .matches_manifest(&changed) ); assert!(!ui.app.content_update_check_pending); - let previous = ui.app.content_update_snapshot.as_ref().unwrap().1.clone(); + let mut previous = ui.app.content_update_snapshot.as_ref().unwrap().1.clone(); + previous.checked_at = 0; assert!(start_check(&changed, Some(previous))); wait_for_requests(); assert!(updates::is_running( diff --git a/src/tui/tests/flows.rs b/src/tui/tests/flows.rs index b9ed533..6c9b3de 100644 --- a/src/tui/tests/flows.rs +++ b/src/tui/tests/flows.rs @@ -601,6 +601,115 @@ fn deleting_a_mod_offers_its_unused_dependency_chain() { assert!(manifest.files.is_empty()); } +#[test] +fn deleting_installed_content_from_either_tab_resets_discovery_version_sources() { + for mode in [ContentMode::Discover, ContentMode::Installed] { + let mut ui = UiHarness::new(); + ui.add_instance("Delete and install again"); + ui.app.sync_instance_content(); + let instance = ui.app.instances_state.selected_instance().unwrap().clone(); + let paths = crate::storage::InstancePaths::new(ui.instance_path(&instance.name)); + let minecraft = paths.minecraft(); + let path = minecraft.join("mods/root.jar"); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, b"root").unwrap(); + let mut record = managed_mod_record(&minecraft, "mods/root.jar", "root", false, Vec::new()); + record.provider_aliases.push(ProviderProject { + provider: "curseforge".to_owned(), + project_id: "other-root".to_owned(), + version_id: "other-version".to_owned(), + }); + let sources = record + .resolved_project() + .into_iter() + .chain(&record.provider_aliases) + .cloned() + .map(|source| ("root".to_owned(), source)) + .collect(); + let mut manifest = ContentManifest::default(); + manifest.upsert(record); + manifest.save(&paths.content_manifest()).unwrap(); + ui.app.content_manifest = Some((instance.name.clone(), manifest.clone())); + ui.app + .mods_state + .set_entries(vec![content_entry("Root", path.clone())]); + let request = ui.app.mods_discovery_state.begin_search(&instance); + request + .stream + .upsert(crate::tui::widgets::content::discovery::project_entry( + DiscoveryProject { + id: "root".to_owned(), + slug: "root".to_owned(), + title: "Root".to_owned(), + description: String::new(), + downloads: 0, + icon_url: None, + icon_bytes: None, + }, + Some(path.clone()), + )); + crate::tui::widgets::content::DiscoveryState::push_provider_result( + &request.pending, + request.generation, + 0, + Ok( + crate::tui::widgets::content::discovery::DiscoveryPageResult { + received: 1, + total_hits: 1, + ..Default::default() + }, + ), + sources, + ); + ui.app.mods_discovery_state.drain_pending(); + ui.app.mods_discovery_state.drain_list(&ui.app.picker); + ui.app + .mods_discovery_state + .refresh_installed_manifest(&manifest, &minecraft); + ui.app.mods_discovery_state.list.list_state.selected = Some(0); + ui.app.focused = FocusedArea::Content; + ui.app.content_tab = ContentTab::Mods; + ui.app.content_mode = mode; + + ui.key(KeyCode::Char('d')); + ui.key(KeyCode::Enter); + assert!(!path.exists()); + assert!( + ContentManifest::load(&paths.content_manifest()) + .unwrap() + .files + .is_empty() + ); + ui.app.content_mode = ContentMode::Discover; + ui.key(KeyCode::Char('v')); + let popup = ui.app.mods_discovery_state.version_popup.as_mut().unwrap(); + assert!(popup.installed_path.is_none()); + assert!( + popup.current_version_id.is_none(), + "{mode:?}: deleted version remains installed" + ); + assert!( + popup + .sources + .iter() + .all(|source| source.version_id.is_empty()) + ); + assert_eq!(popup.title(), "Install Root"); + popup.loading = false; + let switched = ui.app.mods_discovery_state.switch_version_source().unwrap(); + assert!(switched.current_version_id.is_none()); + assert_eq!( + ui.app + .mods_discovery_state + .version_popup + .as_ref() + .unwrap() + .title(), + "Install Root" + ); + } +} + #[test] fn deleting_a_required_library_warns_but_can_continue() { let mut ui = UiHarness::new(); diff --git a/src/tui/tests/widgets/content/discovery.rs b/src/tui/tests/widgets/content/discovery.rs index e81cd64..0835df8 100644 --- a/src/tui/tests/widgets/content/discovery.rs +++ b/src/tui/tests/widgets/content/discovery.rs @@ -2275,7 +2275,30 @@ fn discovery_delete_only_clears_the_matching_installed_badge() { let pending = state.pending_installed_delete().unwrap(); assert_eq!(pending.path, first_path); - assert!(state.clear_installed_path(&pending.path)); + let mut manifest = crate::instance::ContentManifest::default(); + manifest.upsert(crate::instance::ContentFileRecord { + relative_path: second_path.clone(), + kind: ContentKind::Mod, + enabled: true, + fingerprint: crate::instance::FileFingerprint { + size: 0, + modified_ns: 0, + hashes: Default::default(), + }, + resolution: crate::instance::Resolution::Resolved { + project: crate::instance::ProviderProject { + provider: "modrinth".to_owned(), + project_id: "second".to_owned(), + version_id: "second-version".to_owned(), + }, + }, + provider_aliases: Vec::new(), + provider_checks: Vec::new(), + required_dependencies: Vec::new(), + automatic_dependency: false, + cleanup_eligible: false, + }); + state.refresh_installed_manifest(&manifest, std::path::Path::new("")); assert_eq!(state.list.entries.len(), 2); assert!(state.list.entries[0].installed_path.is_none()); @@ -2862,6 +2885,15 @@ fn discovery_restores_cached_sort_and_continues_pagination() { ))); assert!(first.stream.upsert(project_entry(project("second"), None))); drain_discovery_rows(&mut state); + let mut installed = state.list.entries[0].clone(); + installed.installed_path = Some(PathBuf::from("mods/cached.jar")); + installed.title_suffix = Some("Installed".to_owned()); + let source = installed.provider_project.as_mut().unwrap(); + source.version_id = "installed-version".to_owned(); + state + .sources + .insert(installed.file_stem.clone(), vec![source.clone()]); + state.list.entries[0] = installed.clone(); DiscoveryState::push_result( &first.pending, first.generation, @@ -2876,12 +2908,47 @@ fn discovery_restores_cached_sort_and_continues_pagination() { state.sort = crate::instance::content::provider::DiscoverySort::Popular; let other = state.begin_search(&instance); assert!(!other.cached); + state + .preparing_list + .as_mut() + .unwrap() + .entries + .push(installed); + state.refresh_installed_manifest( + &crate::instance::ContentManifest::default(), + std::path::Path::new(""), + ); + let preparing = &state.preparing_list.as_ref().unwrap().entries[0]; + assert!(preparing.installed_path.is_none()); + assert!( + preparing + .provider_project + .as_ref() + .unwrap() + .version_id + .is_empty() + ); state.list.list_state.selected = Some(1); state.sort = crate::instance::content::provider::DiscoverySort::Relevance; let restored = state.begin_search(&instance); assert!(restored.cached); assert!(!state.list.loading); assert_eq!(state.list.entries[0].name, "Cached"); + assert!(state.list.entries[0].installed_path.is_none()); + assert!(state.list.entries[0].title_suffix.is_none()); + assert!( + state.list.entries[0] + .provider_project + .as_ref() + .unwrap() + .version_id + .is_empty() + ); + assert!( + state.sources[&state.list.entries[0].file_stem] + .iter() + .all(|source| source.version_id.is_empty()) + ); assert_eq!(state.list.list_state.selected, Some(1)); assert_eq!(state.next_offset, 2); assert_eq!(state.total_hits, 20); diff --git a/src/tui/widgets/content/discovery.rs b/src/tui/widgets/content/discovery.rs index 108dfe2..3e3d9a9 100644 --- a/src/tui/widgets/content/discovery.rs +++ b/src/tui/widgets/content/discovery.rs @@ -1830,6 +1830,39 @@ impl DiscoveryState { manifest: &crate::instance::ContentManifest, minecraft_dir: &std::path::Path, ) { + let mut changed = Self::refresh_installed_entries( + &mut self.list.entries, + &mut self.sources, + manifest, + minecraft_dir, + ); + if let Some(list) = &mut self.preparing_list { + changed |= Self::refresh_installed_entries( + &mut list.entries, + &mut self.sources, + manifest, + minecraft_dir, + ); + } + for (_, cached) in &mut self.cached_searches { + changed |= Self::refresh_installed_entries( + &mut cached.entries, + &mut cached.sources, + manifest, + minecraft_dir, + ); + } + if changed { + crate::feedback::request_redraw(); + } + } + + fn refresh_installed_entries( + entries: &mut [ContentEntry], + sources: &mut std::collections::HashMap>, + manifest: &crate::instance::ContentManifest, + minecraft_dir: &std::path::Path, + ) -> bool { let installed_identity = |source: &crate::instance::ProviderProject| { manifest.files.iter().find_map(|record| { record @@ -1837,7 +1870,7 @@ impl DiscoveryState { .cloned() }) }; - for sources in self.sources.values_mut() { + for sources in sources.values_mut() { for source in sources { source.version_id = installed_identity(source) .map(|installed| installed.version_id) @@ -1845,18 +1878,13 @@ impl DiscoveryState { } } let mut changed = false; - for entry in self.list.entries.iter_mut().chain( - self.preparing_list - .iter_mut() - .flat_map(|list| &mut list.entries), - ) { + for entry in entries { if let Some(source) = entry.provider_project.as_mut() { source.version_id = installed_identity(source) .map(|installed| installed.version_id) .unwrap_or_default(); } - let installed_path = self - .sources + let installed_path = sources .get(&entry.file_stem) .into_iter() .flatten() @@ -1874,9 +1902,7 @@ impl DiscoveryState { changed = true; } } - if changed { - crate::feedback::request_redraw(); - } + changed } pub fn selected_is_installed(&self) -> bool { @@ -1893,21 +1919,6 @@ impl DiscoveryState { }) } - pub fn clear_installed_path(&mut self, path: &std::path::Path) -> bool { - let Some(entry) = self - .list - .entries - .iter_mut() - .find(|entry| entry.installed_path.as_deref() == Some(path)) - else { - return false; - }; - entry.installed_path = None; - entry.title_suffix = None; - crate::feedback::request_redraw(); - true - } - fn selected_installed_entry(&self) -> Option<&ContentEntry> { let filtered = self.list.filtered_indices(); let index = self