Skip to content

fix(catalog) Improve library browsing state, sort metadata, and stale refresh behavior - #26

Merged
Quick104 merged 11 commits into
mainfrom
web-ui-improvements
May 30, 2026
Merged

Quick104 merged 11 commits into
mainfrom
web-ui-improvements

Conversation

@zZebrahz

@zZebrahz zZebrahz commented May 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This PR improves a few rough edges in the web library/catalog experience:

  • shows richer sort-specific metadata on item cards
  • remembers per-library browse state on a per-device basis
  • preserves the active library query when using the sidebar
  • avoids showing extra skeleton rows after short catalog result pages
  • refreshes stale or incomplete person metadata when a person page is viewed

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_metrics for 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.tsx covers sort-specific card metadata and episode fallback labels.
  • catalog.test.tsx covers the short-result skeleton regression.
  • AppSidebar.test.tsx covers preserving the active library query.
  • settings_device_test.go covers the new device-scoped settings validation and storage behavior.
  • libraryPageSearchParams.test.ts covers saved-state query detection, serialization, and application.
  • LibrarySettings.test.tsx keeps the settings page smoke coverage current.
  • libraryPageState.test.ts is 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 -- --run
  • cd web && pnpm run lint
  • cd web && pnpm run format:check
  • make verify-local-paths

Risks / Follow-ups

  • Person metadata refresh is queued opportunistically on view; if refresh volume becomes noisy, this may need tighter throttling or repo-level freshness checks.
  • Library page state is intentionally device-scoped, so users should expect different saved views across browsers/devices.
  • Client-visible catalog response types gained optional sort_metrics; native clients may choose to ignore it or adopt it later.

Summary by CodeRabbit

  • New Features

    • Item cards show richer sort metrics (resolution, runtime, bitrate, ratings, progress/plays, viewed date).
    • Library pages persist per-device search/tab/sort and can restore them automatically.
    • New "Remember library pages" preference to control per-device persistence.
    • Person pages auto-refresh metadata when details are incomplete.
  • Bug Fixes

    • Fixed catalog pagination to ignore empty buffered pages.
    • Improved sidebar active-library detection and library-link query preservation.

Review Change Stack

@coderabbitai

coderabbitai Bot commented May 30, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds 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.

Changes

Library Browsing Experience Enhancement

Layer / File(s) Summary
Sort Metrics API contract and types
web/src/api/types.ts, internal/scanner/file_repo.go
Introduces BrowseItemSortMetrics and FileRepository.ListByEpisodeIDs to support episode-file grouping for sort metrics.
Backend sort metrics computation
internal/api/handlers/catalog.go, internal/api/handlers/items.go, internal/api/handlers/items_sort_metrics_test.go
Implements listSortMetrics, user-specific listUserSortMetrics, listBrowseItemFiles, completed-history paging helper, and wires catalog handler to attach per-item SortMetrics; includes unit test for user-state sorts.
Frontend sort metrics rendering
web/src/components/ItemCard.tsx, web/src/components/ItemCard.test.tsx
Adds SortMeta formatters and expands rendering to use sort_metrics for many sort fields; tests cover content rating, runtime, ratings, resolution, bitrate, progress, date_viewed, and plays.
Library page state persistence hooks
web/src/hooks/queries/libraryPageState.ts, web/src/hooks/queries/libraryPageState.test.ts
New preference type, parse/serialize/update helpers, and useLibraryPageStatePreference hook that integrates with device settings and exposes a save callback.
Library page search params utilities
web/src/pages/libraryPageSearchParams.ts, web/src/pages/libraryPageSearchParams.test.ts
Adds helpers to detect, serialize, and apply library-scoped search params while preserving unrelated query params; tests added.
Settings system registration
internal/api/handlers/settings.go, internal/api/handlers/settings_device_test.go, web/src/lib/settingsManifest.ts
Registers ui.library_page_state (JSON) and ui.remember_library_page_state (boolean) as device-scoped settings with validation and defaults; frontend manifest adds the remember setting; tests verify resolution and validation.
Settings UI components and tests
web/src/components/settings/SettingRow.tsx, web/src/pages/settings/PlaybackSettings.tsx, web/src/pages/settings/LibrarySettings.tsx, web/src/pages/settings/LibrarySettings.test.tsx
Extracts SettingRow, refactors PlaybackSettings, adds RememberLibraryPageStateSetting to LibrarySettings with device mutation handling, and updates tests/mocks.
LibraryPage component state integration
web/src/pages/LibraryPage.tsx
Wires useLibraryPageStatePreference and search-param helpers to hydrate/apply saved per-library search, normalize canonical URL state, and persist updates back to device preference; uses refs to avoid re-applying just-applied state.
Sidebar active library detection and link preservation
web/src/components/AppSidebar.tsx, web/src/components/AppSidebar.test.tsx
Adds getLibraryIdFromPathname, refines active library resolution, and preserves location.search for active-library base links; test ensures query string preservation.
Person metadata auto-refresh
internal/api/handlers/people.go, web/src/pages/PersonDetail.tsx
Backend enqueues person refresh when metadata is stale and complete; frontend polls briefly while metadata incomplete and triggers a single refresh mutation per incomplete person.
Catalog window empty page fix
web/src/hooks/queries/catalog.ts, web/src/hooks/queries/catalog.test.tsx
Fixes useCatalogWindow to ignore empty buffered pages when computing loaded range; adds test verifying correct total.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 I hopped through lists to tuck your filters tight,
Metrics counted, pages saved each night,
Sidebar links keep their curious strings,
People refresh while the springtime sings—
A tiny rabbit guards your library's light!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly summarizes the main changes: improved library browsing state persistence, sort metadata in catalog responses, and stale refresh behavior for people metadata.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch web-ui-improvements

