Repository navigation
fix(catalog) Improve library browsing state, sort metadata, and stale refresh behavior - #26
Conversation
📝 WalkthroughWalkthroughAdds per-item browse SortMetrics, computes metrics server-side (including user-derived sorts), persists per-library search state to device settings, updates settings UI/manifest/tests, preserves active-library query params in the sidebar, and adds person metadata refresh and related tests. ChangesLibrary Browsing Experience Enhancement
Sequence Diagram(s)sequenceDiagram
participant User as User
participant LibraryPage as LibraryPage
participant StateHook as useLibraryPageStatePreference
participant DeviceSettings as Device Settings API
participant Storage as Device Setting Storage
User->>LibraryPage: Navigate to library
LibraryPage->>StateHook: Read saved search & remember setting
StateHook->>DeviceSettings: Load device settings
DeviceSettings->>Storage: Query setting values
Storage-->>DeviceSettings: Return stored state
DeviceSettings-->>StateHook: Provide preference & remember flag
StateHook-->>LibraryPage: Return parsed state + save callback
LibraryPage->>LibraryPage: Apply saved search params to URL
User->>LibraryPage: Update filters/sort/tab
LibraryPage->>LibraryPage: Normalize and serialize state
LibraryPage->>StateHook: Save updated search
StateHook->>DeviceSettings: Update device setting
DeviceSettings->>Storage: Persist serialized state
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
internal/api/handlers/items.go (1)
925-934: ⚡ Quick winAdd a non-batch fallback for episode file lookup.
If
h.fileRepodoes not implementbatchEpisodeFileProvider, episode overlays/bitrate metrics are skipped entirely. SinceEpisodeFileProvideralready guaranteesGetByEpisodeID, fallback to per-episode fetch preserves correctness across implementations.🔧 Suggested fallback
if len(episodeIDs) > 0 { if batchProvider, ok := h.fileRepo.(batchEpisodeFileProvider); ok { episodeFiles, err := batchProvider.ListByEpisodeIDs(ctx, episodeIDs) if err == nil { for episodeID, files := range episodeFiles { grouped[episodeID] = catalog.FilterMediaFilesByAccess(files, filter) } } + } else { + for _, episodeID := range episodeIDs { + files, err := h.fileRepo.GetByEpisodeID(ctx, episodeID) + if err != nil { + continue + } + grouped[episodeID] = catalog.FilterMediaFilesByAccess(files, filter) + } } }🤖 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 `@internal/api/handlers/items.go` around lines 925 - 934, If h.fileRepo does not implement batchEpisodeFileProvider, fall back to per-episode lookup using the EpisodeFileProvider interface: iterate episodeIDs and call GetByEpisodeID(ctx, episodeID) on h.fileRepo (after asserting it as EpisodeFileProvider), filter the returned files with catalog.FilterMediaFilesByAccess and populate grouped[episodeID]; handle and log individual errors (do not abort the whole loop) so overlays/bitrate metrics are preserved even for repos without ListByEpisodeIDs, while keeping the existing batch path using ListByEpisodeIDs when available.
🤖 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 `@internal/api/handlers/items.go`:
- Around line 844-890: listSortMetrics never handles the "progress",
"date_viewed", and "plays" sort keys so sortMetricsResponse fields
progress_ratio, viewed_at and play_count remain empty; add switch cases for
"progress", "date_viewed", and "plays" in listSortMetrics and populate
metrics[item.ContentID] from overlaySummaries[item.ContentID] (e.g., set
progress_ratio from overlay summary's progress/resume ratio, viewed_at from the
overlay's last-viewed timestamp, and play_count from the overlay's play count),
guarding against nil overlay summaries and zero/empty values and using pointers
where sortMetricsResponse expects them; update listSortMetrics to mirror how
"resolution" and "bitrate" check overlaySummaries and items so the UI receives
the correct active-sort metadata.
In `@web/src/components/ItemCard.tsx`:
- Around line 16-20: The current formatDate in ItemCard.tsx uses new Date(value)
which treats "YYYY-MM-DD" as UTC and causes off-by-one-day for some timezones;
update formatDate to detect date-only strings (e.g., /^\d{4}-\d{2}-\d{2}$/) and
normalize them by appending "T00:00:00" (or otherwise construct a UTC/local-safe
Date) before calling toLocaleDateString so the displayed day is correct across
timezones.
In `@web/src/pages/LibraryPage.tsx`:
- Around line 110-139: The effect can leave applyingSavedSearchParamsRef stuck
because it compares the raw normalizedSearchParams.toString() against the legacy
saved value; fix by comparing/clearing against the canonical serialized form and
also reset the ref when id changes: compute const canonicalSearch =
serializeLibraryPageSearchParams(normalizedSearchParams) and replace the check
that clears applyingSavedSearchParamsRef.current to compare against
canonicalSearch (or clear unconditionally when normalizedSearchParams.toString()
=== searchParams.toString()), and ensure applyingSavedSearchParamsRef is reset
(set to null) when id changes (or at start of this effect when id is different)
so legacy/non-canonical savedLibrarySearch values do not leave the ref stuck;
use the existing symbols applyingSavedSearchParamsRef,
updateLibraryPageSearchParams, serializeLibraryPageSearchParams,
savedLibrarySearch, saveLibrarySearch, id, normalizedSearchParams, and
searchParams to implement this.
---
Nitpick comments:
In `@internal/api/handlers/items.go`:
- Around line 925-934: If h.fileRepo does not implement
batchEpisodeFileProvider, fall back to per-episode lookup using the
EpisodeFileProvider interface: iterate episodeIDs and call GetByEpisodeID(ctx,
episodeID) on h.fileRepo (after asserting it as EpisodeFileProvider), filter the
returned files with catalog.FilterMediaFilesByAccess and populate
grouped[episodeID]; handle and log individual errors (do not abort the whole
loop) so overlays/bitrate metrics are preserved even for repos without
ListByEpisodeIDs, while keeping the existing batch path using ListByEpisodeIDs
when available.
🪄 Autofix (Beta)
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: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: 27180a6d-de7f-47f1-a05b-f870185be052
📒 Files selected for processing (24)
internal/api/handlers/catalog.gointernal/api/handlers/items.gointernal/api/handlers/people.gointernal/api/handlers/settings.gointernal/api/handlers/settings_device_test.gointernal/scanner/file_repo.goweb/src/api/types.tsweb/src/components/AppSidebar.test.tsxweb/src/components/AppSidebar.tsxweb/src/components/ItemCard.test.tsxweb/src/components/ItemCard.tsxweb/src/components/settings/SettingRow.tsxweb/src/hooks/queries/catalog.test.tsxweb/src/hooks/queries/catalog.tsweb/src/hooks/queries/libraryPageState.test.tsweb/src/hooks/queries/libraryPageState.tsweb/src/lib/settingsManifest.tsweb/src/pages/LibraryPage.tsxweb/src/pages/PersonDetail.tsxweb/src/pages/libraryPageSearchParams.test.tsweb/src/pages/libraryPageSearchParams.tsweb/src/pages/settings/LibrarySettings.test.tsxweb/src/pages/settings/LibrarySettings.tsxweb/src/pages/settings/PlaybackSettings.tsx
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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 `@web/src/pages/LibraryPage.tsx`:
- Around line 126-134: The effect is missing id in its dependency array causing
stale reads of id (used around lines 112 and 114) and incorrect library-ID
comparison/ref assignment; update the dependency list for the useEffect that
currently lists activeTab, browseType, queryDefinition, libraryType,
searchParams, setSearchParams, shouldApplySavedLibrarySearch to also include id
(and any related ref like libraryIdRef if used as state), so the effect reruns
whenever id changes and the library-ID comparison and ref assignment are
correct.
🪄 Autofix (Beta)
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: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: 0d52e62a-a3be-4535-a259-2cb021e241f0
📒 Files selected for processing (7)
internal/api/handlers/catalog.gointernal/api/handlers/items.gointernal/api/handlers/items_sort_metrics_test.gointernal/api/handlers/people.goweb/src/components/ItemCard.tsxweb/src/pages/LibraryPage.tsxweb/src/pages/PersonDetail.tsx
💤 Files with no reviewable changes (1)
- internal/api/handlers/people.go
🚧 Files skipped from review as they are similar to previous changes (3)
- internal/api/handlers/catalog.go
- web/src/pages/PersonDetail.tsx
- internal/api/handlers/items.go
| }, [ | ||
| activeTab, | ||
| browseType, | ||
| queryDefinition, | ||
| libraryType, | ||
| searchParams, | ||
| setSearchParams, | ||
| shouldApplySavedLibrarySearch, | ||
| ]); |
There was a problem hiding this comment.
Missing id in dependency array.
The effect reads id at lines 112 and 114 but omits it from the dependency array. If id changes without other dependencies changing, the library-ID comparison and ref assignment will use stale values.
Proposed fix
}, [
activeTab,
browseType,
+ id,
queryDefinition,
libraryType,
searchParams,
setSearchParams,
shouldApplySavedLibrarySearch,
]);📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| }, [ | |
| activeTab, | |
| browseType, | |
| queryDefinition, | |
| libraryType, | |
| searchParams, | |
| setSearchParams, | |
| shouldApplySavedLibrarySearch, | |
| ]); | |
| }, [ | |
| activeTab, | |
| browseType, | |
| id, | |
| queryDefinition, | |
| libraryType, | |
| searchParams, | |
| setSearchParams, | |
| shouldApplySavedLibrarySearch, | |
| ]); |
🤖 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 `@web/src/pages/LibraryPage.tsx` around lines 126 - 134, The effect is missing
id in its dependency array causing stale reads of id (used around lines 112 and
114) and incorrect library-ID comparison/ref assignment; update the dependency
list for the useEffect that currently lists activeTab, browseType,
queryDefinition, libraryType, searchParams, setSearchParams,
shouldApplySavedLibrarySearch to also include id (and any related ref like
libraryIdRef if used as state), so the effect reruns whenever id changes and the
library-ID comparison and ref assignment are correct.
fix(catalog) Improve library browsing state, sort metadata, and stale refresh behavior
fix(catalog) Improve library browsing state, sort metadata, and stale refresh behavior
Summary
This PR improves a few rough edges in the web library/catalog experience:
New Features
Sort metadata on item cards
Catalog item cards now show metadata that matches the active sort field, including runtime, content rating, release date, resolution, TMDB/Rotten Tomatoes ratings, bitrate, progress, play count, and viewed date when available.
The backend now includes
sort_metricsfor catalog responses where the current sort needs data that is not already present on the base item payload.Remember library page state
Library pages can now remember per-library browse state, including tab, sort, order, media type, and filter query params. This is stored as a device-scoped setting so different browsers/devices can keep their own library browsing context.
A new “Remember library pages” setting was added under library settings, along with reusable settings row UI shared by the library/playback settings pages.
Fixes
Avoid stale skeleton rows after short result pages
Catalog windowing no longer treats empty buffered pages as loaded item ranges when totals are omitted. This prevents the UI from showing skeleton placeholders past the real end of short result sets.
Preserve active library query from sidebar
When the current sidebar library item links back to the active library route, it now preserves the current query string instead of resetting the library view.
Refresh stale person metadata on view
Person detail requests now enqueue a metadata refresh when a person has refreshable provider IDs and the local metadata is stale or incomplete.
Test Coverage
Most test changes extend existing colocated tests, matching the repository’s current style:
ItemCard.test.tsxcovers sort-specific card metadata and episode fallback labels.catalog.test.tsxcovers the short-result skeleton regression.AppSidebar.test.tsxcovers preserving the active library query.settings_device_test.gocovers the new device-scoped settings validation and storage behavior.libraryPageSearchParams.test.tscovers saved-state query detection, serialization, and application.LibrarySettings.test.tsxkeeps the settings page smoke coverage current.libraryPageState.test.tsis the one new test file; it covers the new preference parser/serializer/update helper because that helper owns versioning and malformed-input fallback behavior.Validation
Pending before merge:
go test ./internal/api/handlers ./internal/scanner/...cd web && pnpm test -- --runcd web && pnpm run lintcd web && pnpm run format:checkmake verify-local-pathsRisks / Follow-ups
sort_metrics; native clients may choose to ignore it or adopt it later.Summary by CodeRabbit
New Features
Bug Fixes