Skip to content

feat(manga): manga library type — series grouping, reading loop, AniList/MangaDex metadata + status badge - #138

Merged
Quick104 merged 66 commits into
mainfrom
codex/rebase-pr-137
Jun 17, 2026
Merged

Quick104 merged 66 commits into
mainfrom
codex/rebase-pr-137

Conversation

@Quick104

@Quick104 Quick104 commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Prerequisite

Requires Silo-Server/silo-plugin-sdk#4 merged and tagged v0.7.0 before this can build.
The final commit pins github.com/Silo-Server/silo-plugin-sdk v0.7.0, which adds MetadataItem.status. go.sum already carries the canonical v0.7.0 content hashes, so CI will resolve cleanly the moment the tag exists — no further go.sum edits needed.

Problem

Silo had no first-class manga library type. Manga sit awkwardly between ebooks (per-file .cbz/.epub) and series (one enrichment target per title with many child items): scanning a manga folder as loose ebooks produced one card per volume with no series-level cover, synopsis, or read-through, and library-listing sections (recently-added/released/random) were polluted by individual chapters.

Approach

A new type='manga' library forked from the ebook pipeline:

  • Scanner groups .cbz/.epub under a series folder into one type='manga' series plus linked type='ebook' chapter items (manga_chapters join table). One card, one enrichment target.
  • Catalog/browse/detail surface per-series volume + chapter counts, per-chapter read state, and a continue/start-reading loop; library-listing sections exclude manga chapters so only the series card shows.
  • Metadata is provided by the new external silo-plugin-manga-metadata plugin (metadata_provider.v1, capability manga-metadata), enriching series with cover, synopsis, genres, author/artist, year, banner-as-backdrop, and publication status (Ongoing/Completed/Hiatus/Cancelled/Upcoming). Status flows through MetadataItem.status → ShowStatus → a color-coded chip on the detail page and browse cards.
  • Status badge required a new SDK field (MetadataItem.status, field 31). The host consumes it at internal/metadata/plugin_provider.go; the final commit here de-vendors the temporary SDK copy and depends on the published v0.7.0.

Deferred follow-ups

  1. Per-source N+1 in the ebook/audiobook enrichers — manga enrichment batches provider-id lookups, but the sibling ebook/audiobook enrichers still issue one lookup per item. Generalizing the batched path is left as a separate change to keep this PR scoped.
  2. Secondary-field backfill is admin-reset-only by design — backdrop/status backfill for already-matched series runs on an explicit admin "refresh metadata", not automatically, to avoid a full re-enrichment storm. Documented as intentional.
  3. Catalog registration — the plugin still needs an entry in Silo-Server/silo-plugins for one-click install (tracked separately).

Testing

  • go build ./... + go vet ./internal/metadata/... green in a golang:1.26 + libvips-dev container against the published-style v0.7.0 dependency.
  • Frontend: ESLint 0 errors, Prettier clean, 1048/1048 vitest tests pass.
  • make verify-local-paths clean (no absolute paths / worktree IDs in committed docs).
  • Exercised live on the test deployment (manga library scan → AniList/MangaDex enrichment → status chip render).

AI-use disclosure

Implemented with assistance from Claude Code (Claude). All code was reviewed, built, and tested locally by the author before submission.

Summary by CodeRabbit

  • New Features
    • Added first-class manga support across catalog browsing/search/filtering, manga item details (chapters with read/progress), and manga series “View Details” local file listings.
    • Added manga metadata synchronization and manga library scanning to ingest series and chapters.
  • Improvements
    • Enhanced UI with manga volume/chapter count chips and provider show-status, plus series-aware continue-reading navigation.
  • Bug Fixes
    • Prevented manga chapter (“ebook” parts) items from appearing as standalone cards in browse/search/discovery/favorites.

@coderabbitai

coderabbitai Bot commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c3a30e95-1236-49e1-87f0-c9e8aa4a1301

📥 Commits

Reviewing files that changed from the base of the PR and between addd4050bcd12ead4427b36f5e2f180a1f3c0b54 and baf2f41.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (56)
  • .gitignore
  • cmd/silo/main.go
  • go.mod
  • internal/api/handlers/catalog_resources.go
  • internal/api/handlers/ebook_reader.go
  • internal/api/handlers/items.go
  • internal/api/handlers/libraries.go
  • internal/api/handlers/libraries_metadata_levels_test.go
  • internal/api/handlers/sections.go
  • internal/api/router.go
  • internal/catalog/browse.go
  • internal/catalog/browse_manga_counts_test.go
  • internal/catalog/catalog_parser_test.go
  • internal/catalog/catalog_resolver.go
  • internal/catalog/catalog_resolver_test.go
  • internal/catalog/detail.go
  • internal/catalog/detail_manga_test.go
  • internal/catalog/discovery_repo.go
  • internal/catalog/favorites_browse.go
  • internal/catalog/item_repo.go
  • internal/catalog/item_repo_test.go
  • internal/catalog/library_repo.go
  • internal/catalog/manga_chapter_exclusion_test.go
  • internal/catalog/manga_files.go
  • internal/catalog/media_scope_test.go
  • internal/catalog/provider_id_repo.go
  • internal/catalog/query_definition.go
  • internal/catalog/query_definition_test.go
  • internal/catalog/query_executor.go
  • internal/ebooks/enrichment.go
  • internal/manga/enrichment.go
  • internal/manga/enrichment_test.go
  • internal/metadata/merge.go
  • internal/metadata/plugin_provider.go
  • internal/metadata/types.go
  • internal/models/media.go
  • internal/scanner/manga_chapters_repo.go
  • internal/scanner/manga_chapters_repo_test.go
  • internal/scanner/manga_parse.go
  • internal/scanner/manga_parse_test.go
  • internal/scanner/manga_scan.go
  • internal/scanner/probe_repair.go
  • internal/scanner/probe_repair_ebook_test.go
  • internal/scanner/scanner.go
  • internal/scanner/scanner_test.go
  • internal/sections/defaults.go
  • internal/sections/defaults_test.go
  • internal/sections/fetcher.go
  • internal/sections/fetcher_continue_watching_test.go
  • internal/sections/generated.go
  • internal/sections/manga_chapter_exclusion_test.go
  • internal/sections/manga_latest_volume_poster_test.go
  • internal/taskmanager/tasks/sync_manga_metadata.go
  • migrations/sql/20260610193238_manga_chapters.sql
  • migrations/sql/20260611003847_manga_enrichment_state.sql
  • migrations/sql/20260616140000_manga_chapters_series_volume_index.sql

📝 Walkthrough

Walkthrough

This PR adds manga support across backend storage, scanner and catalog flows, section rendering, enrichment, task wiring, and web UI contracts and navigation.

Changes

Manga library implementation

