Repository navigation
feat(collections): add profile-scoped display filters - #191
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds ChangesPersonal collection display filters
MDBList URL normalization
Watchsync provider fixes
Static direct-play bypass
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Possibly related PRs
🚥 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 unit tests (beta)
Comment |
Address code-review feedback on the profile-scoped display filters
without changing behavior:
- Widen CompletedHistoryItemMap to accept ProgressCompletionStore and
drop the duplicate completedHistoryItemMapForProgress copy.
- Extract the duplicated MDBList candidate retry loop into a generic
collectionutil.FetchMDBListWithFallback helper, used by both the user
and library collection syncers, and cover it with unit tests.
- Reuse validateOptionalLibraryIDs in HandleUpdateCollection instead of
an inline positive-ID loop.
- Import the shared COLLECTION_{WATCH,MEDIA}_FILTER_OPTIONS in the
template config form rather than redefining them locally.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (5)
internal/userstore/collection_filters.go (1)
18-28: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAvoid exporting mutable filter-value slices directly.
These exported
[]stringglobals can be mutated by callers at runtime. Prefer immutable backing storage and expose a copy-returning accessor to keep filter capabilities stable.🤖 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/userstore/collection_filters.go` around lines 18 - 28, The exported variables CollectionWatchFilterValues and CollectionMediaFilterValues are mutable slices that can be modified by callers at runtime, compromising filter stability. Refactor by making these slice variables unexported (lowercase names) to prevent direct mutation, then create public accessor functions that return copies of the filter values instead of exposing the original slices. This ensures callers can read the filter options without being able to modify them.internal/userstore/pgstore/collections.go (1)
59-68: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winAlign create-time invalid filter handling with update-time validation.
Create currently coerces invalid filter values to
"all", while update rejects invalid values. Keeping both paths strict for invalid non-empty input improves correctness and surfaces caller bugs earlier.Proposed adjustment
if value, ok := userstore.NormalizeCollectionWatchFilter(input.WatchFilter); ok { input.WatchFilter = value } else { - input.WatchFilter = userstore.CollectionWatchFilterAll + return nil, fmt.Errorf("invalid watch filter %q", input.WatchFilter) } if value, ok := userstore.NormalizeCollectionMediaFilter(input.MediaFilter); ok { input.MediaFilter = value } else { - input.MediaFilter = userstore.CollectionMediaFilterAll + return nil, fmt.Errorf("invalid media filter %q", input.MediaFilter) }🤖 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/userstore/pgstore/collections.go` around lines 59 - 68, The create-time filter validation currently coerces invalid filter values to "all" when NormalizeCollectionWatchFilter and NormalizeCollectionMediaFilter return false, whereas update-time validation rejects invalid values outright. To align both paths and improve correctness, remove the fallback logic that sets input.WatchFilter and input.MediaFilter to CollectionWatchFilterAll and CollectionMediaFilterAll respectively when normalization fails. Instead, return an error when either normalization function returns false for non-empty input values, making the create-time path strict like the update-time validation.internal/userstore/progress_helpers.go (1)
174-193: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDeduplicate the completed-history map logic to avoid drift.
This helper duplicates the mapping flow already present in
CompletedHistoryItemMap. Extract one shared private mapper over a minimal interface and keep both call sites thin.🤖 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/userstore/progress_helpers.go` around lines 174 - 193, The loop that converts completed history items into a map keyed by MediaItemID in the completedHistoryItemMapForProgress function duplicates logic already present in CompletedHistoryItemMap. Extract this shared mapping logic into a private helper function that accepts a minimal interface (the items slice) and returns the constructed map, then have both completedHistoryItemMapForProgress and CompletedHistoryItemMap call this shared helper instead of duplicating the iteration and map-building code. This will prevent logic drift and make the code more maintainable.internal/catalog/user_collection_display_filters_test.go (1)
83-133: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd explicit season-path watch-filter coverage.
userCollectionPlayedMaphas dedicatedseasonlogic, but this suite only validates movies and series. Add one season test (fully complete vs partially complete episodes) to lock that branch and prevent regressions.Proposed test shape
+func TestFilterUserCollectionDisplayItemsSeasonRequiresAllEpisodesComplete(t *testing.T) { + items := []*models.MediaItem{ + {ContentID: "season-a", Type: "season"}, + {ContentID: "season-b", Type: "season"}, + } + store := &displayFilterProgressStore{ + progressByProfile: map[string]map[string]userstore.WatchProgress{ + "profile-a": { + "episode-a1": {ProfileID: "profile-a", MediaItemID: "episode-a1", Completed: true}, + "episode-a2": {ProfileID: "profile-a", MediaItemID: "episode-a2", Completed: true}, + "episode-b1": {ProfileID: "profile-a", MediaItemID: "episode-b1", Completed: true}, + }, + }, + } + episodes := &displayFilterEpisodeLister{ + seasons: map[string][]*models.Episode{ + "season-a": {{ContentID: "episode-a1"}, {ContentID: "episode-a2"}}, + "season-b": {{ContentID: "episode-b1"}, {ContentID: "episode-b2"}}, + }, + } + + watched, err := FilterUserCollectionDisplayItems(context.Background(), store, items, UserCollectionDisplayFilterOptions{ + ProfileID: "profile-a", WatchFilter: userstore.CollectionWatchFilterWatched, EpisodeLister: episodes, + }) + if err != nil { + t.Fatalf("FilterUserCollectionDisplayItems(watched seasons): %v", err) + } + if ids := mediaItemIDs(watched); !reflect.DeepEqual(ids, []string{"season-a"}) { + t.Fatalf("watched season IDs = %#v, want only fully complete season", ids) + } +}🤖 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/catalog/user_collection_display_filters_test.go` around lines 83 - 133, Add a new test function to cover the season-path watch-filter logic that currently lacks explicit coverage. Create a test similar to TestFilterUserCollectionDisplayItemsSeriesRequiresAllEpisodesComplete but for season items instead of series, with media items of type "season", episodes mapped to those seasons, and validation that the watched filter returns only seasons with all episodes completed while the unwatched filter returns seasons with at least one incomplete episode.web/src/components/CollectionTemplateGallery/UserCollectionTemplateConfigForm.tsx (1)
63-74: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsolidate duplicated filter option constants into the shared utility.
Line 63 and Line 69 redefine watch/content options that are already centralized in
web/src/lib/collectionDisplayFilters.ts, which creates drift risk across forms.♻️ Proposed refactor
import type { ImportUserMDBListCollectionRequest, ImportUserTMDBCollectionRequest, ImportUserTraktCollectionRequest, UserCollectionMediaFilter, UserCollectionSyncSchedule, UserCollectionWatchFilter, } from "`@/api/types`"; +import { + COLLECTION_MEDIA_FILTER_OPTIONS, + COLLECTION_WATCH_FILTER_OPTIONS, +} from "`@/lib/collectionDisplayFilters`"; @@ -const WATCH_FILTER_OPTIONS: Array<{ value: UserCollectionWatchFilter; label: string }> = [ - { value: "all", label: "All" }, - { value: "unwatched", label: "Unwatched" }, - { value: "watched", label: "Watched" }, -]; - -const MEDIA_FILTER_OPTIONS: Array<{ value: UserCollectionMediaFilter; label: string }> = [ - { value: "all", label: "All" }, - { value: "movie", label: "Movies" }, - { value: "series", label: "Shows" }, -]; @@ - {WATCH_FILTER_OPTIONS.map((option) => ( + {COLLECTION_WATCH_FILTER_OPTIONS.map((option) => ( @@ - {MEDIA_FILTER_OPTIONS.map((option) => ( + {COLLECTION_MEDIA_FILTER_OPTIONS.map((option) => (As per coding guidelines, keep shared utilities in
web/src/liborweb/src/utils.🤖 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/components/CollectionTemplateGallery/UserCollectionTemplateConfigForm.tsx` around lines 63 - 74, The constants WATCH_FILTER_OPTIONS and MEDIA_FILTER_OPTIONS are defined locally in UserCollectionTemplateConfigForm but duplicate existing definitions in web/src/lib/collectionDisplayFilters.ts. Remove the local definitions of both WATCH_FILTER_OPTIONS and MEDIA_FILTER_OPTIONS from this file and import them instead from the shared collectionDisplayFilters utility module. Update any references in the component to use the imported versions.Source: Coding guidelines
🤖 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/ImportedCollectionEditor.tsx`:
- Around line 1061-1075: The readSourceConfigLibraryIDs function applies
sanitization filters to library IDs extracted from source_config (checking that
they are numbers, finite, positive, and then truncating them while
deduplicating), but the fallback return statement on line 1073 returns
collection.query_definition.library_ids directly without applying the same
sanitization. Apply the same filtering and mapping logic (checking for valid
positive finite numbers, truncating, and deduplicating with Set) to the fallback
library IDs from collection.query_definition.library_ids before returning them
to ensure consistency and prevent invalid IDs from being saved.
---
Nitpick comments:
In `@internal/catalog/user_collection_display_filters_test.go`:
- Around line 83-133: Add a new test function to cover the season-path
watch-filter logic that currently lacks explicit coverage. Create a test similar
to TestFilterUserCollectionDisplayItemsSeriesRequiresAllEpisodesComplete but for
season items instead of series, with media items of type "season", episodes
mapped to those seasons, and validation that the watched filter returns only
seasons with all episodes completed while the unwatched filter returns seasons
with at least one incomplete episode.
In `@internal/userstore/collection_filters.go`:
- Around line 18-28: The exported variables CollectionWatchFilterValues and
CollectionMediaFilterValues are mutable slices that can be modified by callers
at runtime, compromising filter stability. Refactor by making these slice
variables unexported (lowercase names) to prevent direct mutation, then create
public accessor functions that return copies of the filter values instead of
exposing the original slices. This ensures callers can read the filter options
without being able to modify them.
In `@internal/userstore/pgstore/collections.go`:
- Around line 59-68: The create-time filter validation currently coerces invalid
filter values to "all" when NormalizeCollectionWatchFilter and
NormalizeCollectionMediaFilter return false, whereas update-time validation
rejects invalid values outright. To align both paths and improve correctness,
remove the fallback logic that sets input.WatchFilter and input.MediaFilter to
CollectionWatchFilterAll and CollectionMediaFilterAll respectively when
normalization fails. Instead, return an error when either normalization function
returns false for non-empty input values, making the create-time path strict
like the update-time validation.
In `@internal/userstore/progress_helpers.go`:
- Around line 174-193: The loop that converts completed history items into a map
keyed by MediaItemID in the completedHistoryItemMapForProgress function
duplicates logic already present in CompletedHistoryItemMap. Extract this shared
mapping logic into a private helper function that accepts a minimal interface
(the items slice) and returns the constructed map, then have both
completedHistoryItemMapForProgress and CompletedHistoryItemMap call this shared
helper instead of duplicating the iteration and map-building code. This will
prevent logic drift and make the code more maintainable.
In
`@web/src/components/CollectionTemplateGallery/UserCollectionTemplateConfigForm.tsx`:
- Around line 63-74: The constants WATCH_FILTER_OPTIONS and MEDIA_FILTER_OPTIONS
are defined locally in UserCollectionTemplateConfigForm but duplicate existing
definitions in web/src/lib/collectionDisplayFilters.ts. Remove the local
definitions of both WATCH_FILTER_OPTIONS and MEDIA_FILTER_OPTIONS from this file
and import them instead from the shared collectionDisplayFilters utility module.
Update any references in the component to use the imported versions.
🪄 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: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 731a5ae6-6cb7-42d8-b575-7cd0026dd371
📒 Files selected for processing (30)
internal/api/handlers/collections.gointernal/api/handlers/library_collections.gointernal/api/handlers/user_collection_imports.gointernal/api/router.gointernal/catalog/catalog_resolver.gointernal/catalog/library_collection_service.gointernal/catalog/user_collection_display_filters.gointernal/catalog/user_collection_display_filters_test.gointernal/collectionutil/mdblist.gointernal/collectionutil/mdblist_test.gointernal/sections/fetcher.gointernal/sections/user_collection_limit_test.gointernal/usercollections/listing.gointernal/usercollections/sync.gointernal/usercollections/types.gointernal/usercollections/types_test.gointernal/userstore/collection_filters.gointernal/userstore/collection_filters_test.gointernal/userstore/pgstore/collections.gointernal/userstore/progress_helpers.gointernal/userstore/types.gomigrations/sql/20260623184858_user_collection_display_filters.sqlweb/src/api/types.tsweb/src/components/CollectionTemplateGallery/UserCollectionTemplateConfigForm.tsxweb/src/components/collections/CollectionBuilder.tsxweb/src/hooks/queries/collections.tsweb/src/lib/collectionDisplayFilters.tsweb/src/pages/Collections.test.tsxweb/src/pages/ImportedCollectionEditor.tsxweb/src/pages/userCollectionsShared.tsx
readSourceConfigLibraryIDs validated source_config.library_ids (finite, positive, truncated, deduplicated) but returned the query_definition fallback raw, so legacy rows could surface zero/negative/duplicate IDs that the backend now rejects on save. Extract a shared sanitizer and apply it to both paths. Co-Authored-By: Claude Opus 4.8 <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 6
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (4)
internal/sections/fetcher.go (1)
1318-1335: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winApply
display_query_definitionto smart collection sections.This branch returns
fetchFilteredbeforecollection.DisplayQueryDefinitionis evaluated, so smart user collections ignore display filters in Home/section reads. Apply the display filter before the section limit/total calculation, matching the exact collection path below.🤖 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/sections/fetcher.go` around lines 1318 - 1335, The smart collection path in fetcher.go returns from fetchFiltered before collection.DisplayQueryDefinition is applied, so the display filter is being skipped for Home/section reads. Update the isSmartType branch in the fetcher logic to evaluate and apply collection.DisplayQueryDefinition before building the synthetic ResolvedSection and before the fetchFiltered call, matching the exact collection path behavior used for non-smart collections.internal/api/handlers/collections.go (1)
39-61: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy liftKeep the legacy filter API additive.
These structs expose only
display_query_definition. If this replaces existingwatch_filter/media_filterrequest or response fields, existing/api/v1clients silently lose their filters. Keep compatibility fields mapped to/fromdisplay_query_definition, or use the deprecation/sunset flow first. Based on learnings, API changes under/api/v1are additive-only: do not rename or remove response fields, change field types, or repurpose status codes.Also applies to: 71-91
🤖 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/collections.go` around lines 39 - 61, The collection request structs currently surface only display_query_definition, which risks breaking existing /api/v1 clients that still send or read watch_filter and media_filter. Update createCollectionRequest and updateCollectionRequest to remain additive by keeping the legacy filter fields mapped to and from display_query_definition, or preserve the old fields alongside the new one until a deprecation/sunset flow is in place. Verify the collection handler flow in internal/api/handlers/collections.go continues to accept and emit the legacy filter API symbols without renaming, removing, or changing their types.Source: Learnings
internal/catalog/catalog_resolver.go (1)
503-520: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winApply display filters for live user collections without overlays.
FilterCollectionItemsByDisplayQueryonly runs insidecatalogRequestHasOverlay(req). A smart/live user collection opened without overlay params still returnsresolveQuerySourcedirectly, so its storeddisplay_query_definitionis ignored. Route the live branch through base-items → display-filter →resolveExactOrderedMediaItemswhenevercollection.DisplayQueryDefinitionis non-empty.🤖 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/catalog/catalog_resolver.go` around lines 503 - 520, The live collection path in catalogResolver currently skips the stored display query unless catalogRequestHasOverlay(req) is true, so collections with collection.DisplayQueryDefinition set can bypass filtering. Update the branch in resolveQuerySource/resolveExactOrderedMediaItems flow so that non-empty display_query_definition also routes through resolveCollectionQueryBaseItems, FilterCollectionItemsByDisplayQuery, and resolveExactOrderedMediaItems even without overlay params, while preserving the existing overlay behavior for req.web/src/pages/ImportedCollectionEditor.tsx (1)
313-349: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winPopulate these selects from collection capabilities, not local constants.
These controls are still driven by hardcoded option arrays even though this feature added
/collections/capabilitiesfor server-side feature detection. That means a newer client can offer unsupported presets against an older server, or miss newly advertised presets during partial rollouts. Please source the watch/content options fromCollectionCapabilitiesResponsehere instead of assuming the local enum set is always valid. Based on learnings, "For new features, expose capability endpoints for feature detection instead of relying on version sniffing."🤖 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/ImportedCollectionEditor.tsx` around lines 313 - 349, The watch/content selects in ImportedCollectionEditor are still using hardcoded option lists instead of server-provided capabilities. Update the component to derive these options from CollectionCapabilitiesResponse and use the capabilities data when rendering the SelectItem entries, so the UI only shows presets supported by the current server. Keep the existing ImportedCollectionEditor select wiring, but replace COLLECTION_WATCH_FILTER_OPTIONS and COLLECTION_MEDIA_FILTER_OPTIONS with capability-driven data fetched for the collection.Source: Learnings
🧹 Nitpick comments (2)
internal/jellycompat/playback_static_directplay_test.go (1)
136-137: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd lowercase
static=truecoverage for the case-insensitive query path.This test only exercises
Static=true, but the handler explicitly supports lowercase keys for real clients. Add a second assertion/subtest forstatic=trueto prevent regressions.Suggested test tweak
- rawQuery := "Static=true&PlaySessionId=play-1&MediaSourceId=" + url.QueryEscape(sourceID) - rec := serveStaticStream(handler, encodedID, rawQuery) - - if rec.Code != 200 { - t.Fatalf("expected status 200; got %d, body=%s", rec.Code, rec.Body.String()) - } - if got := rec.Body.String(); got != body { - t.Errorf("expected file content %q; got %q", body, got) - } + queries := []string{ + "Static=true&PlaySessionId=play-1&MediaSourceId=" + url.QueryEscape(sourceID), + "static=true&PlaySessionId=play-1&MediaSourceId=" + url.QueryEscape(sourceID), + } + for _, rawQuery := range queries { + rec := serveStaticStream(handler, encodedID, rawQuery) + if rec.Code != 200 { + t.Fatalf("query %q: expected status 200; got %d, body=%s", rawQuery, rec.Code, rec.Body.String()) + } + if got := rec.Body.String(); got != body { + t.Errorf("query %q: expected file content %q; got %q", rawQuery, body, got) + } + }🤖 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/jellycompat/playback_static_directplay_test.go` around lines 136 - 137, Add coverage for the case-insensitive query parsing in the static direct play test by extending the existing serveStaticStream-based assertion in playback_static_directplay_test.go to also exercise the lowercase static=true form. Update the playback_static_directplay_test logic near the current Static=true request setup so it verifies both variants, preferably as a second subtest or assertion alongside the existing one, using the same handler path and encodedID/sourceID flow.internal/catalog/display_query_filter_test.go (1)
9-74: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy liftAdd coverage for
FilterCollectionItemsByDisplayQuery.This suite only exercises normalization. The new executor-backed path still needs a regression test for the PR’s key contract: empty fragments are a no-op, matching items keep source order, and filtering happens against the provided candidate IDs rather than a broader catalog result set.
Based on learnings, this path should stay predictable under load and future refactors.
🤖 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/catalog/display_query_filter_test.go` around lines 9 - 74, Add a regression test for FilterCollectionItemsByDisplayQuery to cover the executor-backed path, not just NormalizeDisplayQueryFragment. Verify that empty or blank fragments return the input unchanged, that matching items are returned in the same order as the source slice, and that filtering is applied only to the provided candidate IDs rather than any wider catalog set. Use the existing NormalizeDisplayQueryFragment and FilterCollectionItemsByDisplayQuery symbols to locate the test insertion point.Source: Learnings
🤖 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/catalog/display_query_filter.go`:
- Around line 96-107: The display filter validator currently accepts any
non-empty string for the `displayFilterFieldType` case in
`validateDisplayFilterValue`, which allows unsupported `type` values to pass.
Update that branch to explicitly allow only the advertised presets (`all`,
`movie`, `series`) and return an error for anything else, keeping the existing
`watched` validation unchanged. Use the existing `validateDisplayFilterValue`
and `displayFilterFieldType` symbols to locate the logic.
In `@internal/userstore/pgstore/collections.go`:
- Around line 44-53: CreateCollection is returning input.DisplayQueryDefinition
verbatim instead of the persisted shape, so whitespace-only values diverge from
what displayQueryDefinitionArg stores and what GetCollection/ListCollections
later read. Update CreateCollection to normalize the returned
DisplayQueryDefinition using the same trimming/empty-to-empty-or-nil logic used
by displayQueryDefinitionArg, and keep the create response consistent with the
stored display_query_definition value.
In `@internal/watchsync/providers/mdblist/provider.go`:
- Around line 594-600: The percentage parsing in the MDBList decoder is trimming
the `%` before whitespace, so values like “45% ” still reach strconv.ParseFloat
with a trailing percent and fail. Update the normalization in the relevant
parsing path in the provider’s percentage decode logic to trim whitespace first
and then remove the optional `%`, keeping the tolerant behavior for
whitespace-padded percentage strings.
In `@internal/watchsync/service.go`:
- Around line 198-199: The manual sync active-run check currently treats a zero
StartedAt as valid and returns early, which prevents stale legacy rows from
reaching the retry/cleanup path. Update the branch in the watchsync service’s
manual-sync flow so only non-zero StartedAt values within manualSyncTimeout
return active; if StartedAt is zero, let the code continue to the stale/failure
handling below. Use the existing active run handling around manualSyncTimeout
and the cleanup/retry path to keep the behavior consistent.
In `@web/src/api/types.ts`:
- Around line 1273-1274: Introduce a dedicated DisplayQueryDefinition type for
the filter-only display_query_definition payload instead of reusing
QueryDefinition. Update the relevant API type declarations in types.ts and any
related references in collectionDisplayFilters.ts and Collections.test.tsx so
omitted execution fields like library_ids and sort are no longer assumed or cast
away. Use the new DisplayQueryDefinition symbol wherever the display query
fragment is modeled so callers can only rely on the filter fields that actually
exist.
In `@web/src/pages/Catalog.tsx`:
- Around line 266-268: The personalized overlay controls are being restricted to
collection sources only, which removes them from existing overlay-capable
sources. Update the `Catalog` page logic around `allowPersonalizedFilters` and
`allowPersonalizedSorts` so it expands support to collections without dropping
the current source set (`query`, `favorites`, `watchlist`, `history`, `person`),
and adjust the guard used near `isCollectionSource` accordingly.
---
Outside diff comments:
In `@internal/api/handlers/collections.go`:
- Around line 39-61: The collection request structs currently surface only
display_query_definition, which risks breaking existing /api/v1 clients that
still send or read watch_filter and media_filter. Update createCollectionRequest
and updateCollectionRequest to remain additive by keeping the legacy filter
fields mapped to and from display_query_definition, or preserve the old fields
alongside the new one until a deprecation/sunset flow is in place. Verify the
collection handler flow in internal/api/handlers/collections.go continues to
accept and emit the legacy filter API symbols without renaming, removing, or
changing their types.
In `@internal/catalog/catalog_resolver.go`:
- Around line 503-520: The live collection path in catalogResolver currently
skips the stored display query unless catalogRequestHasOverlay(req) is true, so
collections with collection.DisplayQueryDefinition set can bypass filtering.
Update the branch in resolveQuerySource/resolveExactOrderedMediaItems flow so
that non-empty display_query_definition also routes through
resolveCollectionQueryBaseItems, FilterCollectionItemsByDisplayQuery, and
resolveExactOrderedMediaItems even without overlay params, while preserving the
existing overlay behavior for req.
In `@internal/sections/fetcher.go`:
- Around line 1318-1335: The smart collection path in fetcher.go returns from
fetchFiltered before collection.DisplayQueryDefinition is applied, so the
display filter is being skipped for Home/section reads. Update the isSmartType
branch in the fetcher logic to evaluate and apply
collection.DisplayQueryDefinition before building the synthetic ResolvedSection
and before the fetchFiltered call, matching the exact collection path behavior
used for non-smart collections.
In `@web/src/pages/ImportedCollectionEditor.tsx`:
- Around line 313-349: The watch/content selects in ImportedCollectionEditor are
still using hardcoded option lists instead of server-provided capabilities.
Update the component to derive these options from CollectionCapabilitiesResponse
and use the capabilities data when rendering the SelectItem entries, so the UI
only shows presets supported by the current server. Keep the existing
ImportedCollectionEditor select wiring, but replace
COLLECTION_WATCH_FILTER_OPTIONS and COLLECTION_MEDIA_FILTER_OPTIONS with
capability-driven data fetched for the collection.
---
Nitpick comments:
In `@internal/catalog/display_query_filter_test.go`:
- Around line 9-74: Add a regression test for
FilterCollectionItemsByDisplayQuery to cover the executor-backed path, not just
NormalizeDisplayQueryFragment. Verify that empty or blank fragments return the
input unchanged, that matching items are returned in the same order as the
source slice, and that filtering is applied only to the provided candidate IDs
rather than any wider catalog set. Use the existing
NormalizeDisplayQueryFragment and FilterCollectionItemsByDisplayQuery symbols to
locate the test insertion point.
In `@internal/jellycompat/playback_static_directplay_test.go`:
- Around line 136-137: Add coverage for the case-insensitive query parsing in
the static direct play test by extending the existing serveStaticStream-based
assertion in playback_static_directplay_test.go to also exercise the lowercase
static=true form. Update the playback_static_directplay_test logic near the
current Static=true request setup so it verifies both variants, preferably as a
second subtest or assertion alongside the existing one, using the same handler
path and encodedID/sourceID flow.
🪄 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: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 5dde0dcb-74ce-4ee2-a908-315c961a5825
📒 Files selected for processing (36)
AGENTS.mddocs/superpowers/plans/2026-06-23-personal-collection-catalog-filter-standardization.mddocs/superpowers/specs/2026-06-23-personal-collection-catalog-filter-standardization-design.mdinternal/api/handlers/collections.gointernal/api/handlers/user_collection_imports.gointernal/catalog/catalog_parser.gointernal/catalog/catalog_parser_test.gointernal/catalog/catalog_resolver.gointernal/catalog/display_query_filter.gointernal/catalog/display_query_filter_test.gointernal/catalog/query_builder.gointernal/catalog/query_builder_test.gointernal/jellycompat/playback_static_directplay_test.gointernal/jellycompat/streams.gointernal/sections/fetcher.gointernal/userstore/collection_filters.gointernal/userstore/pgstore/collections.gointernal/userstore/types.gointernal/watchsync/providers/mdblist/provider.gointernal/watchsync/providers/simkl/provider.gointernal/watchsync/providers/simkl/provider_test.gointernal/watchsync/service.gomigrations/sql/20260624124430_add_user_collection_display_query_definition.sqlweb/src/api/types.tsweb/src/components/CollectionTemplateGallery/UserCollectionTemplateConfigForm.tsxweb/src/components/catalog/CatalogFiltersPanel.test.tsxweb/src/components/catalog/CatalogFiltersPanel.tsxweb/src/components/collections/CollectionBuilder.tsxweb/src/lib/collectionDisplayFilters.test.tsweb/src/lib/collectionDisplayFilters.tsweb/src/pages/Catalog.tsxweb/src/pages/Collections.test.tsxweb/src/pages/ImportedCollectionEditor.tsxweb/src/pages/catalogSearchParams.test.tsweb/src/pages/catalogSearchParams.tsweb/src/pages/userCollectionsShared.tsx
✅ Files skipped from review due to trivial changes (2)
- migrations/sql/20260624124430_add_user_collection_display_query_definition.sql
- AGENTS.md
🚧 Files skipped from review as they are similar to previous changes (1)
- web/src/components/CollectionTemplateGallery/UserCollectionTemplateConfigForm.tsx
There was a problem hiding this comment.
🧹 Nitpick comments (1)
web/src/pages/catalogSearchParams.ts (1)
290-297: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRedundant collection-source block.
After removing the early
return, this block no longer does anything unique:collection_idis already set unconditionally at Lines 299-301, andtitleat Lines 305-307. Forlibrary_collection/user_collectionboth keys are written twice. Dropping this block keeps behavior identical and removes the duplicate writes.♻️ Proposed cleanup
- if (state.source === "library_collection" || state.source === "user_collection") { - if (state.collection_id) { - params.set("collection_id", state.collection_id); - } - if (state.title) { - params.set("title", state.title); - } - } - if (state.collection_id) { params.set("collection_id", state.collection_id); }Based on learnings: "avoid duplicated logic across files, and do not solve new functionality with local one-off shortcuts."
🤖 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/catalogSearchParams.ts` around lines 290 - 297, Remove the redundant collection-source branch in catalogSearchParams because it now duplicates the unconditional parameter writes for collection_id and title. Update the logic around the source handling in the catalogSearchParams builder so the library_collection/user_collection case no longer sets those params a second time, keeping the existing unconditional assignments as the single source of truth.Source: Learnings
🤖 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.
Nitpick comments:
In `@web/src/pages/catalogSearchParams.ts`:
- Around line 290-297: Remove the redundant collection-source branch in
catalogSearchParams because it now duplicates the unconditional parameter writes
for collection_id and title. Update the logic around the source handling in the
catalogSearchParams builder so the library_collection/user_collection case no
longer sets those params a second time, keeping the existing unconditional
assignments as the single source of truth.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 7cc2b807-fb5d-4a2c-987c-00dab3f76cae
📒 Files selected for processing (5)
web/src/components/catalog/CatalogFilterBar.tsxweb/src/components/catalog/CatalogFiltersPanel.tsxweb/src/hooks/queries/catalog.tsweb/src/hooks/queries/keys.tsweb/src/pages/catalogSearchParams.ts
✅ Files skipped from review due to trivial changes (1)
- web/src/hooks/queries/catalog.ts
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/watchsync/service.go (1)
201-217: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winSkip cooldown after recovering a timed-out active run.
After
completeSyncRunstamps the stale run withCompletedAt = s.now(), the subsequent latest-run cooldown check can treat that just-failed timeout as a fresh sync and returnSyncCooldownErrorinstead of creating the retry run.Suggested fix
+ recoveredTimedOutRun := false for { active, ok, err := s.repo.GetActiveSyncRun(ctx, conn.ID) if err != nil { return ManualSyncResult{}, err @@ active.Error = "watch provider sync timed out before completion" if _, err := s.completeSyncRun(ctx, active); err != nil { return ManualSyncResult{}, err } + recoveredTimedOutRun = true } - if latest, ok, err := s.repo.GetLatestSyncRun(ctx, conn.ID); err != nil { + if !recoveredTimedOutRun { + if latest, ok, err := s.repo.GetLatestSyncRun(ctx, conn.ID); err != nil { - return ManualSyncResult{}, err - } else if ok { - reference := latest.StartedAt - if latest.CompletedAt != nil { - reference = *latest.CompletedAt - } - if retryAfter := retryAfterSeconds(s.now(), reference, manualSyncCooldown); retryAfter > 0 { - return ManualSyncResult{}, SyncCooldownError{RetryAfterSeconds: retryAfter} + return ManualSyncResult{}, err + } else if ok { + reference := latest.StartedAt + if latest.CompletedAt != nil { + reference = *latest.CompletedAt + } + if retryAfter := retryAfterSeconds(s.now(), reference, manualSyncCooldown); retryAfter > 0 { + return ManualSyncResult{}, SyncCooldownError{RetryAfterSeconds: retryAfter} + } } }🤖 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/watchsync/service.go` around lines 201 - 217, The cooldown check in s.completeSyncRun/s.repo.GetLatestSyncRun is treating the newly stamped timed-out run as the latest sync and blocking the retry. Update the manual-sync flow in internal/watchsync/service.go to skip the retryAfterSeconds check when the current request is recovering an active run that was just marked failed by completeSyncRun, using the existing active/latest run state to distinguish that case. Make the bypass logic local to the timeout-recovery path so normal cooldown behavior still applies for all other syncs.
🧹 Nitpick comments (1)
internal/sections/fetcher.go (1)
1345-1346: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winSkip the unused count query here.
Previewforces a total count, but this path discards it and computes the displayed total after applying the display filter. UsePreviewPage(..., false)to avoid an extra count query per smart collection section.Based on learnings, “Prioritize performance first, then reliability, and keep behavior predictable under load and during failures.”⚡ Proposed change
- items, _, err := executor.Preview(ctx, qd, filter, limit) + items, _, _, err := executor.PreviewPage(ctx, qd, filter, limit, 0, false)🤖 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/sections/fetcher.go` around lines 1345 - 1346, The smart collection preview path is still invoking the count-producing executor method even though the total is discarded, which adds an unnecessary query. Update the fetch logic in the code that builds `catalog.QueryExecutor` and calls `Preview` so it uses `PreviewPage(..., false)` instead, keeping the existing item retrieval and display-filter behavior while skipping the unused count query.Source: Learnings
🤖 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/sections/fetcher.go`:
- Around line 2204-2205: The single-library branch currently overwrites
def.LibraryIDs instead of narrowing the existing scope, unlike the multi-library
branch. Update the logic around the libraryID switch case in the fetcher flow so
it intersects the requested single library with any preexisting def.LibraryIDs,
and leaves the scope empty when there is no overlap. Use def.LibraryIDs and
libraryID as the key symbols to adjust this behavior consistently with the
multi-library handling.
---
Outside diff comments:
In `@internal/watchsync/service.go`:
- Around line 201-217: The cooldown check in
s.completeSyncRun/s.repo.GetLatestSyncRun is treating the newly stamped
timed-out run as the latest sync and blocking the retry. Update the manual-sync
flow in internal/watchsync/service.go to skip the retryAfterSeconds check when
the current request is recovering an active run that was just marked failed by
completeSyncRun, using the existing active/latest run state to distinguish that
case. Make the bypass logic local to the timeout-recovery path so normal
cooldown behavior still applies for all other syncs.
---
Nitpick comments:
In `@internal/sections/fetcher.go`:
- Around line 1345-1346: The smart collection preview path is still invoking the
count-producing executor method even though the total is discarded, which adds
an unnecessary query. Update the fetch logic in the code that builds
`catalog.QueryExecutor` and calls `Preview` so it uses `PreviewPage(..., false)`
instead, keeping the existing item retrieval and display-filter behavior while
skipping the unused count query.
🪄 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: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: d15cc45b-1def-418a-9f5e-500172759be2
📒 Files selected for processing (16)
internal/catalog/catalog_resolver.gointernal/catalog/display_query_filter.gointernal/catalog/display_query_filter_test.gointernal/jellycompat/playback_static_directplay_test.gointernal/sections/fetcher.gointernal/userstore/pgstore/collections.gointernal/watchsync/providers/mdblist/provider.gointernal/watchsync/service.goweb/src/api/types.tsweb/src/components/collections/CollectionBuilder.tsxweb/src/lib/collectionDisplayFilters.test.tsweb/src/lib/collectionDisplayFilters.tsweb/src/pages/Catalog.tsxweb/src/pages/Collections.test.tsxweb/src/pages/ImportedCollectionEditor.tsxweb/src/pages/catalogSearchParams.ts
💤 Files with no reviewable changes (1)
- web/src/pages/catalogSearchParams.ts
🚧 Files skipped from review as they are similar to previous changes (10)
- internal/jellycompat/playback_static_directplay_test.go
- web/src/components/collections/CollectionBuilder.tsx
- web/src/pages/Catalog.tsx
- web/src/pages/Collections.test.tsx
- internal/watchsync/providers/mdblist/provider.go
- web/src/lib/collectionDisplayFilters.test.ts
- internal/userstore/pgstore/collections.go
- internal/catalog/display_query_filter.go
- web/src/pages/ImportedCollectionEditor.tsx
- internal/catalog/catalog_resolver.go
* feat(collections): add profile-scoped display filters
* refactor(collections): dedup display-filter helpers per review
Address code-review feedback on the profile-scoped display filters
without changing behavior:
- Widen CompletedHistoryItemMap to accept ProgressCompletionStore and
drop the duplicate completedHistoryItemMapForProgress copy.
- Extract the duplicated MDBList candidate retry loop into a generic
collectionutil.FetchMDBListWithFallback helper, used by both the user
and library collection syncers, and cover it with unit tests.
- Reuse validateOptionalLibraryIDs in HandleUpdateCollection instead of
an inline positive-ID loop.
- Import the shared COLLECTION_{WATCH,MEDIA}_FILTER_OPTIONS in the
template config form rather than redefining them locally.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
* fix(collections): sanitize query_definition library_ids fallback
readSourceConfigLibraryIDs validated source_config.library_ids (finite,
positive, truncated, deduplicated) but returned the query_definition
fallback raw, so legacy rows could surface zero/negative/duplicate IDs
that the backend now rejects on save. Extract a shared sanitizer and
apply it to both paths.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
* refactor(docs): This makes the agents annoying to work with
* Improve playback session handling
* Support collection source order in catalog filters
* fix(collections): address display filter review feedback
* refactor(catalog): remove duplicate collection query params
* Hide episode media scope for collection overlays
---------
Co-authored-by: Claude Opus 4.8 <[email protected]>
Summary
all,unwatched,watched) and media type (all,movie,series)./collections/capabilitiesendpoint for client feature detection./jsonsuffixes resolve consistently across user and server collection sync.Part of approved V1 collection filter scope.
Details
This keeps synced collection membership unchanged and filters only the displayed results for the active profile. The shared filtering helper batches watched-state resolution, treats completed progress or completed history as watched, and requires all available child episodes to be complete before series/seasons count as watched.
Existing collections default to
watch_filter="all"andmedia_filter="all", so existing behavior is preserved until a user opts into a display filter.Imported collection editing now updates
source_config.library_idsthrough the dedicated update field instead of writing imported library scope back intoquery_definition, keeping imported collections as exact synced lists.Validation
GOWORK=off go test ./internal/userstore ./internal/catalog ./internal/sections ./internal/api/handlers ./internal/collectionutil ./internal/usercollectionscd web && pnpm exec tsc -b --noEmitcd web && pnpm exec eslint . --quietNotes / Follow-up
AI Use
Implemented with assistance from Codex.
Summary by CodeRabbit
New Features
Bug Fixes