Repository navigation
feat(collections): add profile-scoped default sorting - #489
Conversation
📝 WalkthroughWalkthroughThis PR adds collection default-sort configuration and per-profile sort preferences across storage, catalog resolution, HTTP APIs, collection creation/import flows, collection rails, and frontend forms and catalog state. ChangesCollection Default Sort Feature
Estimated code review effort: 4 (Complex) | ~75 minutes Possibly related issues
Possibly related PRs
Suggested labels: Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/sections/fetcher.go (1)
1329-1377: 🚀 Performance & Scalability | 🟠 Major | 🏗️ Heavy liftBound default-sort collection rails before ordering them by sorted item ID.
OrderCollectionItemsBySortresolves the sort against the fullAllowedContentIDsset and returns only that subset, so both the library collection rail (collectionRailItemsToFetchwithhasDefaultSort == true) and the personal/exact collection rail truncate in application memory after materializing/sorting more rows than needed. Add an optional result-limit path so the DB can applyORDER BY sorted_item_id LIMIT ...and avoid fetching and sorting the full membership for large rails/cache misses.🤖 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 1329 - 1377, The default-sorted collection rail paths currently materialize and sort the full membership before applying ItemLimit. Add an optional result-limit parameter to OrderCollectionItemsBySort and push the limit into its database ORDER BY sorted_item_id query. Update the library rail flow around collectionRailItemsToFetch and the personal/exact collection rail at internal/sections/fetcher.go lines 1513-1522 to pass the requested limit, while preserving existing behavior when no limit is provided.
🧹 Nitpick comments (3)
web/src/api/types.ts (1)
1389-1399: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winLoosely-typed
order: stringdoesn't encode the backend'sasc|desccontract in either location. Both sites accept an arbitrary string for sort order instead of the two values the backend actually validates, so a typo only surfaces as a runtime API error.
web/src/api/types.ts#L1389-L1399: changeCollectionSortConfig.order?: stringtoorder?: "asc" | "desc".web/src/hooks/queries/collections.ts#L396-L401: reuseCollectionSortConfig's (tightened)ordertype in the mutationFn body parameter instead of re-declaringorder: string.🤖 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/api/types.ts` around lines 1389 - 1399, Restrict CollectionSortConfig.order in web/src/api/types.ts:1389-1399 to the backend-supported "asc" | "desc" union. In web/src/hooks/queries/collections.ts:396-401, update the mutationFn body parameter to reuse CollectionSortConfig’s order type instead of redeclaring order as string.web/src/hooks/useAuth.tsx (1)
336-349: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winConsider a ref to keep
selectProfile's identity stable across profile switches.
selectProfilenow depends on[profile?.id], so its reference changes every time the active profile changes. Since it's exposed throughAuthContextapp-wide, any consumer effect keyed onselectProfile(without already depending onprofile) will re-run more often than before. A ref-based latest-profile-id check avoids this identity churn (and sidesteps a theoretical stale-closure issue ifselectProfilewere ever called twice before a re-render commits).♻️ Proposed fix
+ const profileRef = useRef(profile); + useEffect(() => { + profileRef.current = profile; + }, [profile]); + const selectProfile = useCallback( (p: Profile, profileToken?: string) => { - const profileChanged = profile?.id !== p.id; + const profileChanged = profileRef.current?.id !== p.id; setProfileId(p.id); setProfileToken(profileToken ?? null); if (profileChanged) { queryClient.clear(); } storage.set(storage.KEYS.CURRENT_PROFILE, JSON.stringify(p)); setProfile(p); }, - [profile?.id], + [], );Please double check whether any consumer component relies on
selectProfile's referential stability across renders (e.g. as an effect dependency) before merging, since this file doesn't show those call sites.🤖 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/hooks/useAuth.tsx` around lines 336 - 349, Keep selectProfile referentially stable by storing the latest profile?.id in a ref and reading that ref inside the callback, rather than capturing profile?.id in its dependency array. Update the ref whenever the active profile changes, preserve the existing profileChanged comparison and profile-switch behavior, and verify consumers do not require the callback to change when the profile changes.internal/catalog/catalog_resolver.go (1)
500-524: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider extracting the shared "resolve effective sort" step.
resolveLibraryCollectionSourceandresolveUserCollectionSourceboth implement the identical sequence (resolveEffectiveCollectionSortwhenUseSourceOrder, mutatereq.Query.Sort/UseSourceOrder, delegate, stampresult.EffectiveSort). A small shared helper would remove the duplication and prevent the two paths from drifting (theSortConfigcast already differs syntactically between them).♻️ Suggested extraction
func (r *CatalogResolver) applyEffectiveCollectionSort(ctx context.Context, req *CatalogRequest, access AccessFilter, kind, collectionID string, sortConfig []byte) { if !req.UseSourceOrder { return } if qs, ok := r.EffectiveCollectionSort(ctx, access, kind, collectionID, sortConfig); ok { req.Query.Sort = qs req.UseSourceOrder = false } }Also applies to: 582-605
🤖 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 500 - 524, Extract the duplicated effective-sort resolution from resolveLibraryCollectionSource and resolveUserCollectionSource into a shared CatalogResolver helper, such as applyEffectiveCollectionSort, accepting a request pointer, collection kind/ID, and sort configuration. Use it in both paths while preserving their existing sort-config conversions, delegation, and result.EffectiveSort assignment.
🤖 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/userdb/profiles.go`:
- Line 300: Before deleting personal collections in internal/userdb/profiles.go
at lines 300-300, remove collection_sort_preferences rows scoped to
collection_kind = 'user' whose collection IDs belong to collections with
creator_profile_id = id; apply the equivalent delete in
internal/userstore/pgstore/profiles.go at lines 279-279 using user_id and
user_personal_collections.profile_id = id, then retain the existing personal
collection deletion flow.
In `@internal/userdb/schema.go`:
- Around line 127-135: Update both SQLite definitions of
collectionSortPreferencesSchema to add CHECK constraints matching PostgreSQL
validation for collection_kind and sort_order. Ensure direct SQLite writes
reject the same invalid values as the PostgreSQL migration while preserving the
existing columns, defaults, and primary key.
In `@web/src/pages/ImportedCollectionEditor.tsx`:
- Around line 128-135: Update handleDiscard to reset defaultSort to
initialDefaultSort alongside the other edited fields, ensuring discarded sort
changes do not leave the form dirty or persist on a later save.
---
Outside diff comments:
In `@internal/sections/fetcher.go`:
- Around line 1329-1377: The default-sorted collection rail paths currently
materialize and sort the full membership before applying ItemLimit. Add an
optional result-limit parameter to OrderCollectionItemsBySort and push the limit
into its database ORDER BY sorted_item_id query. Update the library rail flow
around collectionRailItemsToFetch and the personal/exact collection rail at
internal/sections/fetcher.go lines 1513-1522 to pass the requested limit, while
preserving existing behavior when no limit is provided.
---
Nitpick comments:
In `@internal/catalog/catalog_resolver.go`:
- Around line 500-524: Extract the duplicated effective-sort resolution from
resolveLibraryCollectionSource and resolveUserCollectionSource into a shared
CatalogResolver helper, such as applyEffectiveCollectionSort, accepting a
request pointer, collection kind/ID, and sort configuration. Use it in both
paths while preserving their existing sort-config conversions, delegation, and
result.EffectiveSort assignment.
In `@web/src/api/types.ts`:
- Around line 1389-1399: Restrict CollectionSortConfig.order in
web/src/api/types.ts:1389-1399 to the backend-supported "asc" | "desc" union. In
web/src/hooks/queries/collections.ts:396-401, update the mutationFn body
parameter to reuse CollectionSortConfig’s order type instead of redeclaring
order as string.
In `@web/src/hooks/useAuth.tsx`:
- Around line 336-349: Keep selectProfile referentially stable by storing the
latest profile?.id in a ref and reading that ref inside the callback, rather
than capturing profile?.id in its dependency array. Update the ref whenever the
active profile changes, preserve the existing profileChanged comparison and
profile-switch behavior, and verify consumers do not require the callback to
change when the profile changes.
🪄 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: 9ab5436e-ba24-44d0-9f6a-f74a25c71532
📒 Files selected for processing (46)
internal/access/resolver_test.gointernal/api/handlers/catalog.gointernal/api/handlers/collection_sort_prefs.gointernal/api/handlers/collection_sort_prefs_test.gointernal/api/handlers/collections.gointernal/api/handlers/collections_capabilities_test.gointernal/api/handlers/library_collections.gointernal/api/handlers/user_collection_imports.gointernal/api/router.gointernal/catalog/catalog_resolver.gointernal/catalog/collection_sort.gointernal/catalog/collection_sort_db_test.gointernal/catalog/collection_sort_precedence_test.gointernal/catalog/collection_sort_test.gointernal/catalog/query_definition.gointernal/jellycompat/content_direct_test.gointernal/sections/collection_rail_fetch_test.gointernal/sections/fetcher.gointernal/userdb/collection_sort_prefs.gointernal/userdb/conformance_test.gointernal/userdb/migrate.gointernal/userdb/profiles.gointernal/userdb/schema.gointernal/userdb/sqlitestore.gointernal/userstore/pgstore/collection_sort_prefs.gointernal/userstore/pgstore/conformance_test.gointernal/userstore/pgstore/profiles.gointernal/userstore/store.gointernal/userstore/storetest/suite.gointernal/userstore/types.gomigrations/sql/20260727094016_add_collection_sort_preferences.sqlweb/src/api/types.tsweb/src/components/CollectionTemplateGallery/CollectionTemplateConfigForm.tsxweb/src/components/CollectionTemplateGallery/UserCollectionTemplateConfigForm.tsxweb/src/components/collections/CollectionDefaultSortField.tsxweb/src/hooks/AuthProvider.test.tsxweb/src/hooks/queries/catalog.tsweb/src/hooks/queries/collections.test.tsxweb/src/hooks/queries/collections.tsweb/src/hooks/useAuth.tsxweb/src/lib/collectionSortConfig.tsweb/src/pages/Catalog.tsxweb/src/pages/ImportedCollectionEditor.tsxweb/src/pages/adminCollectionsShared.tsxweb/src/pages/catalogSearchParams.test.tsweb/src/pages/catalogSearchParams.ts
|
Addressed the CodeRabbit review in d07064b:\n\n- Removed stale per-viewer sort preferences when a personal collection or its creator profile is deleted, in both SQLite and PostgreSQL.\n- Added SQLite CHECK constraints matching PostgreSQL for collection_kind and sort_order.\n- Reset imported-collection defaultSort on Discard.\n- Changed default-sorted rails to apply access scope, display filtering, sorting, and the rail limit in QueryExecutor before full media-row hydration. This keeps large rails bounded while preserving the exact total count.\n- Tightened CollectionSortConfig.order to asc | desc while retaining the empty-string source-order preference at the request boundary.\n\nI did not add the suggested selectProfile callback ref: the current callback uses the requested profile argument directly, and synchronizing another ref in an effect would not close the proposed same-tick race. I also left the resolver precedence code inline because extracting the small branch would be non-functional churn without improving correctness.\n\nValidation completed:\n- targeted Go tests across catalog, sections, API, userstore, userdb, and access\n- go vet ./...\n- frontend TypeScript build and targeted Vitest tests\n- frontend lint (0 errors; existing warnings only) and Prettier check\n- make build\n- migration validation\n- local-path verification\n\nAll three actionable inline threads have replies and are resolved. |
6b35820 to
aa5a6b3
Compare
Quick104
left a comment
There was a problem hiding this comment.
CI is green on the rebased head. I found the following remaining issues outside the Jellyfin compatibility path:
Actionable findings
-
High — editing an imported collection can silently erase
manual_pins.
sortConfigToSelectValuemaps a legacy{"mode":"manual_pins"}config to the source-order sentinel because it has nofield.handleSavethen always submitssort_config: {}, even when the user only changed an unrelated field. That silently destroys the stored ordering mode. Please preserve unknown/legacy modes unless the sort control itself changed, or representmanual_pinsexplicitly in this editor. -
Medium — sort-preference writes accept nonexistent or inaccessible collection IDs.
HandleSetCollectionSortPreferencevalidates only the reference shape and sort value before writing. Any authenticated profile can therefore accumulate preferences for arbitrary IDs, including collections it cannot access, and library-collection deletion has no corresponding cleanup path. Please validate collection existence/access before persisting and define cleanup for deleted library collections. -
Verification gap — the new collection UI has not been exercised through a real signed-in flow.
The PR description says the configured backend was offline, and there is no screenshot or recording. Please add browser evidence covering creation/editing, saving a default sort, reopening the collection, and confirming the applied order.
Scope and maintainability
- The persistent per-viewer override storage, PUT/DELETE API, automatic persistence of every browse-sort change, effective-sort contract, and profile-switch cache behavior are broader than the creator-time default-sort request in #401. Please either split that feature or explicitly record/confirm the expanded scope before merge.
- The effective-sort resolution/delegation/stamping sequence is duplicated between the library and user collection paths in
catalog_resolver.goand the user path. This is non-blocking, but extracting the shared step would reduce drift.
|
@Quick104 Addressed the full follow-up review in
Verification includes targeted Go suites, Reopened editor retained the saved default: Applied Title / Ascending order to an intentionally reverse-ordered source fixture: |