Layer / File(s) Summary
Bootstrap, schema, and metadata contracts
cmd/silo/main.go, go.mod, migrations/sql/*manga*, internal/models/media.go, internal/metadata/*, .gitignore
Adds manga startup wiring, schema migrations, media count fields, ShowStatus metadata plumbing, a plugin SDK upgrade, and local compose ignore rules.
Scanner routing, parsing, and chapter persistence
internal/scanner/manga_parse.go, internal/scanner/manga_chapters_repo.go, internal/scanner/manga_scan.go, internal/scanner/scanner.go, internal/scanner/probe_repair.go, internal/scanner/*test.go
Parses manga paths and indices, persists chapter links, scans manga folders, routes manga libraries through scanner entrypoints, and skips ebook probe repair for manga chapter files.
Catalog contracts, detail payloads, and file-details API
internal/catalog/detail.go, internal/catalog/manga_files.go, internal/api/handlers/catalog_resources.go, internal/api/router.go, internal/api/handlers/items.go, internal/api/handlers/sections.go, internal/api/handlers/libraries.go, internal/api/handlers/libraries_metadata_levels_test.go, internal/catalog/*detail*_test.go, internal/catalog/query_definition.go, internal/catalog/catalog_resolver.go, internal/catalog/catalog_resolver_test.go, internal/catalog/catalog_parser_test.go, internal/catalog/media_scope_test.go
Extends manga validation and response types, adds manga detail/file payloads and files API wiring, and links manga chapters back to their series in section responses.
Catalog browse/search/query engine updates
internal/catalog/browse.go, internal/catalog/item_repo.go, internal/catalog/query_executor.go, internal/catalog/discovery_repo.go, internal/catalog/favorites_browse.go, internal/catalog/library_repo.go, internal/ebooks/enrichment.go, internal/catalog/provider_id_repo.go, internal/catalog/*test.go
Adds manga chapter exclusion rules, manga count projections, browse/search/listing scan changes, provider-ID preservation, and file-based reconciliation exclusions.
Sections defaults, fetcher, and manga enrichment
internal/sections/defaults.go, internal/sections/generated.go, internal/sections/fetcher.go, internal/sections/*test.go, internal/manga/enrichment.go, internal/manga/enrichment_test.go, cmd/silo/main.go, internal/taskmanager/tasks/sync_manga_metadata.go
Scopes section defaults to manga, adds manga-aware fetcher behavior and continue-watching linkage, implements manga metadata enrichment, wires startup/task scheduling, and adds supporting tests.
Frontend navigation, detail pages, and display components
web/src/api/types.ts, web/src/lib/mangaChapters.ts, web/src/lib/mangaChapters.test.ts, web/src/lib/mediaNavigation.ts, web/src/lib/querySortOptions.ts, web/src/pages/EbookReader.tsx, web/src/pages/EbookReader.test.tsx, web/src/pages/ItemDetail/MangaContent.tsx, web/src/pages/ItemDetail/MangaContent.test.tsx, web/src/pages/ItemDetail/*, web/src/components/*, web/src/pages/LibraryBrowse.tsx, web/src/pages/libraryPageSearchParams.ts, web/src/pages/libraryPageSearchParams.test.ts, web/src/app.css
Adds manga API types, chapter list utilities, reader back/next navigation, manga detail pages, manga-aware cards/menus/search/filtering, and library/page scope handling.

🎯 5 (Critical) | ⏱️ ~90+ minutes

Possibly related PRs

  • Silo-Server/silo-server#11: The manga files endpoint redacts path fields using the same file-path visibility logic as the related access-control changes.
  • Silo-Server/silo-server#18: Both PRs update internal/api/handlers/sections.go to enrich section items with additional metadata.
  • Silo-Server/silo-server#49: Both PRs modify internal/catalog/browse.go query planning and execution paths.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/rebase-pr-137

@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: 10

Caution

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

⚠️ Outside diff range comments (5)
internal/catalog/library_repo.go (1)

293-312: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Don't blanket-exempt every manga series from folder reconciliation.

This DELETE is folder-scoped, but the new guard skips all type='manga' memberships in that folder. If a series loses all chapters only in this library, the stale (content_id, media_folder_id) row will now survive here indefinitely and the series can remain visible in the wrong library. The exemption needs to key off "series still has at least one non-missing chapter in this folder", not just mi.type = 'manga'.

Possible predicate shape
-		  AND NOT EXISTS (
-			SELECT 1
-			FROM media_items mi
-			WHERE mi.content_id = mil.content_id
-			  AND mi.type = 'manga'
-		  )
+		  AND NOT EXISTS (
+			SELECT 1
+			FROM manga_chapters mc
+			JOIN media_files mf
+			  ON mf.content_id = mc.chapter_content_id
+			WHERE mc.series_content_id = mil.content_id
+			  AND mf.media_folder_id = mil.media_folder_id
+			  AND mf.missing_since IS NULL
+		  )
🤖 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/library_repo.go` around lines 293 - 312, The current DELETE
uses NOT EXISTS against media_items (mi.type='manga') which exempts any manga
series globally; update the second predicate so it only exempts when that manga
series still has at least one non-missing chapter in the same folder. Replace
the NOT EXISTS(SELECT 1 FROM media_items mi WHERE mi.content_id = mil.content_id
AND mi.type = 'manga') with a NOT EXISTS that joins media_items (mi) to
media_files (mf2) and checks mi.content_id = mil.content_id AND mi.type =
'manga' AND mf2.media_folder_id = mil.media_folder_id AND mf2.missing_since IS
NULL so only per-folder non-missing manga chapters prevent deletion (referencing
mil, mi, mf/mf2 and the tx.Query SQL block in library_repo.go).
web/src/pages/libraryPageSearchParams.ts (1)

101-106: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Mixed-library URL parsing/fallback still excludes manga.

Line 311–317 ignores type=manga when libraryType === "mixed", and Line 101–106 omits "manga" in mediaScope fallback. This causes mixed-library deep links/state restore to lose manga scope and normalize sorts under "all".

Suggested fix
-    (mediaScopeParam === "movie" ||
+    (mediaScopeParam === "movie" ||
       mediaScopeParam === "series" ||
       mediaScopeParam === "episode" ||
       mediaScopeParam === "audiobook" ||
-      mediaScopeParam === "ebook")
+      mediaScopeParam === "ebook" ||
+      mediaScopeParam === "manga")
       ? mediaScopeParam

...

   if (
     mediaScope === "movie" ||
     mediaScope === "series" ||
     mediaScope === "episode" ||
     mediaScope === "audiobook" ||
-    mediaScope === "ebook"
+    mediaScope === "ebook" ||
+    mediaScope === "manga"
   ) {
     return mediaScope;
   }

Also applies to: 311-317

🤖 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/libraryPageSearchParams.ts` around lines 101 - 106, The media
scope handling omits "manga" for mixed libraries: update the conditional checks
that validate/fallback mediaScope and the branch that handles libraryType ===
"mixed" to include "manga" alongside "movie", "series", "episode", "audiobook",
and "ebook" so type=manga is preserved for mixed-library deep links and state
restoration; specifically modify the mediaScope validation (the expression using
mediaScope === "...") and the mixed-library branch where libraryType === "mixed"
to accept "manga" as a valid scope.
web/src/app.css (1)

632-636: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add .glass-chip to the high-contrast glass override selector set.

data-high-contrast="true" currently upgrades .glass/.glass-subtle only. New .glass-chip keeps default translucent treatment, which can reduce chip legibility in high-contrast mode.

Proposed fix
   html[data-high-contrast="true"] .surface-panel-subtle,
   html[data-high-contrast="true"] .surface-panel,
   html[data-high-contrast="true"] .glass,
-  html[data-high-contrast="true"] .glass-subtle {
+  html[data-high-contrast="true"] .glass-subtle,
+  html[data-high-contrast="true"] .glass-chip {
     border-color: color-mix(in srgb, var(--border) 88%, white 12%);
     box-shadow:
       inset 0 1px 0 rgb(255 255 255 / 0.08),
       0 12px 36px -24px rgb(0 0 0 / 0.75);
   }

Also applies to: 939-947

🤖 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/app.css` around lines 632 - 636, The high-contrast selector block
that currently targets html[data-high-contrast="true"] .surface-panel-subtle,
.surface-panel, .glass, .glass-subtle should also include .glass-chip so chips
get the same border-color override in high-contrast mode; update the selector
set (and the duplicate block later in the file that mirrors lines 939-947) to
add .glass-chip alongside .glass and .glass-subtle and keep the same color-mix
rule to ensure consistent legibility for chip components.
web/src/pages/EbookReader.tsx (2)

295-306: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Use robust query composition for chapter navigation and preserve backTo on file switches.

nextChapterHref can become malformed (/reader/ebook/<id>&backTo=...) when libraryId is absent, and handleFileChange currently drops backTo, which breaks the intended series-return loop.

Proposed fix
@@
   const handleFileChange = useCallback(
     (fileID: string) => {
       if (!contentId) return;
       const nextParams = new URLSearchParams();
       nextParams.set("file_id", fileID);
       if (libraryIdParam) {
         nextParams.set("libraryId", libraryIdParam);
       }
+      if (backToParam) {
+        nextParams.set("backTo", backToParam);
+      }
       navigate(`/reader/ebook/${encodeURIComponent(contentId)}?${nextParams.toString()}`, {
         replace: true,
       });
     },
-    [contentId, libraryIdParam, navigate],
+    [backToParam, contentId, libraryIdParam, navigate],
   );
@@
   const nextChapterHref =
     nextChapter && mangaSeriesHref
-      ? `${buildMediaPlayHref({
-          contentId: nextChapter.chapter.content_id,
-          type: "ebook",
-          libraryId: Number.isFinite(libraryIdNumber) ? libraryIdNumber : undefined,
-        })}&backTo=${encodeURIComponent(mangaSeriesHref)}`
+      ? (() => {
+          const base = buildMediaPlayHref({
+            contentId: nextChapter.chapter.content_id,
+            type: "ebook",
+            libraryId: Number.isFinite(libraryIdNumber) ? libraryIdNumber : undefined,
+          });
+          const separator = base.includes("?") ? "&" : "?";
+          return `${base}${separator}backTo=${encodeURIComponent(mangaSeriesHref)}`;
+        })()
       : null;

Also applies to: 574-581

🤖 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/EbookReader.tsx` around lines 295 - 306, The chapter navigation
builds query strings incorrectly and handleFileChange drops the backTo param;
update nextChapterHref construction and the file-change handler
(handleFileChange) to use URLSearchParams for all query params (including
optional libraryId and backTo) so the final URL is always
/reader/ebook/<id>?<querystring> (not concatenated with &), and ensure you copy
any existing backTo value into the new params when switching files; locate
nextChapterHref and handleFileChange in EbookReader.tsx and replace manual
string concat with URLSearchParams that conditionally sets "file_id",
"libraryId", and "backTo" before calling navigate (use
encodeURIComponent(contentId) for the path and nextParams.toString() for the
query).

753-783: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Comic mode still allows persisted reading-ruler UI to render.

You hide ruler controls for comics, but the overlay and ruler-position range are still rendered when readingRuler is already true in saved settings.

Proposed fix
-            {readerSettings.readingRuler && (
+            {!isComicFormat && readerSettings.readingRuler && (
@@
-                    {readerSettings.readingRuler && (
+                    {!isComicFormat && readerSettings.readingRuler && (
                       <ReaderRange
                         label="Ruler position"
                         value={readerSettings.readingRulerTop}

Also applies to: 1204-1214

🤖 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/EbookReader.tsx` around lines 753 - 783, The overlay and ruler
UI are rendered whenever readerSettings.readingRuler is true even in comic mode;
update the conditional that renders the ruler (the block using
readerSettings.readingRuler, effectiveRulerTop, and rulerBandHeight) to also
check the comic-mode flag so the ruler and its handlers
(handleRulerPointerDown/Move/Up/Cancel and handleRulerKeyDown) are not rendered
in comics. Specifically, wrap the existing JSX with a combined condition (e.g.
readerSettings.readingRuler && !isComicMode or readerSettings.readingRuler &&
readerSettings.readingMode !== 'comic' depending on your codebase flag) so the
overlay, button and calls to rulerBandHeight/effectiveRulerTop are skipped when
comic mode is active.
🧹 Nitpick comments (3)
internal/api/handlers/sections.go (1)

1233-1246: ⚡ Quick win

Short-circuit empty ID batches before metadata fetch.

FetchMangaChapterSeriesMeta is called even when no ebook IDs were collected. Add an early return for
len(ids) == 0 to avoid unnecessary fetch work on non-ebook section renders.

♻️ Proposed patch
 func (h *SectionHandler) listSectionMangaChapterItemMeta(ctx context.Context, items []*models.MediaItem) map[string]sections.SectionItemMeta {
 	if h == nil || h.fetcher == nil {
 		return map[string]sections.SectionItemMeta{}
 	}
 	ids := make([]string, 0)
 	seen := make(map[string]struct{})
 	for _, item := range items {
 		if item == nil || item.Type != "ebook" || strings.TrimSpace(item.ContentID) == "" {
 			continue
 		}
 		if _, ok := seen[item.ContentID]; ok {
 			continue
 		}
 		seen[item.ContentID] = struct{}{}
 		ids = append(ids, item.ContentID)
 	}
+	if len(ids) == 0 {
+		return map[string]sections.SectionItemMeta{}
+	}
 	meta, err := h.fetcher.FetchMangaChapterSeriesMeta(ctx, ids)
 	if err != nil {
 		slog.Warn("loading section manga chapter metadata", "error", err)
 		return map[string]sections.SectionItemMeta{}
 	}
 	return meta
 }
🤖 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/sections.go` around lines 1233 - 1246, The loop
building ids can produce an empty slice and you must short-circuit before
calling h.fetcher.FetchMangaChapterSeriesMeta; after building ids (the ids
variable collected from items) add a check if len(ids) == 0 and return early
(skip the FetchMangaChapterSeriesMeta call) so the handler does not perform
unnecessary work — modify the handler flow around the
FetchMangaChapterSeriesMeta call in sections.go to return the appropriate empty
result/response when ids is empty instead of invoking
h.fetcher.FetchMangaChapterSeriesMeta.
internal/sections/manga_chapter_exclusion_test.go (1)

20-24: ⚡ Quick win

Assert query-builder errors before SQL fragment checks.

These tests ignore returned errors, which can hide root cause behind “missing fragment” failures. Fail fast on err first.

Proposed pattern
-	generic, _ := buildRecentlyAddedQuery(ResolvedSection{
+	generic, err := buildRecentlyAddedQuery(ResolvedSection{
 		ItemLimit: 12,
 		Config:    json.RawMessage(`{"filter_library_ids":[1,2],"filter_type":"movie"}`),
 	}, nil, nil, catalog.AccessFilter{})
+	if err != nil {
+		t.Fatalf("buildRecentlyAddedQuery(generic) error: %v", err)
+	}
 	if !strings.Contains(generic, mangaChapterExclusionSQL) {
 		t.Fatalf("recently-added generic query missing manga-chapter exclusion:\n%s", generic)
 	}

Also applies to: 29-33, 41-45, 53-57

🤖 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/manga_chapter_exclusion_test.go` around lines 20 - 24, The
tests call buildRecentlyAddedQuery but ignore the returned error (e.g., generic,
_ := buildRecentlyAddedQuery(...)) which can mask root causes; change these to
capture the error (e.g., generic, err := buildRecentlyAddedQuery(...)) and
assert/require that err is nil (fail fast) before asserting that the SQL string
contains mangaChapterExclusionSQL; apply the same fix to the other occurrences
noted (the similar calls at the other ranges) so each test checks the error from
buildRecentlyAddedQuery prior to performing strings.Contains checks.
internal/sections/defaults_test.go (1)

594-607: ⚡ Quick win

Strengthen the non-manga generated-config invariant.

This test currently only rejects "manga". If the intent is “non-manga stays unscoped,” assert empty media_scope explicitly to catch broader regressions.

Proposed test tightening
-		if def.MediaScope == "manga" {
-			t.Fatalf("section %s unexpectedly carries manga media_scope", sec.SectionType)
-		}
+		if def.MediaScope != "" {
+			t.Fatalf("section %s media_scope = %q, want empty", sec.SectionType, def.MediaScope)
+		}
🤖 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/defaults_test.go` around lines 594 - 607,
TestGeneratedHomeLibraryRecentDefaultsNonMangaNoScope currently only rejects
"manga" but should assert that non-manga sections are unscoped; update the test
examining generatedHomeLibraryRecentDefaults(7, "Movies", "movies") to, after
ParseQueryDefinition(sec.Config), assert that def.MediaScope == "" (empty
string) rather than just checking def.MediaScope != "manga" so the test fails if
any media_scope is set.
🤖 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/browse.go`:
- Around line 347-349: The manga chapter exclusion (mangaChapterExclusionWhere)
is only applied in buildBrowsePlan, causing chapter rows to be hidden from
browse grids but still appear in filters/typeaheads; update the shared filter
builder by adding the same exclusion into filterWhereClauseForSource so
ListGenres, ListContentRatings, ListOriginalLanguages and typeahead queries use
the same predicate; locate filterWhereClauseForSource and append the
mangaChapterExclusionWhere("mi") condition (or otherwise incorporate its logic)
into the conditions it returns so filters and visible browse results remain
aligned.
- Around line 1138-1140: The current mangaCountColumns function builds two
subqueries but manga_chapter_count excludes chapters with a non-empty mc.volume,
causing volume-organized series to report zero; either change the first subquery
in mangaCountColumns to count all rows for mc.series_content_id (remove the
mc.volume IS NULL OR mc.volume = '' filter) so manga_chapter_count reflects
total chapters, or rename the returned field to something like
manga_loose_chapter_count to accurately reflect that it only counts chapters
outside volumes; update the SQL string built in mangaCountColumns and any
callers/consumers expecting the field name accordingly.

In `@internal/catalog/detail.go`:
- Around line 1211-1232: The loop over rows in fetchMangaChapters does not check
rows.Err() after iteration, so iteration errors can be swallowed; after the for
rows.Next() loop (and before returning chapters) call rows.Err() and handle any
non-nil error consistently with this package's error handling (e.g., return the
error or log and wrap it) instead of returning a potentially truncated chapters
slice; locate the rows variable and the fetchMangaChapters function (and adjust
any callers/signature if needed) and ensure scan errors are also propagated
rather than simply returning chapters.

In `@internal/manga/enrichment.go`:
- Around line 602-605: The warning calls that log the provider URL (the
slog.Warn with message "manga enrichment: image cache failed, keeping provider
URL") must not emit full remote URLs; parse the url string (using net/url.Parse)
and redact query and fragment before logging (e.g., reconstruct safeURL from
u.Scheme + "://" + u.Host + u.Path or log u.Host and u.Path separately), or
replace the URL with a hashed/shortened identifier; update both occurrences of
that slog.Warn call to log the sanitized/summarized URL (or host+path) and keep
the existing "content_id" and "error" fields.
- Around line 95-102: The secondary-only enrichment path is overwriting an
existing show_status; when populating fields from the provider you must only set
upd.ShowStatus if the existing item has an empty ShowStatus or the claim is not
a “secondary-only” claim. Update the assignment sites that write upd.ShowStatus
(the code paths that use the HasPoster / HasBackdrop flags) to guard the write:
check the current item's ShowStatus (or that neither HasPoster nor HasBackdrop
is true) before assigning provider.Status to upd.ShowStatus so secondary-only
sweeps (when HasBackdrop/HasPoster is set) only fill missing secondary fields
and never overwrite a present show_status.

In `@internal/sections/fetcher.go`:
- Around line 400-407: collectContinueProgressItems currently stops when it has
gathered "limit" chapter cards before you collapse same-series chapters
(applyMangaChapterSeriesMeta + collapseContinueWatchingSeriesCandidates), which
can leave the final result under-filled; change the logic so you either
over-fetch (fetch more than "limit", e.g., multiply limit by a small factor) or
continue paginating until you have "limit" unique series/cards after applying
applyMangaChapterSeriesMeta and collapseContinueWatchingSeriesCandidates to
orderedItems/itemMeta; specifically, adjust the loop in
collectContinueProgressItems to evaluate
collapseContinueWatchingSeriesCandidates(orderedItems, itemMeta) (or compute
unique series count from itemMeta) and only stop when the collapsed count >=
limit (or you hit a hard max), ensuring orderedItems is collapsed with
applyMangaChapterSeriesMeta before counting.

In `@web/src/components/catalog/CatalogFilterBar.tsx`:
- Around line 69-74: The code coerces "manga" to "ebook" when computing the
relevance scope (see the nextRelevanceScope assignment using
QuerySortRelevanceScope); change the mapping so "manga" remains "manga" instead
of being converted to "ebook". Update the same logic at the other occurrence
(the similar ternary around lines 119-123) so both places return "manga" for v
=== "manga" and otherwise cast v as QuerySortRelevanceScope.

In `@web/src/components/ContinueWatchingCard.tsx`:
- Around line 114-116: Loosen manga-chapter detection by changing isMangaChapter
to only require seriesId (i.e. card.type === "ebook" && !!card.seriesId) and
update heading logic so when headingIsSeries is true but card.seriesTitle is
missing we still show card.title; modify the declarations for isMangaChapter,
headingIsSeries and heading in ContinueWatchingCard.tsx so routing uses the
series-first path when seriesId exists while the displayed heading falls back to
card.title if seriesTitle is undefined.

In `@web/src/pages/ItemDetail/MangaContent.tsx`:
- Around line 262-265: The chapter count currently computed in looseChapterCount
(useMemo over entries) only tallies top-level items with kind === "chapter" and
thus misses chapters nested under container kinds like "section" or "volume";
change the logic to traverse/flatten entries recursively (or implement a helper
like countChapters(entries) or flattenEntries(entries)) and count all nodes
where kind === "chapter", then replace the current useMemo and the other similar
counts (the other chapter-count usage at the later count in the file) to use
this recursive/flattened count so sectioned/volume-grouped series reflect the
true chapter total.
- Around line 70-81: The bug is that chapterReaderHref unconditionally
concatenates "&backTo=..." causing malformed URLs when buildMediaPlayHref (via
appendQuery) returns no query string; update chapterReaderHref to determine the
correct separator by checking the mediaHref returned from buildMediaPlayHref (or
whether it contains '?') and use '?' when no query exists otherwise '&', and
then append the properly encoded backTo value; reference chapterReaderHref and
buildMediaPlayHref (and appendQuery) to locate and fix the logic and ensure
encodeURIComponent(backTo) is still applied.

---

Outside diff comments:
In `@internal/catalog/library_repo.go`:
- Around line 293-312: The current DELETE uses NOT EXISTS against media_items
(mi.type='manga') which exempts any manga series globally; update the second
predicate so it only exempts when that manga series still has at least one
non-missing chapter in the same folder. Replace the NOT EXISTS(SELECT 1 FROM
media_items mi WHERE mi.content_id = mil.content_id AND mi.type = 'manga') with
a NOT EXISTS that joins media_items (mi) to media_files (mf2) and checks
mi.content_id = mil.content_id AND mi.type = 'manga' AND mf2.media_folder_id =
mil.media_folder_id AND mf2.missing_since IS NULL so only per-folder non-missing
manga chapters prevent deletion (referencing mil, mi, mf/mf2 and the tx.Query
SQL block in library_repo.go).

In `@web/src/app.css`:
- Around line 632-636: The high-contrast selector block that currently targets
html[data-high-contrast="true"] .surface-panel-subtle, .surface-panel, .glass,
.glass-subtle should also include .glass-chip so chips get the same border-color
override in high-contrast mode; update the selector set (and the duplicate block
later in the file that mirrors lines 939-947) to add .glass-chip alongside
.glass and .glass-subtle and keep the same color-mix rule to ensure consistent
legibility for chip components.

In `@web/src/pages/EbookReader.tsx`:
- Around line 295-306: The chapter navigation builds query strings incorrectly
and handleFileChange drops the backTo param; update nextChapterHref construction
and the file-change handler (handleFileChange) to use URLSearchParams for all
query params (including optional libraryId and backTo) so the final URL is
always /reader/ebook/<id>?<querystring> (not concatenated with &), and ensure
you copy any existing backTo value into the new params when switching files;
locate nextChapterHref and handleFileChange in EbookReader.tsx and replace
manual string concat with URLSearchParams that conditionally sets "file_id",
"libraryId", and "backTo" before calling navigate (use
encodeURIComponent(contentId) for the path and nextParams.toString() for the
query).
- Around line 753-783: The overlay and ruler UI are rendered whenever
readerSettings.readingRuler is true even in comic mode; update the conditional
that renders the ruler (the block using readerSettings.readingRuler,
effectiveRulerTop, and rulerBandHeight) to also check the comic-mode flag so the
ruler and its handlers (handleRulerPointerDown/Move/Up/Cancel and
handleRulerKeyDown) are not rendered in comics. Specifically, wrap the existing
JSX with a combined condition (e.g. readerSettings.readingRuler && !isComicMode
or readerSettings.readingRuler && readerSettings.readingMode !== 'comic'
depending on your codebase flag) so the overlay, button and calls to
rulerBandHeight/effectiveRulerTop are skipped when comic mode is active.

In `@web/src/pages/libraryPageSearchParams.ts`:
- Around line 101-106: The media scope handling omits "manga" for mixed
libraries: update the conditional checks that validate/fallback mediaScope and
the branch that handles libraryType === "mixed" to include "manga" alongside
"movie", "series", "episode", "audiobook", and "ebook" so type=manga is
preserved for mixed-library deep links and state restoration; specifically
modify the mediaScope validation (the expression using mediaScope === "...") and
the mixed-library branch where libraryType === "mixed" to accept "manga" as a
valid scope.

---

Nitpick comments:
In `@internal/api/handlers/sections.go`:
- Around line 1233-1246: The loop building ids can produce an empty slice and
you must short-circuit before calling h.fetcher.FetchMangaChapterSeriesMeta;
after building ids (the ids variable collected from items) add a check if
len(ids) == 0 and return early (skip the FetchMangaChapterSeriesMeta call) so
the handler does not perform unnecessary work — modify the handler flow around
the FetchMangaChapterSeriesMeta call in sections.go to return the appropriate
empty result/response when ids is empty instead of invoking
h.fetcher.FetchMangaChapterSeriesMeta.

In `@internal/sections/defaults_test.go`:
- Around line 594-607: TestGeneratedHomeLibraryRecentDefaultsNonMangaNoScope
currently only rejects "manga" but should assert that non-manga sections are
unscoped; update the test examining generatedHomeLibraryRecentDefaults(7,
"Movies", "movies") to, after ParseQueryDefinition(sec.Config), assert that
def.MediaScope == "" (empty string) rather than just checking def.MediaScope !=
"manga" so the test fails if any media_scope is set.

In `@internal/sections/manga_chapter_exclusion_test.go`:
- Around line 20-24: The tests call buildRecentlyAddedQuery but ignore the
returned error (e.g., generic, _ := buildRecentlyAddedQuery(...)) which can mask
root causes; change these to capture the error (e.g., generic, err :=
buildRecentlyAddedQuery(...)) and assert/require that err is nil (fail fast)
before asserting that the SQL string contains mangaChapterExclusionSQL; apply
the same fix to the other occurrences noted (the similar calls at the other
ranges) so each test checks the error from buildRecentlyAddedQuery prior to
performing strings.Contains checks.
🪄 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: 256399a4-2ddf-462f-9f7c-e21f71e60a38

📥 Commits

Reviewing files that changed from the base of the PR and between 6781c20 and 232484f.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (81)
  • .gitignore
  • cmd/silo/main.go
  • go.mod
  • internal/api/handlers/catalog_resources.go
  • internal/api/handlers/items.go
  • internal/api/handlers/libraries.go
  • internal/api/handlers/libraries_metadata_levels_test.go
  • internal/api/handlers/sections.go
  • internal/api/router.go
  • internal/catalog/browse.go
  • internal/catalog/browse_manga_counts_test.go
  • internal/catalog/catalog_parser_test.go
  • internal/catalog/catalog_resolver.go
  • internal/catalog/catalog_resolver_test.go
  • internal/catalog/detail.go
  • internal/catalog/detail_manga_test.go
  • internal/catalog/discovery_repo.go
  • internal/catalog/item_repo.go
  • internal/catalog/library_repo.go
  • internal/catalog/manga_chapter_exclusion_test.go
  • internal/catalog/manga_files.go
  • internal/catalog/media_scope_test.go
  • internal/catalog/provider_id_repo.go
  • internal/catalog/query_definition.go
  • internal/catalog/query_definition_test.go
  • internal/catalog/query_executor.go
  • internal/ebooks/enrichment.go
  • internal/manga/enrichment.go
  • internal/manga/enrichment_test.go
  • internal/metadata/merge.go
  • internal/metadata/plugin_provider.go
  • internal/metadata/types.go
  • internal/models/media.go
  • internal/scanner/manga_chapters_repo.go
  • internal/scanner/manga_chapters_repo_test.go
  • internal/scanner/manga_parse.go
  • internal/scanner/manga_parse_test.go
  • internal/scanner/manga_scan.go
  • internal/scanner/scanner.go
  • internal/scanner/scanner_test.go
  • internal/sections/defaults.go
  • internal/sections/defaults_test.go
  • internal/sections/fetcher.go
  • internal/sections/fetcher_continue_watching_test.go
  • internal/sections/generated.go
  • internal/sections/manga_chapter_exclusion_test.go
  • internal/sections/manga_latest_volume_poster_test.go
  • internal/taskmanager/tasks/sync_manga_metadata.go
  • migrations/sql/20260610193238_manga_chapters.sql
  • migrations/sql/20260611003847_manga_enrichment_state.sql
  • web/src/api/types.ts
  • web/src/app.css
  • web/src/components/ContinueWatchingCard.tsx
  • web/src/components/FilterRuleEditor.tsx
  • web/src/components/GlobalSearch.tsx
  • web/src/components/ItemCard.test.tsx
  • web/src/components/ItemCard.tsx
  • web/src/components/MangaFilesDialog.tsx
  • web/src/components/MediaItemMenu.tsx
  • web/src/components/admin/libraries/libraryTypes.ts
  • web/src/components/admin/libraries/useLibraryForm.ts
  • web/src/components/catalog/CatalogFilterBar.tsx
  • web/src/components/collections/CollectionGuidedRulesEditor.tsx
  • web/src/hooks/queries/catalogRead.ts
  • web/src/lib/mangaChapters.test.ts
  • web/src/lib/mangaChapters.ts
  • web/src/lib/mediaNavigation.ts
  • web/src/lib/querySortOptions.ts
  • web/src/pages/EbookReader.test.tsx
  • web/src/pages/EbookReader.tsx
  • web/src/pages/ItemDetail/DetailHero.tsx
  • web/src/pages/ItemDetail/MangaContent.test.tsx
  • web/src/pages/ItemDetail/MangaContent.tsx
  • web/src/pages/ItemDetail/components/HeroCrewLine.tsx
  • web/src/pages/ItemDetail/components/MetadataBadges.tsx
  • web/src/pages/ItemDetail/index.tsx
  • web/src/pages/ItemDetail/watchedState.test.ts
  • web/src/pages/ItemDetail/watchedState.ts
  • web/src/pages/LibraryBrowse.tsx
  • web/src/pages/libraryPageSearchParams.test.ts
  • web/src/pages/libraryPageSearchParams.ts

Comment thread internal/catalog/browse.go Outdated
Comment on lines +347 to +349
// Manga chapters (type='ebook' rows linked into a manga series) are internal
// sub-units and must never surface as standalone catalog items.
conditions = append(conditions, mangaChapterExclusionWhere("mi"))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Keep the facet/typeahead queries aligned with the browse result set.

These lines hide manga chapter rows only in buildBrowsePlan. The shared filterWhereClauseForSource() path below still powers ListGenres, ListContentRatings, ListOriginalLanguages, and the facet typeaheads without that predicate, so hidden chapter rows can still leak into filter options even though the browse grid no longer returns them. Please move the exclusion into the shared filter builder as well so filters and visible results stay in sync.

🤖 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/browse.go` around lines 347 - 349, The manga chapter
exclusion (mangaChapterExclusionWhere) is only applied in buildBrowsePlan,
causing chapter rows to be hidden from browse grids but still appear in
filters/typeaheads; update the shared filter builder by adding the same
exclusion into filterWhereClauseForSource so ListGenres, ListContentRatings,
ListOriginalLanguages and typeahead queries use the same predicate; locate
filterWhereClauseForSource and append the mangaChapterExclusionWhere("mi")
condition (or otherwise incorporate its logic) into the conditions it returns so
filters and visible browse results remain aligned.

Comment on lines +1138 to +1140
func mangaCountColumns(alias string) string {
return "(SELECT count(*) FROM manga_chapters mc WHERE mc.series_content_id = " + alias + ".content_id AND (mc.volume IS NULL OR mc.volume = '')) AS manga_chapter_count, " +
"(SELECT count(DISTINCT mc.volume) FROM manga_chapters mc WHERE mc.series_content_id = " + alias + ".content_id AND mc.volume IS NOT NULL AND mc.volume <> '') AS manga_volume_count"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

manga_chapter_count is only counting loose chapters.

Line 1139 excludes every chapter with a non-empty mc.volume, so a volume-organized series can surface as 0 chapters even though the field and UI copy are "chapter count". If this surface is meant to show total chapters, the first subquery needs to count all linked chapter rows; otherwise the field/API name should reflect that it only means "chapters outside a volume".

Suggested SQL shape
 func mangaCountColumns(alias string) string {
-	return "(SELECT count(*) FROM manga_chapters mc WHERE mc.series_content_id = " + alias + ".content_id AND (mc.volume IS NULL OR mc.volume = '')) AS manga_chapter_count, " +
+	return "(SELECT count(*) FROM manga_chapters mc WHERE mc.series_content_id = " + alias + ".content_id) AS manga_chapter_count, " +
 		"(SELECT count(DISTINCT mc.volume) FROM manga_chapters mc WHERE mc.series_content_id = " + alias + ".content_id AND mc.volume IS NOT NULL AND mc.volume <> '') AS manga_volume_count"
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func mangaCountColumns(alias string) string {
return "(SELECT count(*) FROM manga_chapters mc WHERE mc.series_content_id = " + alias + ".content_id AND (mc.volume IS NULL OR mc.volume = '')) AS manga_chapter_count, " +
"(SELECT count(DISTINCT mc.volume) FROM manga_chapters mc WHERE mc.series_content_id = " + alias + ".content_id AND mc.volume IS NOT NULL AND mc.volume <> '') AS manga_volume_count"
func mangaCountColumns(alias string) string {
return "(SELECT count(*) FROM manga_chapters mc WHERE mc.series_content_id = " + alias + ".content_id) AS manga_chapter_count, " +
"(SELECT count(DISTINCT mc.volume) FROM manga_chapters mc WHERE mc.series_content_id = " + alias + ".content_id AND mc.volume IS NOT NULL AND mc.volume <> '') AS manga_volume_count"
}
🤖 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/browse.go` around lines 1138 - 1140, The current
mangaCountColumns function builds two subqueries but manga_chapter_count
excludes chapters with a non-empty mc.volume, causing volume-organized series to
report zero; either change the first subquery in mangaCountColumns to count all
rows for mc.series_content_id (remove the mc.volume IS NULL OR mc.volume = ''
filter) so manga_chapter_count reflects total chapters, or rename the returned
field to something like manga_loose_chapter_count to accurately reflect that it
only counts chapters outside volumes; update the SQL string built in
mangaCountColumns and any callers/consumers expecting the field name
accordingly.

Comment on lines +1211 to +1232
for rows.Next() {
var (
ch MangaChapter
index *float64
volume *string
progress *float64
posterPath string
)
if err := rows.Scan(&ch.ContentID, &ch.Title, &index, &volume, &ch.Read, &progress, &posterPath); err != nil {
return chapters
}
ch.ChapterIndex = index
if volume != nil {
ch.Volume = *volume
}
ch.Progress = progress
if posterPath != "" {
ch.PosterURL = s.PresignImageURL(ctx, posterPath, "poster", "")
}
chapters = append(chapters, ch)
}
return chapters

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Check row-iteration errors before returning chapters.

fetchMangaChapters returns at Line 1232 without checking rows.Err(). If iteration fails mid-stream, the API can return a silently truncated chapter list.

Suggested fix
 	for rows.Next() {
 		var (
 			ch         MangaChapter
 			index      *float64
 			volume     *string
 			progress   *float64
 			posterPath string
 		)
 		if err := rows.Scan(&ch.ContentID, &ch.Title, &index, &volume, &ch.Read, &progress, &posterPath); err != nil {
 			return chapters
 		}
 		ch.ChapterIndex = index
 		if volume != nil {
 			ch.Volume = *volume
 		}
 		ch.Progress = progress
 		if posterPath != "" {
 			ch.PosterURL = s.PresignImageURL(ctx, posterPath, "poster", "")
 		}
 		chapters = append(chapters, ch)
 	}
+	if err := rows.Err(); err != nil {
+		return []MangaChapter{}
+	}
 	return chapters
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
for rows.Next() {
var (
ch MangaChapter
index *float64
volume *string
progress *float64
posterPath string
)
if err := rows.Scan(&ch.ContentID, &ch.Title, &index, &volume, &ch.Read, &progress, &posterPath); err != nil {
return chapters
}
ch.ChapterIndex = index
if volume != nil {
ch.Volume = *volume
}
ch.Progress = progress
if posterPath != "" {
ch.PosterURL = s.PresignImageURL(ctx, posterPath, "poster", "")
}
chapters = append(chapters, ch)
}
return chapters
for rows.Next() {
var (
ch MangaChapter
index *float64
volume *string
progress *float64
posterPath string
)
if err := rows.Scan(&ch.ContentID, &ch.Title, &index, &volume, &ch.Read, &progress, &posterPath); err != nil {
return chapters
}
ch.ChapterIndex = index
if volume != nil {
ch.Volume = *volume
}
ch.Progress = progress
if posterPath != "" {
ch.PosterURL = s.PresignImageURL(ctx, posterPath, "poster", "")
}
chapters = append(chapters, ch)
}
if err := rows.Err(); err != nil {
return []MangaChapter{}
}
return chapters
🤖 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/detail.go` around lines 1211 - 1232, The loop over rows in
fetchMangaChapters does not check rows.Err() after iteration, so iteration
errors can be swallowed; after the for rows.Next() loop (and before returning
chapters) call rows.Err() and handle any non-nil error consistently with this
package's error handling (e.g., return the error or log and wrap it) instead of
returning a potentially truncated chapters slice; locate the rows variable and
the fetchMangaChapters function (and adjust any callers/signature if needed) and
ensure scan errors are also propagated rather than simply returning chapters.

Comment on lines +95 to +102
// HasPoster marks an already-enriched item claimed only because a
// secondary field (backdrop, status) is missing; the sweep then fetches by
// stored provider ID and touches only the missing secondary fields.
HasPoster bool
// HasBackdrop guards the secondary pass against re-caching an existing
// backdrop when the item was claimed for another missing field.
HasBackdrop bool
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Secondary-only enrichment can overwrite an existing show_status.

Line 435 currently writes upd.ShowStatus whenever the provider returns status, but this code path is also used when the item was claimed only for missing backdrop. That can overwrite an already-populated status instead of “only filling missing secondary fields.”

💡 Proposed fix
 type enrichmentItemRow struct {
@@
 	HasBackdrop bool
+	// HasStatus guards secondary-only updates from overwriting an already set status.
+	HasStatus bool
 }
@@
 		(mi.poster_path IS NOT NULL AND mi.poster_path <> '') AS has_poster,
-		(mi.backdrop_path IS NOT NULL AND mi.backdrop_path <> '') AS has_backdrop
+		(mi.backdrop_path IS NOT NULL AND mi.backdrop_path <> '') AS has_backdrop,
+		(mi.show_status IS NOT NULL AND mi.show_status <> '') AS has_status
@@
 			&item.HasPoster,
 			&item.HasBackdrop,
+			&item.HasStatus,
 		); err != nil {
@@
-	if result != nil && result.ShowStatus != "" {
+	if result != nil && result.ShowStatus != "" && !item.HasStatus {
 		upd.ShowStatus = &result.ShowStatus
 	}

Also applies to: 282-284, 309-318, 435-437

🤖 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/manga/enrichment.go` around lines 95 - 102, The secondary-only
enrichment path is overwriting an existing show_status; when populating fields
from the provider you must only set upd.ShowStatus if the existing item has an
empty ShowStatus or the claim is not a “secondary-only” claim. Update the
assignment sites that write upd.ShowStatus (the code paths that use the
HasPoster / HasBackdrop flags) to guard the write: check the current item's
ShowStatus (or that neither HasPoster nor HasBackdrop is true) before assigning
provider.Status to upd.ShowStatus so secondary-only sweeps (when
HasBackdrop/HasPoster is set) only fill missing secondary fields and never
overwrite a present show_status.

Comment on lines +602 to +605
slog.Warn("manga enrichment: image cache failed, keeping provider URL",
"content_id", contentID,
"url", url,
"error", err,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Avoid logging full remote image URLs in warnings.

Lines 602 and 610 log the full provider URL. If providers return signed URLs, query params/tokens can be persisted in logs.

💡 Proposed fix
 	if err != nil {
+		safeURL := stripURLQuery(url)
 		slog.Warn("manga enrichment: image cache failed, keeping provider URL",
 			"content_id", contentID,
-			"url", url,
+			"url", safeURL,
 			"error", err,
 		)
 		return url, ""
 	}
 	if cached == nil {
+		safeURL := stripURLQuery(url)
 		slog.Warn("manga enrichment: image cache returned no result, keeping provider URL",
 			"content_id", contentID,
-			"url", url,
+			"url", safeURL,
 		)
 		return url, ""
 	}
@@
+func stripURLQuery(raw string) string {
+	if i := strings.IndexByte(raw, '?'); i >= 0 {
+		return raw[:i]
+	}
+	return raw
+}

Also applies to: 610-613

🤖 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/manga/enrichment.go` around lines 602 - 605, The warning calls that
log the provider URL (the slog.Warn with message "manga enrichment: image cache
failed, keeping provider URL") must not emit full remote URLs; parse the url
string (using net/url.Parse) and redact query and fragment before logging (e.g.,
reconstruct safeURL from u.Scheme + "://" + u.Host + u.Path or log u.Host and
u.Path separately), or replace the URL with a hashed/shortened identifier;
update both occurrences of that slog.Warn call to log the sanitized/summarized
URL (or host+path) and keep the existing "content_id" and "error" fields.

Comment on lines +400 to +407
// Manga chapters are ebook items linked to a series; collapse multiple
// in-progress chapters of the same manga to a single card (keeping the
// most recently read), mirroring the episode→series collapse. Resolve
// the linkage into itemMeta so the shared collapse can group by series.
if len(orderedItems) > 1 {
f.applyMangaChapterSeriesMeta(ctx, orderedItems, itemMeta)
orderedItems = collapseContinueWatchingSeriesCandidates(orderedItems, itemMeta)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Collapse after the limit check under-fills Continue Reading.

collectContinueProgressItems has already stopped once it gathered limit chapter cards, and only then this block merges same-series chapters into one card. A reader with many in-progress chapters from the same manga can therefore get a much shorter row even when later progress entries could fill the remaining slots with other series. Keep paginating until you have limit unique series/cards, or deliberately over-fetch before collapsing.

🤖 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 400 - 407,
collectContinueProgressItems currently stops when it has gathered "limit"
chapter cards before you collapse same-series chapters
(applyMangaChapterSeriesMeta + collapseContinueWatchingSeriesCandidates), which
can leave the final result under-filled; change the logic so you either
over-fetch (fetch more than "limit", e.g., multiply limit by a small factor) or
continue paginating until you have "limit" unique series/cards after applying
applyMangaChapterSeriesMeta and collapseContinueWatchingSeriesCandidates to
orderedItems/itemMeta; specifically, adjust the loop in
collectContinueProgressItems to evaluate
collapseContinueWatchingSeriesCandidates(orderedItems, itemMeta) (or compute
unique series count from itemMeta) and only stop when the collapsed count >=
limit (or you hit a hard max), ensuring orderedItems is collapsed with
applyMangaChapterSeriesMeta before counting.

Comment on lines +69 to +74
const nextRelevanceScope: QuerySortRelevanceScope =
v === "all" || v === "video"
? "all"
: v === "manga"
? "ebook"
: (v as QuerySortRelevanceScope);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Use the manga relevance scope instead of coercing to ebook.

Line 69 and Line 121 force "manga" to "ebook" for sort relevance/applicability. That conflicts with the newer manga scope contract and can keep/strip sort options incorrectly when users switch scopes.

Suggested fix
- const nextRelevanceScope: QuerySortRelevanceScope =
-   v === "all" || v === "video"
-     ? "all"
-     : v === "manga"
-       ? "ebook"
-       : (v as QuerySortRelevanceScope);
+ const nextRelevanceScope: QuerySortRelevanceScope =
+   v === "all" || v === "video" ? "all" : (v as QuerySortRelevanceScope);

...
- : state.mediaScope === "manga"
-   ? ["ebook"]
-   : [state.mediaScope];
+ : [state.mediaScope];

Also applies to: 119-123

🤖 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/catalog/CatalogFilterBar.tsx` around lines 69 - 74, The
code coerces "manga" to "ebook" when computing the relevance scope (see the
nextRelevanceScope assignment using QuerySortRelevanceScope); change the mapping
so "manga" remains "manga" instead of being converted to "ebook". Update the
same logic at the other occurrence (the similar ternary around lines 119-123) so
both places return "manga" for v === "manga" and otherwise cast v as
QuerySortRelevanceScope.

Comment on lines +114 to 116
const isMangaChapter = card.type === "ebook" && !!card.seriesId && !!card.seriesTitle;
const headingIsSeries = (hasEpisodeMeta && !!card.seriesTitle) || isMangaChapter;
const heading = headingIsSeries ? card.seriesTitle : card.title;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Loosen manga-chapter detection to series_id presence only

Line 114 currently requires seriesTitle too, so manga chapters with series_id but missing series_title won’t take the series-first routing path.

Suggested fix
-  const isMangaChapter = card.type === "ebook" && !!card.seriesId && !!card.seriesTitle;
+  const isMangaChapter = card.type === "ebook" && !!card.seriesId;
   const headingIsSeries = (hasEpisodeMeta && !!card.seriesTitle) || isMangaChapter;
-  const heading = headingIsSeries ? card.seriesTitle : card.title;
+  const heading = headingIsSeries ? (card.seriesTitle ?? card.title) : card.title;
🤖 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/ContinueWatchingCard.tsx` around lines 114 - 116, Loosen
manga-chapter detection by changing isMangaChapter to only require seriesId
(i.e. card.type === "ebook" && !!card.seriesId) and update heading logic so when
headingIsSeries is true but card.seriesTitle is missing we still show
card.title; modify the declarations for isMangaChapter, headingIsSeries and
heading in ContinueWatchingCard.tsx so routing uses the series-first path when
seriesId exists while the displayed heading falls back to card.title if
seriesTitle is undefined.

Comment on lines +262 to +265
const looseChapterCount = useMemo(
() => entries.filter((e) => e.kind === "chapter").length,
[entries],
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Chapter badge undercounts sectioned manga.

Line 263 counts only top-level kind === "chapter" entries, so chapters nested under section are excluded. Series grouped by volume can show 0 Chapters even with many chapter items.

💡 Proposed fix
-  const looseChapterCount = useMemo(
-    () => entries.filter((e) => e.kind === "chapter").length,
-    [entries],
-  );
+  const chapterCount = chapterRows.length;
...
-            chapterCount={looseChapterCount}
+            chapterCount={chapterCount}

Also applies to: 299-300

🤖 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/ItemDetail/MangaContent.tsx` around lines 262 - 265, The
chapter count currently computed in looseChapterCount (useMemo over entries)
only tallies top-level items with kind === "chapter" and thus misses chapters
nested under container kinds like "section" or "volume"; change the logic to
traverse/flatten entries recursively (or implement a helper like
countChapters(entries) or flattenEntries(entries)) and count all nodes where
kind === "chapter", then replace the current useMemo and the other similar
counts (the other chapter-count usage at the later count in the file) to use
this recursive/flattened count so sectioned/volume-grouped series reflect the
true chapter total.

@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: 232484fc0a

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +219 to +221
} else if isUnchanged {
atomic.AddInt64(skipped, 1)
return nil

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 Repair manga links before skipping unchanged files

When a scan sees an unchanged archive, this returns before findOrCreateMangaSeries and upsertMangaChapter run. Since ebookFileShouldSkip only proves that the existing media_files row is current, converting an already-scanned ebook library to manga (or retrying after a previous scan failed after the chapter upsert but before linking) will skip every file and never create the series item or manga_chapters rows until file mtimes change. The unchanged path needs to verify/repair the manga series link before returning.

Useful? React with 👍 / 👎.

Comment on lines 167 to +170
label: "Progress",
defaultOrder: "desc",
personalized: true,
applicableMediaScopes: ALL_MEDIA_SCOPES,
applicableMediaScopes: [...ALL_MEDIA_SCOPES, "manga"],

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 Remove manga from the non-aggregating progress sort

Adding manga to this personalized sort exposes a broken ordering for manga libraries: the backend only uses the ebook reader progress join when mediaScope == "ebook"; for "manga" it falls through to user_watch_progress keyed by the manga series content_id, while actual chapter reading writes ebook_reader_progress on chapter content_ids. In normal manga reading, every series therefore sorts with null progress instead of by chapter progress, so this option should stay hidden or the backend should aggregate linked chapter progress for manga.

Useful? React with 👍 / 👎.


providerIDs = filterMangaProviderIDs(providerIDs)
if e.providerIDs != nil && len(providerIDs) > 0 {
if err := e.providerIDs.ReplaceByContentID(ctx, contentID, providerIDs); err != nil {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve manga_series provider IDs when enriching

When a provider returns external IDs, this call replaces all provider IDs for the series after filterMangaProviderIDs has removed the scanner's internal manga_series identity. The next scan can no longer find the existing series by its group key, so it creates a duplicate pending series, relinks chapters to it, and the orphan cleanup can delete the enriched series metadata. Persist the external IDs without deleting the internal identity row.

Useful? React with 👍 / 👎.

Comment on lines +76 to +80
return `${buildMediaPlayHref({
contentId: chapterContentId,
type: "ebook",
libraryId,
})}&backTo=${encodeURIComponent(backTo)}`;

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 Append backTo with the correct query separator

When a manga detail page is opened without a libraryId query parameter, buildMediaPlayHref returns /reader/ebook/<id> with no ?, so appending &backTo=... produces /reader/ebook/<id>&backTo=... instead of a query string. The route then treats the whole suffix as the content id and the chapter reader link fails from global catalog/search entry points; use URLSearchParams or choose ? vs & based on the existing href.

Useful? React with 👍 / 👎.

parsed.Title = ebookTitleFromPath(filePath)
}

seriesName := mangaSeriesFromPath(filePath)

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 Avoid grouping root-level archives as the library root

For archives placed directly under a configured manga library path, mangaSeriesFromPath(filePath) returns the parent directory name, which is the library root, for every file. A simple layout like /Manga/Naruto 001.cbz and /Manga/Bleach 001.cbz is therefore scanned as one series named Manga; the scan needs root awareness or a filename-derived fallback for files whose parent is the scanned root.

Useful? React with 👍 / 👎.

Comment on lines +120 to +122
if m := mangaVolume.FindStringSubmatch(clean); m != nil {
if n, err := strconv.ParseFloat(m[1], 64); err == nil {
return "v" + m[1], n, true

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 Parse chapter tokens before volume tokens

For common filenames that include both a volume and chapter marker, such as Series v03 c012.cbz, this returns the volume number as chapter_index before the chapter regex is checked. Those rows all persist as chapter 3 (with volume v03), so the detail page labels and next-chapter ordering are wrong for multi-chapter volumes; when both tokens are present, keep the volume label but use the chapter token for the index.

Useful? React with 👍 / 👎.

Comment on lines +404 to +406
if len(orderedItems) > 1 {
f.applyMangaChapterSeriesMeta(ctx, orderedItems, itemMeta)
orderedItems = collapseContinueWatchingSeriesCandidates(orderedItems, itemMeta)

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 Backfill after collapsing manga continue-reading cards

This collapses the already-limited orderedItems slice without fetching replacements, so a reader with many in-progress chapters from one manga can get a Continue Reading section with one card even when there are more distinct series beyond the first page. The collapse needs to happen during collection or the query needs to over-fetch/backfill until the post-collapse result reaches the section limit.

Useful? React with 👍 / 👎.

Comment on lines +50 to +51
// Ebook and manga are read rather than watched, so relabel "watched".
if (mediaScope !== "ebook" && mediaScope !== "manga") {

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 Do not advertise unsupported manga read filters

For manga media scopes this relabels the personalized watched/in_progress filters as read-state filters, but the backend only switches to ebook_reader_progress for mediaScope == "ebook"; "manga" falls through to user_watch_progress on the series content_id while actual reading progress is stored on linked chapter ids. Manga smart collections or catalog filters using Read/Unread/In Progress therefore return incorrect results until the backend aggregates chapter read state for series.

Useful? React with 👍 / 👎.

Comment on lines 33 to 35
case "ebook":
case "manga":
return played ? "Mark Unread" : "Mark Read";

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 Hide or implement the manga Mark Read action

Adding manga to the read/unread label makes manga cards expose the shared watched-state menu action, but resolveWatchedTargets has no manga branch and returns ErrItemNotFound for a series id. From a manga browse card, selecting Mark Read/Unread therefore sends a request that fails instead of marking all chapters (or being hidden).

Useful? React with 👍 / 👎.

@fluxis

fluxis commented Jun 12, 2026

Copy link
Copy Markdown
Contributor

Heads-up: #142 stacks on this branch and should be merged into it before this lands — it fixes a scan-time flood where all 31,564 manga chapter items (status='pending' by design) were funneled through the matcher's retry loop, adding ~8h46m of rate-limited, guaranteed-no-match ebook-plugin searches to every manga library scan. With the guard, the same library scans in 27s (live-verified).

@fluxis fluxis added the v1.0 Silo v1 scope - auto-adds to the Silo v1 project label Jun 12, 2026
@fluxis fluxis added this to the v1 milestone Jun 12, 2026
@fluxis fluxis added v1.0-proposed Proposed for the v1 scope lock; awaiting triage v1.0 Silo v1 scope - auto-adds to the Silo v1 project and removed v1.0 Silo v1 scope - auto-adds to the Silo v1 project v1.0-proposed Proposed for the v1 scope lock; awaiting triage labels Jun 13, 2026
@Quick104

Copy link
Copy Markdown
Contributor Author

Code review

Found 4 issues:

  1. Manga enrichment deletes the manga_series identity provider-id row, breaking re-scan idempotency (bug). In persist(), filterMangaProviderIDs strips the internal manga_series provider from the write set, then ReplaceByContentID deletes all provider-id rows for the series before re-inserting only the external IDs. manga_series is not in excludedProviderIDs and nothing recreates it, so on a normal successful match the scanner's identity anchor is destroyed. The next scan can't resolve the series via lookupMangaSeries, mints a new content_id, relinks chapters, and deleteOrphanedMangaSeries then deletes the original enriched series — duplicate series, lost metadata, and repeated provider re-enrichment.

providerIDs = filterMangaProviderIDs(providerIDs)
if e.providerIDs != nil && len(providerIDs) > 0 {
if err := e.providerIDs.ReplaceByContentID(ctx, contentID, providerIDs); err != nil {
slog.Warn("manga enrichment: failed to persist provider IDs",

  1. Manga series-card poster override uses COALESCE without NULLIF, yielding blank posters for cover-less chapters (bug). The fallback is COALESCE(latest_chapter_poster, series_poster), but a chapter's poster_path is an empty string (Go zero value), not NULL, when no cover is extracted — so COALESCE returns '' instead of the series' own (e.g. AniList) poster. The sibling poster expressions in this same file wrap each operand in NULLIF(..., ''); this one should too (same class of fix as dc4c20bb).

func mangaLatestVolumePosterExpr(alias, col string) string {
return "CASE WHEN " + alias + ".type = 'manga' THEN COALESCE((" +
"SELECT c." + col + " FROM media_items c " +
"JOIN manga_chapters mc ON mc.chapter_content_id = c.content_id " +
"WHERE mc.series_content_id = " + alias + ".content_id " +
"ORDER BY c.created_at DESC, c.content_id DESC LIMIT 1), " +
alias + "." + col + ") ELSE " + alias + "." + col + " END AS " + col
}

  1. chapterReaderHref builds the backTo link by string concatenation, producing a malformed URL when libraryId is absent (bug). appendQuery omits the ? when there are no params, so deep-linking /item/{mangaId} without ?libraryId= yields /reader/ebook/{id}&backTo=.... The router then captures {id}&backTo=... as the contentId and the back target is silently lost. Route backTo through the query helper instead of &-concatenating it.

const backTo = buildItemHref({ contentId: seriesContentId, libraryId });
return `${buildMediaPlayHref({
contentId: chapterContentId,
type: "ebook",
libraryId,
})}&backTo=${encodeURIComponent(backTo)}`;
}

  1. Feature PR opened while v1 scope is NOT LOCKED, with no linked scope item (CLAUDE.md adherence). docs/architecture/v1-scope.md states scope is "NOT LOCKED", and CLAUDE.md's scope gate says that in that case you should file a v1 capability proposal issue rather than open a feature PR; the PR body also has no Part of #NNN link ("PRs with no linked scope item will be questioned at review").

https://github.com/Silo-Server/silo-server/blob/232484fc0a0222535ebc4692c03907e7dc7e34b5/CLAUDE.md#L95-L97

🤖 Generated with Claude Code

- If this code review was useful, please react with 👍. Otherwise, react with 👎.

fluxis and others added 15 commits June 16, 2026 19:59
Forks the ebooks library type into a 'manga' type: series detected from the
folder tree as a first-class type='manga' item, .cbz/.cbr chapters stay
readable ebook items linked via a new manga_chapters table, browse shows series
cards, enrichment targets the series item at content level 'manga'. Hands off to
a follow-on plugin spec for the manga metadata source.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ern (no test-DB)

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add TestParseMangaIndexCorpus — 36 real-world scanlation filenames
covering bare chapter, decimal chapter, v/vol-prefix volume, and
c/ch-prefix chapter patterns; asserts <5% miss rate.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Adds mangaChapterWrite (pure, unit-tested), upsertMangaChapter, and
listMangaChapters following the ebook/audiobook thin-SQL pattern.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Add isMangaLibraryType helper (unexported, matching the style of
isEbookLibraryType / isAudiobookLibraryType) with a corresponding
TestIsMangaLibraryType unit test.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Map library type "manga" to content level ["manga"] in
metadataContentLevelsForLibraryType so that seedDefaultChain seeds a
manga-level metadata provider chain when a manga library is created.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Accept "manga" as a valid media_scope so a manga library browses only its
type='manga' series items; the per-chapter type='ebook' items are naturally
excluded because MediaScopeItemTypes("manga") expands to {"manga"}. Add the
manga default library sections (scoped to media_scope='manga') so the library
feed shows series cards. Refresh the two media_scope validation error messages.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
For a type='manga' item, attach its chapters to the detail response via a new
MangaDetailExtension. fetchMangaChapters joins manga_chapters to media_items on
the chapter content ID, scopes to the series, and orders by chapter_index
(NULLS LAST) then sort_title — matching the scanner's chapter ordering.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
fluxis and others added 16 commits June 16, 2026 20:04
…-state hint

- buildMangaList buckets volumes by canonical numeric token so mixed
  release naming (v01 + 1) yields one Volume 1 instead of duplicates
- cbz/cbr readers start with the side panel closed and hide prose-only
  chrome (reading ruler, TTS, typography/font controls, hyphenation,
  writing mode) while keeping comic-relevant settings (theme, brightness,
  margin, right-to-left, spread, flow)
- manga empty state mentions chapters appear after the library scan

Co-Authored-By: Claude Fable 5 <[email protected]>
- vendor the unpublished plugin SDK (adds MetadataItem.status) under
  internal/compat/ with a relative go.mod replace, following the
  zishang520-webtransport-go convention; swap to the published module
  before the upstream PR
- map plugin status into MetadataResult.ShowStatus, persist it during
  manga enrichment, and show it as the hero status badge (show_status was
  already on the detail payload and MetadataBadges)

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

The backdrop-only claim arm becomes a secondary-fields pass: enriched items
missing a backdrop and/or publication status are claimed, fetched by stored
provider ID, and only the missing secondary fields are written. Lets the
new status field backfill across the already-enriched library instead of
applying only to future enrichments.

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

The new MetadataResult.ShowStatus never reached the accumulated result the
manga enricher persists from - the field-by-field merges didn't know it, so
the status backfill pass obtained nothing. Regression-tested on both paths.

Co-Authored-By: Claude Fable 5 <[email protected]>
filterMangaProviderIDs passed the scanner's manga_series identity row
through, so the search-skip-when-already-matched guard saw provider IDs on
every item and never searched: unmatched items went straight to a by-ID
fetch with no usable ID and were stamped as terminal no-match without a
single provider request (and the MangaDex fallback was never consulted).

Co-Authored-By: Claude Fable 5 <[email protected]>
The override unpublishes the bundled redis/postgres host ports
(ports: !override []). It is a per-deployment, local-only file: ignoring it
keeps a rebase from main and git clean -fd from disturbing it, and keeps it
out of any PR. Its accidental absence once exposed Redis to the internet.

Co-Authored-By: Claude Fable 5 <[email protected]>
…me-count consistency

- enrichWithProviders: set accumulator.HasMetadata after a provider result
  merges (MergeMetadata doesn't propagate it). Without this, a confident
  match carrying only genres/authors/status/year but no cover and no overview
  failed the no-match check and was discarded + terminally stamped.
- byChapterIndex: both un-indexed chapters yield POSITIVE_INFINITY, so the
  subtraction was Infinity-Infinity=NaN (Array.sort treats NaN as 0, leaving
  order undefined). Compare explicitly for a stable order.
- MangaContent volume/chapter badges: derive counts from the rendered
  buildMangaList entries (which canonicalize v01 ≡ 1) instead of raw distinct
  volume tokens, so the badge can no longer say '2 Volumes' over one row.

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

The secondary arm (poster present, backdrop/status missing) requires
last_refreshed IS NULL, so it is only reachable when an operator resets
last_refreshed to backfill a newly-added field — not an automatic periodic
re-check (which would re-fetch banner-less series every sweep). Documents the
intent so it does not read as dead code.

Co-Authored-By: Claude Fable 5 <[email protected]>
…ider-id lookup

- Continue Reading now collapses multiple in-progress chapters of the same
  manga into one card (most recently read kept), mirroring the episode→series
  collapse. The reading section resolves chapter→series linkage into itemMeta
  (applyMangaChapterSeriesMeta) and runs the shared
  collapseContinueWatchingSeriesCandidates, which the reading path previously
  skipped.
- claimBatch resolves provider IDs for the whole batch in one query via the
  new ProviderIDRepository.GetByContentIDs (content_id = ANY), replacing the
  per-item GetByContentID N+1.

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

- Color-coded publication status pill (Ongoing/Completed/Hiatus/Cancelled/
  Upcoming) in the manga card's top-left corner, mirroring the vol/chapter
  count chip top-right. Strictly manga-gated; show_status was already on the
  browse payload.
- New .glass-chip (78% surface vs glass-subtle's 40%) for the manga count +
  status pills so the labels stay legible over busy cover art.

Co-Authored-By: Claude Fable 5 <[email protected]>
Replace the vendored internal/compat/silo-plugin-sdk copy with a normal
dependency on the published SDK module at v0.7.0, which adds
MetadataItem.status (publication/airing status) consumed by the manga
status badge at internal/metadata/plugin_provider.go.

- go.mod: pin v0.7.0, drop the local-path replace directive
- remove the vendored internal/compat/silo-plugin-sdk tree
- Dockerfile: drop the vendored-SDK COPY
- strip the manga design docs/plans from docs/superpowers (internal)

Requires Silo-Server/silo-plugin-sdk#4 merged and tagged v0.7.0.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Manga chapters are type='ebook' items that stay status='pending' by
design - provider metadata lives on the type='manga' series item. The
scan-final RetryUnmatchedItemsByFolderAndPathPrefix listed all of them
and ran a rate-limited ebook-plugin search per chapter: 31,564 chapters
x ~1s = 8h46m appended to a 2-minute manga library scan (observed
live), every one a guaranteed no-match. Earlier runs never survived to
completion, so the library's last_scanned_at stayed NULL forever.

Add the same manga_chapters NOT EXISTS guard the ebook enricher's
claim query already uses. Verified live: the same library now scans in
27s with retried_items=0.

Co-Authored-By: Claude Fable 5 <[email protected]>
…l-page killer)

NeedsCriticalProbeRepair was always true for BaseType 'ebook' files (epub, pdf,
cbz, cbr — incl. manga chapters): buildEbookMediaFile leaves ProbeUpdatedAt nil
and they have no audio/video, so probeEnsurer.Ensure spawned ffprobe per file on
every detail/watch load and never converged (ffprobe errors on zip/rar, result
never persisted). Short-circuit probe-repair for ebook base type — they're read
directly and never use the transcode/playback probe pipeline.

SHARED fix: benefits both the ebooks and manga library types.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ad-state

- buildEbookExtension ran its 3 related-content queries (series, also-by-author,
  similar) sequentially; run them concurrently like buildAudiobookExtension so
  ebook detail latency is the slowest query, not their sum.
- PGEbookReaderProgressStore.Upsert did an unconditional SET progress=EXCLUDED;
  a routine autosave (e.g. reopening a finished book) could drop it below the
  0.9 finished threshold and silently un-mark it read (and clear the manga
  chapter checkmark, which rides on the same row). Guard: once finished,
  progress only moves on an explicit unread (row delete); below threshold it
  tracks freely.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
- fetchMangaChapters presigned each chapter poster individually; a long-running
  series has hundreds of chapters. Batch them in one PresignImageURLs call, and
  add the missing rows.Err() check (was silently returning partial lists).
- The browse manga count chip's count(DISTINCT volume) subquery wasn't covered
  by manga_chapters_series (series_content_id, chapter_index); add
  idx_manga_chapters_series_volume (series_content_id, volume) so both count
  subqueries are index-only.
- Downgrade the per-chapter "manga scan: indexed" log from Info to Debug (one
  line per .cbz; the 500-file progress log already covers operator visibility).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Folds PR #142 into the manga branch (already done via fast-forward) and
remediates the issues surfaced in the #138 code review.

Correctness:
- Preserve the scanner's manga_series identity anchor through enrichment.
  ReplaceByContentID's DELETE was unconditional, so the first successful
  enrichment wiped the manga_series provider-id row the scanner relies on
  for idempotency, causing duplicate series + metadata loss on the next
  scan. excludedProviderIDs now also means "not deleted", and the DELETE
  preserves those rows. (internal/catalog/provider_id_repo.go)
- Fall back to the series cover when the latest chapter has no poster.
  Poster columns default to '' (not NULL), so the manga series-card poster
  override blanked cards via a plain COALESCE; wrap operands in NULLIF.
  (internal/sections/fetcher.go)
- Keep backTo a real query param on reader links when libraryId is absent.
  It was string-concatenated with '&', producing a malformed URL on
  deep-links; route it through the query helper instead.
  (web/src/lib/mediaNavigation.ts, EbookReader.tsx, MangaContent.tsx)

Quality:
- Hide manga chapters from favorites/watchlist browse, matching the
  exclusion enforced on every other listing surface.
  (internal/catalog/favorites_browse.go)
- Centralize the manga chapter exclusion predicate into a single exported
  catalog.MangaChapterExclusionWhere, removing four duplicated copies.
  (catalog, sections, ebooks)
- Skip the two manga count subqueries on browse scopes that cannot contain
  manga (non-manga type filters), substituting NULL placeholders.
  (internal/catalog/browse.go)
- Normalize provider publication status (AniList/MangaDex/SDK variants)
  into a stable label set so show_status carries one manga value-domain.
  (internal/manga/enrichment.go)

Adds unit tests for the poster NULLIF contract, browse gating, and status
normalization.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

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

Caution

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

⚠️ Outside diff range comments (1)
internal/catalog/detail.go (1)

1197-1221: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Apply access filters to manga chapter rows.

mangaChaptersQuery only scopes by series ID and reader-progress identity. Since chapter rows are still media_items with library/file membership, a series visible through one library can expose linked chapters from a disabled or otherwise inaccessible library. Add chapter-row access predicates before executing the query.

🛡️ Suggested shape
-var mangaChaptersQuery = fmt.Sprintf(`
+const mangaChaptersQueryTemplate = `
 	SELECT m.content_id, m.title, mc.chapter_index, mc.volume,
-	       COALESCE(erp.progress >= %s, false) AS read,
+	       COALESCE(erp.progress >= %s, false) AS read,
 	       erp.progress::double precision,
 	       COALESCE(m.poster_path, '') AS poster_path
 	FROM manga_chapters mc
 	JOIN media_items m ON m.content_id = mc.chapter_content_id
 	LEFT JOIN ebook_reader_progress erp
 	  ON erp.content_id = mc.chapter_content_id
 	 AND erp.user_id = $2
 	 AND erp.profile_id = $3
-	WHERE mc.series_content_id = $1
+	WHERE %s
 	ORDER BY mc.chapter_index NULLS LAST, m.sort_title
-`, EbookFinishedProgressThresholdSQL)
+`
-	rows, err := s.itemRepo.pool.Query(ctx, mangaChaptersQuery, seriesContentID, filter.UserID, filter.ProfileID)
+	args := []any{seriesContentID, filter.UserID, filter.ProfileID}
+	argIdx := 4
+	conditions := []string{"mc.series_content_id = $1"}
+	if !appendAudiobookItemAccessConditions("m", filter, &conditions, &args, &argIdx) {
+		return chapters
+	}
+	query := fmt.Sprintf(
+		mangaChaptersQueryTemplate,
+		EbookFinishedProgressThresholdSQL,
+		strings.Join(conditions, " AND "),
+	)
+	rows, err := s.itemRepo.pool.Query(ctx, query, args...)
🤖 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/detail.go` around lines 1197 - 1221, The mangaChaptersQuery
variable constructs a SQL query that only filters by series ID and reader
progress identity, but fails to apply access control filters for library and
file membership. Since chapter rows are media_items with library and file
memberships, you need to add WHERE clause predicates to the query that validate
chapters against the access filter's library and file permissions. Modify the
mangaChaptersQuery SQL statement to include these access control predicates
before the query is executed in the fetchMangaChapters method to prevent
unauthorized access to chapters from inaccessible libraries.
🤖 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.

Outside diff comments:
In `@internal/catalog/detail.go`:
- Around line 1197-1221: The mangaChaptersQuery variable constructs a SQL query
that only filters by series ID and reader progress identity, but fails to apply
access control filters for library and file membership. Since chapter rows are
media_items with library and file memberships, you need to add WHERE clause
predicates to the query that validate chapters against the access filter's
library and file permissions. Modify the mangaChaptersQuery SQL statement to
include these access control predicates before the query is executed in the
fetchMangaChapters method to prevent unauthorized access to chapters from
inaccessible libraries.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 4e77bfa6-620b-4e94-8c37-0efc736b7af1

📥 Commits

Reviewing files that changed from the base of the PR and between 232484f and addd4050bcd12ead4427b36f5e2f180a1f3c0b54.

📒 Files selected for processing (22)
  • internal/api/handlers/ebook_reader.go
  • internal/catalog/browse.go
  • internal/catalog/browse_manga_counts_test.go
  • internal/catalog/detail.go
  • internal/catalog/discovery_repo.go
  • internal/catalog/favorites_browse.go
  • internal/catalog/item_repo.go
  • internal/catalog/item_repo_test.go
  • internal/catalog/provider_id_repo.go
  • internal/catalog/query_executor.go
  • internal/ebooks/enrichment.go
  • internal/manga/enrichment.go
  • internal/manga/enrichment_test.go
  • internal/scanner/manga_scan.go
  • internal/scanner/probe_repair.go
  • internal/scanner/probe_repair_ebook_test.go
  • internal/sections/fetcher.go
  • internal/sections/manga_latest_volume_poster_test.go
  • migrations/sql/20260616140000_manga_chapters_series_volume_index.sql
  • web/src/lib/mediaNavigation.ts
  • web/src/pages/EbookReader.tsx
  • web/src/pages/ItemDetail/MangaContent.tsx
🚧 Files skipped from review as they are similar to previous changes (8)
  • internal/ebooks/enrichment.go
  • internal/catalog/discovery_repo.go
  • internal/catalog/query_executor.go
  • internal/sections/manga_latest_volume_poster_test.go
  • internal/manga/enrichment_test.go
  • internal/scanner/manga_scan.go
  • internal/sections/fetcher.go
  • internal/manga/enrichment.go

Quick104 and others added 2 commits June 16, 2026 20:07
Drops stale silo-plugin-sdk v0.6.0 and other leftover hashes from the
intermediate rebased states; go.mod is now on the published v0.7.0 tag.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
main changed ebookFileShouldSkip to also return the existing content ID;
the manga scan path only needs the unchanged flag, so discard the new
return. Resolves a silent semantic conflict from the rebase onto main.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@Quick104
Quick104 force-pushed the codex/rebase-pr-137 branch from addd405 to baf2f41 Compare June 17, 2026 00:10
@Quick104
Quick104 merged commit e1fda74 into main Jun 17, 2026
1 check was pending
@Quick104
Quick104 deleted the codex/rebase-pr-137 branch June 17, 2026 00:13
Quick104 added a commit that referenced this pull request Jun 17, 2026
…ist/MangaDex metadata + status badge (#138)

* docs: design spec for manga library type (host sub-project)

Forks the ebooks library type into a 'manga' type: series detected from the
folder tree as a first-class type='manga' item, .cbz/.cbr chapters stay
readable ebook items linked via a new manga_chapters table, browse shows series
cards, enrichment targets the series item at content level 'manga'. Hands off to
a follow-on plugin spec for the manga metadata source.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* docs: implementation plan for manga library type (host)

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(scanner): manga filename index/volume parser

* feat(scanner): manga series-name-from-folder detection

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* docs(plan): align manga DB/scanner tasks to scanner pure-planner pattern (no test-DB)

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* test(scanner): manga parser corpus regression

Add TestParseMangaIndexCorpus — 36 real-world scanlation filenames
covering bare chapter, decimal chapter, v/vol-prefix volume, and
c/ch-prefix chapter patterns; asserts <5% miss rate.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* feat(db): manga_chapters link table

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* feat(scanner): manga_chapters repository + pure chapter-write mapping

Adds mangaChapterWrite (pure, unit-tested), upsertMangaChapter, and
listMangaChapters following the ebook/audiobook thin-SQL pattern.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* feat(scanner): recognize manga library type

Add isMangaLibraryType helper (unexported, matching the style of
isEbookLibraryType / isAudiobookLibraryType) with a corresponding
TestIsMangaLibraryType unit test.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* feat(api): manga library content level

Map library type "manga" to content level ["manga"] in
metadataContentLevelsForLibraryType so that seedDefaultChain seeds a
manga-level metadata provider chain when a manga library is created.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* feat(scanner): route manga libraries to a manga scan path

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(scanner): group manga chapters under a manga series item

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(scanner): give manga series item a library membership so it browses

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(catalog): browse manga libraries as series

Accept "manga" as a valid media_scope so a manga library browses only its
type='manga' series items; the per-chapter type='ebook' items are naturally
excluded because MediaScopeItemTypes("manga") expands to {"manga"}. Add the
manga default library sections (scoped to media_scope='manga') so the library
feed shows series cards. Refresh the two media_scope validation error messages.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(catalog): manga series detail lists chapters

For a type='manga' item, attach its chapters to the detail response via a new
MangaDetailExtension. fetchMangaChapters joins manga_chapters to media_items on
the chapter content ID, scopes to the series, and orders by chapter_index
(NULLS LAST) then sort_title — matching the scanner's chapter ordering.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(web): manga detail types + library browse scoping

Add MangaChapter/MangaDetailExtension TS types mirroring the host
catalog structs, wire manga? onto ItemDetail, and admit "manga" as a
QueryDefinition.media_scope. Scope manga libraries to media_scope=manga
in browse (host expands it to type=manga series items) while reusing the
ebook sort universe via getLibrarySortRelevanceScope. Add isMangaLibraryType.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(web): manga series detail with volume-grouped chapter list

Add MangaContent detail view: a DetailHero series header plus a chapter
list grouped by volume. groupMangaChapters (pure, unit-tested) buckets
chapters by their volume token, orders chapters within a group by
chapter_index (nulls last) and orders groups by their minimum index;
loose (volume-less) chapters collapse into a trailing "Chapters" group.
Each chapter links to the existing ebook reader by content_id alone
(file_id is optional — the reader resolves the file server-side), reusing
buildMediaPlayHref. Admit "manga" into ItemDetail.type and wire the
detail switch. Continue-reading is deferred (needs per-chapter progress
fan-out / a last-read timestamp not in the current payload).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(web): handle manga in playable-type + collection filter-scope unions

Adding "manga" to the shared ItemDetail["type"] and
QueryDefinition["media_scope"] unions leaked into consumers with narrower
local types, breaking the production tsc build. Fixes:

- mediaNavigation: admit "manga" into PlayableMediaType. Manga series are
  not directly playable (you open the detail page and read a chapter,
  itself an ebook item), so buildMediaPlayHref falls through to the item
  href for them, like series/season.
- FilterRuleEditor: add "manga" to FilterRuleMediaScope and relabel
  "watched" -> "Read" for manga as well as ebook (manga is read).
- CollectionGuidedRulesEditor: add "manga" to GuidedFormState.mediaScope,
  a "Manga" media-type option, ebook-like "Read Status" labels, and map
  manga -> ebook sort-relevance scope (manga has no dedicated sort scope).
- CatalogFilterBar (cascading leak surfaced after the above): add a
  "Manga" scope option and map manga -> ebook sort-relevance scope in both
  scope handlers.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(web): offer manga as a library type in the create dialog

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(scanner): strip scene-release junk from manga series names

Add cleanMangaSeriesName which repeatedly strips trailing parenthetical
groups (year, year-range, Digital, release-group tags) then trims any
dangling dash, so folder names like "404 Demons (Digital) (Oak)" resolve
to "404 Demons". Wire it into mangaSeriesFromPath so both the series
title and the mangaSeriesGroupKey identity key use the cleaned value.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(web): flat volume/chapter manga list; nest only multi-chapter volumes

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(scanner): parse manga index after stripping series-name prefix

Numbers inside a series title (e.g. "404 Demons", "365 Days to the
Wedding") were wrongly grabbed as the chapter number because
parseMangaIndex matched the first bare number in the full filename.
mangaIndexForFile now strips the series-name prefix before delegating
to parseMangaIndex, so only the number that follows the title is used.
reconcileMangaFile in manga_scan.go is updated to call mangaIndexForFile
instead of parseMangaIndex directly.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(scanner): stop missing-file reconcile from deleting manga series items

Manga series items are file-less virtual parents; the shared
ReconcileFolderMembership swept them every scan because they have no
media_file. Exclude type='manga' from file-presence membership reconciliation,
and add a manga-scan step that deletes only series with zero remaining chapters.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(ebooks): exclude manga chapters from individual ebook enrichment

Manga chapters are type='ebook' parts of a series; the ebook enrichment sweep
was searching each one against book sources (Gutenberg/Anna's/etc.) and failing
in a pointless storm. Exclude items with a manga_chapters link; series-level
enrichment is handled separately.

* docs: design spec for manga metadata plugin + series enrichment (sub-project 2)

New silo-plugin-manga-metadata (AniList, high-confidence matching) + a host
MangaEnricher for type='manga' series; default-enabled metadata source for manga
libraries.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* docs: implementation plan for manga metadata plugin + series enrichment

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(db): manga_enrichment_state table

Mirrors ebook_enrichment_state: dedicated failure counter for the manga
enrichment sweep so it does not contend with media_items.refresh_failures.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* feat(manga): series enricher (claims type='manga', resolves manga chain)

* feat(manga): sync_manga_metadata task + enricher wiring

* feat(catalog): expose manga chapter/volume counts in browse

Add manga_chapter_count and manga_volume_count to browse cards so the
frontend can render a Vols N / Ch N chip on manga series. The counts come
from two index-backed correlated subqueries over manga_chapters in the
browse SELECT (mangaCountColumns), scanned positionally before added_at and
nilled out for non-manga rows. Threaded through models.MediaItem and exposed
on the itemListResponse JSON card.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(sections): scope manga home recent sections to type=manga series

A manga library mixes type='manga' series with type='ebook' chapters, so
the auto-generated home 'Recently Added/Released in <Library>' rows surfaced
the junk chapter filenames. Add GeneratedHomeLibraryRecentConfigScoped which
emits the modern QueryDefinition shape (library_ids + media_scope) so a manga
library's generated home rows filter to type='manga' only. Other library
types are unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(catalog): exclude manga chapters from browse/section/search surfaces

Manga CHAPTER items (type='ebook' rows linked into a type='manga' series
via manga_chapters) were leaking into catalog browse, section resolution,
and search as standalone items showing junk filenames. They are internal
sub-units of the series and only the series should appear.

There is no single shared item-listing chokepoint: browse, the query/preview
executor, and search each build their own WHERE. Add a shared, index-backed
anti-join predicate (manga_chapters.chapter_content_id is the PK) via
mangaChapterExclusionWhere and wire it into all three builders. By-id fetch
paths that legitimately resolve chapters (ebook reader, continue-reading,
series detail chapter list) use separate queries and are unaffected.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(scanner): use #NN as the manga volume for Vol.YYYY #NN releases

mangaVolYearIssue early-return was returning the year token (e.g. "Vol.2003")
as the volume label, which the frontend couldn't prettify to "Volume N".
Now returns "v<issue>" (e.g. "v04") so the existing frontend regex ^v?(\d+)$
renders it as "Volume 4" correctly.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* feat(web): manga count chip on posters

Add an optional manga_chapter_count / manga_volume_count to the browse
item type and render a top-right "Vols N" / "Ch N" chip on ItemCard,
strictly gated on type==='manga'. The label prefers "Vols" when the
volume count dominates, "Ch" otherwise; the chip is hidden when the
chapter count is missing or non-positive. No other card type renders it.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(web): manga reader back returns to series (no loop)

The ebook reader's back action defaulted to the chapter's own item
detail (/item/<chapter>), whose back returned to the reader — an
infinite loop for manga chapters. The reader now honors an explicit
backTo search param when present, navigating there instead. Absent for
normal ebooks, so their back behavior is unchanged. Only manga chapter
rows pass backTo, keeping the fix manga-only.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(web): manga chapter row actions (read/mark-read/download)

Each manga chapter/volume row now offers Read (the existing reader link,
now carrying a backTo to the series), Mark-read (the shared watched-state
mutation per chapter content_id), and Download (lazily fetches the
chapter's file versions on demand and opens the shared
DownloadVersionPicker, gated on user.download_allowed). The
volume-unit / loose-chapter / section structure from buildMangaList is
unchanged. Scoped to MangaContent only; EbookContent is untouched.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(web): validate reader backTo param is a safe in-app relative path

Prevents open-redirect / javascript:-URI XSS from a crafted ?backTo= URL.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(catalog): include per-chapter read state in manga detail

Manga chapters are ebook items, so a chapter is "read" when the viewer's
ebook_reader_progress row crosses the finished threshold. fetchMangaChapters
now LEFT JOINs that table scoped to the AccessFilter's user_id/profile_id and
exposes a per-chapter Read bool on MangaChapter, threaded through
buildMangaExtension. The detail payload previously carried no read state, so
the row toggle always started unread.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(web): manga rows reflect read state on load

MangaChapter now carries an optional read flag from the detail payload, and
MangaRow seeds its mark-read toggle from chapter.read instead of always
starting unread. The optimistic toggle + shared watched mutation are
unchanged; only the initial value is seeded.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(sections): exclude manga chapters from recently-added/released/random + other library-listing sections

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* feat(sections): manga recently-added/released cards show the latest volume's cover

* fix(manga): keep enrichment honest about no-match vs enriched, batch 50->200

- sweep stats now separate enriched / no_match / failed: a stamped no-match
  was counted (and logged) as an enrichment, which masked a collapse of the
  real match rate during the backfill
- batch size 50 -> 200 (SILO_MANGA_ENRICH_BATCH overrides): with the plugin
  serving GetMetadata from its search cache an item costs one rate-limited
  AniList request, so a sweep still fits the 5-minute task interval

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

* fix(manga): size enrich batch to the 5-minute interval at AniList's real budget

140 items x ~2.1s/request fits the interval; an overlong sweep makes the task
manager drop the next trigger and the effective rate falls below the AniList
budget.

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

* fix(catalog): manga count chip data missing from library browse

manga_chapter_count/manga_volume_count were only added to BrowseRepository,
but /library/{id}?tab=library flows through previewQuerySource ->
QueryExecutor.PreviewPage, which selects qualifiedListItemColumns and scans
with scanItems - so manga cards never carried the counts and the Vols/Ch
poster chip stayed hidden.

Append mangaCountColumns to the preview-page SELECT and scan them via a new
scanItemsWithMangaCounts (nil for non-manga rows, mirroring scanBrowseItems).
Extract listItemScanDests so the three scan variants share one destination
list instead of duplicating the 48-column scan.

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

* feat(web): manga chip reads 'X Volumes · X Chapters', menu verbs say Read

- chip: show distinct-volume and loose-chapter counts side by side instead
  of the single 'Vols N'/'Ch N' heuristic; mangaCountColumns now counts
  DISTINCT volume tokens (rows sharing a volume are one volume) and only
  un-volumed rows as chapters
- watched-state labels: type='manga' fell through to the video default, so
  the card dot menu and detail page said 'Mark Watched' - manga now uses
  the ebook reading verbs (Mark Read / Mark Unread, 'Marked as read' toast)
- format MangaContent.test.tsx (pre-existing prettier miss)

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

* feat(manga): backdrop enrichment - banner hero art + backdrop-only backfill

- cache remote backdrops like posters (cacheRemoteImages generalizes the
  poster-only path; failures keep the provider URL, which still renders)
- claim arm for enriched items missing a backdrop: fetched by stored
  provider ID (search skipped - no rate spend, no re-match risk) and only
  the backdrop is written; stamping after the attempt keeps banner-less
  series from being re-claimed every sweep
- backfill = one-time SQL clearing last_refreshed for poster-set/
  backdrop-empty manga

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

* feat(manga): reading-loop UX - continue CTA, next chapter, series-aware cards, file details

Fixes the four high-priority findings from the manga UX review plus a
file-inspector request:

- H1: series hero gets a Continue / Start Reading / Read Again CTA
  targeting the first unread chapter (firstUnreadChapter over the ordered
  list), plus an overflow menu (View Details, admin Refresh Metadata)
- H2: the reader resolves its owning manga series (chapter detail now
  carries series_id/series_title) and offers next-chapter navigation: a
  header next button and an end-of-book floating CTA at >=99.5% progress;
  back defaults to the series even without a backTo param
- H3: chapter rows show a persistent read check + muted title, and the
  mark-read mutation carries series_id so the series detail cache
  invalidates (read states no longer revert on revisit)
- H4: continue-reading cards for manga chapters present the series:
  sections payload resolves chapter->series linkage, the card heading/image
  link to the series, and meta lines launch the reader
- View Details: manga series menus (card dot menu + detail overflow) open
  a file inspector showing folder paths and per-chapter file names/sizes
  via GET /catalog/items/{id}/manga-files; paths are stripped for viewers
  without file-path visibility (item-versions policy)

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

* feat(manga): UX mediums - richer detail page, smarter list, manga sort scope

Second batch from the manga UX review (M1-M7):

- M1: multi-chapter volume sections are collapsible (fully read sections
  start collapsed) with sticky headers, and long series get a 'Jump to
  <next unread>' anchor above the list
- M2: the series hero shows the author line (HeroCrewLine learns Author
  credits with person links; DetailHero now renders crewLine and genre
  chips independently) and Volumes/Chapters badges
- M3: browse-card count chip abbreviates to '12 Vol - 3 Ch' so it fits
  narrow cards without occluding covers
- M4: manga gets its own sort scope: Duration/Bitrate (meaningless for
  file-less series rows) disappear, reading labels (Date Read / Reads)
  apply, Author stays
- M5: global search labels manga results 'Manga' instead of the raw type
- M6: chapters carry the viewer's reading fraction; part-read rows show an
  inline progress bar + percent
- M7: chapter rows show the extracted cover thumbnail (presigned
  poster_url on the chapters payload) instead of a generic icon

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

* fix(manga): UX lows - volume token dedupe, comic reader chrome, empty-state hint

- buildMangaList buckets volumes by canonical numeric token so mixed
  release naming (v01 + 1) yields one Volume 1 instead of duplicates
- cbz/cbr readers start with the side panel closed and hide prose-only
  chrome (reading ruler, TTS, typography/font controls, hyphenation,
  writing mode) while keeping comic-relevant settings (theme, brightness,
  margin, right-to-left, spread, flow)
- manga empty state mentions chapters appear after the library scan

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

* feat(manga): publication status badge via new SDK status field

- vendor the unpublished plugin SDK (adds MetadataItem.status) under
  internal/compat/ with a relative go.mod replace, following the
  zishang520-webtransport-go convention; swap to the published module
  before the upstream PR
- map plugin status into MetadataResult.ShowStatus, persist it during
  manga enrichment, and show it as the hero status badge (show_status was
  already on the detail payload and MetadataBadges)

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

* feat(manga): generalize backdrop pass to secondary fields (backdrop + status)

The backdrop-only claim arm becomes a secondary-fields pass: enriched items
missing a backdrop and/or publication status are claimed, fetched by stored
provider ID, and only the missing secondary fields are written. Lets the
new status field backfill across the already-enriched library instead of
applying only to future enrichments.

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

* fix(metadata): merge ShowStatus through MergeMetadata/MergeGlobalMetadata

The new MetadataResult.ShowStatus never reached the accumulated result the
manga enricher persists from - the field-by-field merges didn't know it, so
the status backfill pass obtained nothing. Regression-tested on both paths.

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

* fix(manga): keep scanner identity IDs out of the metadata flow

filterMangaProviderIDs passed the scanner's manga_series identity row
through, so the search-skip-when-already-matched guard saw provider IDs on
every item and never searched: unmatched items went straight to a by-ID
fetch with no usable ID and were stamped as terminal no-match without a
single provider request (and the MangaDex fallback was never consulted).

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

* chore: gitignore docker-compose.override.yml (local deployment override)

The override unpublishes the bundled redis/postgres host ports
(ports: !override []). It is a per-deployment, local-only file: ignoring it
keeps a rebase from main and git clean -fd from disturbing it, and keeps it
out of any PR. Its accidental absence once exposed Redis to the internet.

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

* fix(manga): code-review fixes — no-match guard, sort comparator, volume-count consistency

- enrichWithProviders: set accumulator.HasMetadata after a provider result
  merges (MergeMetadata doesn't propagate it). Without this, a confident
  match carrying only genres/authors/status/year but no cover and no overview
  failed the no-match check and was discarded + terminally stamped.
- byChapterIndex: both un-indexed chapters yield POSITIVE_INFINITY, so the
  subtraction was Infinity-Infinity=NaN (Array.sort treats NaN as 0, leaving
  order undefined). Compare explicitly for a stable order.
- MangaContent volume/chapter badges: derive counts from the rendered
  buildMangaList entries (which canonicalize v01 ≡ 1) instead of raw distinct
  volume tokens, so the badge can no longer say '2 Volumes' over one row.

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

* docs(manga): clarify the enrichment claim's secondary arm is admin-reset-only

The secondary arm (poster present, backdrop/status missing) requires
last_refreshed IS NULL, so it is only reachable when an operator resets
last_refreshed to backfill a newly-added field — not an automatic periodic
re-check (which would re-fetch banner-less series every sweep). Documents the
intent so it does not read as dead code.

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

* fix(manga): collapse continue-reading chapters per series; batch provider-id lookup

- Continue Reading now collapses multiple in-progress chapters of the same
  manga into one card (most recently read kept), mirroring the episode→series
  collapse. The reading section resolves chapter→series linkage into itemMeta
  (applyMangaChapterSeriesMeta) and runs the shared
  collapseContinueWatchingSeriesCandidates, which the reading path previously
  skipped.
- claimBatch resolves provider IDs for the whole batch in one query via the
  new ProviderIDRepository.GetByContentIDs (content_id = ANY), replacing the
  per-item GetByContentID N+1.

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

* feat(web): manga publication-status chip on browse cards + more legible chips

- Color-coded publication status pill (Ongoing/Completed/Hiatus/Cancelled/
  Upcoming) in the manga card's top-left corner, mirroring the vol/chapter
  count chip top-right. Strictly manga-gated; show_status was already on the
  browse payload.
- New .glass-chip (78% surface vs glass-subtle's 40%) for the manga count +
  status pills so the labels stay legible over busy cover art.

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

* build(manga): depend on published silo-plugin-sdk v0.7.0

Replace the vendored internal/compat/silo-plugin-sdk copy with a normal
dependency on the published SDK module at v0.7.0, which adds
MetadataItem.status (publication/airing status) consumed by the manga
status badge at internal/metadata/plugin_provider.go.

- go.mod: pin v0.7.0, drop the local-path replace directive
- remove the vendored internal/compat/silo-plugin-sdk tree
- Dockerfile: drop the vendored-SDK COPY
- strip the manga design docs/plans from docs/superpowers (internal)

Requires Silo-Server/silo-plugin-sdk#4 merged and tagged v0.7.0.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(manga): exclude chapters from the matcher's unmatched-item lister

Manga chapters are type='ebook' items that stay status='pending' by
design - provider metadata lives on the type='manga' series item. The
scan-final RetryUnmatchedItemsByFolderAndPathPrefix listed all of them
and ran a rate-limited ebook-plugin search per chapter: 31,564 chapters
x ~1s = 8h46m appended to a 2-minute manga library scan (observed
live), every one a guaranteed no-match. Earlier runs never survived to
completion, so the library's last_scanned_at stayed NULL forever.

Add the same manga_chapters NOT EXISTS guard the ebook enricher's
claim query already uses. Verified live: the same library now scans in
27s with retried_items=0.

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

* fix(scanner): never probe-repair ebook/comic files (ebook+manga detail-page killer)

NeedsCriticalProbeRepair was always true for BaseType 'ebook' files (epub, pdf,
cbz, cbr — incl. manga chapters): buildEbookMediaFile leaves ProbeUpdatedAt nil
and they have no audio/video, so probeEnsurer.Ensure spawned ffprobe per file on
every detail/watch load and never converged (ffprobe errors on zip/rar, result
never persisted). Short-circuit probe-repair for ebook base type — they're read
directly and never use the transcode/playback probe pipeline.

SHARED fix: benefits both the ebooks and manga library types.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* perf+fix(ebooks): parallelize detail extension + preserve finished read-state

- buildEbookExtension ran its 3 related-content queries (series, also-by-author,
  similar) sequentially; run them concurrently like buildAudiobookExtension so
  ebook detail latency is the slowest query, not their sum.
- PGEbookReaderProgressStore.Upsert did an unconditional SET progress=EXCLUDED;
  a routine autosave (e.g. reopening a finished book) could drop it below the
  0.9 finished threshold and silently un-mark it read (and clear the manga
  chapter checkmark, which rides on the same row). Guard: once finished,
  progress only moves on an explicit unread (row delete); below threshold it
  tracks freely.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* perf(manga): batch chapter presign, index volume counts, quiet scan log

- fetchMangaChapters presigned each chapter poster individually; a long-running
  series has hundreds of chapters. Batch them in one PresignImageURLs call, and
  add the missing rows.Err() check (was silently returning partial lists).
- The browse manga count chip's count(DISTINCT volume) subquery wasn't covered
  by manga_chapters_series (series_content_id, chapter_index); add
  idx_manga_chapters_series_volume (series_content_id, volume) so both count
  subqueries are index-only.
- Downgrade the per-chapter "manga scan: indexed" log from Info to Debug (one
  line per .cbz; the 500-file progress log already covers operator visibility).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

* fix(manga): address PR #138 code-review findings

Folds PR #142 into the manga branch (already done via fast-forward) and
remediates the issues surfaced in the #138 code review.

Correctness:
- Preserve the scanner's manga_series identity anchor through enrichment.
  ReplaceByContentID's DELETE was unconditional, so the first successful
  enrichment wiped the manga_series provider-id row the scanner relies on
  for idempotency, causing duplicate series + metadata loss on the next
  scan. excludedProviderIDs now also means "not deleted", and the DELETE
  preserves those rows. (internal/catalog/provider_id_repo.go)
- Fall back to the series cover when the latest chapter has no poster.
  Poster columns default to '' (not NULL), so the manga series-card poster
  override blanked cards via a plain COALESCE; wrap operands in NULLIF.
  (internal/sections/fetcher.go)
- Keep backTo a real query param on reader links when libraryId is absent.
  It was string-concatenated with '&', producing a malformed URL on
  deep-links; route it through the query helper instead.
  (web/src/lib/mediaNavigation.ts, EbookReader.tsx, MangaContent.tsx)

Quality:
- Hide manga chapters from favorites/watchlist browse, matching the
  exclusion enforced on every other listing surface.
  (internal/catalog/favorites_browse.go)
- Centralize the manga chapter exclusion predicate into a single exported
  catalog.MangaChapterExclusionWhere, removing four duplicated copies.
  (catalog, sections, ebooks)
- Skip the two manga count subqueries on browse scopes that cannot contain
  manga (non-manga type filters), substituting NULL placeholders.
  (internal/catalog/browse.go)
- Normalize provider publication status (AniList/MangaDex/SDK variants)
  into a stable label set so show_status carries one manga value-domain.
  (internal/manga/enrichment.go)

Adds unit tests for the poster NULLIF contract, browse gating, and status
normalization.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* chore: regenerate go.sum after rebase onto main

Drops stale silo-plugin-sdk v0.6.0 and other leftover hashes from the
intermediate rebased states; go.mod is now on the published v0.7.0 tag.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

* fix(scanner): adapt manga scan to ebookFileShouldSkip 3-value signature

main changed ebookFileShouldSkip to also return the existing content ID;
the manga scan path only needs the unchanged flag, so discard the new
return. Resolves a silent semantic conflict from the rebase onto main.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

---------

Co-authored-by: Silo Server Developer <[email protected]>
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
@zZebrahz zZebrahz removed this from the v1.0 milestone Sep 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v1.0 Silo v1 scope - auto-adds to the Silo v1 project

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants