Terminal interface to find, download, and stream movies, TV shows, and live TV using local media players.
feat(tui): add home continue watching deck and multi-tab navigation
Samir Hossains66c888060ef2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 68c29e0..f9010ae 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,12 @@## [Unreleased]### Added+- **Home Landing Deck Continue Watching & Multi-Tab Navigation**:+ - Implemented interactive multi-tab landing deck on the Home screen supporting both `Continue Watching` and `Favorites`.+ - Added seamless `Tab` and `Shift+Tab` keyboard cycling between Continue Watching and Favorites tabs with instant row focus retention.+ - Added one-click/key direct resume (`Enter`, `Space`, or `P`) on Continue Watching items, automatically configuring episode advancement, season positioning, and auto-play in Details view.+ - Formatted Continue Watching rows with title truncation, series episode badge (`S01E03`), progress percentage, and remaining duration (`45% · 24m left`).+ - Added mouse support for clicking the landing deck header bar to switch tabs, and double-clicking items to play/open.- **Windows TrueColor & High-Contrast Terminal Theming**:- Enabled 24-bit TrueColor auto-detection by default on Windows 10/11 (`conhost.exe`, Windows Terminal, PowerShell, CMD), ensuring Windows users receive rich Catppuccin themes out of the box.- Overhauled 16-color ANSI dark fallback palette (`Theme::fallback`), replacing low-contrast dark blue and magenta with high-contrast cyan accents for borders, titles, headers, and highlights.@@ -21,6 +27,14 @@- Removed redundant `Poster Graphics` toggle from Settings Hub (`/settings` $\to$ Appearance) and `config.json`, delegating terminal graphics strictly to automatic native GPU protocol detection (Kitty, Sixel, iTerm2).### Fixed+- **High-Precision Playback Tracking & Race Elimination**:+ - Eliminated wall-clock race condition where process elapsed time overwrote exact seek/pause positions from `mpv` and `iina-cli` Lua trackers.+ - Hardened `moviebox_tracker.lua` with latched completion: reaching $\ge 90\%$ playback or EOF permanently latches completion, preventing shutdown events from reverting completed status.+ - Implemented atomic state file persistence in Lua using temporary files (`.tmp`) and clean destination replacement for Windows and Unix platforms.+ - Handled unknown stream durations by writing JSON `null`, preventing zero-duration calculations.+ - Pre-registered media playback on launch (`record_start`), ensuring immediate watch history persistence for Android intent dispatchers (`termux-open`, `am start`) and app fallbacks.+ - Added self-healing recovery in `reconcile_from_dir`: pre-seeded pending state files carry metadata (`title`, `cover_url`, `stype`, `release_year`), restoring new items into watch history even after sudden terminal exits or reboots.+ - Implemented smart series episode advancement: completing an episode automatically cues the next episode (`episode + 1` or next season) on resume (`Space`/`P`) and in the Details view.- **Standardized 'No Art' Poster Containers Across Terminals**:- Replaced robot eyes and broken infinite loading spinners with clean, static, centered `No Art` bordered blocks across search results and details screens on terminals without graphics support.- Preserved full-fidelity native GPU graphics rendering on supported terminals while standardizing card geometry and poster container boundaries across all platforms.@@ -34,6 +48,9 @@- **Pruned Redundant Theme Slash Command**:- Removed standalone `/theme` slash command, parser routing, and auto-suggestions; theme selection and visual palette swatches are managed directly within the interactive Settings Hub (`/settings` $\to$ Appearance $\to$ Theme).- **Discover Categories Landing Card UX**:+- **Clean Segmented Landing Deck Header Styling**:+ - Replaced crowded decorative star (`★`) and bracket (`[ ]`) glyphs with a clean, segmented tab bar header (`Continue Watching │ Favorites (Tab)`).+ - Streamlined overflow row formatting to centered minimalist pill indicators (`+N more · /history` and `+N more · /favorites`).- Streamlined `Discover & Quick Categories` card: elevated `/browse` command to a right-aligned header badge (`[ /browse ]`), eliminated redundant `/browse ·` row prefixes, and adapted category rows dynamically between Streaming and Addon modes.- Added direct mouse click navigation to discover categories, routing clicks to preset browse queries or the addon catalog menu.- **Command Dispatch & Cache Lookup Optimization**:diff --git a/docs/controls.md b/docs/controls.mdindex 5cdbd36..d4f827f 100644--- a/docs/controls.md+++ b/docs/controls.md@@ -11,9 +11,9 @@ MovieBox-TUI is designed for fast keyboard navigation with complete mouse suppor| **`Home` / `End` / `g` / `G`** | Jump to start / end of list or search results (auto-fetches next page), or move cursor to beginning / end of input line || **`PageUp` / `PageDown`** | Scroll search results, lists, and modal pickers by visible page height (or scroll help overlay) || **`Enter`** | Open, play, or confirm the selected item |-| **`Space` / `P`** | Direct resume playback for recorded season/episode on `/history` items |+| **`Space` / `P`** | Direct resume playback for recorded season/episode on `/history` or Home Continue Watching items || **`Esc`** | Focus search input (when results present), dismiss popup dialog, or return to landing |-| **`Tab` / `Shift+Tab`** | Auto-complete suggestion / command; switch details panes; toggle dialog buttons |+| **`Tab` / `Shift+Tab`** | Auto-complete suggestion / command; cycle landing deck tabs (Continue Watching / Favorites); switch details panes; toggle dialog buttons || **`Backspace`** | Delete character before cursor, or return focus to search bar from results || **`Delete`** | Delete character at cursor in text inputs, or remove entry in TV/Addon managers || **`Ctrl+U`** | Clear entire input line (Search, TV URL, Addon URL) |@@ -90,8 +90,10 @@ All popup dialogs (Theme picker, Browse categories, Settings Media Player picker| **Click search bar** | Enter search input mode || **Click suggestion item** | Search for that suggestion immediately || **Click search result row** | Select item and load preview; click again to open full details |-| **Click Favorites row (landing)** | Select a starred title; click again to open it |-| **Click "+N more • /favorites"** | Open the full favorites list |+| **Click landing deck tab header** | Switch between Continue Watching and Favorites tabs |+| **Click Continue Watching row (landing)** | Select an in-progress title; click again to resume playback with auto-play |+| **Click Favorites row (landing)** | Select a starred title; click again to open details |+| **Click "+N more • /history" or "+N more • /favorites"** | Open the full watch history or favorites list || **Click audio / season / episode / stream** | Switch audio language, change season, or select episode; click a specific stream row to play; click empty stream pane space to focus without playing || **Click footer buttons** | Switch provider / mode, open help (`[?]`), or quit (`[q]`) || **Click modal buttons** | Choose a theme, subtitles, player, or confirm actions |diff --git a/docs/players.md b/docs/players.mdindex 3248d51..5ba80aa 100644--- a/docs/players.md+++ b/docs/players.md@@ -44,13 +44,12 @@ The `supports_headers` gate in `app/playback.rs` validates whether a player can## Playback Tracking & Resume-When launching media with in-progress watch history, the player command automatically-includes the starting position (`--start` / `--mpv-start` / `--start-time`). For `mpv`,-`src/player/tracker.rs` writes a companion tracker script (`moviebox_tracker.lua`) that-observes `time-pos` and `duration`, periodically saving playback state every 5 seconds to-the local data directory. On startup or after player exit, pending playback states are-reconciled into `history.json`.+When launching media with in-progress watch history, the player command automatically includes the starting position (`--start` / `--mpv-start` / `--start-time`).+- **Immediate Start Registration**: Media sessions are pre-registered into watch history (`record_start`) upon launch, ensuring that fast-exiting intent dispatchers (Android `termux-open` / `am start`, macOS `open -a IINA`) and unexpected terminal terminations retain history immediately.+- **Pre-Seeded State Files**: Before launching mpv or IINA, MovieBox-TUI creates a pending state file populated with metadata (`title`, `cover_url`, `stype`, `release_year`). If the application exits abruptly during playback, `reconcile_from_dir` self-heals and inserts new items into watch history without data loss.+- **Latched Lua Tracker (`moviebox_tracker.lua`)**: Observes `time-pos` and `duration` every 5 seconds. State file writes are atomic (`.tmp` file flushed and renamed with destination removal for Windows compatibility). Video completion at $\ge 90\%$ or EOF is permanently latched, preventing player shutdown events from resetting completion status. Missing or live stream durations write JSON `null` to prevent invalid duration calculations.+- **Isolated Tracker vs Fallback Reconciliation**: Players with active Lua trackers (`mpv`, `iina-cli`) rely strictly on state file reconciliation, eliminating wall-clock progress overwrite races during pauses or seeks. Process elapsed time is used strictly as a guarded fallback for players without tracker scripts (e.g. VLC).## Spawning`launch_player` spawns the player with null stdin/stdout, piped stderr, and its owndiff --git a/src/history.rs b/src/history.rsindex ec9fea9..b18ca09 100644--- a/src/history.rs+++ b/src/history.rs@@ -163,6 +163,20 @@ impl WatchHistoryItem {format!("{}w ago", delta / 604800)}}++ pub fn to_search_result(&self) -> crate::models::SearchResult {+ crate::models::SearchResult {+ id: self.subject_id.clone(),+ title: self.title.clone(),+ stype: self.stype,+ release_year: self.release_year.clone(),+ cover_url: self.cover_url.clone(),+ season: self.season,+ episode: self.episode.max(1),+ provider: crate::models::ProviderKind::parse(&self.provider)+ .unwrap_or(crate::models::ProviderKind::MovieBox),+ }+ }}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -175,6 +189,41 @@ pub struct PendingPlaybackState {pub duration_seconds: Option<u64>,pub completed: bool,pub timestamp: u64,+ #[serde(default)]+ pub title: Option<String>,+ #[serde(default)]+ pub cover_url: Option<String>,+ #[serde(default)]+ pub stype: Option<i64>,+ #[serde(default)]+ pub release_year: Option<String>,+}++impl PendingPlaybackState {+ pub fn from_item(+ item: &WatchHistoryItem,+ progress: u64,+ duration: Option<u64>,+ completed: bool,+ ) -> Self {+ Self {+ provider: item.provider.clone(),+ subject_id: item.subject_id.clone(),+ season: item.season,+ episode: item.episode,+ progress_seconds: progress,+ duration_seconds: duration,+ completed,+ timestamp: std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap_or_default()+ .as_secs(),+ title: Some(item.title.clone()),+ cover_url: item.cover_url.clone(),+ stype: Some(item.stype),+ release_year: Some(item.release_year.clone()),+ }+ }}#[derive(Default, Clone, Serialize, Deserialize)]@@ -417,6 +466,36 @@ impl HistoryManager {}self.save();}+ pub fn record_start(&mut self, item: &WatchHistoryItem, start_pos: u64) {+ let mut new_item = item.clone();+ if let Some(existing) = self.recent.iter().find(|i| Self::is_same_show(i, item)) {+ if new_item.cover_url.is_none() {+ new_item.cover_url = existing.cover_url.clone();+ }+ if existing.season == new_item.season && existing.episode == new_item.episode {+ new_item.progress_seconds = existing.progress_seconds.max(start_pos);+ new_item.duration_seconds = existing.duration_seconds.or(new_item.duration_seconds);+ new_item.completed = existing.completed;+ } else {+ new_item.progress_seconds = start_pos;+ }+ } else {+ new_item.progress_seconds = start_pos;+ }+ new_item.timestamp = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap_or_default()+ .as_secs();++ self.recent.retain(|i| !Self::is_same_show(i, &new_item));+ self.recent.push(new_item);++ if self.recent.len() > 100 {+ let excess = self.recent.len() - 100;+ self.recent.drain(0..excess);+ }+ self.save();+ }pub fn remove(&mut self, provider: &str, subject_id: &str, season: usize, episode: usize) {let key = Self::key(provider, subject_id, season, episode);@@ -576,6 +655,37 @@ impl HistoryManager {}modified = true;}+ } else if let Some(title) = state.title.filter(|t| !t.trim().is_empty()) {+ let new_item = WatchHistoryItem {+ provider: state.provider.clone(),+ subject_id: state.subject_id.clone(),+ title,+ cover_url: state.cover_url,+ stype: state+ .stype+ .unwrap_or(if state.season > 0 || state.episode > 0 {+ 2+ } else {+ 1+ }),+ release_year: state.release_year.unwrap_or_default(),+ season: state.season,+ episode: state.episode,+ timestamp: state.timestamp,+ duration_seconds: state.duration_seconds,+ progress_seconds: state.progress_seconds,+ completed: state.completed,+ };+ if new_item.completed {+ self.watched.insert(key);+ }+ self.recent.retain(|i| !Self::is_same_show(i, &new_item));+ self.recent.push(new_item);+ if self.recent.len() > 100 {+ let excess = self.recent.len() - 100;+ self.recent.drain(0..excess);+ }+ modified = true;}let _ = fs::remove_file(&path);}@@ -671,6 +781,10 @@ mod tests {duration_seconds: Some(3600),completed: true,timestamp: 2000,+ title: None,+ cover_url: None,+ stype: None,+ release_year: None,};std::fs::write(&state_file, serde_json::to_string(&state).unwrap()).unwrap();diff --git a/src/player/tracker.rs b/src/player/tracker.rsindex 3fe59b7..c602ffa 100644--- a/src/player/tracker.rs+++ b/src/player/tracker.rs@@ -14,6 +14,27 @@ options.read_options(opts, "moviebox")local last_pos = 0local last_dur = 0+local has_completed = false+local meta_title = ""+local meta_cover = ""+local meta_stype = 0+local meta_year = ""+local seed_read = false++local function read_seed_meta()+ if seed_read or opts.state_file == "" then return end+ seed_read = true+ local f = io.open(opts.state_file, "r")+ if not f then return end+ local content = f:read("*a")+ f:close()+ if not content then return end+ meta_title = content:match('"title":%s*"([^"]-)"') or ""+ meta_cover = content:match('"cover_url":%s*"([^"]-)"') or ""+ local st = content:match('"stype":%s*(%d+)')+ if st then meta_stype = tonumber(st) or 0 end+ meta_year = content:match('"release_year":%s*"([^"]-)"') or ""+endmp.observe_property("time-pos", "number", function(name, val)if val then@@ -31,25 +52,53 @@ local function write_state(force_completed)if opts.state_file == "" then return endif last_dur <= 0 and last_pos <= 0 then return end- local completed = force_completed or (last_dur > 0 and last_pos >= (0.90 * last_dur))+ read_seed_meta()++ if force_completed then+ has_completed = true+ end+ if last_dur > 0 and last_pos >= (0.90 * last_dur) then+ has_completed = true+ end+local now = os.time()+ local dur_val = "null"+ if last_dur > 0 then+ dur_val = string.format("%d", math.floor(last_dur + 0.5))+ end++ local meta_json = ""+ if meta_title ~= "" then+ meta_json = string.format(+ ',"title":%q,"cover_url":%q,"stype":%d,"release_year":%q',+ meta_title,+ meta_cover,+ meta_stype,+ meta_year+ )+ endlocal json = string.format(- '{"provider":%q,"subject_id":%q,"season":%d,"episode":%d,"progress_seconds":%d,"duration_seconds":%d,"completed":%s,"timestamp":%d}',+ '{"provider":%q,"subject_id":%q,"season":%d,"episode":%d,"progress_seconds":%d,"duration_seconds":%s,"completed":%s,"timestamp":%d%s}',opts.provider,opts.subject_id,tonumber(opts.season) or 0,tonumber(opts.episode) or 0,math.floor(last_pos + 0.5),- math.floor(last_dur + 0.5),- completed and "true" or "false",- now+ dur_val,+ has_completed and "true" or "false",+ now,+ meta_json)- local f = io.open(opts.state_file, "w")+ local tmp_file = opts.state_file .. ".tmp"+ local f = io.open(tmp_file, "w")if f thenf:write(json)+ f:flush()f:close()+ os.remove(opts.state_file)+ os.rename(tmp_file, opts.state_file)endenddiff --git a/src/tui/action.rs b/src/tui/action.rsindex 2a04be5..d85a55c 100644--- a/src/tui/action.rs+++ b/src/tui/action.rs@@ -158,4 +158,5 @@ pub enum Action {ToggleFavorite,ShowFavorites,OpenFavorite(usize),+ OpenContinueWatching(usize),}diff --git a/src/tui/app/favorites.rs b/src/tui/app/favorites.rsindex 8666242..5b618a5 100644--- a/src/tui/app/favorites.rs+++ b/src/tui/app/favorites.rs@@ -25,6 +25,9 @@ impl App {Action::OpenFavorite(index) => {self.open_favorite(index);}+ Action::OpenContinueWatching(index) => {+ self.open_continue_watching(index);+ }_ => return None,}None@@ -42,10 +45,26 @@ impl App {Screen::Home => {if self.state.favorites_focus {let idx = self.state.favorites_landing_state.selected()?;- self.state- .favorites_landing_items()- .get(idx)- .map(|item| (*item).clone())+ match self.state.effective_home_deck_tab() {+ crate::tui::state::HomeDeckTab::ContinueWatching => {+ let items = self.state.continue_watching_items();+ let item = items.get(idx)?;+ Some(crate::favorites::FavoriteItem {+ provider: item.provider.clone(),+ subject_id: item.subject_id.clone(),+ title: item.title.clone(),+ cover_url: item.cover_url.clone(),+ stype: item.stype,+ release_year: item.release_year.clone(),+ added_at: now_secs(),+ })+ }+ crate::tui::state::HomeDeckTab::Favorites => self+ .state+ .favorites_landing_items()+ .get(idx)+ .map(|item| (*item).clone()),+ }} else {let idx = self.state.search_list_state.selected()?;let res = self.state.search_results.get(idx)?;@@ -116,7 +135,7 @@ impl App {);}- fn open_favorite(&mut self, index: usize) {+ pub(super) fn open_favorite(&mut self, index: usize) {let Some(item) = self.state.favorites_landing_items()@@ -162,6 +181,65 @@ impl App {.ok();}+ pub(super) fn open_continue_watching(&mut self, index: usize) {+ let items = self.state.continue_watching_items();+ let Some(item) = items.get(index).cloned().cloned() else {+ return;+ };+ let subject_id = item.subject_id.clone();+ let title = item.title.clone();+ let search_res = item.to_search_result();++ self.state.active_screen = Screen::Details;+ self.state.active_subject_id = Some(subject_id.clone());+ self.state.selected_details = Some(crate::models::MediaDetails::from_search_result(+ &search_res,+ self.state.search_preview.as_ref(),+ ));+ self.state.selected_resources.clear();+ self.state.is_loading = true;+ self.state.is_fetching_streams = false;+ self.state.stream_error = None;+ self.state.resource_list_state.select(None);+ self.state.language_list_state.select(Some(0));++ let se = if item.season > 0 { item.season } else { 1 };+ let mut ep = if item.episode > 0 { item.episode } else { 1 };+ if item.completed && item.stype == 2 {+ ep = ep.saturating_add(1);+ }+ self.state.selected_season = se;+ self.state.selected_episode = ep;+ self.state+ .season_list_state+ .select(Some(se.saturating_sub(1)));+ self.state+ .episode_list_state+ .select(Some(ep.saturating_sub(1)));++ self.state.auto_play_on_ready = true;+ self.state.language_chosen = false;+ self.state.available_seasons.clear();++ if let Some(cached) = self+ .state+ .image_cache+ .get(&subject_id)+ .or_else(|| self.state.search_posters.get(&subject_id))+ {+ self.state.poster_image = Some(std::sync::Arc::clone(cached));+ } else {+ self.state.poster_image = None;+ }++ self.state+ .set_status_default(format!("Resuming playback for {title}..."));++ self.action_sender+ .send(Action::FetchDetails(subject_id, false))+ .ok();+ }+pub(super) fn load_favorites_virtual_list(&mut self) {self.state.input_mode = InputMode::Normal;self.state.is_loading = false;diff --git a/src/tui/app/keyboard.rs b/src/tui/app/keyboard.rsindex 5c07d5c..37de752 100644--- a/src/tui/app/keyboard.rs+++ b/src/tui/app/keyboard.rs@@ -789,6 +789,11 @@ impl App {KeyCode::Right => {self.action_sender.send(Action::MoveRight).ok();}+ KeyCode::Tab | KeyCode::BackTab => {+ if self.state.landing_deck_visible() {+ self.state.cycle_home_deck_tab();+ }+ }KeyCode::Home | KeyCode::Char('g') => {if self.state.favorites_focus {self.state.favorites_landing_state.select(Some(0));@@ -805,7 +810,7 @@ impl App {}KeyCode::End | KeyCode::Char('G') => {if self.state.favorites_focus {- let total = self.state.favorites_landing_items().len();+ let total = self.state.landing_deck_items_count();if total > 0 {self.state.favorites_landing_state.select(Some(total - 1));}@@ -826,7 +831,7 @@ impl App {if self.state.favorites_focus {let cur =self.state.favorites_landing_state.selected().unwrap_or(0);- let total = self.state.favorites_landing_items().len();+ let total = self.state.landing_deck_items_count();if total > 0 {self.state.favorites_landing_state@@ -921,14 +926,25 @@ impl App {self.action_sender.send(Action::ToggleFavorite).ok();}KeyCode::Char(' ') | KeyCode::Char('p') | KeyCode::Char('P')- if self+ if (self.state.search_query.trim().eq_ignore_ascii_case("/history")- && !self.state.search_results.is_empty() =>+ && !self.state.search_results.is_empty())+ || (self.state.favorites_focus+ && self.state.effective_home_deck_tab()+ == crate::tui::state::HomeDeckTab::ContinueWatching) =>{- self.resume_history_playback();+ if self.state.favorites_focus {+ if let Some(idx) = self.state.favorites_landing_state.selected() {+ self.action_sender+ .send(Action::OpenContinueWatching(idx))+ .ok();+ }+ } else {+ self.resume_history_playback();+ }}KeyCode::Char(c)if (key.modifiers.is_empty()diff --git a/src/tui/app/mouse.rs b/src/tui/app/mouse.rsindex ee00c6e..209e147 100644--- a/src/tui/app/mouse.rs+++ b/src/tui/app/mouse.rs@@ -451,7 +451,7 @@ impl App {area,self.state.is_tv_mode,self.state.basic_terminal,- self.state.favorites_landing_visible(),+ self.state.landing_deck_visible(),))} else {None@@ -561,34 +561,33 @@ impl App {return None;}- if self.state.favorites_landing_visible() {- let fav_y = rows.rects[rows.favorites].y;- let favorites_items = self.state.favorites_landing_items();- let fav_count = favorites_items.len() as u16;- let overflow = self- .state- .favorites- .items- .len()- .saturating_sub(favorites_items.len());+ if self.state.landing_deck_visible() {+ let deck_y = rows.rects[rows.favorites].y;+ let item_count = self.state.landing_deck_items_count() as u16;+ let total_count = self.state.landing_deck_total_items_count();+ let overflow = total_count.saturating_sub(item_count as usize);let overflow_row = u16::from(overflow > 0);- let fav_height =- (fav_count + overflow_row + 2).min(rows.rects[rows.favorites].height);+ let deck_height =+ (item_count + overflow_row + 2).min(rows.rects[rows.favorites].height);- let fav_card_area = Rect {+ let deck_card_area = Rect {x: card_x,- y: fav_y,+ y: deck_y,width: card_width,- height: fav_height,+ height: deck_height,};- if col >= fav_card_area.left()- && col < fav_card_area.right()- && row >= fav_card_area.top()- && row < fav_card_area.bottom()+ if col >= deck_card_area.left()+ && col < deck_card_area.right()+ && row >= deck_card_area.top()+ && row < deck_card_area.bottom(){- let rel_row = row - fav_card_area.top();- if rel_row >= 1 && rel_row <= fav_count {+ let rel_row = row - deck_card_area.top();+ if rel_row == 0 {+ self.state.cycle_home_deck_tab();+ self.state.favorites_focus = true;+ self.state.input_mode = InputMode::Normal;+ } else if rel_row >= 1 && rel_row <= item_count {let idx = (rel_row - 1) as usize;let prev_selected = if self.state.favorites_focus {self.state.favorites_landing_state.selected()@@ -599,10 +598,31 @@ impl App {self.state.input_mode = InputMode::Normal;self.state.favorites_landing_state.select(Some(idx));if prev_selected == Some(idx) {- self.action_sender.send(Action::OpenFavorite(idx)).ok();+ match self.state.effective_home_deck_tab() {+ crate::tui::state::HomeDeckTab::ContinueWatching => {+ self.action_sender+ .send(Action::OpenContinueWatching(idx))+ .ok();+ }+ crate::tui::state::HomeDeckTab::Favorites => {+ self.action_sender.send(Action::OpenFavorite(idx)).ok();+ }+ }+ }+ } else if overflow > 0 && rel_row == item_count + 1 {+ match self.state.effective_home_deck_tab() {+ crate::tui::state::HomeDeckTab::ContinueWatching => {+ self.action_sender+ .send(Action::Search {+ query: "/history".to_string(),+ force_refresh: false,+ })+ .ok();+ }+ crate::tui::state::HomeDeckTab::Favorites => {+ self.action_sender.send(Action::ShowFavorites).ok();+ }}- } else if overflow > 0 && rel_row == fav_count + 1 {- self.action_sender.send(Action::ShowFavorites).ok();} else {self.state.favorites_focus = true;self.state.input_mode = InputMode::Normal;diff --git a/src/tui/app/navigation.rs b/src/tui/app/navigation.rsindex 115a697..ea4fe74 100644--- a/src/tui/app/navigation.rs+++ b/src/tui/app/navigation.rs@@ -590,7 +590,7 @@ impl App {match self.state.active_screen {Screen::Home => {if self.state.favorites_focus {- let total = self.state.favorites_landing_items().len();+ let total = self.state.landing_deck_items_count();let current =self.state.favorites_landing_state.selected().unwrap_or(0);if current + 1 < total {@@ -600,7 +600,7 @@ impl App {}if self.state.search_results.is_empty()&& self.state.search_query.trim().is_empty()- && self.state.favorites_landing_visible()+ && self.state.landing_deck_visible(){self.state.favorites_focus = true;self.state.favorites_landing_state.select(Some(0));@@ -662,6 +662,10 @@ impl App {Action::MoveLeft => {if self.state.active_screen == Screen::Home {+ if self.state.favorites_focus {+ self.state.cycle_home_deck_tab();+ return None;+ }let current = self.state.search_list_state.selected().unwrap_or(0);let jump = 1;if current > jump {@@ -684,6 +688,10 @@ impl App {Action::MoveRight => {if self.state.active_screen == Screen::Home {+ if self.state.favorites_focus {+ self.state.cycle_home_deck_tab();+ return None;+ }let current = self.state.search_list_state.selected().unwrap_or(0);let jump = 1;let total = self.state.search_results.len();@@ -757,7 +765,14 @@ impl App {}if self.state.favorites_focus {if let Some(idx) = self.state.favorites_landing_state.selected() {- self.action_sender.send(Action::OpenFavorite(idx)).ok();+ match self.state.effective_home_deck_tab() {+ crate::tui::state::HomeDeckTab::ContinueWatching => {+ self.open_continue_watching(idx);+ }+ crate::tui::state::HomeDeckTab::Favorites => {+ self.open_favorite(idx);+ }+ }}return None;}@@ -869,7 +884,17 @@ impl App {self.state.language_list_state.select(Some(0));let se = if item.season > 0 { item.season } else { 1 };- let ep = if item.episode > 0 { item.episode } else { 1 };+ let mut ep = if item.episode > 0 { item.episode } else { 1 };+ let provider_key = self.state.active_provider.cache_key();+ if let Some(hist) =+ self.state+ .history+ .get_item(provider_key, &item.id, se, ep, Some(&item.title))+ {+ if hist.completed && item.stype == 2 {+ ep = ep.saturating_add(1);+ }+ }self.state.selected_season = se;self.state.selected_episode = ep;self.statediff --git a/src/tui/app/playback.rs b/src/tui/app/playback.rsindex a74da1b..7d25efb 100644--- a/src/tui/app/playback.rs+++ b/src/tui/app/playback.rs@@ -256,6 +256,25 @@ impl App {item.episode,)});+ if let Some(item) = &history_item {+ self.state+ .history+ .record_start(item, resume_seconds.unwrap_or(0));+ }++ if let (Some((p, s, se, ep)), Some(item)) = (&tracker_opts, &history_item) {+ if let Some(state_path) = crate::player::tracker::state_file_path(p, s, *se, *ep) {+ let initial_state = crate::history::PendingPlaybackState::from_item(+ item,+ resume_seconds.unwrap_or(0),+ item.duration_seconds,+ false,+ );+ if let Ok(serialized) = serde_json::to_string(&initial_state) {+ let _ = std::fs::write(&state_path, serialized);+ }+ }+ }let sender = self.action_sender.clone();let cell_size = self@@ -342,9 +361,16 @@ impl App {match result {Ok(status) if status.success() => {- sender.send(Action::ReconcileHistory).ok();-- if let Some(item) = history_item {+ let has_tracker = tracker_opts.is_some()+ && matches!(+ kind,+ crate::tui::state::PlayerKind::Mpv+ | crate::tui::state::PlayerKind::Iina+ );++ if has_tracker {+ sender.send(Action::ReconcileHistory).ok();+ } else if let Some(item) = history_item {let elapsed = start_time.elapsed().as_secs();if elapsed >= 30 {let duration = item.duration_seconds;@@ -737,10 +763,12 @@ impl App {self.state.history.reconcile_pending_playback_states();}Action::PlayerExited => {+ self.state.history.reconcile_pending_playback_states();self.state.is_playing = false;self.state.is_resolving_playback = false;}Action::PlayerCrashed(code, error_msg) => {+ self.state.history.reconcile_pending_playback_states();self.state.is_playing = false;self.state.is_resolving_playback = false;let code_str = codediff --git a/src/tui/app/requests.rs b/src/tui/app/requests.rsindex 2d3c872..4376969 100644--- a/src/tui/app/requests.rs+++ b/src/tui/app/requests.rs@@ -1012,7 +1012,23 @@ impl App {&& item.episode > 0}) {default_season = history.season;- default_episode = history.episode;+ if history.completed {+ let current_season_eps = self+ .state+ .available_seasons+ .iter()+ .find(|s| s.number == history.season)+ .map(|s| s.episodes.len())+ .unwrap_or(0);+ if current_season_eps > 0 && history.episode >= current_season_eps {+ default_season = history.season.saturating_add(1);+ default_episode = 1;+ } else {+ default_episode = history.episode.saturating_add(1);+ }+ } else {+ default_episode = history.episode;+ }}let target_season = if self.state.selected_season > 0 {diff --git a/src/tui/app/run.rs b/src/tui/app/run.rsindex 6db93dc..15f51d3 100644--- a/src/tui/app/run.rs+++ b/src/tui/app/run.rs@@ -469,7 +469,10 @@ impl App {self.handle_playback(action).await;}- Action::ToggleFavorite | Action::ShowFavorites | Action::OpenFavorite(..) => {+ Action::ToggleFavorite+ | Action::ShowFavorites+ | Action::OpenFavorite(..)+ | Action::OpenContinueWatching(..) => {self.handle_favorites(action).await;}diff --git a/src/tui/screens/home.rs b/src/tui/screens/home.rsindex ddaac87..7778df9 100644--- a/src/tui/screens/home.rs+++ b/src/tui/screens/home.rs@@ -498,28 +498,62 @@ pub(crate) fn no_results_button_hitboxes(};(btn1, btn2)}+#[allow(dead_code)]pub(crate) fn render_favorites_landing(frame: &mut Frame,area: Rect,state: &AppState,theme: &Theme,) {+ render_landing_deck(frame, area, state, theme);+}++pub(crate) fn render_landing_deck(frame: &mut Frame, area: Rect, state: &AppState, theme: &Theme) {if area.height < 3 || area.width < 20 {return;}- let items: Vec<crate::favorites::FavoriteItem> = state- .favorites_landing_items()- .into_iter()- .cloned()- .collect();- if items.is_empty() {+ let tab = state.effective_home_deck_tab();+ let has_cw = state.continue_watching_available();+ let has_fav = state.favorites_available() && !state.favorites.items.is_empty();++ if !has_cw && !has_fav {return;}- let overflow = state.favorites.items.len().saturating_sub(items.len());+ let is_focused = state.favorites_focus;++ let cw_items = if has_cw {+ state.continue_watching_items()+ } else {+ Vec::new()+ };+ let fav_items = if has_fav {+ state.favorites_landing_items()+ } else {+ Vec::new()+ };++ let (item_count, total_count) = match tab {+ crate::tui::state::HomeDeckTab::ContinueWatching => {+ let total = state+ .history+ .recent+ .iter()+ .filter(|i| i.is_in_progress())+ .count();+ (cw_items.len(), total)+ }+ crate::tui::state::HomeDeckTab::Favorites => (fav_items.len(), state.favorites.items.len()),+ };++ if item_count == 0 {+ return;+ }++ let overflow = total_count.saturating_sub(item_count);let card_width = search_deck_width(area, state, true);- let row_count = items.len() as u16;+ let row_count = item_count as u16;let overflow_row = u16::from(overflow > 0);let content_height = (row_count + overflow_row + 2).min(area.height);@@ -530,24 +564,57 @@ pub(crate) fn render_favorites_landing(height: content_height,};- let (bar, star) = if state.basic_terminal {- ("-", "*")- } else {- ("─", "★")- };- let border_style = if state.favorites_focus {+ let border_style = if is_focused {theme.border_focus} else {theme.surface1};- let title = format!("{bar} {star} Favorites ");- let block = Block::default()- .title(title)- .title_style(if state.favorites_focus {++ let mut title_spans: Vec<Span> = Vec::new();+ if has_cw && has_fav {+ let sep = if state.basic_terminal { " | " } else { " │ " };+ match tab {+ crate::tui::state::HomeDeckTab::ContinueWatching => {+ let active_style = if is_focused {+ theme.title.add_modifier(Modifier::BOLD)+ } else {+ theme.text.add_modifier(Modifier::BOLD)+ };+ title_spans.push(Span::styled(" Continue Watching ", active_style));+ title_spans.push(Span::styled(sep, theme.surface1));+ title_spans.push(Span::styled("Favorites", theme.subtext1));+ title_spans.push(Span::styled(" (Tab) ", theme.text_dim));+ }+ crate::tui::state::HomeDeckTab::Favorites => {+ title_spans.push(Span::styled(" Continue Watching", theme.subtext1));+ title_spans.push(Span::styled(" (Tab)", theme.text_dim));+ title_spans.push(Span::styled(sep, theme.surface1));+ let active_style = if is_focused {+ theme.title.add_modifier(Modifier::BOLD)+ } else {+ theme.text.add_modifier(Modifier::BOLD)+ };+ title_spans.push(Span::styled(" Favorites ", active_style));+ }+ }+ } else if has_cw {+ let active_style = if is_focused {+ theme.title.add_modifier(Modifier::BOLD)+ } else {+ theme.text.add_modifier(Modifier::BOLD)+ };+ title_spans.push(Span::styled(" Continue Watching ", active_style));+ } else {+ let active_style = if is_focused {theme.title.add_modifier(Modifier::BOLD)} else {- theme.subtext1- })+ theme.text.add_modifier(Modifier::BOLD)+ };+ title_spans.push(Span::styled(" Favorites ", active_style));+ }++ let block = Block::default()+ .title(Line::from(title_spans)).borders(Borders::ALL).border_type(crate::tui::overlay::border_type(state.basic_terminal)).border_style(border_style);@@ -563,78 +630,172 @@ pub(crate) fn render_favorites_landing(}let mut curr_y = inner_area.y;-- let selected = if state.favorites_focus {+ let selected = if is_focused {state.favorites_landing_state.selected()} else {None};- for (i, item) in items.iter().enumerate() {- if curr_y >= inner_area.bottom() {- break;- }- let is_selected = selected == Some(i);- let type_tag = if item.stype == 2 { "Series" } else { "Movie" };- let right_tag = if item.release_year.is_empty() {- type_tag.to_string()- } else {- format!("{} {type_tag}", item.release_year)- };+ match tab {+ crate::tui::state::HomeDeckTab::ContinueWatching => {+ for (i, item) in cw_items.iter().enumerate() {+ if curr_y >= inner_area.bottom() {+ break;+ }+ let is_selected = selected == Some(i);- let pointer = if is_selected {- if state.basic_terminal { "> " } else { "▌ " }- } else {- " "- };+ let episode_tag = if item.season > 0 {+ format!("S{:02}E{:02}", item.season, item.episode)+ } else {+ String::new()+ };- let title_style = if is_selected {- theme.title.add_modifier(Modifier::BOLD)- } else {- theme.text- };+ let progress_str = if let Some(rem) = item.formatted_remaining() {+ if let Some(pct) = item.progress_percentage() {+ format!("{:.0}% · {rem}", pct)+ } else {+ rem+ }+ } else if let Some(pct) = item.progress_percentage() {+ format!("{:.0}%", pct)+ } else {+ item.formatted_progress()+ };- let row_style = if is_selected {- Style::default().bg(theme.surface0.fg.unwrap_or(theme.base))- } else {- Style::default()- };+ let right_tag = if !episode_tag.is_empty() {+ format!("{episode_tag} · {progress_str}")+ } else if !item.release_year.is_empty() {+ format!("{} · {progress_str}", item.release_year)+ } else {+ progress_str+ };- let left_margin = " ";- let right_margin = " ";- let tag_len = crate::tui::text::width(&right_tag);- let pointer_len = 3;- let margins_len = 3;- let fixed_overhead = margins_len + pointer_len + tag_len;+ let pointer = if is_selected {+ if state.basic_terminal { "> " } else { "▌ " }+ } else {+ " "+ };- let max_title_width = (inner_area.width as usize).saturating_sub(fixed_overhead + 1);- let truncated_title = crate::tui::text::truncate_width(&item.title, max_title_width);- let title_width = crate::tui::text::width(&truncated_title);- let pad_len = (inner_area.width as usize)- .saturating_sub(margins_len + pointer_len + title_width + tag_len);+ let title_style = if is_selected {+ theme.title.add_modifier(Modifier::BOLD)+ } else {+ theme.text+ };- let line = Line::from(vec![- Span::raw(left_margin),- Span::styled(pointer, theme.accent),- Span::styled(truncated_title, title_style),- Span::raw(" ".repeat(pad_len)),- Span::styled(right_tag, theme.text_dim),- Span::raw(right_margin),- ]);+ let row_style = if is_selected {+ Style::default().bg(theme.surface0.fg.unwrap_or(theme.base))+ } else {+ Style::default()+ };- let row_area = Rect {- x: inner_area.x,- y: curr_y,- width: inner_area.width,- height: 1,- };- frame.render_widget(Paragraph::new(line).style(row_style), row_area);- curr_y += 1;+ let left_margin = " ";+ let right_margin = " ";+ let tag_len = crate::tui::text::width(&right_tag);+ let pointer_len = 3;+ let margins_len = 3;+ let fixed_overhead = margins_len + pointer_len + tag_len;++ let max_title_width =+ (inner_area.width as usize).saturating_sub(fixed_overhead + 1);+ let truncated_title =+ crate::tui::text::truncate_width(&item.title, max_title_width);+ let title_width = crate::tui::text::width(&truncated_title);+ let pad_len = (inner_area.width as usize)+ .saturating_sub(margins_len + pointer_len + title_width + tag_len);++ let line = Line::from(vec![+ Span::raw(left_margin),+ Span::styled(pointer, theme.accent),+ Span::styled(truncated_title, title_style),+ Span::raw(" ".repeat(pad_len)),+ Span::styled(right_tag, theme.text_dim),+ Span::raw(right_margin),+ ]);++ let row_area = Rect {+ x: inner_area.x,+ y: curr_y,+ width: inner_area.width,+ height: 1,+ };+ frame.render_widget(Paragraph::new(line).style(row_style), row_area);+ curr_y += 1;+ }+ }+ crate::tui::state::HomeDeckTab::Favorites => {+ for (i, item) in fav_items.iter().enumerate() {+ if curr_y >= inner_area.bottom() {+ break;+ }+ let is_selected = selected == Some(i);+ let type_tag = if item.stype == 2 { "Series" } else { "Movie" };+ let right_tag = if item.release_year.is_empty() {+ type_tag.to_string()+ } else {+ format!("{} {type_tag}", item.release_year)+ };++ let pointer = if is_selected {+ if state.basic_terminal { "> " } else { "▌ " }+ } else {+ " "+ };++ let title_style = if is_selected {+ theme.title.add_modifier(Modifier::BOLD)+ } else {+ theme.text+ };++ let row_style = if is_selected {+ Style::default().bg(theme.surface0.fg.unwrap_or(theme.base))+ } else {+ Style::default()+ };++ let left_margin = " ";+ let right_margin = " ";+ let tag_len = crate::tui::text::width(&right_tag);+ let pointer_len = 3;+ let margins_len = 3;+ let fixed_overhead = margins_len + pointer_len + tag_len;++ let max_title_width =+ (inner_area.width as usize).saturating_sub(fixed_overhead + 1);+ let truncated_title =+ crate::tui::text::truncate_width(&item.title, max_title_width);+ let title_width = crate::tui::text::width(&truncated_title);+ let pad_len = (inner_area.width as usize)+ .saturating_sub(margins_len + pointer_len + title_width + tag_len);++ let line = Line::from(vec![+ Span::raw(left_margin),+ Span::styled(pointer, theme.accent),+ Span::styled(truncated_title, title_style),+ Span::raw(" ".repeat(pad_len)),+ Span::styled(right_tag, theme.text_dim),+ Span::raw(right_margin),+ ]);++ let row_area = Rect {+ x: inner_area.x,+ y: curr_y,+ width: inner_area.width,+ height: 1,+ };+ frame.render_widget(Paragraph::new(line).style(row_style), row_area);+ curr_y += 1;+ }+ }}if overflow > 0 && curr_y < inner_area.bottom() {let sep = if state.basic_terminal { "-" } else { "·" };- let pill_text = format!("[ +{overflow} more {sep} /favorites ]");+ let cmd = match tab {+ crate::tui::state::HomeDeckTab::ContinueWatching => "/history",+ crate::tui::state::HomeDeckTab::Favorites => "/favorites",+ };+ let pill_text = format!("+{overflow} more {sep} {cmd}");let pill_style = if state.basic_terminal {theme.sapphire} else {@@ -1356,7 +1517,7 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)area,state.is_tv_mode,basic_terminal,- state.favorites_landing_visible(),+ state.landing_deck_visible(),);let vertical_chunks = rows.rects.clone();@@ -1450,8 +1611,8 @@ pub fn draw(frame: &mut Frame, area: Rect, state: &mut AppState, theme: &Theme)let suggestions_open =state.input_mode == InputMode::Editing && !state.search_suggestions.is_empty();- if state.favorites_landing_visible() && !state.tv_config_popup {- render_favorites_landing(frame, vertical_chunks[rows.favorites], state, theme);+ if state.landing_deck_visible() && !state.tv_config_popup {+ render_landing_deck(frame, vertical_chunks[rows.favorites], state, theme);} else if !state.is_tv_mode&& !state.tv_config_popup&& !suggestions_open@@ -2777,6 +2938,7 @@ mod tests {active_provider: crate::providers::models::ProviderKind::MovieBox,..Default::default()};+ state.history.recent.clear();state.favorites.items.clear();let theme = Theme::mocha();@@ -2815,6 +2977,7 @@ mod tests {active_provider: crate::providers::models::ProviderKind::Addons,..Default::default()};+ state.history.recent.clear();state.favorites.items.clear();let theme = Theme::mocha();@@ -3012,6 +3175,7 @@ mod tests {basic_terminal: false,..Default::default()};+ state.history.recent.clear();state.favorites.items.clear();state.favorites_landing_state.select(Some(0));for i in 0..10 {@@ -3042,12 +3206,12 @@ mod tests {}rendered.push('\n');}-- assert!(rendered.contains("─ ★ Favorites"));+ assert!(rendered.contains("Favorites"));+ assert!(!rendered.contains("★"));assert!(rendered.contains(" ▌ Favorite Movie 0"));assert!(rendered.contains(" Favorite Movie 1"));assert!(rendered.contains("2024 Movie "));- assert!(rendered.contains("[ +5 more · /favorites ]"));+ assert!(rendered.contains("+5 more · /favorites"));}#[test]fn test_favorites_landing_rendering_basic_terminal() {@@ -3058,6 +3222,7 @@ mod tests {basic_terminal: true,..Default::default()};+ state.history.recent.clear();state.favorites.items.clear();state.favorites_landing_state.select(Some(0));for i in 0..10 {@@ -3089,11 +3254,70 @@ mod tests {rendered.push('\n');}- assert!(rendered.contains("- * Favorites"));+ assert!(rendered.contains("Favorites"));+ assert!(!rendered.contains("* Favorites"));assert!(rendered.contains(" > Favorite Movie 0"));assert!(rendered.contains(" Favorite Movie 1"));assert!(rendered.contains("2024 Movie "));- assert!(rendered.contains("[ +5 more - /favorites ]"));+ assert!(rendered.contains("+5 more - /favorites"));+ }+ #[test]+ fn test_landing_deck_continue_watching_rendering() {+ let backend = TestBackend::new(80, 24);+ let mut terminal = Terminal::new(backend).unwrap();+ let mut state = AppState {+ favorites_focus: true,+ streaming_enabled: true,+ ..Default::default()+ };+ state.history.recent.push(crate::history::WatchHistoryItem {+ provider: "moviebox".to_string(),+ subject_id: "show-1".to_string(),+ title: "Severance".to_string(),+ cover_url: None,+ stype: 2,+ release_year: "2022".to_string(),+ season: 1,+ episode: 3,+ progress_seconds: 1200,+ duration_seconds: Some(3000),+ completed: false,+ timestamp: 100,+ });+ state.favorites.items.push(crate::favorites::FavoriteItem {+ provider: "moviebox".to_string(),+ subject_id: "fav-1".to_string(),+ title: "Inception".to_string(),+ cover_url: None,+ stype: 1,+ release_year: "2010".to_string(),+ added_at: 100,+ });+ state.favorites_landing_state.select(Some(0));+ let theme = Theme::mocha();++ terminal+ .draw(|frame| {+ let area = Rect::new(0, 0, 80, 24);+ render_landing_deck(frame, area, &state, &theme);+ })+ .unwrap();++ let buffer = terminal.backend().buffer();+ let mut rendered = String::new();+ for y in 0..24 {+ for x in 0..80 {+ rendered.push_str(buffer[(x, y)].symbol());+ }+ rendered.push('\n');+ }++ assert!(rendered.contains("Continue Watching"));+ assert!(rendered.contains("Favorites"));+ assert!(rendered.contains("(Tab)"));+ assert!(rendered.contains("Severance"));+ assert!(rendered.contains("S01E03"));+ assert!(rendered.contains("40%"));}#[test]@@ -3197,6 +3421,7 @@ mod tests {basic_terminal: false,..Default::default()};+ state.history.recent.clear();for i in 1..=6 {state.favorites.items.push(crate::favorites::FavoriteItem {provider: "moviebox".to_string(),diff --git a/src/tui/state.rs b/src/tui/state.rsindex 55dc8ac..1a10180 100644--- a/src/tui/state.rs+++ b/src/tui/state.rs@@ -26,6 +26,13 @@ pub enum AppMode {Addon,}+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]+pub enum HomeDeckTab {+ #[default]+ ContinueWatching,+ Favorites,+}+#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]pub enum InputMode {#[default]@@ -361,6 +368,7 @@ pub struct AppState {pub history: crate::history::HistoryManager,pub favorites: crate::favorites::FavoritesManager,pub favorites_focus: bool,+ pub home_deck_tab: HomeDeckTab,pub favorites_landing_state: ListState,}@@ -516,6 +524,7 @@ impl Default for AppState {history: crate::history::HistoryManager::new(),favorites: crate::favorites::FavoritesManager::new(),favorites_focus: false,+ home_deck_tab: HomeDeckTab::default(),favorites_landing_state: ListState::default(),}}@@ -794,6 +803,87 @@ impl AppState {items}+ pub fn continue_watching_items(&self) -> Vec<&crate::history::WatchHistoryItem> {+ let mut items: Vec<&crate::history::WatchHistoryItem> = self+ .history+ .recent+ .iter()+ .filter(|item| item.is_in_progress())+ .collect();+ items.sort_by_key(|item| std::cmp::Reverse(item.timestamp));+ items.truncate(5);+ items+ }++ pub fn continue_watching_available(&self) -> bool {+ self.streaming_enabled+ && !self.is_tv_mode+ && self.history.recent.iter().any(|item| item.is_in_progress())+ }++ pub fn effective_home_deck_tab(&self) -> HomeDeckTab {+ let cw_has = self.continue_watching_available();+ let fav_has = self.favorites_available() && !self.favorites.items.is_empty();+ match self.home_deck_tab {+ HomeDeckTab::ContinueWatching => {+ if cw_has {+ HomeDeckTab::ContinueWatching+ } else if fav_has {+ HomeDeckTab::Favorites+ } else {+ HomeDeckTab::ContinueWatching+ }+ }+ HomeDeckTab::Favorites => {+ if fav_has {+ HomeDeckTab::Favorites+ } else if cw_has {+ HomeDeckTab::ContinueWatching+ } else {+ HomeDeckTab::Favorites+ }+ }+ }+ }++ pub fn landing_deck_visible(&self) -> bool {+ (self.continue_watching_available() || self.favorites_landing_visible())+ && !(self.input_mode == InputMode::Editing && !self.search_suggestions.is_empty())+ }++ pub fn landing_deck_items_count(&self) -> usize {+ match self.effective_home_deck_tab() {+ HomeDeckTab::ContinueWatching => self.continue_watching_items().len(),+ HomeDeckTab::Favorites => self.favorites_landing_items().len(),+ }+ }++ pub fn landing_deck_total_items_count(&self) -> usize {+ match self.effective_home_deck_tab() {+ HomeDeckTab::ContinueWatching => self+ .history+ .recent+ .iter()+ .filter(|i| i.is_in_progress())+ .count(),+ HomeDeckTab::Favorites => self.favorites.items.len(),+ }+ }++ pub fn cycle_home_deck_tab(&mut self) {+ let cw_has = self.continue_watching_available();+ let fav_has = self.favorites_available() && !self.favorites.items.is_empty();+ if cw_has && fav_has {+ self.home_deck_tab = match self.effective_home_deck_tab() {+ HomeDeckTab::ContinueWatching => HomeDeckTab::Favorites,+ HomeDeckTab::Favorites => HomeDeckTab::ContinueWatching,+ };+ if self.favorites_focus {+ self.favorites_landing_state.select(Some(0));+ }+ }+ }+pub fn loading_dots(&self) -> &'static str {match (self.tick_count / 4) % 4 {0 => "",diff --git a/tests/history_audit.rs b/tests/history_audit.rsindex ba26b92..574d09e 100644--- a/tests/history_audit.rs+++ b/tests/history_audit.rs@@ -310,6 +310,10 @@ fn test_reconciliation_from_lua_tracker_state_files() {duration_seconds: Some(3600),completed: true,timestamp: 1100,+ title: None,+ cover_url: None,+ stype: None,+ release_year: 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();@@ -323,6 +327,10 @@ fn test_reconciliation_from_lua_tracker_state_files() {duration_seconds: Some(3600),completed: false,timestamp: 1200,+ title: None,+ cover_url: None,+ stype: None,+ release_year: 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();@@ -482,3 +490,97 @@ fn test_corrupted_history_deserialization_recovery() {let empty_manager = serde_json::from_str::<HistoryManager>(empty_json).unwrap();assert!(empty_manager.recent.is_empty());}+#[test]+fn test_reconciliation_self_heals_unseen_items_with_metadata() {+ let temp_dir = tempfile::tempdir().unwrap();+ let state_file = temp_dir.path().join("moviebox_new_movie_0_0.json");+ let state = PendingPlaybackState {+ provider: "moviebox".to_string(),+ subject_id: "new_movie".to_string(),+ season: 0,+ episode: 0,+ progress_seconds: 4200,+ duration_seconds: Some(7200),+ completed: false,+ timestamp: 5000,+ title: Some("Inception".to_string()),+ cover_url: Some("https://example.com/inception.jpg".to_string()),+ stype: Some(1),+ release_year: Some("2010".to_string()),+ };+ std::fs::write(&state_file, serde_json::to_string(&state).unwrap()).unwrap();++ let mut manager = HistoryManager::default();+ assert!(manager.recent.is_empty());++ let modified = manager.reconcile_from_dir(temp_dir.path());+ assert!(modified);+ assert_eq!(manager.recent.len(), 1);++ let recovered = manager.recent.first().unwrap();+ assert_eq!(recovered.title, "Inception");+ assert_eq!(recovered.subject_id, "new_movie");+ assert_eq!(recovered.progress_seconds, 4200);+ assert_eq!(recovered.duration_seconds, Some(7200));+ assert_eq!(recovered.release_year, "2010");+ assert_eq!(recovered.stype, 1);+ assert!(!state_file.exists());+}++#[test]+fn test_record_start_registers_history_immediately() {+ let mut manager = HistoryManager::default();+ let item = dummy_history_item(+ "moviebox",+ "interstellar",+ "Interstellar",+ 1,+ "2014",+ 0,+ 0,+ Some(10140),+ 0,+ false,+ );++ manager.record_start(&item, 120);+ assert_eq!(manager.recent.len(), 1);+ let first = manager.recent.first().unwrap();+ assert_eq!(first.subject_id, "interstellar");+ assert_eq!(first.progress_seconds, 120);+ assert!(!first.completed);++ manager.record_start(&item, 60);+ let second = manager.recent.first().unwrap();+ assert_eq!(second.progress_seconds, 120);++ manager.record_start(&item, 500);+ let third = manager.recent.first().unwrap();+ assert_eq!(third.progress_seconds, 500);+}++#[test]+fn test_pending_playback_state_from_item_fidelity() {+ let item = dummy_history_item(+ "moviebox",+ "oppenheimer",+ "Oppenheimer",+ 1,+ "2023",+ 0,+ 0,+ Some(10800),+ 3600,+ false,+ );++ let pending = PendingPlaybackState::from_item(&item, 3600, Some(10800), false);+ assert_eq!(pending.provider, "moviebox");+ assert_eq!(pending.subject_id, "oppenheimer");+ assert_eq!(pending.title.as_deref(), Some("Oppenheimer"));+ assert_eq!(pending.release_year.as_deref(), Some("2023"));+ assert_eq!(pending.stype, Some(1));+ assert_eq!(pending.progress_seconds, 3600);+ assert_eq!(pending.duration_seconds, Some(10800));+ assert!(!pending.completed);+}diff --git a/tests/tui_acceptance.rs b/tests/tui_acceptance.rsindex 6234ae2..4a365e8 100644--- a/tests/tui_acceptance.rs+++ b/tests/tui_acceptance.rs@@ -856,3 +856,185 @@ async fn test_tui_layout_truncation_and_bounds() {assert_eq!(tier.footer_height(106), 1);assert_eq!(tier.footer_height(120), 1);}++#[tokio::test]+async fn test_home_deck_tab_switching() {+ let mut app = App::new();+ app.state_mut().active_screen = Screen::Home;+ app.state_mut().input_mode = InputMode::Normal;+ app.state_mut().streaming_enabled = true;+ app.state_mut().history.recent.clear();+ app.state_mut().favorites.items.clear();++ app.state_mut()+ .history+ .recent+ .push(moviebox_tui::history::WatchHistoryItem {+ provider: "moviebox".to_string(),+ subject_id: "show_1".to_string(),+ title: "Severance".to_string(),+ cover_url: None,+ stype: 2,+ release_year: "2022".to_string(),+ season: 1,+ episode: 2,+ progress_seconds: 1000,+ duration_seconds: Some(3000),+ completed: false,+ timestamp: 100,+ });+ app.state_mut()+ .favorites+ .items+ .push(moviebox_tui::favorites::FavoriteItem {+ provider: "moviebox".to_string(),+ subject_id: "fav_1".to_string(),+ title: "Inception".to_string(),+ cover_url: None,+ stype: 1,+ release_year: "2010".to_string(),+ added_at: 100,+ });++ assert!(app.state().continue_watching_available());+ assert!(app.state().favorites_available());+ assert!(app.state().landing_deck_visible());+ assert_eq!(+ app.state().effective_home_deck_tab(),+ moviebox_tui::tui::state::HomeDeckTab::ContinueWatching+ );++ let tab_key = crossterm::event::KeyEvent::new(+ crossterm::event::KeyCode::Tab,+ crossterm::event::KeyModifiers::NONE,+ );+ app.handle_action(Action::Key(tab_key)).await;+ assert_eq!(+ app.state().effective_home_deck_tab(),+ moviebox_tui::tui::state::HomeDeckTab::Favorites+ );++ let backtab_key = crossterm::event::KeyEvent::new(+ crossterm::event::KeyCode::BackTab,+ crossterm::event::KeyModifiers::SHIFT,+ );+ app.handle_action(Action::Key(backtab_key)).await;+ assert_eq!(+ app.state().effective_home_deck_tab(),+ moviebox_tui::tui::state::HomeDeckTab::ContinueWatching+ );++ app.state_mut().favorites_focus = true;+ app.state_mut().favorites_landing_state.select(Some(0));+ app.handle_action(Action::MoveRight).await;+ assert_eq!(+ app.state().effective_home_deck_tab(),+ moviebox_tui::tui::state::HomeDeckTab::Favorites+ );+ app.handle_action(Action::MoveLeft).await;+ assert_eq!(+ app.state().effective_home_deck_tab(),+ moviebox_tui::tui::state::HomeDeckTab::ContinueWatching+ );+}++#[tokio::test]+async fn test_home_deck_continue_watching_resume() {+ let mut app = App::new();+ app.state_mut().active_screen = Screen::Home;+ app.state_mut().input_mode = InputMode::Normal;+ app.state_mut().streaming_enabled = true;+ app.state_mut().history.recent.clear();+ app.state_mut().favorites.items.clear();++ app.state_mut()+ .history+ .recent+ .push(moviebox_tui::history::WatchHistoryItem {+ provider: "moviebox".to_string(),+ subject_id: "cw_target".to_string(),+ title: "Severance".to_string(),+ cover_url: None,+ stype: 2,+ release_year: "2022".to_string(),+ season: 1,+ episode: 3,+ progress_seconds: 1200,+ duration_seconds: Some(3000),+ completed: false,+ timestamp: 200,+ });++ app.state_mut().favorites_focus = true;+ app.state_mut().favorites_landing_state.select(Some(0));+ assert_eq!(+ app.state().effective_home_deck_tab(),+ moviebox_tui::tui::state::HomeDeckTab::ContinueWatching+ );++ app.handle_action(Action::Submit).await;++ assert_eq!(app.state().active_screen, Screen::Details);+ assert_eq!(app.state().active_subject_id.as_deref(), Some("cw_target"));+ assert_eq!(app.state().selected_season, 1);+ assert_eq!(app.state().selected_episode, 3);+ assert!(app.state().auto_play_on_ready);+}++#[tokio::test]+async fn test_landing_deck_header_renders_without_star_or_bracket() {+ let mut app = App::new();+ app.state_mut().active_screen = Screen::Home;+ app.state_mut().streaming_enabled = true;+ app.state_mut().history.recent.clear();+ app.state_mut().favorites.items.clear();++ app.state_mut()+ .history+ .recent+ .push(moviebox_tui::history::WatchHistoryItem {+ provider: "moviebox".to_string(),+ subject_id: "show_1".to_string(),+ title: "Severance".to_string(),+ cover_url: None,+ stype: 2,+ release_year: "2022".to_string(),+ season: 1,+ episode: 2,+ progress_seconds: 1000,+ duration_seconds: Some(3000),+ completed: false,+ timestamp: 100,+ });+ app.state_mut()+ .favorites+ .items+ .push(moviebox_tui::favorites::FavoriteItem {+ provider: "moviebox".to_string(),+ subject_id: "fav_1".to_string(),+ title: "Inception".to_string(),+ cover_url: None,+ stype: 1,+ release_year: "2010".to_string(),+ added_at: 100,+ });++ let backend = ratatui::backend::TestBackend::new(80, 24);+ let mut terminal = ratatui::Terminal::new(backend).unwrap();++ let res = terminal.draw(|frame| app.draw(frame));+ assert!(res.is_ok());++ let text: String = terminal+ .backend()+ .buffer()+ .content()+ .iter()+ .map(|c| c.symbol())+ .collect();++ assert!(text.contains("Continue Watching"));+ assert!(text.contains("Favorites"));+ assert!(!text.contains("★"));+ assert!(!text.contains("- * Favorites"));+}