Repository navigation
refactor(core): split app.rs into a src/core/app/ module folder - #446
Conversation
Move the 10,920-line app.rs into 33 files grouped by concern. The App struct stays flat in mod.rs and each module contributes its own impl App block. mod.rs blanket re-exports every module, so crate::core::app::<Name> paths are unchanged outside the folder and no caller in tui/ or infra/ needed touching. Behaviour is unchanged: this is pure code movement plus eight private items widened to pub(super) where a sibling module calls them, and the per-module import blocks. Tests are colocated with the code they cover, with the six shared fixtures in test_support.rs. Also refresh CLAUDE.md for the new layout and correct its CI section: the matrix has five legs, not three. The two undocumented ones (mcp-only, ai-dj-only) build dj-core without streaming, which no other leg covers. Mirror the whole file into AGENTS.md, which had drifted.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughThe PR modularizes ChangesApplication modularization
Estimated code review effort: 5 (Critical) | ~120 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
✨ Simplify code
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 11
🧹 Nitpick comments (6)
src/core/app/playlist_pages.rs (1)
158-172: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse
replace_track_table_tracksfor search results. The direct assignment leavespending_track_table_selectionset. A later table replacement can consume it and move the selection in the filtered table. Call the helper before restoringplaylist_track_positions, then setselected_index = 0.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/core/app/playlist_pages.rs` around lines 158 - 172, The search-results update in the playlist filtering flow should use replace_track_table_tracks instead of directly assigning track_table.tracks, so pending_track_table_selection is cleared. Invoke the helper with the collected tracks, then restore playlist_track_positions and set track_table.selected_index to 0.src/core/app/mod.rs (1)
670-680: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReplace
println!indispatchwith a log call.
dispatchruns while the TUI owns the terminal. Aprintln!writes into the alternate screen and corrupts the frame until the next full redraw. The failure also has no visible surface for the user.The
dispatch_without_spinnersibling below already useslog::warn!for the same send failure, so this is also an inconsistency inside the sameimplblock.♻️ Proposed change
if let Some(io_tx) = &self.io_tx { if let Err(e) = io_tx.send(action) { self.is_loading = false; - println!("Error from dispatch {}", e); - // TODO: handle error + log::error!("dispatch failed (shutting down?): {e}"); }; }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/core/app/mod.rs` around lines 670 - 680, Replace the println! error output in dispatch with the existing log::warn! pattern used by dispatch_without_spinner, preserving the send-error handling and is_loading reset while ensuring the failure is reported through logging rather than terminal output.src/core/app/library.rs (1)
191-212: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winAvoid cloning the whole artist page cache to read one page.
Line 203 clones
self.library.saved_artists(every cached page ofArtistInfo) only to read the last item's id. This runs on each "next page" keypress. Take the id first, then dispatch, so no clone is needed.♻️ Proposed refactor
None => { - if let Some(saved_artists) = &self.library.saved_artists.clone().get_results(None) { - if let Some(last_artist) = saved_artists.items.last() { - if let Some(after) = last_artist.id.as_deref() { - self.dispatch(IoEvent::GetFollowedArtists(Some(after.to_string()))); - } - } - } + let after = self + .library + .saved_artists + .get_results(None) + .and_then(|saved_artists| saved_artists.items.last()) + .and_then(|last_artist| last_artist.id.clone()); + if let Some(after) = after { + self.dispatch(IoEvent::GetFollowedArtists(Some(after))); + } }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/core/app/library.rs` around lines 191 - 212, Update get_current_user_saved_artists_next so the fallback reads the last artist ID from saved_artists without cloning the entire library.saved_artists cache. Borrow the cached page, extract or copy the required ID before dispatching IoEvent::GetFollowedArtists, and preserve the existing behavior when no page, artist, or ID is available.src/core/app/seek.rs (1)
75-88: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtract the native seek throttle into a helper.
The same 14-line throttle-and-queue block appears three times:
seek_forwards,seek_backwards, andseek_to. The file already establishes this pattern withqueue_source_seekandqueue_api_seek. Aqueue_native_seekhelper removes the duplication and keeps the three transports consistent when the throttle changes.♻️ Proposed refactor
Add the helper next to
queue_source_seek:/// Queue a native librespot seek with throttling #[cfg(feature = "streaming")] fn queue_native_seek(&mut self, position_ms: u32) { // Always update UI immediately self.song_progress_ms = position_ms as u128; self.seek_ms = None; const SEEK_THROTTLE_MS: u128 = 50; let should_seek_now = self .last_native_seek .is_none_or(|t| t.elapsed().as_millis() >= SEEK_THROTTLE_MS); if should_seek_now { self.execute_native_seek(position_ms); } else { self.pending_native_seek = Some(position_ms); } }Then replace each of the three blocks, for example in
seek_forwards:#[cfg(feature = "streaming")] if self.is_native_streaming_active_for_playback() && self.streaming_player.is_some() { - // Always update UI immediately - self.song_progress_ms = new_progress as u128; - self.seek_ms = None; - - // Throttle actual seeks to avoid overwhelming librespot (max ~20/sec) - const SEEK_THROTTLE_MS: u128 = 50; - let should_seek_now = self - .last_native_seek - .is_none_or(|t| t.elapsed().as_millis() >= SEEK_THROTTLE_MS); - - if should_seek_now { - self.execute_native_seek(new_progress); - } else { - // Queue the seek - will be flushed by tick loop or next seek - self.pending_native_seek = Some(new_progress); - } + self.queue_native_seek(new_progress); return; }Also applies to: 125-138, 179-192
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/core/app/seek.rs` around lines 75 - 88, Extract the duplicated native seek throttling and queueing logic from seek_forwards, seek_backwards, and seek_to into a #[cfg(feature = "streaming")] queue_native_seek method beside queue_source_seek. Move the immediate UI updates, throttle check, execute_native_seek call, and pending_native_seek assignment into that helper, then have all three methods call it with the target position.src/core/app/volume.rs (2)
95-147: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDelegate
increase_volumeanddecrease_volumetoset_volume_percent.
set_volume_percent,increase_volume, anddecrease_volumeeach carry the same three routing branches: decoded source, native streaming with MPRIS notification, and API coalescing. That is roughly 40 duplicated lines per method, including the#[cfg(all(feature = "mpris", target_os = "linux"))]block.increase_volumeanddecrease_volumediffer only in how they compute the target. Delegating keeps the three volume entry points behaviorally identical when the routing changes.♻️ Proposed refactor
pub fn increase_volume(&mut self) { let current_volume = self.desired_volume() as u8; - let next_volume = min( - current_volume + self.user_config.behavior.volume_increment, - 100, - ); - - if next_volume != current_volume { - info!("increasing volume: {} -> {}", current_volume, next_volume); - // ... three routing branches ... - } + let next_volume = current_volume + .saturating_add(self.user_config.behavior.volume_increment) + .min(100); + info!("increasing volume: {} -> {}", current_volume, next_volume); + self.set_volume_percent(next_volume); }
set_volume_percentalready returns early when the target equalsdesired_volume(), so the no-change guard is preserved. Drop the#[cfg_attr(not(feature = "scripting"), allow(dead_code))]onset_volume_percentonce the keyboard paths call it.Also applies to: 151-208
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/core/app/volume.rs` around lines 95 - 147, Refactor increase_volume and decrease_volume to compute their target percentages and delegate to set_volume_percent, removing their duplicated decoded-source, native-streaming/MPRIS, and API-coalescing routing logic. Preserve set_volume_percent’s existing no-change handling and update its dead-code annotation since the keyboard paths now use it.
151-159: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winAvoid the
i8round trip indecrease_volume.
self.desired_volume() as i8truncates any value above 127 into a negative number. The arithmetic stays in range today only becausesettings_apply.rsclampsvolume_incrementto 0..100 (Line 33) and Spotify reportsvolume_percentin 0..100. Both invariants live outside this function.saturating_subonu8removes the dependency and drops the lateras u8cast at Line 159.♻️ Proposed refactor
pub fn decrease_volume(&mut self) { - let current_volume = self.desired_volume() as i8; - let next_volume = max( - current_volume - self.user_config.behavior.volume_increment as i8, - 0, - ); + let current_volume = self.desired_volume().min(100) as u8; + let next_volume_u8 = current_volume.saturating_sub(self.user_config.behavior.volume_increment); - if next_volume != current_volume { - let next_volume_u8 = next_volume as u8; + if next_volume_u8 != current_volume { info!( "decreasing volume: {} -> {}", current_volume, next_volume_u8 );🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/core/app/volume.rs` around lines 151 - 159, Update decrease_volume to keep volume arithmetic in u8: replace the desired_volume as i8 conversion and max-based subtraction with u8 saturating_sub using the configured volume increment, and remove the unnecessary next_volume_u8 cast while preserving the existing zero-floor behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In @.github/copilot-instructions.md:
- Line 83: Update the synchronized data-flow diagram fences to specify the text
language: change the opening fence at .github/copilot-instructions.md lines
83-83, AGENTS.md lines 85-85, and CLAUDE.md lines 85-85 to ```text.
In `@src/core/app/friends.rs`:
- Around line 52-63: Update App::clear_dialog_state() to centrally close the
friend dialog and reset its associated state, including
friend_add_dialog_visible and related fields. Change
clear_friend_add_dialog_state() into an initialization-only helper for fields
needed before opening, and have open_friend_add_dialog() use the central
clear_dialog_state() path so generic dialog, confirmation, and keybinding state
is also cleared.
In `@src/core/app/library.rs`:
- Around line 270-278: Replace every UI-selected direct index in the affected
match arms with bounds-checked `.get()` access: album and artist selections,
related-artist selections, and the show selection. Preserve each arm’s existing
behavior by continuing only when the selected item exists, then access its
fields and dispatch the same events; update the handlers around
`ActiveBlock::SearchResultBlock` and the other listed match arms consistently.
In `@src/core/app/persistence.rs`:
- Around line 309-321: Update flush_state_save so a failed save restores
state_save_due, allowing subsequent ticks and forced shutdown flushes to retry
the retained pending_state_save_patch. Lift the debounce duration currently
local to schedule_state_save into a shared module-level constant, and reuse that
constant when restoring the deadline and scheduling saves.
- Around line 244-256: Update the Added branch in add_radio_station so a missing
station lookup at before_len is not returned as successful without persistence:
roll back the in-memory radio_stations state consistently with the
save_runtime_state error path, or propagate an appropriate error instead of
returning Ok(RadioStationAddOutcome::Added).
In `@src/core/app/playlist_folders.rs`:
- Around line 82-92: Update get_playlist_display_count and
get_playlist_display_item_at to use the same raw-page fallback when
playlist_folder_items is empty: include the rendered “+ Add Playlist” row,
community pin, and every item in self.playlists, matching the renderer’s row
order and indexing. Preserve the existing folder-item behavior when
playlist_folder_items is populated.
In `@src/core/app/playlists.rs`:
- Around line 189-197: Prevent stale search-result indices from panicking in
both user_follow_playlist at src/core/app/playlists.rs#L189-L197 and
user_unfollow_playlist_search_result at src/core/app/playlists.rs#L236-L244 by
replacing direct playlists.items indexing with checked get access and returning
early when no item exists.
In `@src/core/app/queue.rs`:
- Around line 176-194: Update the doc comment for the native-streaming
EndOfTrack handler to state that it covers three cases instead of two, leaving
the three bullet descriptions and implementation unchanged.
In `@src/core/app/scrollable_pages.rs`:
- Around line 30-34: The offset-keyed page cache must remain sorted by page
offset, but ScrollableResultPages::add_pages currently appends unsafely. In
src/core/app/scrollable_pages.rs:30-34, restrict or remove add_pages for
offset-keyed caches so callers use upsert_page_by_offset; in
src/core/app/playlist_pages.rs:44-79, update the offset-keyed test setup to use
upsert_page_by_offset and add coverage proving out-of-order insertion preserves
page_index_for_offset lookups and contiguity traversal.
In `@src/core/app/seek.rs`:
- Around line 61-64: Update the forward-seek target calculation in the seek
logic around new_progress to use saturating_add when combining old_progress with
self.user_config.behavior.seek_milliseconds, then retain the existing min cap at
duration_ms. Match the saturating arithmetic used by the sibling seek paths.
In `@src/core/app/transport.rs`:
- Around line 211-219: Guard all deferred skip-thread commands against stale
playback intent and generation. In src/core/app/transport.rs lines 211-219
within previous_track, capture the native playback generation before spawning
and skip the delayed play when the generation changes or native playback intent
is paused; apply the equivalent generation guard to both delayed prev and play
commands in force_previous_track at lines 261-268 and to the delayed play in
next_track at lines 335-340.
---
Nitpick comments:
In `@src/core/app/library.rs`:
- Around line 191-212: Update get_current_user_saved_artists_next so the
fallback reads the last artist ID from saved_artists without cloning the entire
library.saved_artists cache. Borrow the cached page, extract or copy the
required ID before dispatching IoEvent::GetFollowedArtists, and preserve the
existing behavior when no page, artist, or ID is available.
In `@src/core/app/mod.rs`:
- Around line 670-680: Replace the println! error output in dispatch with the
existing log::warn! pattern used by dispatch_without_spinner, preserving the
send-error handling and is_loading reset while ensuring the failure is reported
through logging rather than terminal output.
In `@src/core/app/playlist_pages.rs`:
- Around line 158-172: The search-results update in the playlist filtering flow
should use replace_track_table_tracks instead of directly assigning
track_table.tracks, so pending_track_table_selection is cleared. Invoke the
helper with the collected tracks, then restore playlist_track_positions and set
track_table.selected_index to 0.
In `@src/core/app/seek.rs`:
- Around line 75-88: Extract the duplicated native seek throttling and queueing
logic from seek_forwards, seek_backwards, and seek_to into a #[cfg(feature =
"streaming")] queue_native_seek method beside queue_source_seek. Move the
immediate UI updates, throttle check, execute_native_seek call, and
pending_native_seek assignment into that helper, then have all three methods
call it with the target position.
In `@src/core/app/volume.rs`:
- Around line 95-147: Refactor increase_volume and decrease_volume to compute
their target percentages and delegate to set_volume_percent, removing their
duplicated decoded-source, native-streaming/MPRIS, and API-coalescing routing
logic. Preserve set_volume_percent’s existing no-change handling and update its
dead-code annotation since the keyboard paths now use it.
- Around line 151-159: Update decrease_volume to keep volume arithmetic in u8:
replace the desired_volume as i8 conversion and max-based subtraction with u8
saturating_sub using the configured volume increment, and remove the unnecessary
next_volume_u8 cast while preserving the existing zero-floor behavior.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: d93a575c-6263-4397-8cf0-3302d625bed0
📒 Files selected for processing (38)
.github/copilot-instructions.mdAGENTS.mdCLAUDE.mdCONTRIBUTING.mdsrc/core/app.rssrc/core/app/album_theme.rssrc/core/app/construction.rssrc/core/app/discover.rssrc/core/app/dj.rssrc/core/app/friends.rssrc/core/app/help.rssrc/core/app/keybindings.rssrc/core/app/library.rssrc/core/app/lyrics.rssrc/core/app/mod.rssrc/core/app/models.rssrc/core/app/native_backend.rssrc/core/app/native_recovery.rssrc/core/app/native_shuffle.rssrc/core/app/persistence.rssrc/core/app/playback_routing.rssrc/core/app/playlist_folders.rssrc/core/app/playlist_pages.rssrc/core/app/playlists.rssrc/core/app/plugins.rssrc/core/app/queue.rssrc/core/app/queue_suspend.rssrc/core/app/route.rssrc/core/app/scrollable_pages.rssrc/core/app/seek.rssrc/core/app/settings_apply.rssrc/core/app/settings_schema.rssrc/core/app/shuffle_repeat.rssrc/core/app/status.rssrc/core/app/test_support.rssrc/core/app/tick.rssrc/core/app/transport.rssrc/core/app/volume.rs
Pre-existing issues CodeRabbit flagged on the moved code, fixed where the change is small and mechanical: - library.rs, playlists.rs: replace unchecked search-result indexing with .get() in the seven arms that still panicked on a stale UI-selected index; adjacent arms already used the checked form. - seek.rs: saturating_add on the forward-seek target, matching the three sibling seek paths. - persistence.rs: a failed debounced save now restores the deadline so the retained patch is retried instead of dropped (including at shutdown); add_radio_station rolls back and errors instead of reporting Added without persisting; debounce constant lifted to module level. - scrollable_pages.rs: document that add_pages is for index-ordered caches only and offset-keyed caches must use upsert_page_by_offset. - queue.rs: doc comment said "Two cases" over three bullets. - CLAUDE.md/AGENTS.md/copilot-instructions.md: language tag on the data-flow diagram fence (MD040).
Follow-up to the add_pages doc boundary from the previous commit: the upsert tests set up their offset-keyed caches with add_pages, the one method the boundary says those caches must not use. Setup state is identical either way (empty-cache insert lands on index 0; the mid-test index override stays), so this is test hygiene, not a behavior change. Also add a direct out-of-order test: three upserts arriving 4, 0, 2 keep the cache sorted and page_index_for_offset resolves every offset to the right page, with a miss for an absent offset.
Summary
src/core/app.rshad grown to 10,920 lines. This splits it into asrc/core/app/folder of 33 files grouped by concern, with no behavior change:Appstruct stays flat — all ~237 fields declared once inmod.rs; each module contributes its ownimpl Appblock for its ~210 methods.mod.rsblanket re-exports every module, socrate::core::app::<Name>paths are unchanged — no file outside the folder is touched.use super::*;and declare no imports of their own; all external imports stay inmod.rs.pub(super)where a sibling module now calls them, 7 test modules gated by thecfgall their tests share, and the module scaffolding. Tests are colocated per module; the six shared fixtures moved totest_support.rs.Also refreshes the agent guidance docs (CLAUDE.md / AGENTS.md / copilot-instructions) for the new layout, and corrects the CI section: the matrix has five legs, not three — the undocumented
mcp-onlyandai-dj-onlylegs builddj-corewithoutstreaming, a combination nothing else covers.Testing
All five CI legs run locally (Windows):
cargo fmt --allcargo clippy -- -D warnings— clean;cargo test— 847 passedcargo clippy --no-default-features --features telemetry -- -D warnings— clean;cargo test(slim) — 568 passedcargo clippy --locked --no-default-features --features telemetry,mcp-server -- -D warnings— clean; tests — 684 passedcargo clippy --locked --no-default-features --features telemetry,ai-dj -- -D warnings— clean; tests — 827 passedaudio-viz) — clean; 14-featurecargo test— 1261 passed, 1 failedThe one failure is
infra::local::tests::uri_round_trip, pre-existing and Windows-only (Url::to_file_path()rejects the hardcoded/home/user/...path); it passes on CI'subuntu-latest. Test totals are identical before and after the split (84#[test]in the moved code; 1277 in the full suite).Additional notes
impl App { }/mod tests { }wrappers, not duplicated code.load_settings_for_category(736 lines) andapply_settings_changes(715 lines) moved verbatim and dominate their files; breaking them into per-category helpers needs its own review.--all-featurescannot build on Windows (alsa-sysneeds pkg-config), andaudio-vizoff-Linux hits aSpectrumDatadouble-definition insrc/infra/audio/mod.rs.Summary by CodeRabbit
New Features
Documentation