Skip to content

feat(sections): fix broken home section templates and add six new ones - #332

Merged
Quick104 merged 2 commits into
mainfrom
claude/interesting-solomon-47eafd
Jul 7, 2026
Merged

Quick104 merged 2 commits into
mainfrom
claude/interesting-solomon-47eafd

Conversation

@Quick104

@Quick104 Quick104 commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Problem

A review of the home page section templates (recipes) found several that are advertised in the gallery but silently produce nothing — the home page hides empty sections, so they just never appear:

  • Award Winners (all 3 presets): fetchAwardWinners is a stub that always returns empty.
  • Seasonal Picks went dark during the biggest holidays: christmas/st_patricks/thanksgiving have date predicates but no query, and theme selection picked them by priority anyway — an enabled christmas theme suppressed the whole section for all of December.
  • Taste Match default preset: the fetcher required a genre but the preset ships {}, so it never rendered.
  • Because You Watched: the recipe/UI write anchor_item_id but the fetcher only read source_item_id — pinning an anchor did nothing.
  • Editor's Picks (admin_curated_list): no item picker existed, and the preset's empty item_ids always failed validation → add always 400s. It also leaked into non-admin galleries because admin_only was never enforced client-side.
  • Editorial franchise subject validated but can never resolve (no data source).
  • Library scoping: hidden_gems/forgotten_favorites ignored library scope entirely and critically_acclaimed dropped multi-library scope, leaking items across libraries on scoped pages; hidden_gems' advertised max_play_count param was dead.

What changed

Fixes

  • award_winners marked Hidden (stays resolvable for saved sections).
  • Seasonal: interim title-keyword resolver for christmas/st_patricks/thanksgiving (until a proper keyword/tag column lands), and ActiveSeasonalThemeWhere skips themes that can't produce items so a data-less theme never blacks out the section in its own window. Title overrides track the same selection.
  • Taste match: empty genre auto-picks the profile's strongest taste cluster, falling back to the server-wide top genre.
  • Because You Watched: fetcher honors both anchor_item_id and legacy source_item_id (legacy wins when both set).
  • Editorial: franchise removed from valid subject types; drawer no longer misrepresents pinned presets (e.g. "The 80s") as auto-rotate.
  • Editor's Picks: new catalog-search item picker (ordered, reorderable) in the recipe drawer (reused by the admin edit drawer); Add is blocked until the list is non-empty; admin_only recipes hidden from profile-facing galleries.
  • Discovery repo filters take single/multi library scope, intersected with viewer access so a scoped section can never widen access; max_play_count implemented as a watch-count threshold.

New templates

  • returning_shows — shows you've watched with a brand-new season (newer than any you've seen, with playable files) in the lookback window.
  • genre_roulette — deterministic rotating top-genre spotlight (reuses editorial rotation hashing + candidate cache), row title carries the active genre.
  • anniversaries — movies with a milestone release anniversary this month (5-year multiples by default).
  • short_watches — well-rated movies under a runtime cap ("Short & Sweet").
  • family_movie_night — new seasonal theme for Friday/Saturday evenings, with preset and holiday-picker entry.
  • format_showcase gains sort: recent + a "New in 4K" preset.

Review notes

  • New user-agnostic fetchers (short_watches, anniversaries) join the shared resolved-list cache via userAgnosticSectionFetcher, so cacheability tracks dispatch as before; genre_roulette mirrors the editorial_spotlight title-override interception in FetchOne; returning_shows is per-user.
  • A new blanket test asserts every visible gallery preset's default params pass that recipe's own validation (with an explicit allowlist for presets whose drawer requires input) — this is the test that would have caught taste_match and Editor's Picks.
  • All four new SQL shapes were validated with EXPLAIN against the dev database; plans use existing indexes.
  • Seasonal keyword matching is an explicit interim heuristic; it should be replaced when keyword/tag metadata lands.
  • Pre-existing failures not touched: jellycompat TestBeginWebOperation* (flaky), setup-wizard/compat-proxy vitest files (fail on HEAD).
  • Scope: ad-hoc fix from a section-template review in this session — no linked epic; happy to file/link an issue if wanted.