Problem
Admin/server collections did not expose the same configurable ordering and display-filter behavior as personal collections. Collection viewers also had no profile-scoped way to retain their own sort choice without changing the creator's default.
Approach
Impact
Collection creators can choose a default order, while each viewer can retain a different order privately. Existing collections without a configured default keep their previous source ordering, bounded rail queries, and rail total semantics.
Part of #401.
Risks and follow-up
Verification
Passed:
GOWORK=off go test ./internal/catalog/... ./internal/sections/... ./internal/api/... ./internal/userstore/... ./internal/userdb/... ./internal/access/...go vet ./...make buildmake migrate-validatemake verify-local-pathscd web && pnpm exec tsc -b --noEmitcd web && pnpm run lint(0 errors; existing repository warnings only)cd web && pnpm run format:checkgolangci-lint run --new-from-rev=51d2b58e ./...(0 issues)git diff --checkBrowser evidence:
Known unrelated failures observed in the broad suites:
SeasonContent.test.tsxandServerStorageStep.test.tsxfail because their fixtures lack QueryClient/ResizeObserver setupAdversarial review
The review found and resolved seven material issues: unbounded unsorted rail hydration, changed legacy rail totals, destructive
manual_pinsnormalization, server-derived sorts leaking into URLs, rejected personalized library-viewer sorts, orphaned preferences on profile deletion, and missing SQLite timestamps/capability discovery. It also added serialized preference writes and profile-switch cache isolation. Quick's follow-up review identified legacy manual-pin preservation, write-time collection access validation, deletion cleanup, UI evidence, and resolver duplication. Commit84b0d217addresses all five; preference writes remain authenticated, profile-scoped, access-checked, normalized, and parameterized. The per-viewer override is intentional product scope: it lets viewers retain a private sort without mutating the creator's default.AI Disclosure
Summary by CodeRabbit
New Features
Bug Fixes
Tests
Maintainer-assisted conflict resolution disclosure