Terminal interface to find, download, and stream movies, TV shows, and live TV using local media players.
fix(history): preserve precision tracker positions and advance series monotonically
Samir Hossains325da1dba09d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 859c397..4fc1772 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,7 +4,7 @@### Added- **Comprehensive QA & Regression Test Architecture**:- - Introduced a 78-test automated suite covering critical algorithmic boundaries, end-to-end user journeys, content & metadata loading pipelines, stale request isolation, active player session lifecycle & duplicate launch protection, dynamic slash command autocomplete (`/download-dir reset`), search/command draft cancellation via `Esc`, error handling, addon manifest validation, mouse interactions, modal dismissals, TUI rendering across terminal size matrices, state reconciliation, crypto HMAC signing, download chunk arithmetic, and URL/stem security.+ - Introduced an 83-test automated suite covering critical algorithmic boundaries, end-to-end user journeys, watch history reconciliation & precision progress tracking, content & metadata loading pipelines, stale request isolation, active player session lifecycle & duplicate launch protection, dynamic slash command autocomplete (`/download-dir reset`), search/command draft cancellation via `Esc`, error handling, addon manifest validation, mouse interactions, modal dismissals, TUI rendering across terminal size matrices, state reconciliation, crypto HMAC signing, download chunk arithmetic, and URL/stem security.- Added structured integration tests in `tests/` (`content_pipeline.rs`, `error_handling.rs`, `tui_acceptance.rs`, `history_reconciliation.rs`, `cache_lifecycle.rs`, `player_integration.rs`, `m3u_integration.rs`, `addons_manifest.rs`, `download_integration.rs`, `url_security.rs`) and test fixtures (`tests/fixtures/`).- Added [`docs/testing.md`](docs/testing.md) detailing test architecture, command references, and manual QA procedures.- **Playback Tracking & Watch History Progress**:diff --git a/docs/known-issues.md b/docs/known-issues.mdindex 56c7631..b836dc5 100644--- a/docs/known-issues.md+++ b/docs/known-issues.md@@ -26,6 +26,6 @@ Tracked here so future work and issue reports reference the same facts.## Verification-- Automated testing is enforced via `cargo test --locked` covering 78 unit and integration tests across 11 test suites (see [`docs/testing.md`](testing.md)).+- Automated testing is enforced via `cargo test --locked` covering 83 unit and integration tests across 11 test suites (see [`docs/testing.md`](testing.md)).- Static correctness is enforced by strict compiler type checking, the lint gate (`cargo clippy --all-targets --all-features -- -D warnings`), formatting (`cargo fmt --check`), dependency vulnerability scanning (`cargo audit`), and packaging verification (`cargo package --locked`).- Runtime and platform-specific behavior (terminal resize, focus handling, external player launch, and Termux chooser) are verified through the release checklist in [`release-checklist.md`](release-checklist.md).diff --git a/src/history.rs b/src/history.rsindex 0c66806..cfc336e 100644--- a/src/history.rs+++ b/src/history.rs@@ -363,14 +363,17 @@ impl HistoryManager {self.watched.remove(&key);}- if item.cover_url.is_none() {- if let Some(existing) = self- .recent- .iter()- .find(|i| Self::is_same_show(i, &item))- .and_then(|i| i.cover_url.clone())+ if let Some(existing) = self.recent.iter().find(|i| Self::is_same_show(i, &item)) {+ if item.cover_url.is_none() {+ item.cover_url = existing.cover_url.clone();+ }+ if existing.season == item.season+ && existing.episode == item.episode+ && existing.progress_seconds >= progress+ && (existing.timestamp >= item.timestamp+ || item.timestamp.saturating_sub(existing.timestamp) < 60){- item.cover_url = Some(existing);+ return;}}@@ -503,6 +506,37 @@ impl HistoryManager {self.watched.remove(&key);}modified = true;+ } else if let Some(existing_series) = self.recent.iter_mut().find(|i| {+ let same_provider =+ crate::providers::models::ProviderKind::parse(&i.provider)+ .zip(crate::providers::models::ProviderKind::parse(+ &state.provider,+ ))+ .map_or_else(+ || {+ i.provider+ .trim()+ .eq_ignore_ascii_case(state.provider.trim())+ },+ |(p1, p2)| p1 == p2,+ );+ same_provider && i.stype == 2 && i.subject_id == state.subject_id+ }) {+ if (state.season, state.episode)+ >= (existing_series.season, existing_series.episode)+ && state.timestamp >= existing_series.timestamp+ {+ existing_series.season = state.season;+ existing_series.episode = state.episode;+ existing_series.progress_seconds = state.progress_seconds;+ existing_series.duration_seconds = state.duration_seconds;+ existing_series.completed = state.completed;+ existing_series.timestamp = state.timestamp;+ if !existing_series.completed {+ self.watched.remove(&key);+ }+ modified = true;+ }}}}diff --git a/src/tui/app/playback.rs b/src/tui/app/playback.rsindex 47186f9..c506925 100644--- a/src/tui/app/playback.rs+++ b/src/tui/app/playback.rs@@ -243,14 +243,16 @@ impl App {let elapsed = start_time.elapsed().as_secs();if elapsed >= 30 {let duration = item.duration_seconds;- let completed = duration.is_some_and(|d| {- d > 0 && elapsed >= (d as f64 * 0.90) as u64- });+ let start_pos = resume_seconds.unwrap_or(0);+ let total_pos = start_pos.saturating_add(elapsed);let progress = if let Some(d) = duration {- elapsed.min(d)+ total_pos.min(d)} else {- elapsed+ total_pos};+ let completed = duration.is_some_and(|d| {+ d > 0 && progress >= (d as f64 * 0.90) as u64+ });sender.send(Action::UpdateProgress {item,diff --git a/tests/content_pipeline.rs b/tests/content_pipeline.rsindex 21a5cf5..df166c2 100644--- a/tests/content_pipeline.rs+++ b/tests/content_pipeline.rs@@ -89,19 +89,16 @@ fn test_search_result_identity_and_similar_title_isolation() {assert_eq!(subjects.len(), 3);- // Verify item 1 (Batman 1989)assert_eq!(subjects[0]["subjectId"], "tt0096895");assert_eq!(subjects[0]["title"], "Batman");assert_eq!(subjects[0]["subjectType"], 1);assert_eq!(subjects[0]["releaseDate"], "1989");- // Verify item 2 (The Batman 2022)assert_eq!(subjects[1]["subjectId"], "tt1877830");assert_eq!(subjects[1]["title"], "The Batman");assert_eq!(subjects[1]["subjectType"], 1);assert_eq!(subjects[1]["releaseDate"], "2022");- // Verify item 3 (Batman: The Animated Series - Series stype=2)assert_eq!(subjects[2]["subjectId"], "tt0103359");assert_eq!(subjects[2]["title"], "Batman: The Animated Series");assert_eq!(subjects[2]["subjectType"], 2);@@ -115,7 +112,6 @@ async fn test_stale_details_response_protection() {app.state_mut().active_provider = ProviderKind::MovieBox;app.state_mut().active_screen = Screen::Details;- // Simulate opening Movie A (id = "movie_a", request_id = 1)let context_a = RequestContext {provider: ProviderKind::MovieBox,generation: app.state().provider_generation,@@ -127,7 +123,6 @@ async fn test_stale_details_response_protection() {"title": "Movie A",}));- // Immediately user opens Movie B (id = "movie_b", request_id = 2)let context_b = RequestContext {provider: ProviderKind::MovieBox,generation: app.state().provider_generation,@@ -139,7 +134,6 @@ async fn test_stale_details_response_protection() {"title": "Movie B Draft",}));- // Now Movie A's stale response arrives with request_id = 1let stale_payload = serde_json::json!({"id": "movie_a","title": "Movie A Full Metadata",@@ -147,20 +141,18 @@ async fn test_stale_details_response_protection() {});app.handle_action(Action::DetailsSuccess(context_a,- 1, // Stale request ID+ 1,"movie_a".to_string(),stale_payload,)).await;- // Verify Movie A was REJECTED and did NOT overwrite Movie Bassert_eq!(app.state().active_subject_id.as_deref(), Some("movie_b"));assert_eq!(app.state().selected_details.as_ref().unwrap()["title"],"Movie B Draft");- // Now Movie B's legitimate response arrives with request_id = 2let valid_payload = serde_json::json!({"id": "movie_b","title": "Movie B Full Metadata",@@ -168,13 +160,12 @@ async fn test_stale_details_response_protection() {});app.handle_action(Action::DetailsSuccess(context_b,- 2, // Current request ID+ 2,"movie_b".to_string(),valid_payload,)).await;- // Verify Movie B was ACCEPTEDassert_eq!(app.state().active_subject_id.as_deref(), Some("movie_b"));assert_eq!(app.state().selected_details.as_ref().unwrap()["title"],@@ -192,7 +183,6 @@ fn test_cache_key_isolation_across_providers_queries_and_dimensions() {get_provider_details_path, get_provider_search_path, get_provider_stream_path,};- // 1. Search paths isolation across providers, queries, and pageslet search_mb_batman_p1 = get_provider_search_path(ProviderKind::MovieBox, "batman", 1);let search_mb_batman_p2 = get_provider_search_path(ProviderKind::MovieBox, "batman", 2);let search_mb_superman_p1 = get_provider_search_path(ProviderKind::MovieBox, "superman", 1);@@ -202,7 +192,6 @@ fn test_cache_key_isolation_across_providers_queries_and_dimensions() {assert_ne!(search_mb_batman_p1, search_mb_superman_p1);assert_ne!(search_mb_batman_p1, search_addon_batman_p1);- // 2. Details paths isolation across providers and IDslet details_mb_1 = get_provider_details_path(ProviderKind::MovieBox, "1001");let details_mb_2 = get_provider_details_path(ProviderKind::MovieBox, "1002");let details_4k_1 = get_provider_details_path(ProviderKind::FourKHdHub, "1001");@@ -210,7 +199,6 @@ fn test_cache_key_isolation_across_providers_queries_and_dimensions() {assert_ne!(details_mb_1, details_mb_2);assert_ne!(details_mb_1, details_4k_1);- // 3. Stream paths isolation across seasons and episodeslet stream_s1_e1 = get_provider_stream_path(ProviderKind::MovieBox, "series_1", 1, 1);let stream_s1_e2 = get_provider_stream_path(ProviderKind::MovieBox, "series_1", 1, 2);let stream_s2_e1 = get_provider_stream_path(ProviderKind::MovieBox, "series_1", 2, 1);@@ -221,7 +209,6 @@ fn test_cache_key_isolation_across_providers_queries_and_dimensions() {#[test]fn test_addon_metadata_mapping_and_partial_data_degradation() {- // Minimal MetaDetail with missing optional fieldslet minimal = MetaDetail {id: "tt9999999".to_string(),r#type: "movie".to_string(),@@ -257,7 +244,6 @@ fn test_addon_metadata_mapping_and_partial_data_degradation() {assert!(json_output["director"].is_null());assert!(json_output["stars"].is_null());- // Series with decomposed multi-season video recordslet series_detail = MetaDetail {id: "tt8888888".to_string(),r#type: "series".to_string(),@@ -344,7 +330,6 @@ async fn test_search_failure_vs_empty_result_distinction() {generation: app.state().provider_generation,};- // Case 1: Search succeeds with 0 resultsapp.handle_action(Action::SearchSuccess {context,request_id: app.state().active_search_request,@@ -362,7 +347,6 @@ async fn test_search_failure_vs_empty_result_distinction() {assert!(app.state().search_error.is_none());assert!(!app.state().is_loading);- // Case 2: Search fails due to network outageapp.handle_action(Action::SearchFailure(context,app.state().active_search_request,@@ -393,12 +377,10 @@ async fn test_mode_switch_stale_response_protection() {app.state_mut().active_search_request = 1;app.state_mut().search_query = "avatar".to_string();- // User switches mode to Addon Mode while MovieBox search is in-flightapp.handle_action(Action::ToggleAddonMode).await;assert_eq!(app.state().mode(), AppMode::Addon);assert_ne!(app.state().provider_generation, streaming_generation);- // Now MovieBox search response arrives with previous generation contextlet moviebox_payload = serde_json::json!({"results": [{"subjects": [{@@ -420,7 +402,6 @@ async fn test_mode_switch_stale_response_protection() {}).await;- // Stale streaming search MUST NOT leak into Addon Modeassert!(app.state().search_results.is_empty());}@@ -434,23 +415,19 @@ async fn test_poster_identity_isolation() {let dynamic_img = std::sync::Arc::new(image::DynamicImage::new_rgb8(10, 10));- // Stale poster for a different movie arrivesapp.handle_action(Action::PosterSuccess("other_movie_id".to_string(),dynamic_img.clone(),)).await;- // Target movie's poster remains untouched (None)assert!(app.state().poster_image.is_none());- // Legitimate poster for target movie arrivesapp.handle_action(Action::PosterSuccess("target_movie_id".to_string(),dynamic_img.clone(),)).await;- // Poster is now populatedassert!(app.state().poster_image.is_some());}diff --git a/tests/history_reconciliation.rs b/tests/history_reconciliation.rsindex fddb59e..6482f5f 100644--- a/tests/history_reconciliation.rs+++ b/tests/history_reconciliation.rs@@ -71,3 +71,90 @@ fn test_history_reconciliation_multi_episode_flow() {assert!(!state_file_ep1.exists());assert!(!state_file_ep2.exists());}++#[test]+fn test_movie_resume_progress_and_completion() {+ let mut movie = make_history_item("moviebox", "mb_m1", "Inception", 1, "2010", 0, 0);+ movie.duration_seconds = Some(8880);+ movie.progress_seconds = 20;+ assert!(!movie.is_in_progress());++ movie.progress_seconds = 4440;+ assert!(movie.is_in_progress());+ assert_eq!(movie.progress_percentage(), Some(50.0));+ assert_eq!(movie.formatted_progress(), "1:14:00 / 2:28:00");+ assert_eq!(movie.formatted_remaining(), Some("1h 14m left".to_string()));++ movie.progress_seconds = 8000;+ assert!(!movie.is_in_progress());+}++#[test]+fn test_episode_progress_isolation() {+ let mut manager = HistoryManager::default();+ let ep1 = make_history_item("moviebox", "show_x", "Severance", 2, "2022", 1, 1);+ let ep2 = make_history_item("moviebox", "show_x", "Severance", 2, "2022", 1, 2);+ let ep3 = make_history_item("moviebox", "show_x", "Severance", 2, "2022", 2, 1);++ manager.update_progress(ep1.clone(), 3000, Some(3000), true);+ assert!(manager.is_watched("moviebox", "show_x", 1, 1));+ assert!(!manager.is_watched("moviebox", "show_x", 1, 2));+ assert!(!manager.is_watched("moviebox", "show_x", 2, 1));++ manager.update_progress(ep2.clone(), 1500, Some(3000), false);+ assert!(manager.is_watched("moviebox", "show_x", 1, 1));+ assert!(!manager.is_watched("moviebox", "show_x", 1, 2));++ manager.update_progress(ep3.clone(), 3200, Some(3200), true);+ assert!(manager.is_watched("moviebox", "show_x", 1, 1));+ assert!(manager.is_watched("moviebox", "show_x", 2, 1));+ assert!(!manager.is_watched("moviebox", "show_x", 1, 2));++ assert_eq!(manager.recent.len(), 1);+ assert_eq!(manager.recent.first().unwrap().season, 2);+ assert_eq!(manager.recent.first().unwrap().episode, 1);+}++#[test]+fn test_update_progress_precision_preservation() {+ let mut manager = HistoryManager::default();+ let now = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_secs();+ let mut item = make_history_item("moviebox", "mb_m2", "Interstellar", 1, "2014", 0, 0);+ item.duration_seconds = Some(10140);+ item.progress_seconds = 5000;+ item.timestamp = now;++ manager.recent.push(item.clone());++ let lower_item = item.clone();+ manager.update_progress(lower_item, 3000, Some(10140), false);++ assert_eq!(manager.recent.first().unwrap().progress_seconds, 5000);+}++#[test]+fn test_duplicate_history_prevention_on_repeated_play() {+ let mut manager = HistoryManager::default();+ let item = make_history_item("moviebox", "mb_m3", "The Matrix", 1, "1999", 0, 0);++ manager.update_progress(item.clone(), 1200, Some(8160), false);+ manager.update_progress(item.clone(), 2400, Some(8160), false);+ manager.update_progress(item.clone(), 3600, Some(8160), false);++ assert_eq!(manager.recent.len(), 1);+ assert_eq!(manager.recent.first().unwrap().progress_seconds, 3600);+}++#[test]+fn test_corrupted_history_deserialization_recovery() {+ let malformed_json = "{ \"watched\": [\"corrupt\"], \"recent\": \"invalid_shape\" }";+ let deserialized = serde_json::from_str::<HistoryManager>(malformed_json);+ assert!(deserialized.is_err());++ let empty_json = "{}";+ let empty_manager = serde_json::from_str::<HistoryManager>(empty_json).unwrap();+ assert!(empty_manager.recent.is_empty());+}