Verification

  • go build ./..., go test ./internal/... ./cmd/... (only the documented pre-existing failures), gofmt, make verify-local-paths.
  • Web: tsc -b, pnpm run lint (0 errors), pnpm run format:check, vitest (RecipeGallery suites pass; full-suite failures are pre-existing).

AI-use disclosure

Implemented by Claude (Fable 5) via Claude Code under human direction, including the review that found the defects; verified with the test runs and dev-DB EXPLAIN checks above.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added new home screen and discovery options, including returning shows, genre roulette, anniversaries, short watches, and a family movie night seasonal theme.
    • Added more flexible recipe settings, including recent sorting, max plays, and multi-library selection.
    • Improved the recipe gallery with curated list editing and support for more parameter types.
  • Bug Fixes

    • Refined matching and seasonal selection behavior so empty inputs and unavailable themes fall back more reliably.
    • Tightened access checks so scoped sections won’t expand beyond permitted libraries.
  • UI Improvements

    • Hidden admin-only items from the public recipe gallery view.

Fixes templates that silently produced nothing:
- award_winners: hide from gallery (resolver is a stub until award data
  exists); saved sections keep resolving
- seasonal_themed: christmas/st_patricks/thanksgiving get an interim
  title-keyword resolver, and multi-theme selection skips themes without
  an executable query so a data-less theme can no longer black out the
  section during its own window (previously killed the section all of
  December)
- taste_match: empty genre now auto-picks the profile's strongest taste
  cluster (fallback: server top genre); the default preset was permanently
  empty
- because_you_watched: honor the recipe's anchor_item_id key (fetcher only
  read legacy source_item_id, so pinning an anchor did nothing)
- editorial_spotlight: reject subject_type=franchise (validated but could
  never resolve); fix drawer misrepresenting pinned presets as auto-rotate
- admin_curated_list: add a catalog-search item picker so Editor's Picks
  is actually addable; block saving an empty list; hide admin_only recipes
  from profile-facing galleries
- discovery fetchers (hidden_gems, forgotten_favorites,
  critically_acclaimed): honor single/multi library scope, intersected
  with viewer access; implement hidden_gems max_play_count