Comment @coderabbitai help to get the list of available commands and usage tips.

@zZebrahz zZebrahz changed the title [codex] Improve library browsing state, sort metadata, and stale refresh behavior Improve library browsing state, sort metadata, and stale refresh behavior May 30, 2026
@zZebrahz
zZebrahz marked this pull request as ready for review May 30, 2026 02:32
@zZebrahz zZebrahz changed the title Improve library browsing state, sort metadata, and stale refresh behavior fix(library) Improve library browsing state, sort metadata, and stale refresh behavior May 30, 2026
@zZebrahz zZebrahz changed the title fix(library) Improve library browsing state, sort metadata, and stale refresh behavior fix(catalog) Improve library browsing state, sort metadata, and stale refresh behavior May 30, 2026
@zZebrahz
zZebrahz marked this pull request as draft May 30, 2026 02:44

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (1)
internal/api/handlers/items.go (1)

925-934: ⚡ Quick win

Add a non-batch fallback for episode file lookup.

If h.fileRepo does not implement batchEpisodeFileProvider, episode overlays/bitrate metrics are skipped entirely. Since EpisodeFileProvider already guarantees GetByEpisodeID, 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

📥 Commits

Reviewing files that changed from the base of the PR and between e15c07d and 95006a3.

📒 Files selected for processing (24)
  • internal/api/handlers/catalog.go
  • internal/api/handlers/items.go
  • internal/api/handlers/people.go
  • internal/api/handlers/settings.go
  • internal/api/handlers/settings_device_test.go
  • internal/scanner/file_repo.go
  • web/src/api/types.ts
  • web/src/components/AppSidebar.test.tsx
  • web/src/components/AppSidebar.tsx
  • web/src/components/ItemCard.test.tsx
  • web/src/components/ItemCard.tsx
  • web/src/components/settings/SettingRow.tsx
  • web/src/hooks/queries/catalog.test.tsx
  • web/src/hooks/queries/catalog.ts
  • web/src/hooks/queries/libraryPageState.test.ts
  • web/src/hooks/queries/libraryPageState.ts
  • web/src/lib/settingsManifest.ts
  • web/src/pages/LibraryPage.tsx
  • web/src/pages/PersonDetail.tsx
  • web/src/pages/libraryPageSearchParams.test.ts
  • web/src/pages/libraryPageSearchParams.ts
  • web/src/pages/settings/LibrarySettings.test.tsx
  • web/src/pages/settings/LibrarySettings.tsx
  • web/src/pages/settings/PlaybackSettings.tsx

Comment thread internal/api/handlers/items.go Resolved
Comment thread web/src/components/ItemCard.tsx Resolved
Comment thread web/src/pages/LibraryPage.tsx Resolved
@zZebrahz
zZebrahz marked this pull request as ready for review May 30, 2026 04:07

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 95006a3 and be5dde2.

📒 Files selected for processing (7)
  • internal/api/handlers/catalog.go
  • internal/api/handlers/items.go
  • internal/api/handlers/items_sort_metrics_test.go
  • internal/api/handlers/people.go
  • web/src/components/ItemCard.tsx
  • web/src/pages/LibraryPage.tsx
  • web/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

Comment on lines +126 to +134
}, [
activeTab,
browseType,
queryDefinition,
libraryType,
searchParams,
setSearchParams,
shouldApplySavedLibrarySearch,
]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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.

Suggested change
}, [
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.

@Quick104
Quick104 merged commit 626e1f9 into main May 30, 2026
3 checks passed
@Quick104
Quick104 deleted the web-ui-improvements branch May 30, 2026 04:18
Quick104 added a commit to thezak48/silo-server that referenced this pull request Jun 7, 2026
fix(catalog) Improve library browsing state, sort metadata, and stale refresh behavior
Quick104 added a commit that referenced this pull request Jun 11, 2026
fix(catalog) Improve library browsing state, sort metadata, and stale refresh behavior
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants