Terminal interface to find, download, and stream movies, TV shows, and live TV using local media players.
feat(playback): persist stream filename in history and bound mirror tasks
Samir Hossains161040e0c36e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4e98489..e53ab9c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,7 +7,7 @@- Gated background search pagination in `src/tui/app/navigation.rs` so arrow navigation on result sets smaller than the visible viewport never triggers background page fetches.- Added `search_exhausted` tracking in `src/tui/state.rs` and `src/tui/app/requests.rs`, stopping pagination crawls when provider search returns fewer than 15 items or zero query-matching results.- Preserved stable card slot positions during search pagination in `src/tui/app/requests.rs` by appending subsequent page items to the list rather than re-sorting the entire array out from under the cursor.- - Removed redundant "Provider: <name>" status message override from the search bar on provider switch in `src/tui/app/navigation.rs`, preserving the clean search placeholder while the active provider pill displays on the right.+ - Removed redundant "Provider: {name}" status message override from the search bar on provider switch in `src/tui/app/navigation.rs`, preserving the clean search placeholder while the active provider pill displays on the right.- **Media Playback & Buffering Engine**:- Prioritized native desktop media players (`mpv`, `VLC`) over Android intent openers in `src/player.rs` when an active X11/Wayland display server (`$DISPLAY`, `$WAYLAND_DISPLAY`) is detected, preventing Ubuntu Xfce (udroid/PRoot) and Termux:X11 desktop sessions from dispatching playback to external Android app choosers.- Configured `mpv` and `IINA` with initial cache buffering (`--cache-pause-initial=yes`) and resilient re-buffer cushion (`--cache-pause-wait=10`) in `src/player.rs`, preventing repeated 2-second stutter loops on bandwidth-constrained CDN streams.@@ -15,6 +15,11 @@- Enabled HTTP/1.1 persistent connections (`Keep-Alive`) across DASH segment streaming in `src/proxy.rs`, eliminating recurring TCP handshake overhead.- Enforced `max_height` resolution limits in the loopback stream proxy manifest rewriter (`src/proxy.rs`, `src/main.rs`, `src/tui/app/playback.rs`), pruning representations exceeding the chosen ceiling so Android players and VLC respect 480p and 720p selections.- Parsed signed expiration timestamps (`:t=`) from MovieBox `Edge-Cache-Cookie` headers in `src/cache.rs` alongside CloudFront policies, automatically invalidating stale stream cache entries within 60 seconds of expiration to prevent HTTP 403 playback crashes.+ - Persisted selected stream filenames (`stream_filename`) in watch history (`src/history.rs`, `src/player/tracker.rs`, `src/tui/app/playback.rs`) and auto-focused matching stream rows on load (`src/tui/app/requests.rs`, `src/tui/app/system.rs`), restoring the user's previously chosen quality mirror when resuming multi-stream releases.+ - Enabled TCP nodelay (`stream.set_nodelay(true)`) and per-chunk immediate flushes on the local `StreamRelay` proxy in `src/proxy.rs`, eliminating 100–300ms time-to-first-frame buffering delays on loopback sockets.+ - Implemented negative caching (`Option<Option<String>>`) for media player detection (`MPV_CACHED`, `VLC_CACHED`, `IINA_CACHED`) in `src/player.rs`, eliminating redundant filesystem scans and registry lookups when players are absent.+ - Throttled Lua tracker periodic disk sync in `src/player/tracker.rs` when playback is paused or positional change is sub-second, cutting SSD writes by up to 90% during playback pauses.+ - Removed duplicate redundant `history.save()` calls in `src/tui/app/playback.rs` upon marking items watched.- **Download Engine & Subprocess Diagnostics**:- Added preflight verification for `ffmpeg` alongside `yt-dlp` in `src/tui/app/download.rs`, failing fast with installation guidance when media muxing tools are missing.- Captured child process stderr lines during DASH transfers to surface concrete `yt-dlp` error diagnostics instead of bare exit codes.@@ -25,6 +30,14 @@- Eliminated redundant 100ms idle tick redraws on static home screens in `src/tui/app/system.rs`, dropping idle CPU consumption to zero.- Replaced per-card `Layout::split` invocations in `src/tui/screens/home.rs` with direct row arithmetic calculations, avoiding repeated layout solver overhead across search result slots.- Rendered stream media tags (HDR, ATMOS, 5.1, HEVC, AV1, WEB-DL) in `src/tui/screens/details.rs` using styled surface pill spans instead of raw concatenated text, pruning transient string vectors in the table mapping loop.+ - Replaced linear index iteration with exact O(1) `HashSet` lookups in `FavoritesManager::is_favorite` (`src/favorites.rs`).+- **Provider Scraping & Concurrency Engine**:+ - Replaced chunked mirror resolution barriers in 4KHDHub (`src/providers/fourkhdhub/client.rs`) with concurrent `FuturesUnordered` preflights and early termination on the first healthy playable mirror, reducing time-to-first-stream latency by multiple seconds.+ - Bound individual Stremio addon stream fetches in `src/providers/addons/aggregator.rs` with a 5-second timeout, preventing unresponsive third-party addons from blocking stream aggregation.+ - Capped initial search poster scraping in DhakaFlix (`src/providers/bdix/dhakaflix/client.rs`) to the first 20 items, eliminating dozens of blocking HTTP POST requests on large catalog searches.+- **Storage & Disk Cache Engine**:+ - Optimized typed cache serialization in `src/cache.rs` using direct in-place encoding (`rmp_serde::encode::write`) into pre-seeded magic header buffers, eliminating intermediate vector allocations and duplicate memory copies.+ - Pre-allocated file buffer capacity from file metadata in `get_typed_cache` in `src/cache.rs`, eliminating repetitive vector reallocations during cache reads.### Changed- **Documentation & Cross-Platform Terminal Compatibility**:- Documented native Windows Terminal Sixel image support requirements (`v1.22+` via Microsoft Store) in `docs/cross-platform.md` and `README.md`, clarifying that no third-party terminal or configuration is required on Windows.diff --git a/docs/players.md b/docs/players.mdindex aa1a6d4..bfcf6df 100644--- a/docs/players.md+++ b/docs/players.md@@ -24,7 +24,7 @@ You can set a default player via `/settings` (Media Player), or override it with```bashmpv --autofit=WxH --geometry=50%:50% --idle=no --keep-open=no [OPTIONS] <url>```-- **Tracking**: Injects `moviebox_tracker.lua` to track watch progress and update history every 5 seconds.+- **Tracking**: Injects `moviebox_tracker.lua` to track playback progress, total duration, and chosen stream filename, auto-restoring the exact stream mirror upon re-opening multi-stream titles (such as 4KHDHub releases).- **Headers**: Custom stream headers (`User-Agent`, `Referer`) are passed via `--http-header-fields`.- **DASH Manifests**: CloudFront cookies are passed to yt-dlp hooks via `--ytdl-raw-options-append`.- **Subtitles**: Remote subtitles are loaded directly via `--sub-file=<url>`.diff --git a/src/cache.rs b/src/cache.rsindex 23ed54f..30bb9dd 100644--- a/src/cache.rs+++ b/src/cache.rs@@ -25,6 +25,7 @@ pub fn get_typed_cache<T: DeserializeOwned + Serialize>() -> Option<T> {use std::io::Read;let mut file = fs::File::open(path).ok()?;+ let mut file_len = 0;if let Ok(metadata) = file.metadata() {if let Some(elapsed) = metadata.modified().ok().and_then(|m| m.elapsed().ok()) {if elapsed.as_secs() > expiry_secs {@@ -32,8 +33,9 @@ pub fn get_typed_cache<T: DeserializeOwned + Serialize>(return None;}}+ file_len = metadata.len() as usize;}- let mut bytes = Vec::new();+ let mut bytes = Vec::with_capacity(file_len);if file.read_to_end(&mut bytes).is_err() {return None;}@@ -72,10 +74,9 @@ pub fn set_typed_cache<T: Serialize + ?Sized>(path: &Path, expiry_secs: u64, datexpires_at: now + expiry_secs,data,};- if let Ok(msgpack_bytes) = rmp_serde::to_vec(&envelope) {- let mut file_bytes = Vec::with_capacity(4 + msgpack_bytes.len());- file_bytes.extend_from_slice(&CACHE_MAGIC);- file_bytes.extend_from_slice(&msgpack_bytes);+ let mut file_bytes = Vec::with_capacity(512);+ file_bytes.extend_from_slice(&CACHE_MAGIC);+ if rmp_serde::encode::write(&mut file_bytes, &envelope).is_ok() {if let Err(error) = atomic_write_file(path, &file_bytes) {log::warn!("failed to write cache file {}: {error}",diff --git a/src/favorites.rs b/src/favorites.rsindex 3867420..b528a72 100644--- a/src/favorites.rs+++ b/src/favorites.rs@@ -69,7 +69,7 @@ pub struct FavoritesManager {#[serde(default)]pub items: Vec<FavoriteItem>,#[serde(skip)]- id_index: std::collections::HashSet<(String, String, i64)>,+ id_index: std::collections::HashSet<String>,}impl FavoritesManager {@@ -137,21 +137,23 @@ impl FavoritesManager {let prov_canonical = crate::providers::models::ProviderKind::parse(&item.provider).map(|p| p.cache_key().to_string()).unwrap_or_else(|| item.provider.trim().to_ascii_lowercase());- self.id_index- .insert((prov_canonical, item.subject_id.clone(), item.stype));+ self.id_index.insert(format!(+ "{}:{}:{}",+ prov_canonical, item.subject_id, item.stype+ ));}}pub fn is_favorite(&self, identity: &crate::models::SubjectIdentity<'_>) -> bool {if !identity.subject_id.is_empty() {let prov_canonical = crate::providers::models::ProviderKind::parse(identity.provider)- .map(|p| p.cache_key())- .unwrap_or_else(|| identity.provider.trim());- if self.id_index.iter().any(|(p, id, st)| {- *st == identity.stype- && p.eq_ignore_ascii_case(prov_canonical)- && id == identity.subject_id- }) {+ .map(|p| p.cache_key().to_string())+ .unwrap_or_else(|| identity.provider.trim().to_ascii_lowercase());+ let key = format!(+ "{}:{}:{}",+ prov_canonical, identity.subject_id, identity.stype+ );+ if self.id_index.contains(key.as_str()) {return true;}}diff --git a/src/history.rs b/src/history.rsindex aadcfed..765cd3d 100644--- a/src/history.rs+++ b/src/history.rs@@ -20,6 +20,8 @@ pub struct WatchHistoryItem {pub progress_seconds: u64,#[serde(default)]pub completed: bool,+ #[serde(default)]+ pub stream_filename: Option<String>,}impl WatchHistoryItem {@@ -59,6 +61,7 @@ impl WatchHistoryItem {duration_seconds,progress_seconds: 0,completed: false,+ stream_filename: None,}}@@ -198,6 +201,8 @@ pub struct PendingPlaybackState {pub stype: Option<i64>,#[serde(default)]pub release_year: Option<String>,+ #[serde(default)]+ pub stream_filename: Option<String>,}impl PendingPlaybackState {@@ -223,6 +228,7 @@ impl PendingPlaybackState {cover_url: item.cover_url.clone(),stype: Some(item.stype),release_year: Some(item.release_year.clone()),+ stream_filename: item.stream_filename.clone(),}}}@@ -622,6 +628,9 @@ impl HistoryManager {existing.duration_seconds = state.duration_seconds;existing.completed = state.completed;existing.timestamp = state.timestamp;+ if state.stream_filename.is_some() {+ existing.stream_filename = state.stream_filename.clone();+ }if !existing.completed {self.watched.remove(&key);}@@ -651,6 +660,9 @@ impl HistoryManager {existing_series.duration_seconds = state.duration_seconds;existing_series.completed = state.completed;existing_series.timestamp = state.timestamp;+ if state.stream_filename.is_some() {+ existing_series.stream_filename = state.stream_filename.clone();+ }if !existing_series.completed {self.watched.remove(&key);}@@ -676,6 +688,7 @@ impl HistoryManager {duration_seconds: state.duration_seconds,progress_seconds: state.progress_seconds,completed: state.completed,+ stream_filename: state.stream_filename,};if new_item.completed {self.watched.insert(key);@@ -721,6 +734,7 @@ mod tests {duration_seconds: Some(3600),progress_seconds: 1800,completed: false,+ stream_filename: None,}}@@ -786,6 +800,7 @@ mod tests {cover_url: None,stype: None,release_year: None,+ stream_filename: None,};std::fs::write(&state_file, serde_json::to_string(&state).unwrap()).unwrap();diff --git a/src/player.rs b/src/player.rsindex cfd5bb3..c660261 100644--- a/src/player.rs+++ b/src/player.rs@@ -567,21 +567,20 @@ fn probe_iina_resolution() -> Option<IinaResolution> {}#[cfg(target_os = "macos")]-static IINA_CACHED: std::sync::RwLock<Option<IinaResolution>> = std::sync::RwLock::new(None);+static IINA_CACHED: std::sync::RwLock<Option<Option<IinaResolution>>> =+ std::sync::RwLock::new(None);#[cfg(target_os = "macos")]fn iina_resolution() -> Option<IinaResolution> {if let Ok(guard) = IINA_CACHED.read() {- if let Some(res) = &*guard {- return Some(res.clone());+ if let Some(cached) = &*guard {+ return cached.clone();}}let detected = probe_iina_resolution();- if let Some(res) = &detected {- if let Ok(mut guard) = IINA_CACHED.write() {- *guard = Some(res.clone());- }+ if let Ok(mut guard) = IINA_CACHED.write() {+ *guard = Some(detected.clone());}detected}@@ -1280,41 +1279,45 @@ fn probe_vlc() -> Option<String> {)}-static MPV_CACHED: std::sync::RwLock<Option<String>> = std::sync::RwLock::new(None);-static VLC_CACHED: std::sync::RwLock<Option<String>> = std::sync::RwLock::new(None);+static MPV_CACHED: std::sync::RwLock<Option<Option<String>>> = std::sync::RwLock::new(None);+static VLC_CACHED: std::sync::RwLock<Option<Option<String>>> = std::sync::RwLock::new(None);fn mpv_executable() -> Option<String> {if let Ok(guard) = MPV_CACHED.read() {- if let Some(path) = &*guard {- if path.starts_with("flatpak run ") || Path::new(path).is_file() {- return Some(path.clone());+ if let Some(cached) = &*guard {+ if let Some(path) = cached {+ if path.starts_with("flatpak run ") || Path::new(path).is_file() {+ return Some(path.clone());+ }+ } else {+ return None;}}}let detected = probe_mpv();- if let Some(path) = &detected {- if let Ok(mut guard) = MPV_CACHED.write() {- *guard = Some(path.clone());- }+ if let Ok(mut guard) = MPV_CACHED.write() {+ *guard = Some(detected.clone());}detected}fn vlc_executable() -> Option<String> {if let Ok(guard) = VLC_CACHED.read() {- if let Some(path) = &*guard {- if path.starts_with("flatpak run ") || Path::new(path).is_file() {- return Some(path.clone());+ if let Some(cached) = &*guard {+ if let Some(path) = cached {+ if path.starts_with("flatpak run ") || Path::new(path).is_file() {+ return Some(path.clone());+ }+ } else {+ return None;}}}let detected = probe_vlc();- if let Some(path) = &detected {- if let Ok(mut guard) = VLC_CACHED.write() {- *guard = Some(path.clone());- }+ if let Ok(mut guard) = VLC_CACHED.write() {+ *guard = Some(detected.clone());}detected}diff --git a/src/player/tracker.rs b/src/player/tracker.rsindex 5f22cc1..80c6135 100644--- a/src/player/tracker.rs+++ b/src/player/tracker.rs@@ -19,8 +19,10 @@ local meta_title = ""local meta_cover = ""local meta_stype = 0local meta_year = ""+local meta_stream = ""local seed_read = false-+local last_written_pos = -1+local last_written_completed = falselocal function read_seed_meta()if seed_read or opts.state_file == "" then return endseed_read = true@@ -34,6 +36,7 @@ local function read_seed_meta()local st = content:match('"stype":%s*(%d+)')if st then meta_stype = tonumber(st) or 0 endmeta_year = content:match('"release_year":%s*"([^"]-)"') or ""+ meta_stream = content:match('"stream_filename":%s*"([^"]-)"') or ""endmp.observe_property("time-pos", "number", function(name, val)@@ -52,8 +55,6 @@ local function write_state(force_completed)if opts.state_file == "" then return endif last_dur <= 0 and last_pos <= 0 then return end- read_seed_meta()-if force_completed thenhas_completed = trueend@@ -61,7 +62,16 @@ local function write_state(force_completed)has_completed = trueend- local now = os.time()+ local pos_floor = math.floor(last_pos + 0.5)+ local is_paused = mp.get_property_native("pause") == true+ if not force_completed and is_paused and pos_floor == last_written_pos and has_completed == last_written_completed then+ return+ end+ if not force_completed and math.abs(pos_floor - last_written_pos) < 1 and has_completed == last_written_completed then+ return+ end++ read_seed_meta()local dur_val = "null"if last_dur > 0 thendur_val = string.format("%d", math.floor(last_dur + 0.5))@@ -77,6 +87,9 @@ local function write_state(force_completed)meta_year)end+ if meta_stream ~= "" then+ meta_json = meta_json .. string.format(',"stream_filename":%q', meta_stream)+ endlocal json = string.format('{"provider":%q,"subject_id":%q,"season":%d,"episode":%d,"progress_seconds":%d,"duration_seconds":%s,"completed":%s,"timestamp":%d%s}',@@ -99,9 +112,17 @@ local function write_state(force_completed)f:close()os.remove(opts.state_file)os.rename(tmp_file, opts.state_file)+ last_written_pos = pos_floor+ last_written_completed = has_completedendend+mp.observe_property("pause", "bool", function(name, val)+ if val then+ write_state(false)+ end+end)+mp.register_event("end-file", function(event)if event and event.reason == "eof" thenwrite_state(true)diff --git a/src/providers/addons/aggregator.rs b/src/providers/addons/aggregator.rsindex 6d705da..8274d58 100644--- a/src/providers/addons/aggregator.rs+++ b/src/providers/addons/aggregator.rs@@ -37,11 +37,13 @@ pub async fn aggregate_streams(let m_type = media_type.to_string();tasks.push(async move {- let streams_res = client_clone- .fetch_streams(&base_url, &m_type, &id_clone)- .await;+ let streams_res = tokio::time::timeout(+ std::time::Duration::from_millis(5000),+ client_clone.fetch_streams(&base_url, &m_type, &id_clone),+ )+ .await;match streams_res {- Ok(items) => {+ Ok(Ok(items)) => {let mut releases = Vec::new();for item in &items {if let Some(rel) =@@ -56,10 +58,14 @@ pub async fn aggregate_streams((releases, None)}}- Err(err) => {+ Ok(Err(err)) => {log::warn!("addon {addon_name} failed to fetch streams: {err}");(Vec::new(), None)}+ Err(_) => {+ log::warn!("addon {addon_name} timed out fetching streams");+ (Vec::new(), None)+ }}});}diff --git a/src/providers/bdix/dhakaflix/client.rs b/src/providers/bdix/dhakaflix/client.rsindex b1a9251..5a2c5a0 100644--- a/src/providers/bdix/dhakaflix/client.rs+++ b/src/providers/bdix/dhakaflix/client.rs@@ -229,9 +229,9 @@ impl DhakaFlixClient {let item_ids: Vec<(usize, String)> = all_results.iter().enumerate()+ .take(20).map(|(idx, item)| (idx, item.id.value.clone())).collect();-let poster_stream = futures::stream::iter(item_ids.into_iter().map(|(idx, id)| {let client = self.client.clone();diff --git a/src/providers/fourkhdhub/client.rs b/src/providers/fourkhdhub/client.rsindex 458e97f..a076c56 100644--- a/src/providers/fourkhdhub/client.rs+++ b/src/providers/fourkhdhub/client.rs@@ -152,32 +152,31 @@ impl FourKHdHubClient {));}- for chunk in unique_candidates.chunks(3) {- let chunk_futures = chunk.iter().map(|(url, label, headers)| {- let this = self.clone();- let url = url.clone();- let label = label.clone();- let mut merged = headers.clone();- if !merged- .iter()- .any(|(name, _)| name.eq_ignore_ascii_case("referer"))- {- merged.push(("Referer".to_string(), referer.clone()));- }- if !merged- .iter()- .any(|(name, _)| name.eq_ignore_ascii_case("user-agent"))- {- merged.push(("User-Agent".to_string(), BROWSER_UA.to_string()));- }- Box::pin(async move {- let playable_url = this.preflight(&url, &merged).await?;- Ok::<_, FourKHdHubError>((playable_url, label, merged))- })- });- if let Ok(((playable_url, label, headers), _)) =- futures::future::select_ok(chunk_futures).await+ use futures::StreamExt;+ let mut preflight_tasks = futures::stream::FuturesUnordered::new();+ for (url, label, headers) in unique_candidates.into_iter().take(6) {+ let this = self.clone();+ let mut merged = headers;+ if !merged+ .iter()+ .any(|(name, _)| name.eq_ignore_ascii_case("referer")){+ merged.push(("Referer".to_string(), referer.clone()));+ }+ if !merged+ .iter()+ .any(|(name, _)| name.eq_ignore_ascii_case("user-agent"))+ {+ merged.push(("User-Agent".to_string(), BROWSER_UA.to_string()));+ }+ preflight_tasks.push(async move {+ let playable_url = this.preflight(&url, &merged).await?;+ Ok::<_, FourKHdHubError>((playable_url, label, merged))+ });+ }++ while let Some(res) = preflight_tasks.next().await {+ if let Ok((playable_url, label, headers)) = res {log::info!("4KHDHub mirror playable: {label} ({})",crate::logging::sanitize_url(&playable_url)diff --git a/src/proxy.rs b/src/proxy.rsindex 2e32f71..71f8a45 100644--- a/src/proxy.rs+++ b/src/proxy.rs@@ -161,7 +161,10 @@ pub async fn run_sidecar(loop {let (stream, _) = match listener.accept().await {- Ok(val) => val,+ Ok(conn) => {+ let _ = conn.0.set_nodelay(true);+ conn+ }Err(err) => {log::warn!("transient proxy accept error: {err}");tokio::time::sleep(Duration::from_millis(50)).await;@@ -407,7 +410,10 @@ async fn handle_connection(tokio::time::timeout(Duration::from_secs(CHUNK_IDLE_TIMEOUT_SECS), stream.next()).await;match chunk_result {- Ok(Some(Ok(chunk))) => writer.write_all(&chunk).await?,+ Ok(Some(Ok(chunk))) => {+ writer.write_all(&chunk).await?;+ writer.flush().await?;+ }Ok(Some(Err(e))) => return Err(Box::new(e)),Ok(None) => break,Err(_elapsed) => break,diff --git a/src/tui/app/keyboard.rs b/src/tui/app/keyboard.rsindex 90c8041..b9445f4 100644--- a/src/tui/app/keyboard.rs+++ b/src/tui/app/keyboard.rs@@ -1367,6 +1367,7 @@ mod tests {duration_seconds: Some(500),completed: false,timestamp: 1000,+ stream_filename: None,};app.state.history.record_start(&item, 50);app.state.search_results.push(item.to_search_result());diff --git a/src/tui/app/playback.rs b/src/tui/app/playback.rsindex 34172ad..b05fef4 100644--- a/src/tui/app/playback.rs+++ b/src/tui/app/playback.rs@@ -162,10 +162,12 @@ impl App {let provider = self.provider_for_subject(subject_id).cache_key();let season = self.state.selected_season;let episode = self.state.selected_episode;+ let selected_stream_filename = self.get_selected_release().map(|r| r.filename.clone());if let Some(details) = &self.state.selected_details {let mut item =crate::history::WatchHistoryItem::from_details(provider, details, season, episode);+ item.stream_filename = selected_stream_filename;if item.cover_url.is_none() {item.cover_url = self.state@@ -223,6 +225,7 @@ impl App {duration_seconds: None,progress_seconds: 0,completed: false,+ stream_filename: selected_stream_filename,})}@@ -1042,8 +1045,6 @@ impl App {}Action::MarkWatched(item) => {self.state.history.mark_watched(*item);- let history = self.state.history.clone();- tokio::task::spawn_blocking(move || history.save());}Action::UpdateProgress {item,diff --git a/src/tui/app/requests.rs b/src/tui/app/requests.rsindex a783b6a..fcd65f1 100644--- a/src/tui/app/requests.rs+++ b/src/tui/app/requests.rs@@ -1751,9 +1751,37 @@ impl App {self.state.is_fetching_streams = false;self.state.has_streams_settled = true;self.state.stream_error = None;- self.state- .resource_list_state- .select(if count > 0 { Some(0) } else { None });+ let preferred_stream_idx = if count > 0 {+ let saved_stream = self+ .state+ .active_subject_id+ .as_deref()+ .and_then(|sid| {+ self.state.history.get_item(+ context.provider.cache_key(),+ sid,+ target_se,+ target_ep,+ self.state+ .selected_details+ .as_ref()+ .map(|d| d.title.as_str()),+ )+ })+ .and_then(|item| item.stream_filename.as_deref());+ if let Some(target_file) = saved_stream {+ self.state+ .selected_resources+ .iter()+ .position(|r| r.filename == target_file)+ .or(Some(0))+ } else {+ Some(0)+ }+ } else {+ None+ };+ self.state.resource_list_state.select(preferred_stream_idx);self.state.set_status_default(format!("{} streams available.", count));@@ -2163,4 +2191,101 @@ mod tests {assert_eq!(app.state.search_results.len(), 2);assert!(app.state.search_exhausted);}++ #[tokio::test]+ async fn test_episode_streams_auto_selects_saved_stream_filename() {+ let mut app = App::new();+ app.state.active_provider = ProviderKind::FourKHdHub;+ let context = app.request_context();+ app.state.active_subject_id = Some("dune-2021".to_string());+ app.state.selected_details = Some(crate::providers::models::MediaDetails {+ id: crate::providers::models::ProviderMediaId {+ provider: ProviderKind::FourKHdHub,+ value: "dune-2021".to_string(),+ },+ title: "Dune".to_string(),+ media_type: crate::models::MediaType::Movie,+ year: Some("2021".to_string()),+ description: None,+ tagline: None,+ imdb_rating: None,+ director: None,+ stars: None,+ prints: None,+ audios: None,+ poster_url: None,+ duration: None,+ genres: vec![],+ seasons: vec![],+ dubs: vec![],+ });++ let hist = crate::history::WatchHistoryItem {+ provider: "4khdhub".to_string(),+ subject_id: "dune-2021".to_string(),+ title: "Dune".to_string(),+ cover_url: None,+ stype: 1,+ release_year: "2021".to_string(),+ season: 1,+ episode: 1,+ timestamp: 1000,+ duration_seconds: Some(7200),+ progress_seconds: 1500,+ completed: false,+ stream_filename: Some("Dune.1080p.mkv".to_string()),+ };+ app.state.history.recent.push(hist);++ let streams = vec![+ Release {+ provider: ProviderKind::FourKHdHub,+ filename: "Dune.2160p.mkv".to_string(),+ quality: Some("2160p".to_string()),+ codec: Some("hevc".to_string()),+ language: None,+ size_bytes: Some(15000000000),+ season: None,+ episode: None,+ mirrors: vec![],+ resource_id: None,+ },+ Release {+ provider: ProviderKind::FourKHdHub,+ filename: "Dune.1080p.mkv".to_string(),+ quality: Some("1080p".to_string()),+ codec: Some("hevc".to_string()),+ language: None,+ size_bytes: Some(3000000000),+ season: None,+ episode: None,+ mirrors: vec![],+ resource_id: None,+ },+ Release {+ provider: ProviderKind::FourKHdHub,+ filename: "Dune.720p.mkv".to_string(),+ quality: Some("720p".to_string()),+ codec: Some("h264".to_string()),+ language: None,+ size_bytes: Some(1000000000),+ season: None,+ episode: None,+ mirrors: vec![],+ resource_id: None,+ },+ ];++ app.handle_requests(Action::EpisodeStreamsReady(+ context,+ 0,+ "dune-2021".to_string(),+ 1,+ 1,+ streams,+ ))+ .await;++ assert_eq!(app.state.resource_list_state.selected(), Some(1));+ }}diff --git a/src/tui/app/system.rs b/src/tui/app/system.rsindex 9fa9d53..29faba4 100644--- a/src/tui/app/system.rs+++ b/src/tui/app/system.rs@@ -77,11 +77,35 @@ impl App {let count = cached.len();self.state.selected_resources = cached.clone();self.state.is_loading = false;- self.state.resource_list_state.select(if count > 0 {- Some(0)+ let preferred_stream_idx = if count > 0 {+ let provider_key =+ self.provider_for_subject(&subject_id).cache_key();+ let saved_stream = self+ .state+ .history+ .get_item(+ provider_key,+ &subject_id,+ se,+ ep,+ self.state+ .selected_details+ .as_ref()+ .map(|d| d.title.as_str()),+ )+ .and_then(|item| item.stream_filename.as_deref());+ if let Some(target_file) = saved_stream {+ cached+ .iter()+ .position(|r| r.filename == target_file)+ .or(Some(0))+ } else {+ Some(0)+ }} else {None- });+ };+ self.state.resource_list_state.select(preferred_stream_idx);self.state.set_status_default(format!("Resolved {} direct stream sources (cached).",countdiff --git a/src/tui/screens/home.rs b/src/tui/screens/home.rsindex 7d049dc..ca78200 100644--- a/src/tui/screens/home.rs+++ b/src/tui/screens/home.rs@@ -3242,6 +3242,7 @@ mod tests {duration_seconds: Some(3000),completed: false,timestamp: 100,+ stream_filename: None,});state.favorites.items.push(crate::favorites::FavoriteItem {provider: "moviebox".to_string(),diff --git a/tests/content_pipeline.rs b/tests/content_pipeline.rsindex b473695..ef1f5c6 100644--- a/tests/content_pipeline.rs+++ b/tests/content_pipeline.rs@@ -461,6 +461,7 @@ async fn test_series_details_resumes_watch_history() {timestamp: 1000,release_year: "2008".to_string(),cover_url: None,+ stream_filename: None,});app.state_mut().active_details_request = 1;diff --git a/tests/history_audit.rs b/tests/history_audit.rsindex 951fb63..2fc6bc7 100644--- a/tests/history_audit.rs+++ b/tests/history_audit.rs@@ -30,6 +30,7 @@ fn dummy_history_item(duration_seconds: duration,progress_seconds: progress,completed,+ stream_filename: None,}}@@ -314,6 +315,7 @@ fn test_reconciliation_from_lua_tracker_state_files() {cover_url: None,stype: None,release_year: None,+ stream_filename: None,};let state_file_1 = temp_dir.path().join("moviebox_show_alpha_1_1.json");std::fs::write(&state_file_1, serde_json::to_string(&state1).unwrap()).unwrap();@@ -331,6 +333,7 @@ fn test_reconciliation_from_lua_tracker_state_files() {cover_url: None,stype: None,release_year: None,+ stream_filename: None,};let state_file_2 = temp_dir.path().join("moviebox_show_alpha_1_2.json");std::fs::write(&state_file_2, serde_json::to_string(&state2).unwrap()).unwrap();@@ -523,6 +526,7 @@ fn test_reconciliation_self_heals_unseen_items_with_metadata() {cover_url: Some("https://example.com/inception.jpg".to_string()),stype: Some(1),release_year: Some("2010".to_string()),+ stream_filename: None,};std::fs::write(&state_file, serde_json::to_string(&state).unwrap()).unwrap();diff --git a/tests/settings_hub.rs b/tests/settings_hub.rsindex 53fc83d..dc442ca 100644--- a/tests/settings_hub.rs+++ b/tests/settings_hub.rs@@ -383,6 +383,7 @@ async fn test_settings_hub_clear_watch_history_activation() {duration_seconds: Some(600),completed: false,timestamp: 1000,+ stream_filename: None,};app.state_mut().history.record_start(&item, 120);assert!(!app.state().history.recent.is_empty());diff --git a/tests/tui_acceptance.rs b/tests/tui_acceptance.rsindex b250e3e..4ddd8da 100644--- a/tests/tui_acceptance.rs+++ b/tests/tui_acceptance.rs@@ -1083,6 +1083,7 @@ async fn test_home_deck_tab_switching() {duration_seconds: Some(3000),completed: false,timestamp: 100,+ stream_filename: None,});app.state_mut().favorites@@ -1201,6 +1202,7 @@ async fn test_home_deck_continue_watching_resume() {duration_seconds: Some(3000),completed: false,timestamp: 200,+ stream_filename: None,});app.state_mut().favorites_focus = true;@@ -1246,6 +1248,7 @@ async fn test_landing_deck_header_renders_without_star_or_bracket() {duration_seconds: Some(3000),completed: false,timestamp: 100,+ stream_filename: None,});app.state_mut().favorites