New templates: returning_shows (new season of shows you've watched),
genre_roulette (rotating top-genre spotlight with title override),
anniversaries (milestone release anniversaries this month), short_watches
(well-rated movies under a runtime cap), family_movie_night seasonal
theme (Fri/Sat evenings), and a "New in 4K" format_showcase preset via a
new sort=recent param.

Adds a blanket test asserting every visible gallery preset's defaults
pass its own recipe validation — the gap that let taste_match and
Editor's Picks ship broken. New SQL shapes validated with EXPLAIN against
the dev database.

Co-Authored-By: Claude Fable 5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

You’ve reached a temporary PR review limit under our Fair Usage Limits Policy.

Your recent review volume is higher than typical usage, so adaptive limits are currently applied.

Next review available in: 23 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a7cd4f99-ee27-4415-9fa0-44f3dc28bf08

📥 Commits

Reviewing files that changed from the base of the PR and between 03dcc7f and 9afa7c8.

📒 Files selected for processing (9)
  • internal/recommendations/reader.go
  • internal/sections/fetcher.go
  • internal/sections/recently_added_query_test.go
  • internal/sections/recipes/discovery.go
  • internal/sections/recipes/editorial.go
  • internal/sections/recipes/personalized.go
  • internal/sections/recipes/seasonal_test.go
  • internal/sections/recipes/types.go
  • web/src/components/RecipeGallery/RecipeParamFields.tsx
📝 Walkthrough

Walkthrough

This PR extends discovery filters with multi-library scoping and max-plays semantics, adds four new section types (genre roulette, returning shows, anniversaries, short watches) with corresponding recipes and fetchers, introduces taste-match/recommendation auto-pick fallbacks, adds seasonal theme keyword-fallback logic, and updates web recipe gallery components with new param fields and admin-only filtering.

Changes

Backend discovery scoping and new sections

Layer / File(s) Summary
Discovery filter contracts and library-scope query wiring
internal/catalog/discovery_repo.go, internal/catalog/discovery_repo_test.go
RatingFilter, UnplayedFilter, ForgottenFavoritesFilter gain LibraryIDs/MaxPlays; appendDiscoveryLibraryScope intersects scope with AllowedLibraryIDs; tests cover scope intersection, multi-library semi-joins, and max-plays threshold.
Section fetcher discovery-rail wiring
internal/sections/fetcher.go
fetchHiddenGems, fetchCriticallyAcclaimed, fetchForgottenFavorites pass library scope fields; fetchFormatShowcase supports configurable orderBy.
Taste-match and recommendation anchor auto-pick
internal/recommendations/reader.go, internal/sections/fetcher.go, internal/sections/recipes/personalized.go, internal/sections/seasonal_query_test.go
Empty genre triggers auto-pick across taste clusters and top-genre fallback; anchor() prefers SourceItemID over AnchorItemID.
Seasonal theme predicate and keyword fallback
internal/sections/recipes/seasonal.go, internal/sections/recipes/seasonal_test.go, internal/sections/fetcher.go, internal/sections/seasonal_query_test.go
Adds family_movie_night theme, ActiveSeasonalThemeWhere usable filter, and keyword-title fallback for themes without genre queries.
New section types and recipes
internal/sections/types.go, internal/sections/fetcher.go, internal/sections/recipes/editorial.go, internal/sections/recipes/mood.go, internal/sections/recipes/discovery.go, internal/sections/recipes/*_test.go
Adds genre roulette, returning shows, anniversaries, short watches sections/recipes; removes franchise support; adds format_showcase sort validation.

Estimated code review effort: 4 (Complex) | ~75 minutes

Web recipe gallery UI updates

Layer / File(s) Summary
Admin-only recipe filtering
web/src/components/RecipeGallery/RecipeGalleryModal.tsx, web/src/pages/ProfileCustomizeHome.tsx, web/src/pages/settings/HomeScreenSettings.tsx
RecipeGalleryModal gains hideAdminOnly prop to filter admin_only recipes; callers pass the new prop.
New param field UIs and curated list validation
web/src/components/RecipeGallery/RecipeParamFields.tsx, web/src/components/RecipeGallery/RecipeConfigDrawer.tsx
Adds NumberParamField and CuratedItemsParamField, updates taste_match copy/seasonal themes, and blocks submission when curated list is empty.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Fetcher
  participant Reader
  participant Repo
  Fetcher->>Reader: GetTasteMatchRow(genre="")
  Reader->>Reader: include all taste clusters
  Reader->>Repo: GetTopGenres(ctx, 1)
  Repo-->>Reader: top genre
  Reader-->>Fetcher: taste match row
Loading
sequenceDiagram
  participant Client
  participant FetchOne
  participant fetchSection
  participant GenreRouletteFetcher
  Client->>FetchOne: request SectionGenreRoulette
  FetchOne->>fetchSection: dispatch
  fetchSection->>GenreRouletteFetcher: fetchGenreRouletteWithTitle
  GenreRouletteFetcher-->>FetchOne: items + title
  FetchOne-->>Client: SectionWithItems
Loading

Possibly related PRs

  • Silo-Server/silo-server#88: Prior refactor to semi-join-based library scoping in the same discovery_repo.go helpers and related scope tests that this PR builds upon.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: fixing broken section templates and adding several new ones.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/interesting-solomon-47eafd

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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 03dcc7f3a0

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread internal/sections/fetcher.go Outdated
Comment on lines +3771 to +3773
SELECT 1 FROM media_files mf
WHERE mf.episode_id = ne.content_id
AND mf.missing_since IS NULL

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Scope returning-season files to the selected libraries

In library-scoped or restricted views where a series row is visible in the selected library but the newly arrived episode file is only in another folder, this inner EXISTS still passes because it ignores mf.media_folder_id. That makes Returning Shows appear based on out-of-scope files and can reveal a new season outside the viewer's library set; apply the selected/allowed/disabled library predicates to the episode file or episode_libraries before treating it as available.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 9afa7c8 — the inner media_files EXISTS now applies the effective folder scope (section scope ∩ viewer-allowed, minus disabled) to mf.media_folder_id, with an early empty return when the intersection is empty.

argIdx += 2
}

fromClause, libConditions, libArgs, newArgIdx := buildLibraryScope(libraryID, libraryIDs, nil, filter.DisabledLibraryIDs, argIdx)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Deduplicate multi-library direct SQL rails

When libraryIDs contains multiple folders, buildLibraryScope changes fromClause to a join against media_item_libraries; because this new SELECT does not group or distinct on mi.content_id, a title present in two selected libraries is returned twice and can consume multiple limit slots. The same direct-SQL pattern appears in the other new rails, so these queries should use a semi-join or DISTINCT before scanning.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 9afa7c8 by converting buildLibraryScope itself to EXISTS/NOT EXISTS semi-joins (the catalog package's canonical Pattern D shape) rather than patching each rail: this dedupes every non-GROUP BY rail (including pre-existing ones like format_showcase and new_to_library), makes the disabled-library check item-level, and adds the deny-only positive-membership guard. The one SQL-shape test pinning the old JOIN was updated.

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/recommendations/reader.go (1)

172-210: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Cluster fallback bails early instead of trying the next weaker cluster.

The new comment promises "every taste cluster qualifies (strongest first)" when genre is empty, but the existing loop body at Lines 206-208 returns nil, nil the moment filterRows empties out the first cluster it finds cached items for — it never tries the next cluster in matching, and never reaches the global top-genre fallback below.

Before this change, matching typically held 0-1 clusters (exact dominant-genre matches), so this quirk was rarely exercised. Now that genre="" pulls in all clusters sorted by weight, a top cluster whose cached items get entirely filtered out by filter (e.g. due to library-scope access restrictions) will short-circuit the whole function instead of falling through to the next cluster or the genre-sampler fallback.

🐛 Proposed fix: continue instead of early return
 		rows, err := r.filterRows(ctx, userID, profileID, []ForYouRow{clusterRow(cluster, items)}, filter)
 		if err != nil {
 			return nil, err
 		}
 		rows = trimRows(rows, limit)
 		if len(rows) == 0 {
-			return nil, nil
+			continue
 		}
 		return &rows[0], nil
 	}
🤖 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/recommendations/reader.go` around lines 172 - 210, The cluster
fallback in reader.go stops too early when the first cached cluster has no
usable rows after filtering. Update the loop in the recommendation path that
builds and iterates over matching clusters so it continues to the next cluster
instead of returning nil,nil when trimRows(filterRows(...)) is empty. Keep the
strongest-first ordering from matching/sort.SliceStable, and only return a
recommendation once a cluster yields rows; otherwise fall through so later
clusters and the existing top-genre fallback can still run.
🧹 Nitpick comments (6)
internal/sections/recipes/seasonal_test.go (1)

371-395: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a direct title-override test for the usable filter.

ActiveSeasonalThemeWhere is covered, but SeasonalTitleOverride(..., usable) is the public helper the fetcher calls to keep the displayed title aligned with the resolved theme. A small assertion where "christmas" is unusable and "saturday_morning" wins would lock that contract down.

🤖 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/recipes/seasonal_test.go` around lines 371 - 395, Add a
direct test for SeasonalTitleOverride with a usable filter, since this public
helper is what the fetcher uses to keep the title aligned with the resolved
theme. In the existing seasonal tests near
TestActiveSeasonalThemeWhereSkipsUnusable, add an assertion that when
"christmas" is rejected by the usable predicate, SeasonalTitleOverride falls
through to "saturday_morning" instead of returning the higher-priority unusable
theme. Use SeasonalTitleOverride and the same usable-filter pattern already
exercised by ActiveSeasonalThemeWhere so the contract is covered end to end.
internal/sections/fetcher.go (1)

3844-3849: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Include multi-library scope in the roulette rotation seed.

When libraryID == nil, every multi-library scoped row uses libKey = "all", so different scoped genre-roulette rows share the same rotation bucket. Include libraryIDs in the seed to keep rotation deterministic per scope.

Proposed fix
 	libKey := "all"
 	if libraryID != nil {
 		libKey = strconv.Itoa(*libraryID)
+	} else if len(libraryIDs) > 0 {
+		parts := make([]string, len(libraryIDs))
+		for i, id := range libraryIDs {
+			parts[i] = strconv.Itoa(id)
+		}
+		libKey = strings.Join(parts, ",")
 	}
🤖 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 3844 - 3849, The genre-roulette
rotation seed currently collapses all multi-library scoped rows into the same
"all" bucket when libraryID is nil, so different scopes share one rotation.
Update the rotation key construction around the RotationIndex call in the genre
roulette logic to incorporate libraryIDs (or another scope-unique identifier)
when libraryID is nil, while preserving the existing single-library behavior for
non-nil libraryID.
web/src/components/RecipeGallery/RecipeParamFields.tsx (2)

454-467: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Catalog search failures are silent.

results.error is never surfaced; on a failed request (results.isError), found falls back to [] and the UI shows "No matches." indistinguishable from a genuine empty result, which could mislead admins into thinking their search term has no matches when the request actually failed.

Also applies to: 504-508

🤖 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/RecipeGallery/RecipeParamFields.tsx` around lines 454 -
467, The catalog search in RecipeParamFields uses useQuery for the curated list,
but failed requests are being treated like empty results. Update the
search/results handling around results.isError, results.error, and found so a
fetch failure is surfaced to the UI instead of falling back to an empty array
and showing “No matches.”; keep the logic in RecipeParamFields and the
fetchCatalogPage/queryFn flow aligned so error state is distinguishable from a
genuine empty response.

436-440: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Hydrate curated-item titles on open web/src/components/RecipeGallery/RecipeParamFields.tsx:547-550 Existing params.item_ids never seed labels, so saved curated items render as raw IDs until they’re re-added. Populate labels for the initial IDs when the drawer mounts using the catalog item-detail fetcher.

🤖 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/RecipeGallery/RecipeParamFields.tsx` around lines 436 -
440, The curated-items field is not hydrating labels for preexisting
params.item_ids, so saved items show as raw IDs until reselected. Update
CuratedItemsParamField to seed the labels state on mount for any initial
item_ids by fetching their titles through the same catalog item-detail fetcher
used elsewhere. Keep the logic inside CuratedItemsParamField so the initial
render of existing curated items uses populated labels instead of falling back
to ids.
internal/sections/recipes/personalized.go (1)

114-134: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Consider bounding LookbackDays.

ReturningShowsParams.LookbackDays has no validation — negative or absurdly large values pass Validate() unchanged. If the downstream fetchReturningShows builds a SQL interval or date-window directly from this value (not shown in this batch), a negative lookback could silently produce an empty or malformed query.

♻️ Optional bounds check
 func (returningShowsRecipe) Validate(raw json.RawMessage) error {
 	if len(raw) == 0 {
 		return nil
 	}
 	var p ReturningShowsParams
-	return json.Unmarshal(raw, &p)
+	if err := json.Unmarshal(raw, &p); err != nil {
+		return err
+	}
+	if p.LookbackDays < 0 {
+		return errors.New("returning_shows: lookback_days must be non-negative")
+	}
+	return nil
 }

Worth confirming how fetchReturningShows in internal/sections/fetcher.go consumes this field.

🤖 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/recipes/personalized.go` around lines 114 - 134, Add
validation for ReturningShowsParams.LookbackDays in
returningShowsRecipe.Validate so negative or unreasonably large values are
rejected instead of passing through unchanged. Keep the existing json.Unmarshal
path, then enforce a sensible range on the LookbackDays field before returning,
and make sure any future use in fetchReturningShows is safe to consume.
internal/sections/recipes/editorial.go (1)

166-180: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider extracting a shared enum-validation helper.

The ""/daily/weekly/monthly and milestone_years >= 0 checks repeat the same shape seen in mood.go (short_watches) and discovery.go (format_showcase). A small validateEnum(field string, value string, allowed ...string) error helper would reduce duplication as more recipes are added.

♻️ Example helper
func validateEnum(field, value string, allowed ...string) error {
	for _, a := range allowed {
		if value == a {
			return nil
		}
	}
	return fmt.Errorf("%s: invalid value %q (want one of %v)", field, value, allowed)
}

Also applies to: 215-227

🤖 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/recipes/editorial.go` around lines 166 - 180, The
validation logic in genreRouletteRecipe.Validate duplicates the same enum-check
pattern used in other recipe validators, so extract a shared helper such as
validateEnum and reuse it here and in the matching checks from mood.go and
discovery.go. Update Validate to call the helper for rotation_cadence, keeping
the same field-specific error context and allowed values, so future recipe
validators can share the same pattern.
🤖 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/components/RecipeGallery/RecipeParamFields.tsx`:
- Around line 408-427: The numeric field handling in RecipeParamFields should
reject fractional input for integer-only params. Update the onChange logic in
the numeric input helper so it only stores values when Number.isFinite(parsed),
parsed > 0, and Number.isInteger(parsed) are all true, leaving invalid or
fractional entries as undefined. Use the existing paramKey-based setter in this
component to keep the fix localized to the fields for lookback_days,
max_minutes, and milestone_years.

---

Outside diff comments:
In `@internal/recommendations/reader.go`:
- Around line 172-210: The cluster fallback in reader.go stops too early when
the first cached cluster has no usable rows after filtering. Update the loop in
the recommendation path that builds and iterates over matching clusters so it
continues to the next cluster instead of returning nil,nil when
trimRows(filterRows(...)) is empty. Keep the strongest-first ordering from
matching/sort.SliceStable, and only return a recommendation once a cluster
yields rows; otherwise fall through so later clusters and the existing top-genre
fallback can still run.

---

Nitpick comments:
In `@internal/sections/fetcher.go`:
- Around line 3844-3849: The genre-roulette rotation seed currently collapses
all multi-library scoped rows into the same "all" bucket when libraryID is nil,
so different scopes share one rotation. Update the rotation key construction
around the RotationIndex call in the genre roulette logic to incorporate
libraryIDs (or another scope-unique identifier) when libraryID is nil, while
preserving the existing single-library behavior for non-nil libraryID.

In `@internal/sections/recipes/editorial.go`:
- Around line 166-180: The validation logic in genreRouletteRecipe.Validate
duplicates the same enum-check pattern used in other recipe validators, so
extract a shared helper such as validateEnum and reuse it here and in the
matching checks from mood.go and discovery.go. Update Validate to call the
helper for rotation_cadence, keeping the same field-specific error context and
allowed values, so future recipe validators can share the same pattern.

In `@internal/sections/recipes/personalized.go`:
- Around line 114-134: Add validation for ReturningShowsParams.LookbackDays in
returningShowsRecipe.Validate so negative or unreasonably large values are
rejected instead of passing through unchanged. Keep the existing json.Unmarshal
path, then enforce a sensible range on the LookbackDays field before returning,
and make sure any future use in fetchReturningShows is safe to consume.

In `@internal/sections/recipes/seasonal_test.go`:
- Around line 371-395: Add a direct test for SeasonalTitleOverride with a usable
filter, since this public helper is what the fetcher uses to keep the title
aligned with the resolved theme. In the existing seasonal tests near
TestActiveSeasonalThemeWhereSkipsUnusable, add an assertion that when
"christmas" is rejected by the usable predicate, SeasonalTitleOverride falls
through to "saturday_morning" instead of returning the higher-priority unusable
theme. Use SeasonalTitleOverride and the same usable-filter pattern already
exercised by ActiveSeasonalThemeWhere so the contract is covered end to end.

In `@web/src/components/RecipeGallery/RecipeParamFields.tsx`:
- Around line 454-467: The catalog search in RecipeParamFields uses useQuery for
the curated list, but failed requests are being treated like empty results.
Update the search/results handling around results.isError, results.error, and
found so a fetch failure is surfaced to the UI instead of falling back to an
empty array and showing “No matches.”; keep the logic in RecipeParamFields and
the fetchCatalogPage/queryFn flow aligned so error state is distinguishable from
a genuine empty response.
- Around line 436-440: The curated-items field is not hydrating labels for
preexisting params.item_ids, so saved items show as raw IDs until reselected.
Update CuratedItemsParamField to seed the labels state on mount for any initial
item_ids by fetching their titles through the same catalog item-detail fetcher
used elsewhere. Keep the logic inside CuratedItemsParamField so the initial
render of existing curated items uses populated labels instead of falling back
to ids.
🪄 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: 477283f0-6509-41f4-8e02-8153740f5612

📥 Commits

Reviewing files that changed from the base of the PR and between fd7df8b and 03dcc7f.

📒 Files selected for processing (20)
  • internal/catalog/discovery_repo.go
  • internal/catalog/discovery_repo_test.go
  • internal/recommendations/reader.go
  • internal/sections/fetcher.go
  • internal/sections/recipes/discovery.go
  • internal/sections/recipes/discovery_test.go
  • internal/sections/recipes/editorial.go
  • internal/sections/recipes/editorial_test.go
  • internal/sections/recipes/mood.go
  • internal/sections/recipes/personalized.go
  • internal/sections/recipes/presets_test.go
  • internal/sections/recipes/seasonal.go
  • internal/sections/recipes/seasonal_test.go
  • internal/sections/seasonal_query_test.go
  • internal/sections/types.go
  • web/src/components/RecipeGallery/RecipeConfigDrawer.tsx
  • web/src/components/RecipeGallery/RecipeGalleryModal.tsx
  • web/src/components/RecipeGallery/RecipeParamFields.tsx
  • web/src/pages/ProfileCustomizeHome.tsx
  • web/src/pages/settings/HomeScreenSettings.tsx

Codex review:
- returning_shows: the new-season file check now applies the effective
  library scope (section scope ∩ viewer-allowed, minus disabled) to
  media_files.media_folder_id, so an episode file that only exists in an
  out-of-scope folder can no longer surface the series
- buildLibraryScope: replaced the media_item_libraries row join with
  EXISTS / NOT EXISTS semi-joins. An item in several in-scope libraries
  now yields exactly one row in the non-GROUP BY rails (short_watches,
  anniversaries, seasonal keyword, format_showcase, new_to_library, ...),
  and the disabled-library check is item-level, closing the join-row leak
  where membership in an allowed library masked membership in a disabled
  one. Deny-only mode keeps the positive-membership guard, mirroring
  catalog's appendDiscoveryLibraryScope.

CodeRabbit review:
- recommendations reader: a taste cluster whose cached items are entirely
  filtered out now falls through to the next cluster / global fallback
  instead of returning an empty row
- genre_roulette: multi-library scopes get distinct rotation seeds
- returning_shows: reject negative lookback_days at validation
- shared oneOf() enum validator replaces per-recipe switch duplication
- SeasonalTitleOverride usable-filter contract covered by a direct test
- web NumberParamField: integer-only guard + step=1 (backend fields are
  Go ints; fractional values failed unmarshalling at save)
- curated list picker: search failures show an error instead of a
  misleading "No matches."; pre-existing item_ids hydrate display titles
  via the watch-detail endpoint instead of rendering raw ids

Co-Authored-By: Claude Fable 5 <[email protected]>
@Quick104

Quick104 commented Jul 7, 2026

Copy link
Copy Markdown
Contributor Author

Addressed all review findings in 9afa7c8:

Codex

  • Returning-shows file scope: the new-season file check now applies the effective library scope (section scope ∩ viewer-allowed, minus disabled) to media_files.media_folder_id.
  • Multi-library duplicate rows: fixed at the source — buildLibraryScope now uses EXISTS/NOT EXISTS semi-joins instead of a row join, so every rail (new and pre-existing) returns one row per item, and the disabled-library check became item-level, closing the join-row leak. Deny-only mode keeps a positive-membership guard, mirroring appendDiscoveryLibraryScope in catalog.

CodeRabbit

  • Reader cluster fallback: continue to the next-strongest cluster instead of returning empty when a cluster's cached items are fully filtered out — applied as proposed.
  • Genre-roulette rotation seed now includes multi-library scope IDs.
  • returning_shows rejects negative lookback_days.
  • Extracted a shared oneOf() enum validator (used by editorial cadence, genre_roulette, format_showcase).
  • Added the direct SeasonalTitleOverride usable-filter test.
  • Web: NumberParamField is integer-only (Number.isInteger + step=1); curated-list search failures now show an error instead of "No matches."; pre-existing item_ids hydrate display titles via the watch-detail endpoint.

Verified: full Go build + package tests green, both reshaped SQL queries EXPLAIN cleanly against the dev database, web tsc/eslint/prettier/vitest green.

@Quick104
Quick104 merged commit e81cdbc into main Jul 7, 2026
9 checks passed
@Quick104
Quick104 deleted the claude/interesting-solomon-47eafd branch July 7, 2026 14:47
Quick104 added a commit that referenced this pull request Jul 10, 2026
#332)

* feat(sections): fix broken home section templates and add six new ones

Fixes templates that silently produced nothing:
- award_winners: hide from gallery (resolver is a stub until award data
  exists); saved sections keep resolving
- seasonal_themed: christmas/st_patricks/thanksgiving get an interim
  title-keyword resolver, and multi-theme selection skips themes without
  an executable query so a data-less theme can no longer black out the
  section during its own window (previously killed the section all of
  December)
- taste_match: empty genre now auto-picks the profile's strongest taste
  cluster (fallback: server top genre); the default preset was permanently
  empty
- because_you_watched: honor the recipe's anchor_item_id key (fetcher only
  read legacy source_item_id, so pinning an anchor did nothing)
- editorial_spotlight: reject subject_type=franchise (validated but could
  never resolve); fix drawer misrepresenting pinned presets as auto-rotate
- admin_curated_list: add a catalog-search item picker so Editor's Picks
  is actually addable; block saving an empty list; hide admin_only recipes
  from profile-facing galleries
- discovery fetchers (hidden_gems, forgotten_favorites,
  critically_acclaimed): honor single/multi library scope, intersected
  with viewer access; implement hidden_gems max_play_count

New templates: returning_shows (new season of shows you've watched),
genre_roulette (rotating top-genre spotlight with title override),
anniversaries (milestone release anniversaries this month), short_watches
(well-rated movies under a runtime cap), family_movie_night seasonal
theme (Fri/Sat evenings), and a "New in 4K" format_showcase preset via a
new sort=recent param.

Adds a blanket test asserting every visible gallery preset's defaults
pass its own recipe validation — the gap that let taste_match and
Editor's Picks ship broken. New SQL shapes validated with EXPLAIN against
the dev database.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(sections): address PR #332 review findings

Codex review:
- returning_shows: the new-season file check now applies the effective
  library scope (section scope ∩ viewer-allowed, minus disabled) to
  media_files.media_folder_id, so an episode file that only exists in an
  out-of-scope folder can no longer surface the series
- buildLibraryScope: replaced the media_item_libraries row join with
  EXISTS / NOT EXISTS semi-joins. An item in several in-scope libraries
  now yields exactly one row in the non-GROUP BY rails (short_watches,
  anniversaries, seasonal keyword, format_showcase, new_to_library, ...),
  and the disabled-library check is item-level, closing the join-row leak
  where membership in an allowed library masked membership in a disabled
  one. Deny-only mode keeps the positive-membership guard, mirroring
  catalog's appendDiscoveryLibraryScope.

CodeRabbit review:
- recommendations reader: a taste cluster whose cached items are entirely
  filtered out now falls through to the next cluster / global fallback
  instead of returning an empty row
- genre_roulette: multi-library scopes get distinct rotation seeds
- returning_shows: reject negative lookback_days at validation
- shared oneOf() enum validator replaces per-recipe switch duplication
- SeasonalTitleOverride usable-filter contract covered by a direct test
- web NumberParamField: integer-only guard + step=1 (backend fields are
  Go ints; fractional values failed unmarshalling at save)
- curated list picker: search failures show an error instead of a
  misleading "No matches."; pre-existing item_ids hydrate display titles
  via the watch-detail endpoint instead of rendering raw ids

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: Claude Fable 5 <[email protected]>
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.

1 participant