Repository navigation
feat(ebooks): first-class ebook libraries, scanner, and reader - #124
Conversation
* feat(ebooks): extract local covers during scan * fix(ebooks): read nullable poster paths during cover scan * fix(catalog): coalesce nullable media artwork fields * fix(ebooks): group sibling formats by book identity * fix(ebooks): tolerate legacy ebook metadata encodings * fix(ebooks): decode PDF hex metadata strings * fix(ebooks): harden local cover extraction and format grouping Address review findings on the local cover scan: - Restrict generic sidecar covers (cover.jpg, folder.png, ...) to single-book directories, always accept images named after the book file, and apply exactly one cover per reconcile with sidecar taking precedence over the embedded cover. - Replace the read-then-write poster update with an atomic conditional UPDATE (ItemRepository.SetLocalPoster) so provider/admin artwork is never clobbered by concurrent writers, and refresh locally owned posters when the extracted cover bytes change (thumbhash compare). - Preserve UTF-8 PDF Info strings (including a UTF-8 BOM) instead of forcing everything through Windows-1252; the cp1252 fallback now only applies to non-UTF-8 bytes. - Select EPUB covers by manifest media-type with properties="cover-image" outranking the EPUB2 meta name="cover" id, so XHTML cover pages no longer shadow the real image. - Order CBZ pages naturally (2.jpg before 10.jpg, ch2/ before ch10/) when picking the cover page, via a single O(n) min-scan. - Bump the ebook content group key scheme to version 2 and reprocess rows written under older versions so pre-existing libraries gain sibling-format grouping instead of accumulating duplicates. - Group different formats only (a same-format sibling with colliding sparse metadata stays a separate item) and stop a joining sibling's embedded metadata from overwriting a provider-matched item. - Decode any IANA-labelled OPF/FB2 XML charset (windows-1251, koi8-r, shift_jis, ...) via x/net/html/charset, and wire the charset reader into FB2 parsing which previously had none. - Strip the full .fb2.zip double extension from filename-derived titles and group keys. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: rxwatcher <rxwatcher@users.noreply.github.com> Co-authored-by: Quick <31828688+Quick104@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* feat(ebooks): extract local covers during scan * fix(ebooks): read nullable poster paths during cover scan * fix(catalog): coalesce nullable media artwork fields * fix(ebooks): group sibling formats by book identity * fix(ebooks): tolerate legacy ebook metadata encodings * fix(ebooks): decode PDF hex metadata strings * feat(ebooks): add reader profiles and ruler * fix(ebooks): address reader ruler and profile review findings - skip renderer setStyles/render when computed styles and attributes are unchanged, so ruler position updates no longer re-style the book view - drag the ruler via a local draft that commits on release, with the surface rect cached at pointer-down - migrate font values persisted before the generic stacks (Inter, Georgia, Merriweather, legacy serif) so the font select never renders blank, with a Custom fallback option for unknown values - make the ruler band click-through and move dragging to a dedicated keyboard-accessible slider handle so links and text selection keep working under the band - share font stacks between options and profiles via READER_FONT_STACKS - surface the active reading profile, move presets to the top of the settings panel, and drop the redundant profile button aria-labels Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(ebooks): resolve prefer-const lint error in readest document lib `pnpm run lint` failed on the branch because `direction` is never reassigned in getDirection; split the destructure so only the reassigned `writingMode` stays mutable. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: rxwatcher <rxwatcher@users.noreply.github.com> Co-authored-by: Quick <31828688+Quick104@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Brings the ebook integration branch up to date with main (audiobook library redesign, continue-watching rework and card affordances, quic-go bump, jellycompat fixes). Conflict resolutions favor main's generalized mechanisms and register ebooks with them: - media scope validation goes through IsValidMediaScope (now including "ebook" alongside main's "video" group scope), in Go and in the web filter/search types - continue-watching uses main's typed rails; reading-type sections pull resume points from ebook_reader_progress and the ebook library default section is wired to ContinueTypeConfig(ContinueTypeReading) - item_repo keeps main's derived select-list machinery (itemColumnExpr) and both poster accessors (GetPoster/SetLocalPoster for ebook covers, GetPosterPath for audiobook covers) - web cards/hero/watch-tonight adopt main's buildMediaPlayHref helpers, which now route ebooks to /reader/ebook and encode content ids; ebook affordances (BookOpen icon, Read verb, percent-read subtitle) carry over onto main's reworked components - LibraryForm ebook support ported into main's refactored useLibraryForm/libraryTypes modules Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The previous commit aea8d85 already contains the fully resolved result of merging main into this branch, but it was created without merge parentage (a stash during conflict resolution dropped MERGE_HEAD). This empty -s ours merge records main as an ancestor so the eventual PR to main does not re-conflict; the tree is unchanged. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
📝 WalkthroughWalkthroughThis PR adds ebook reader APIs and persistence, ebook-aware catalog and recommendation behavior, ebook scanning/enrichment support, and frontend routing plus UI updates for ebook content. ChangesEbook parity rollout
Sequence Diagram(s)sequenceDiagram
participant Client
participant Router
participant ItemsHandler
participant EbookReaderHandler
participant EbookReaderProgressStore
Client->>Router: request /ebooks and item state
Router->>EbookReaderHandler: route ebook reader request
Router->>ItemsHandler: inject ebook progress store
ItemsHandler->>EbookReaderProgressStore: resolve progress/user state
EbookReaderHandler->>EbookReaderProgressStore: get/save config, progress, annotations
Estimated code review effort🎯 5 (Critical) | ⏱️ ~90+ minutes Possibly related PRs
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
|
foliate-js is a file:vendor/foliate-js dependency, so pnpm install needs the vendor directory before the lockfile install layer. The production Dockerfile already copies it; the dev image was missed, breaking make dev-deploy with ENOENT on /app/web/vendor/foliate-js. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9b8e725567
ℹ️ 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".
| if isEbookLibraryType(folder.Type) { | ||
| if err := s.ScanEbookFolder(watchCtx, folder); err != nil { | ||
| return nil, err | ||
| } | ||
| return &ScanResult{}, nil |
There was a problem hiding this comment.
Reconcile removed ebook files during scans
In the ebook branch, a folder scan returns immediately after indexing current candidates and never runs the missing-file / membership reconciliation that the movie path runs later in scanPaths. For ebook libraries, deleting or moving an ebook (including the case where the root becomes empty, since scanEbookPaths returns nil with zero candidates) leaves the old media_files and library membership in the DB, so removed books continue to appear in the catalog until manually cleaned up.
Useful? React with 👍 / 👎.
| metadata := req.Metadata | ||
| if len(metadata) == 0 { | ||
| metadata = json.RawMessage(`{}`) | ||
| } |
There was a problem hiding this comment.
Preserve metadata on partial annotation updates
When a PATCH omits metadata, this helper replaces the missing field with {}, and the SQL update always assigns metadata = $12::jsonb; as a result, any partial annotation edit such as changing only note or color silently erases existing metadata. Treat an omitted metadata field as “leave unchanged” instead of defaulting it to an empty object for updates.
Useful? React with 👍 / 👎.
| } | ||
|
|
||
| export function ebookReaderProgressQueryKey(contentID: string | undefined) { | ||
| return ["ebook-reader-progress", contentID] as const; |
There was a problem hiding this comment.
Include profile in ebook progress cache key
The reader progress query key is only contentID, but the server stores progress per profile and the profile-switch cache cleanup in QueryCacheManager does not remove ebook-reader-progress. After switching household profiles, item detail pages can immediately render the previous profile's saved percentage/file choice from React Query cache before the background refetch finishes, leaking and briefly using another profile's reading state.
Useful? React with 👍 / 👎.
| if (type === "ebook") { | ||
| return appendQuery(`/reader/ebook/${encodeURIComponent(contentId)}`, { libraryId }); |
There was a problem hiding this comment.
Carry saved file id into reading links
For ebook continue-reading surfaces, this link omits the saved file_id, so EbookReader falls back to its preferred version (EPUB first) and FoliateBookReader only restores progress when the saved progress belongs to that same file. If a user was reading a different format/version of a multi-file ebook, Continue Reading opens the wrong file and starts at the beginning instead of resuming.
Useful? React with 👍 / 👎.
| WHERE mi.type = 'ebook' | ||
| AND (mi.poster_path IS NULL OR mi.poster_path = '') | ||
| AND mi.last_refreshed IS NULL |
There was a problem hiding this comment.
Run enrichment for ebooks with local covers
Because this batch only claims ebooks whose poster_path is empty, any EPUB/CBZ/etc. where the scanner extracted an embedded or sidecar cover is skipped by the enrichment task even when last_refreshed is still NULL. In that common case the item never gets provider metadata such as overview, genres, people, or provider IDs; claim based on refresh/metadata state rather than requiring a missing poster.
Useful? React with 👍 / 👎.
| INSERT INTO media_item_provider_ids (content_id, provider, provider_id, item_type) | ||
| VALUES ($1, 'isbn', $2, 'ebook') | ||
| ON CONFLICT DO NOTHING |
There was a problem hiding this comment.
Update ISBN provider IDs when tags change
If an ebook file is rescanned after its embedded ISBN is corrected, this insert conflicts on the existing (content_id, provider) row and DO NOTHING leaves the old ISBN in media_item_provider_ids. Since enrichment and provider lookups consume these IDs, the item can keep matching/searching by a stale ISBN until the row is manually fixed; update the provider_id on the content/provider conflict instead of ignoring it.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Actionable comments posted: 12
🧹 Nitpick comments (9)
migrations/sql/20260608000300_ebook_reader_state.sql (1)
3-10: 💤 Low valueConsider adding a
created_attimestamp toebook_reader_config.The
ebook_reader_configtable hasupdated_atbut nocreated_atcolumn. While not critical if only the last-update time matters, addingcreated_atwould improve auditability and align with theebook_reader_annotationstable schema (which has both).📅 Optional: Add created_at column
CREATE TABLE ebook_reader_config ( user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, profile_id TEXT NOT NULL, content_id TEXT NOT NULL REFERENCES media_items(content_id) ON DELETE CASCADE, config JSONB NOT NULL DEFAULT '{}'::jsonb, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), PRIMARY KEY (user_id, profile_id, content_id) );🤖 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 `@migrations/sql/20260608000300_ebook_reader_state.sql` around lines 3 - 10, Add a created_at TIMESTAMPTZ column to the ebook_reader_config table to match ebook_reader_annotations and improve auditability: alter the CREATE TABLE for ebook_reader_config to include created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), ensuring the schema includes both created_at and updated_at for records (keep PRIMARY KEY on (user_id, profile_id, content_id) and the existing FK constraints on users(id) and media_items(content_id)).internal/api/handlers/user_state_test.go (1)
22-35: ⚡ Quick winAdd a boundary assertion around the completion cutoff
Please add a case at/near the completion threshold (e.g.,
0.90and just below) to lock the played/unplayed boundary and prevent regressions in the heuristic.🤖 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/user_state_test.go` around lines 22 - 35, Add boundary test entries around the completion cutoff in the progress map used by the test: create two new EbookReaderProgress entries (e.g., "ebook-cutoff-below" with Progress 0.899 and "ebook-cutoff-at" with Progress 0.90) alongside the existing "ebook-complete" and "ebook-progress" entries, and update the assertions in the test that inspects played/unplayed classification to expect the below entry to be unplayed and the at/above entry to be played; reference the existing progress map and the EbookReaderProgress struct to locate where to add these cases.internal/taskmanager/tasks/sync_ebook_metadata.go (1)
52-52: ⚡ Quick winConsider handling the JSON marshal error.
While
json.Marshalis unlikely to fail for a simplemap[string]int, ignoring the error could mask future issues if the result structure becomes more complex.🛡️ Proposed fix to handle marshal error
- result, _ := json.Marshal(map[string]int{"items_enriched": enriched}) + result, err := json.Marshal(map[string]int{"items_enriched": enriched}) + if err != nil { + return fmt.Errorf("marshal result: %w", err) + } progress.SetResultData(result)🤖 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/taskmanager/tasks/sync_ebook_metadata.go` at line 52, Replace the ignored marshal error by capturing it (result, err := json.Marshal(map[string]int{"items_enriched": enriched})) and handle err immediately: if err != nil return fmt.Errorf("marshal enriched count: %w", err) (or propagate/log via the function's existing logger), so the code using result never proceeds with a nil/invalid value; update imports to include fmt if needed and keep the variable names result and enriched.internal/api/handlers/ebook_reader.go (1)
853-891: 💤 Low value
ListByContentIDsreturnsnilinstead of empty map for early-exit cases.When
userID <= 0,profileID == "", orlen(contentIDs) == 0, the method returnsnil, nil. Callers expecting a non-nil map would encounter nil pointer dereference. Consider returning an empty map for consistency with successful but empty queries.Suggested fix
func (s *PGEbookReaderProgressStore) ListByContentIDs(ctx context.Context, userID int, profileID string, contentIDs []string) (map[string]EbookReaderProgress, error) { if s == nil || s.pool == nil { return nil, fmt.Errorf("ebook reader progress store is not configured") } if userID <= 0 || profileID == "" || len(contentIDs) == 0 { - return nil, nil + return map[string]EbookReaderProgress{}, nil }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/api/handlers/ebook_reader.go` around lines 853 - 891, The early-exit branch in ListByContentIDs currently returns nil, nil for cases userID <= 0, profileID == "" or len(contentIDs) == 0 which can cause callers to panic; change that branch to return an empty map (e.g. make(map[string]EbookReaderProgress)) and nil error so callers receive a non-nil progressByContentID; keep the existing error return for the s == nil || s.pool == nil check unchanged.web/src/app.css (1)
123-133: ⚡ Quick winConsider a more maintainable approach for blur removal.
The current implementation hardcodes specific Tailwind blur utility class names. If Tailwind adds new blur variants (e.g.,
.blur-4xl,.backdrop-blur-xl), they won't be covered.A more robust approach would be to use a wildcard attribute selector or Tailwind plugin:
body.eink [class*="blur"], body.eink [class*="backdrop-blur"] { filter: none !important; backdrop-filter: none !important; }This targets any element with a class containing "blur" or "backdrop-blur", making it resilient to future Tailwind additions.
🤖 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 123 - 133, The current CSS explicitly lists blur utility selectors (e.g., body.eink .blur-3xl, body.eink .backdrop-blur-md) which is brittle; replace the hardcoded selector list with attribute selectors that match any class containing "blur" or "backdrop-blur" scoped under body.eink (e.g., use body.eink [class*="blur"] and body.eink [class*="backdrop-blur"]) so all current and future Tailwind blur/backdrop-blur utilities are covered, keeping the same declarations (filter: none !important; backdrop-filter: none !important;).internal/scanner/ebook.go (1)
212-215: ⚡ Quick winDead code:
looksLikeHTMLis defined but never called.This function is not referenced anywhere in the file. The description cleanup at line 164 uses an inline check instead. Remove to avoid confusion.
🗑️ Proposed removal
-func looksLikeHTML(value string) bool { - value = strings.TrimSpace(value) - return strings.Contains(value, "<") && strings.Contains(value, ">") -}🤖 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/scanner/ebook.go` around lines 212 - 215, The function looksLikeHTML is dead code (defined but never used); remove the looksLikeHTML function declaration from internal/scanner/ebook.go and ensure any logic relying on an inline check (as used in the description cleanup) remains unchanged—delete the looksLikeHTML function to avoid confusion and unused symbols.web/src/components/WatchTonightCard.test.tsx (1)
12-45: ⚡ Quick winConsider using Testing Library queries instead of
renderToStaticMarkupfor client component tests.The test uses
renderToStaticMarkupand string matching (toContain) to verify links and text. Testing Library's semantic queries would be more maintainable and aligned with user-facing behavior:it("links ebook cards to the reader and shows percent read", () => { render( <MemoryRouter> <WatchTonightCard item={{...}} onPlay={() => {}} /> </MemoryRouter> ); expect(screen.getByRole("link", { name: /read a reader/i })) .toHaveAttribute("href", "/reader/ebook/ebook%201"); expect(screen.getByText("57% read")).toBeInTheDocument(); expect(screen.queryByText(/min left/i)).not.toBeInTheDocument(); });🤖 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/WatchTonightCard.test.tsx` around lines 12 - 45, Replace the string-based renderToStaticMarkup assertions in WatchTonightCard.test.tsx with Testing Library render and semantic queries: import and use render (from `@testing-library/react`) instead of renderToStaticMarkup, render the MemoryRouter+WatchTonightCard the same way, then replace markup string assertions with screen.getByRole("link", { name: /.../ }) checks for the reader link (use the accessible link text to locate the reader link for item with content_id "ebook 1") and screen.getByText("57% read") to assert progress, and use screen.queryByText(/min left/i) to assert the "min left" absence; keep the same props to WatchTonightCard and keep onPlay noop. Ensure you assert the link's href via toHaveAttribute("href", "/reader/ebook/ebook%201") and remove renderToStaticMarkup and toContain-based string checks.web/src/api/client.ts (1)
440-463: ⚡ Quick winExtract shared fetch logic to reduce duplication.
apiBlobduplicates the auth/refresh/error-handling flow fromapi()(lines 343-380) andapiDownload()(lines 405-438). Consider extracting a shared helper:async function fetchWithAuth( path: string, options: RequestInit, ): Promise<Response> { let headers = buildApiHeaders(options); let res = await fetch(`/api/v1${path}`, { ...options, headers }); if (res.status === 401 && getRefreshToken()) { if (!refreshPromise) { refreshPromise = attemptRefresh().finally(() => { refreshPromise = null; }); } const refreshed = await refreshPromise; if (refreshed) { headers = buildApiHeaders(options); headers["Authorization"] = `Bearer ${accessToken}`; res = await fetch(`/api/v1${path}`, { ...options, headers }); } } if (!res.ok) { throw apiClientErrorFrom(res.status, await parseApiError(res)); } return res; }Then simplify
apiBlobto:export async function apiBlob(path: string, options: RequestInit = {}): Promise<Blob> { const res = await fetchWithAuth(path, options); return res.blob(); }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/api/client.ts` around lines 440 - 463, apiBlob duplicates the auth/refresh/error-handling flow used by api() and apiDownload(); extract that logic into a shared helper (e.g., fetchWithAuth) that accepts (path: string, options: RequestInit) and returns a Response, reusing buildApiHeaders, refreshPromise/attemptRefresh, accessToken, apiClientErrorFrom and parseApiError; then change apiBlob to call fetchWithAuth(path, options) and return res.blob(), leaving existing behavior (401 refresh retry and error-to-apiClientError conversion) intact.internal/catalog/item_repo.go (1)
57-79: 💤 Low valueConsider escaping LIKE special characters in localPrefix.
The LIKE pattern
$4 || '%'(line 73) will match any poster_path starting withlocalPrefix, but iflocalPrefixcontains LIKE special characters like%or_, they won't be escaped and could cause unexpected matches. SincelocalPrefixis likely a controlled constant from internal scanner code, the risk is low, but defensive escaping would be safer.♻️ Optional: escape LIKE special characters
PostgreSQL doesn't have a built-in LIKE escape function, but you could:
- Document that
localPrefixmust not contain LIKE special characters- Add validation that
localPrefixdoesn't contain%or_- Use a different approach like
poster_path >= $4 AND poster_path < $4 || chr(255)for prefix matching (range scan)Given this is internal code with controlled input, documentation might be sufficient.
🤖 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/item_repo.go` around lines 57 - 79, The WHERE clause in SetLocalPoster uses "poster_path LIKE $4 || '%'" which will treat % and _ in localPrefix as wildcards; update SetLocalPoster's SQL to avoid LIKE-special-character issues—either validate/reject localPrefix containing '%' or '_' before calling SetLocalPoster, or replace the LIKE condition with a prefix range check such as "poster_path >= $4 AND poster_path < $4 || chr(255)" (and keep the other NULL/empty checks), and adjust parameter usage accordingly; ensure the change is made inside the SetLocalPoster method and that error handling and return semantics remain the same.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/api/handlers/items.go`:
- Around line 1015-1018: The current early return when
listEbookReaderProgressByContentIDs (and similarly failures from
listUserSortMetrics) errors out drops all non-ebook sort metrics; change the
handler so ebook-specific store failures are non-fatal: catch the error, log it
(include context like userID/profileID), set ebookProgressMap to an empty map
(or leave existing progressMap intact), and continue processing so
progress/date_viewed/plays sorting still use the user-store metrics; modify code
around listEbookReaderProgressByContentIDs and any listUserSortMetrics call to
avoid returning on transient ebook errors and ensure downstream code can handle
an empty ebookProgressMap.
In `@internal/api/handlers/user_state.go`:
- Around line 148-149: The code unconditionally indexes ebookProgressMap in the
user-state loop (case "ebook": state.Played =
ebookProgressMap[item.ContentID].Progress >= 0.9) but
resolveEbookProgressForUserStates can return nil; guard against a nil map or
ensure the resolver returns an empty map: either check ebookProgressMap != nil
before indexing and treat missing entries as zero progress, or change
resolveEbookProgressForUserStates to always return a non-nil map (e.g.,
make/return map[string]EbookProgress{} when prerequisites are missing) so the
assignment in the "ebook" case is safe.
In `@internal/catalog/catalog_resolver.go`:
- Around line 838-840: validateCatalogOverlayQuery currently allows field ==
"narrator" even when mediaScope == "ebook"; add a guard in
validateCatalogOverlayQuery to reject queries where field (or facet) is
"narrator" and mediaScope == "ebook" by returning ErrInvalidCatalogRequest (same
error used elsewhere) with a clear message indicating narrator is not available
for ebook scope; reference the mediaScope, field, validateCatalogOverlayQuery,
and ErrInvalidCatalogRequest symbols so the validation logic matches the runtime
check you already added.
In `@internal/ebooks/enrichment.go`:
- Around line 193-195: The SQL sweep currently limits candidates with "AND
mi.last_refreshed IS NULL" in the WHERE clause (the block beginning "WHERE
mi.type = 'ebook' AND (mi.poster_path IS NULL OR mi.poster_path = '') ..."),
which causes overview-only ebooks and transient-provider-failure cases to be
skipped; remove that strict last_refreshed IS NULL check and instead select rows
based on missing/empty metadata or an explicit retry policy (e.g., replace the
condition with something like "AND (mi.poster_path IS NULL OR mi.poster_path =
'' OR mi.overview IS NULL OR mi.provider IS NULL OR mi.last_refreshed IS NULL OR
mi.last_refreshed < now() - interval 'X')" so records with missing poster or
other metadata or older refresh timestamps are retried; apply the same fix to
the other analogous SQL blocks in enrichment.go that use the same last_refreshed
IS NULL predicate.
In `@internal/recommendations/repo.go`:
- Around line 1192-1216: GetEbookReaderProgressForUser is missing the same
user_history_hidden_items exclusion applied elsewhere; update the SQL in
GetEbookReaderProgressForUser so ebook_reader_progress rows for the given
userID/profileID exclude hidden content (same logic used by
GetWatchProgressForUser and watchedActivityCTE). Concretely, adjust the query
for Repo.GetEbookReaderProgressForUser to filter out content_id values present
in user_history_hidden_items for the same user_id and profile_id (either via a
NOT IN subquery or a LEFT JOIN ... WHERE user_history_hidden_items.content_id IS
NULL) so hidden ebook progress is not returned.
In `@migrations/sql/20260608000200_ebook_reader_progress.sql`:
- Around line 3-13: ebook_reader_progress currently has profile_id TEXT NOT NULL
but no foreign key to public.user_profiles, so deleting a user_profiles row
won't cascade; add a composite foreign key for (user_id, profile_id) referencing
public.user_profiles(user_id, id) ON DELETE CASCADE (matching other migrations)
and remove or adjust the existing PRIMARY KEY if needed to keep PRIMARY KEY
(user_id, profile_id, content_id) intact; update the CREATE TABLE for
ebook_reader_progress to include FOREIGN KEY (user_id, profile_id) REFERENCES
public.user_profiles(user_id, id) ON DELETE CASCADE.
In `@web/public/vendor/pdfjs/annotation_layer_builder.css`:
- Line 328: Replace the deprecated CSS property "word-wrap: break-word;" with
the standard "overflow-wrap: break-word;" in the same CSS rule (remove or
replace the existing word-wrap declaration so you don't leave a duplicate),
i.e., locate the declaration "word-wrap: break-word;" and change it to
"overflow-wrap: break-word;" to satisfy linters/CI.
In `@web/public/vendor/pdfjs/cmaps/ETenms-B5-H.bcmap`:
- Around line 1-3: The two CMap assets ETenms-B5-H.bcmap and ETenms-B5-V.bcmap
are corrupted (too small and missing CMap sections); re-vendor the correct files
from the exact PDF.js release/tag used by this project: download the
ETenms-B5-H.bcmap and ETenms-B5-V.bcmap from that PDF.js source, copy them into
the vendor cmaps location preserving binary encoding, replace the existing
files, and commit; after replacing, verify each file contains CMap markers like
begincmap/endcmap, codespacerange, bfchar/bfrange and that file sizes are
substantially larger than the current 101/172 bytes.
In `@web/public/vendor/pdfjs/text_layer_builder.css`:
- Line 19: The vendored CSS (text_layer_builder.css) is triggering Stylelint
errors; either update the Stylelint config to explicitly exclude the vendor
folder pattern (web/public/vendor/pdfjs/**) or add file-level Stylelint
suppression in text_layer_builder.css by inserting the appropriate top-of-file
disable marker and matching re-enable if needed (e.g., a file-scope disable for
all rules), ensuring you reference text_layer_builder.css and mirror the same
treatment for the other affected vendor files (the other PDF.js files listed in
the review).
In `@web/src/components/collections/CollectionGuidedRulesEditor.tsx`:
- Around line 191-194: The narrator rule guard is too strict—it's only matching
when normalized.media_scope === "audiobook" so narrator filters don't survive
editor instances scoped via libraryType. Update the condition in the case
"narrator" branch (and the similar check at the later occurrence around the
other narrator handling) to accept library-scoped audiobook editors as well
(e.g., allow normalized.media_scope === "audiobook" OR normalized.libraryType
indicates an audiobook library such as "audiobook" or starting with
"audiobook"), so existing narrator rules load and are preserved on save.
In `@web/src/components/ContinueWatchingCard.tsx`:
- Around line 135-136: The ebook progress display currently uses
Math.round(progressPercent) which can show 100% for in-progress items; change
the logic in the ContinueWatchingCard's ebook branch (the conditional using
card.type === "ebook" and variable progressPercent) to either use
Math.floor(Math.max(0, Math.min(progressPercent, 100))) or cap values below 100
at 99 (e.g., compute pct = Math.min(Math.floor(progressPercent), progressPercent
< 100 ? 99 : 100)) so unfinished ebooks never render as "100% read" until the
backend marks them complete.
In `@web/src/components/FilterRuleEditor.tsx`:
- Around line 42-59: getFilterRuleFieldOptions currently only remaps labels for
ebook scope and still returns COLLECTION_FIELD_OPTIONS entries that have
option.value === "narrator", which produces invalid requests for mediaScope ===
"ebook"; update the function to filter out options with value "narrator" when
mediaScope === "ebook" (i.e., chain a filter like option.value !== "narrator"
for that scope) before mapping, and apply the same change to the other
COLLECTION_FIELD_OPTIONS mapping used later (the block at lines 67-76) so the
narrator option is never selectable for ebook scope.
---
Nitpick comments:
In `@internal/api/handlers/ebook_reader.go`:
- Around line 853-891: The early-exit branch in ListByContentIDs currently
returns nil, nil for cases userID <= 0, profileID == "" or len(contentIDs) == 0
which can cause callers to panic; change that branch to return an empty map
(e.g. make(map[string]EbookReaderProgress)) and nil error so callers receive a
non-nil progressByContentID; keep the existing error return for the s == nil ||
s.pool == nil check unchanged.
In `@internal/api/handlers/user_state_test.go`:
- Around line 22-35: Add boundary test entries around the completion cutoff in
the progress map used by the test: create two new EbookReaderProgress entries
(e.g., "ebook-cutoff-below" with Progress 0.899 and "ebook-cutoff-at" with
Progress 0.90) alongside the existing "ebook-complete" and "ebook-progress"
entries, and update the assertions in the test that inspects played/unplayed
classification to expect the below entry to be unplayed and the at/above entry
to be played; reference the existing progress map and the EbookReaderProgress
struct to locate where to add these cases.
In `@internal/catalog/item_repo.go`:
- Around line 57-79: The WHERE clause in SetLocalPoster uses "poster_path LIKE
$4 || '%'" which will treat % and _ in localPrefix as wildcards; update
SetLocalPoster's SQL to avoid LIKE-special-character issues—either
validate/reject localPrefix containing '%' or '_' before calling SetLocalPoster,
or replace the LIKE condition with a prefix range check such as "poster_path >=
$4 AND poster_path < $4 || chr(255)" (and keep the other NULL/empty checks), and
adjust parameter usage accordingly; ensure the change is made inside the
SetLocalPoster method and that error handling and return semantics remain the
same.
In `@internal/scanner/ebook.go`:
- Around line 212-215: The function looksLikeHTML is dead code (defined but
never used); remove the looksLikeHTML function declaration from
internal/scanner/ebook.go and ensure any logic relying on an inline check (as
used in the description cleanup) remains unchanged—delete the looksLikeHTML
function to avoid confusion and unused symbols.
In `@internal/taskmanager/tasks/sync_ebook_metadata.go`:
- Line 52: Replace the ignored marshal error by capturing it (result, err :=
json.Marshal(map[string]int{"items_enriched": enriched})) and handle err
immediately: if err != nil return fmt.Errorf("marshal enriched count: %w", err)
(or propagate/log via the function's existing logger), so the code using result
never proceeds with a nil/invalid value; update imports to include fmt if needed
and keep the variable names result and enriched.
In `@migrations/sql/20260608000300_ebook_reader_state.sql`:
- Around line 3-10: Add a created_at TIMESTAMPTZ column to the
ebook_reader_config table to match ebook_reader_annotations and improve
auditability: alter the CREATE TABLE for ebook_reader_config to include
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), ensuring the schema includes both
created_at and updated_at for records (keep PRIMARY KEY on (user_id, profile_id,
content_id) and the existing FK constraints on users(id) and
media_items(content_id)).
In `@web/src/api/client.ts`:
- Around line 440-463: apiBlob duplicates the auth/refresh/error-handling flow
used by api() and apiDownload(); extract that logic into a shared helper (e.g.,
fetchWithAuth) that accepts (path: string, options: RequestInit) and returns a
Response, reusing buildApiHeaders, refreshPromise/attemptRefresh, accessToken,
apiClientErrorFrom and parseApiError; then change apiBlob to call
fetchWithAuth(path, options) and return res.blob(), leaving existing behavior
(401 refresh retry and error-to-apiClientError conversion) intact.
In `@web/src/app.css`:
- Around line 123-133: The current CSS explicitly lists blur utility selectors
(e.g., body.eink .blur-3xl, body.eink .backdrop-blur-md) which is brittle;
replace the hardcoded selector list with attribute selectors that match any
class containing "blur" or "backdrop-blur" scoped under body.eink (e.g., use
body.eink [class*="blur"] and body.eink [class*="backdrop-blur"]) so all current
and future Tailwind blur/backdrop-blur utilities are covered, keeping the same
declarations (filter: none !important; backdrop-filter: none !important;).
In `@web/src/components/WatchTonightCard.test.tsx`:
- Around line 12-45: Replace the string-based renderToStaticMarkup assertions in
WatchTonightCard.test.tsx with Testing Library render and semantic queries:
import and use render (from `@testing-library/react`) instead of
renderToStaticMarkup, render the MemoryRouter+WatchTonightCard the same way,
then replace markup string assertions with screen.getByRole("link", { name:
/.../ }) checks for the reader link (use the accessible link text to locate the
reader link for item with content_id "ebook 1") and screen.getByText("57% read")
to assert progress, and use screen.queryByText(/min left/i) to assert the "min
left" absence; keep the same props to WatchTonightCard and keep onPlay noop.
Ensure you assert the link's href via toHaveAttribute("href",
"/reader/ebook/ebook%201") and remove renderToStaticMarkup and toContain-based
string 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: 842a0b24-458a-4b5d-9d33-a731ff45a55c
⛔ Files ignored due to path filters (9)
web/pnpm-lock.yamlis excluded by!**/pnpm-lock.yamlweb/public/vendor/pdfjs/standard_fonts/LiberationSans-Bold.ttfis excluded by!**/*.ttfweb/public/vendor/pdfjs/standard_fonts/LiberationSans-BoldItalic.ttfis excluded by!**/*.ttfweb/public/vendor/pdfjs/standard_fonts/LiberationSans-Italic.ttfis excluded by!**/*.ttfweb/public/vendor/pdfjs/standard_fonts/LiberationSans-Regular.ttfis excluded by!**/*.ttfweb/public/vendor/pdfjs/wasm/jbig2.wasmis excluded by!**/*.wasmweb/public/vendor/pdfjs/wasm/openjpeg.wasmis excluded by!**/*.wasmweb/public/vendor/pdfjs/wasm/qcms_bg.wasmis excluded by!**/*.wasmweb/public/vendor/pdfjs/wasm/quickjs-eval.wasmis excluded by!**/*.wasm
📒 Files selected for processing (291)
DockerfileDockerfile.devcmd/silo/main.godocs/superpowers/plans/2026-06-08-ebook-reader-full-parity.mddocs/superpowers/plans/2026-06-08-ebook-reader-shell-parity.mdgo.modinternal/api/handlers/catalog.gointernal/api/handlers/catalog_resources.gointernal/api/handlers/ebook_reader.gointernal/api/handlers/ebook_reader_test.gointernal/api/handlers/favorites.gointernal/api/handlers/items.gointernal/api/handlers/items_sort_metrics_test.gointernal/api/handlers/items_user_data_test.gointernal/api/handlers/libraries.gointernal/api/handlers/libraries_metadata_levels_test.gointernal/api/handlers/recommendations.gointernal/api/handlers/sections.gointernal/api/handlers/taste_seed.gointernal/api/handlers/user_state.gointernal/api/handlers/user_state_test.gointernal/api/handlers/watch_tonight.gointernal/api/router.gointernal/catalog/browse.gointernal/catalog/catalog_parser_test.gointernal/catalog/catalog_resolver.gointernal/catalog/catalog_resolver_test.gointernal/catalog/detail.gointernal/catalog/detail_audiobook_test.gointernal/catalog/item_repo.gointernal/catalog/query_builder.gointernal/catalog/query_builder_test.gointernal/catalog/query_definition.gointernal/catalog/query_definition_test.gointernal/ebooks/enrichment.gointernal/ebooks/enrichment_test.gointernal/imagecache/imagecache.gointernal/metadata/provider_id_integrity.gointernal/metadata/provider_id_integrity_test.gointernal/recommendations/accuracy_test.gointernal/recommendations/embeddings/text.gointernal/recommendations/embeddings/text_test.gointernal/recommendations/personal.gointernal/recommendations/repo.gointernal/recommendations/repo_test.gointernal/recommendations/signals.gointernal/recommendations/signals_test.gointernal/recommendations/worker.gointernal/scanner/audiobook_cover.gointernal/scanner/ebook.gointernal/scanner/ebook_scan.gointernal/scanner/ebook_test.gointernal/scanner/scanner.gointernal/scanner/scanner_test.gointernal/sections/defaults.gointernal/sections/defaults_test.gointernal/sections/fetcher.gointernal/taskmanager/tasks/sync_ebook_metadata.gointernal/taskmanager/tasks/sync_ebook_metadata_test.gomigrations/sql/20260608000100_ebook_series.sqlmigrations/sql/20260608000200_ebook_reader_progress.sqlmigrations/sql/20260608000300_ebook_reader_state.sqlweb/package.jsonweb/public/vendor/pdfjs/annotation_layer_builder.cssweb/public/vendor/pdfjs/cmaps/78-EUC-H.bcmapweb/public/vendor/pdfjs/cmaps/78-EUC-V.bcmapweb/public/vendor/pdfjs/cmaps/78-H.bcmapweb/public/vendor/pdfjs/cmaps/78-RKSJ-H.bcmapweb/public/vendor/pdfjs/cmaps/78-RKSJ-V.bcmapweb/public/vendor/pdfjs/cmaps/78-V.bcmapweb/public/vendor/pdfjs/cmaps/78ms-RKSJ-H.bcmapweb/public/vendor/pdfjs/cmaps/78ms-RKSJ-V.bcmapweb/public/vendor/pdfjs/cmaps/83pv-RKSJ-H.bcmapweb/public/vendor/pdfjs/cmaps/90ms-RKSJ-H.bcmapweb/public/vendor/pdfjs/cmaps/90ms-RKSJ-V.bcmapweb/public/vendor/pdfjs/cmaps/90msp-RKSJ-H.bcmapweb/public/vendor/pdfjs/cmaps/90msp-RKSJ-V.bcmapweb/public/vendor/pdfjs/cmaps/90pv-RKSJ-H.bcmapweb/public/vendor/pdfjs/cmaps/90pv-RKSJ-V.bcmapweb/public/vendor/pdfjs/cmaps/Add-H.bcmapweb/public/vendor/pdfjs/cmaps/Add-RKSJ-H.bcmapweb/public/vendor/pdfjs/cmaps/Add-RKSJ-V.bcmapweb/public/vendor/pdfjs/cmaps/Add-V.bcmapweb/public/vendor/pdfjs/cmaps/Adobe-CNS1-0.bcmapweb/public/vendor/pdfjs/cmaps/Adobe-CNS1-1.bcmapweb/public/vendor/pdfjs/cmaps/Adobe-CNS1-2.bcmapweb/public/vendor/pdfjs/cmaps/Adobe-CNS1-3.bcmapweb/public/vendor/pdfjs/cmaps/Adobe-CNS1-4.bcmapweb/public/vendor/pdfjs/cmaps/Adobe-CNS1-5.bcmapweb/public/vendor/pdfjs/cmaps/Adobe-CNS1-6.bcmapweb/public/vendor/pdfjs/cmaps/Adobe-CNS1-UCS2.bcmapweb/public/vendor/pdfjs/cmaps/Adobe-GB1-0.bcmapweb/public/vendor/pdfjs/cmaps/Adobe-GB1-1.bcmapweb/public/vendor/pdfjs/cmaps/Adobe-GB1-2.bcmapweb/public/vendor/pdfjs/cmaps/Adobe-GB1-3.bcmapweb/public/vendor/pdfjs/cmaps/Adobe-GB1-4.bcmapweb/public/vendor/pdfjs/cmaps/Adobe-GB1-5.bcmapweb/public/vendor/pdfjs/cmaps/Adobe-GB1-UCS2.bcmapweb/public/vendor/pdfjs/cmaps/Adobe-Japan1-0.bcmapweb/public/vendor/pdfjs/cmaps/Adobe-Japan1-1.bcmapweb/public/vendor/pdfjs/cmaps/Adobe-Japan1-2.bcmapweb/public/vendor/pdfjs/cmaps/Adobe-Japan1-3.bcmapweb/public/vendor/pdfjs/cmaps/Adobe-Japan1-4.bcmapweb/public/vendor/pdfjs/cmaps/Adobe-Japan1-5.bcmapweb/public/vendor/pdfjs/cmaps/Adobe-Japan1-6.bcmapweb/public/vendor/pdfjs/cmaps/Adobe-Japan1-UCS2.bcmapweb/public/vendor/pdfjs/cmaps/Adobe-Korea1-0.bcmapweb/public/vendor/pdfjs/cmaps/Adobe-Korea1-1.bcmapweb/public/vendor/pdfjs/cmaps/Adobe-Korea1-2.bcmapweb/public/vendor/pdfjs/cmaps/Adobe-Korea1-UCS2.bcmapweb/public/vendor/pdfjs/cmaps/B5-H.bcmapweb/public/vendor/pdfjs/cmaps/B5-V.bcmapweb/public/vendor/pdfjs/cmaps/B5pc-H.bcmapweb/public/vendor/pdfjs/cmaps/B5pc-V.bcmapweb/public/vendor/pdfjs/cmaps/CNS-EUC-H.bcmapweb/public/vendor/pdfjs/cmaps/CNS-EUC-V.bcmapweb/public/vendor/pdfjs/cmaps/CNS1-H.bcmapweb/public/vendor/pdfjs/cmaps/CNS1-V.bcmapweb/public/vendor/pdfjs/cmaps/CNS2-H.bcmapweb/public/vendor/pdfjs/cmaps/CNS2-V.bcmapweb/public/vendor/pdfjs/cmaps/ETHK-B5-H.bcmapweb/public/vendor/pdfjs/cmaps/ETHK-B5-V.bcmapweb/public/vendor/pdfjs/cmaps/ETen-B5-H.bcmapweb/public/vendor/pdfjs/cmaps/ETen-B5-V.bcmapweb/public/vendor/pdfjs/cmaps/ETenms-B5-H.bcmapweb/public/vendor/pdfjs/cmaps/ETenms-B5-V.bcmapweb/public/vendor/pdfjs/cmaps/EUC-H.bcmapweb/public/vendor/pdfjs/cmaps/EUC-V.bcmapweb/public/vendor/pdfjs/cmaps/Ext-H.bcmapweb/public/vendor/pdfjs/cmaps/Ext-RKSJ-H.bcmapweb/public/vendor/pdfjs/cmaps/Ext-RKSJ-V.bcmapweb/public/vendor/pdfjs/cmaps/Ext-V.bcmapweb/public/vendor/pdfjs/cmaps/GB-EUC-H.bcmapweb/public/vendor/pdfjs/cmaps/GB-EUC-V.bcmapweb/public/vendor/pdfjs/cmaps/GB-H.bcmapweb/public/vendor/pdfjs/cmaps/GB-V.bcmapweb/public/vendor/pdfjs/cmaps/GBK-EUC-H.bcmapweb/public/vendor/pdfjs/cmaps/GBK-EUC-V.bcmapweb/public/vendor/pdfjs/cmaps/GBK2K-H.bcmapweb/public/vendor/pdfjs/cmaps/GBK2K-V.bcmapweb/public/vendor/pdfjs/cmaps/GBKp-EUC-H.bcmapweb/public/vendor/pdfjs/cmaps/GBKp-EUC-V.bcmapweb/public/vendor/pdfjs/cmaps/GBT-EUC-H.bcmapweb/public/vendor/pdfjs/cmaps/GBT-EUC-V.bcmapweb/public/vendor/pdfjs/cmaps/GBT-H.bcmapweb/public/vendor/pdfjs/cmaps/GBT-V.bcmapweb/public/vendor/pdfjs/cmaps/GBTpc-EUC-H.bcmapweb/public/vendor/pdfjs/cmaps/GBTpc-EUC-V.bcmapweb/public/vendor/pdfjs/cmaps/GBpc-EUC-H.bcmapweb/public/vendor/pdfjs/cmaps/GBpc-EUC-V.bcmapweb/public/vendor/pdfjs/cmaps/H.bcmapweb/public/vendor/pdfjs/cmaps/HKdla-B5-H.bcmapweb/public/vendor/pdfjs/cmaps/HKdla-B5-V.bcmapweb/public/vendor/pdfjs/cmaps/HKdlb-B5-H.bcmapweb/public/vendor/pdfjs/cmaps/HKdlb-B5-V.bcmapweb/public/vendor/pdfjs/cmaps/HKgccs-B5-H.bcmapweb/public/vendor/pdfjs/cmaps/HKgccs-B5-V.bcmapweb/public/vendor/pdfjs/cmaps/HKm314-B5-H.bcmapweb/public/vendor/pdfjs/cmaps/HKm314-B5-V.bcmapweb/public/vendor/pdfjs/cmaps/HKm471-B5-H.bcmapweb/public/vendor/pdfjs/cmaps/HKm471-B5-V.bcmapweb/public/vendor/pdfjs/cmaps/HKscs-B5-H.bcmapweb/public/vendor/pdfjs/cmaps/HKscs-B5-V.bcmapweb/public/vendor/pdfjs/cmaps/Hankaku.bcmapweb/public/vendor/pdfjs/cmaps/Hiragana.bcmapweb/public/vendor/pdfjs/cmaps/KSC-EUC-H.bcmapweb/public/vendor/pdfjs/cmaps/KSC-EUC-V.bcmapweb/public/vendor/pdfjs/cmaps/KSC-H.bcmapweb/public/vendor/pdfjs/cmaps/KSC-Johab-H.bcmapweb/public/vendor/pdfjs/cmaps/KSC-Johab-V.bcmapweb/public/vendor/pdfjs/cmaps/KSC-V.bcmapweb/public/vendor/pdfjs/cmaps/KSCms-UHC-H.bcmapweb/public/vendor/pdfjs/cmaps/KSCms-UHC-HW-H.bcmapweb/public/vendor/pdfjs/cmaps/KSCms-UHC-HW-V.bcmapweb/public/vendor/pdfjs/cmaps/KSCms-UHC-V.bcmapweb/public/vendor/pdfjs/cmaps/KSCpc-EUC-H.bcmapweb/public/vendor/pdfjs/cmaps/KSCpc-EUC-V.bcmapweb/public/vendor/pdfjs/cmaps/Katakana.bcmapweb/public/vendor/pdfjs/cmaps/LICENSEweb/public/vendor/pdfjs/cmaps/NWP-H.bcmapweb/public/vendor/pdfjs/cmaps/NWP-V.bcmapweb/public/vendor/pdfjs/cmaps/RKSJ-H.bcmapweb/public/vendor/pdfjs/cmaps/RKSJ-V.bcmapweb/public/vendor/pdfjs/cmaps/Roman.bcmapweb/public/vendor/pdfjs/cmaps/UniCNS-UCS2-H.bcmapweb/public/vendor/pdfjs/cmaps/UniCNS-UCS2-V.bcmapweb/public/vendor/pdfjs/cmaps/UniCNS-UTF16-H.bcmapweb/public/vendor/pdfjs/cmaps/UniCNS-UTF16-V.bcmapweb/public/vendor/pdfjs/cmaps/UniCNS-UTF32-H.bcmapweb/public/vendor/pdfjs/cmaps/UniCNS-UTF32-V.bcmapweb/public/vendor/pdfjs/cmaps/UniCNS-UTF8-H.bcmapweb/public/vendor/pdfjs/cmaps/UniCNS-UTF8-V.bcmapweb/public/vendor/pdfjs/cmaps/UniGB-UCS2-H.bcmapweb/public/vendor/pdfjs/cmaps/UniGB-UCS2-V.bcmapweb/public/vendor/pdfjs/cmaps/UniGB-UTF16-H.bcmapweb/public/vendor/pdfjs/cmaps/UniGB-UTF16-V.bcmapweb/public/vendor/pdfjs/cmaps/UniGB-UTF32-H.bcmapweb/public/vendor/pdfjs/cmaps/UniGB-UTF32-V.bcmapweb/public/vendor/pdfjs/cmaps/UniGB-UTF8-H.bcmapweb/public/vendor/pdfjs/cmaps/UniGB-UTF8-V.bcmapweb/public/vendor/pdfjs/cmaps/UniJIS-UCS2-H.bcmapweb/public/vendor/pdfjs/cmaps/UniJIS-UCS2-HW-H.bcmapweb/public/vendor/pdfjs/cmaps/UniJIS-UCS2-HW-V.bcmapweb/public/vendor/pdfjs/cmaps/UniJIS-UCS2-V.bcmapweb/public/vendor/pdfjs/cmaps/UniJIS-UTF16-H.bcmapweb/public/vendor/pdfjs/cmaps/UniJIS-UTF16-V.bcmapweb/public/vendor/pdfjs/cmaps/UniJIS-UTF32-H.bcmapweb/public/vendor/pdfjs/cmaps/UniJIS-UTF32-V.bcmapweb/public/vendor/pdfjs/cmaps/UniJIS-UTF8-H.bcmapweb/public/vendor/pdfjs/cmaps/UniJIS-UTF8-V.bcmapweb/public/vendor/pdfjs/cmaps/UniJIS2004-UTF16-H.bcmapweb/public/vendor/pdfjs/cmaps/UniJIS2004-UTF16-V.bcmapweb/public/vendor/pdfjs/cmaps/UniJIS2004-UTF32-H.bcmapweb/public/vendor/pdfjs/cmaps/UniJIS2004-UTF32-V.bcmapweb/public/vendor/pdfjs/cmaps/UniJIS2004-UTF8-H.bcmapweb/public/vendor/pdfjs/cmaps/UniJIS2004-UTF8-V.bcmapweb/public/vendor/pdfjs/cmaps/UniJISPro-UCS2-HW-V.bcmapweb/public/vendor/pdfjs/cmaps/UniJISPro-UCS2-V.bcmapweb/public/vendor/pdfjs/cmaps/UniJISPro-UTF8-V.bcmapweb/public/vendor/pdfjs/cmaps/UniJISX0213-UTF32-H.bcmapweb/public/vendor/pdfjs/cmaps/UniJISX0213-UTF32-V.bcmapweb/public/vendor/pdfjs/cmaps/UniJISX02132004-UTF32-H.bcmapweb/public/vendor/pdfjs/cmaps/UniJISX02132004-UTF32-V.bcmapweb/public/vendor/pdfjs/cmaps/UniKS-UCS2-H.bcmapweb/public/vendor/pdfjs/cmaps/UniKS-UCS2-V.bcmapweb/public/vendor/pdfjs/cmaps/UniKS-UTF16-H.bcmapweb/public/vendor/pdfjs/cmaps/UniKS-UTF16-V.bcmapweb/public/vendor/pdfjs/cmaps/UniKS-UTF32-H.bcmapweb/public/vendor/pdfjs/cmaps/UniKS-UTF32-V.bcmapweb/public/vendor/pdfjs/cmaps/UniKS-UTF8-H.bcmapweb/public/vendor/pdfjs/cmaps/UniKS-UTF8-V.bcmapweb/public/vendor/pdfjs/cmaps/V.bcmapweb/public/vendor/pdfjs/cmaps/WP-Symbol.bcmapweb/public/vendor/pdfjs/pdf.min.mjsweb/public/vendor/pdfjs/pdf.worker.min.mjsweb/public/vendor/pdfjs/standard_fonts/FoxitDingbats.pfbweb/public/vendor/pdfjs/standard_fonts/FoxitFixed.pfbweb/public/vendor/pdfjs/standard_fonts/FoxitFixedBold.pfbweb/public/vendor/pdfjs/standard_fonts/FoxitFixedBoldItalic.pfbweb/public/vendor/pdfjs/standard_fonts/FoxitFixedItalic.pfbweb/public/vendor/pdfjs/standard_fonts/FoxitSerif.pfbweb/public/vendor/pdfjs/standard_fonts/FoxitSerifBold.pfbweb/public/vendor/pdfjs/standard_fonts/FoxitSerifBoldItalic.pfbweb/public/vendor/pdfjs/standard_fonts/FoxitSerifItalic.pfbweb/public/vendor/pdfjs/standard_fonts/FoxitSymbol.pfbweb/public/vendor/pdfjs/standard_fonts/LICENSE_FOXITweb/public/vendor/pdfjs/standard_fonts/LICENSE_LIBERATIONweb/public/vendor/pdfjs/text_layer_builder.cssweb/public/vendor/pdfjs/wasm/LICENSE_JBIG2web/public/vendor/pdfjs/wasm/LICENSE_OPENJPEGweb/public/vendor/pdfjs/wasm/LICENSE_PDFJS_JBIG2web/public/vendor/pdfjs/wasm/LICENSE_PDFJS_OPENJPEGweb/public/vendor/pdfjs/wasm/LICENSE_PDFJS_QCMSweb/public/vendor/pdfjs/wasm/LICENSE_QCMSweb/public/vendor/pdfjs/wasm/jbig2_nowasm_fallback.jsweb/public/vendor/pdfjs/wasm/openjpeg_nowasm_fallback.jsweb/public/vendor/pdfjs/wasm/quickjs-eval.jsweb/src/App.tsxweb/src/api/client.tsweb/src/api/types.tsweb/src/app.cssweb/src/components/ContinueWatchingCard.test.tsxweb/src/components/ContinueWatchingCard.tsxweb/src/components/DownloadVersionPicker.test.tsxweb/src/components/DownloadVersionPicker.tsxweb/src/components/FilterRuleEditor.test.tsxweb/src/components/FilterRuleEditor.tsxweb/src/components/GlobalSearch.test.tsxweb/src/components/GlobalSearch.tsxweb/src/components/HeroBanner.test.tsxweb/src/components/HeroBanner.tsxweb/src/components/ItemCard.test.tsxweb/src/components/ItemCard.tsxweb/src/components/MediaItemMenu.test.tsxweb/src/components/MediaItemMenu.tsxweb/src/components/MediaLocations.tsxweb/src/components/RecommendationGrid.test.tsxweb/src/components/RecommendationGrid.tsxweb/src/components/SectionItemCard.test.tsxweb/src/components/SectionItemCard.tsxweb/src/components/WatchTonightCard.test.tsxweb/src/components/WatchTonightCard.tsxweb/src/components/admin/libraries/LibraryForm.test.tsxweb/src/components/admin/libraries/libraryTypes.tsweb/src/components/admin/libraries/useLibraryForm.tsweb/src/components/catalog/CatalogFilterBar.test.tsxweb/src/components/catalog/CatalogFilterBar.tsxweb/src/components/catalog/catalogFilterBadges.test.tsweb/src/components/catalog/catalogFilterBadges.tsweb/src/components/collections/CollectionGuidedRulesEditor.test.tsxweb/src/components/collections/CollectionGuidedRulesEditor.tsx
| ebookProgressMap, err := h.listEbookReaderProgressByContentIDs(ctx, userID, profileID, contentIDs) | ||
| if err != nil { | ||
| return | ||
| } |
There was a problem hiding this comment.
Don't drop non-ebook sort metrics when the ebook progress store fails.
At this point progressMap has already been loaded from the user store, but an ebook progress error returns from listUserSortMetrics before any metrics are emitted. A transient ebook-progress failure will therefore break progress, date_viewed, and plays sorting for movies/episodes too.
Suggested fix
ebookProgressMap, err := h.listEbookReaderProgressByContentIDs(ctx, userID, profileID, contentIDs)
- if err != nil {
- return
- }
+ if err != nil {
+ slog.Warn("items: ebook progress lookup failed", "error", err)
+ ebookProgressMap = nil
+ }📝 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.
| ebookProgressMap, err := h.listEbookReaderProgressByContentIDs(ctx, userID, profileID, contentIDs) | |
| if err != nil { | |
| return | |
| } | |
| ebookProgressMap, err := h.listEbookReaderProgressByContentIDs(ctx, userID, profileID, contentIDs) | |
| if err != nil { | |
| slog.Warn("items: ebook progress lookup failed", "error", err) | |
| ebookProgressMap = nil | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/api/handlers/items.go` around lines 1015 - 1018, The current early
return when listEbookReaderProgressByContentIDs (and similarly failures from
listUserSortMetrics) errors out drops all non-ebook sort metrics; change the
handler so ebook-specific store failures are non-fatal: catch the error, log it
(include context like userID/profileID), set ebookProgressMap to an empty map
(or leave existing progressMap intact), and continue processing so
progress/date_viewed/plays sorting still use the user-store metrics; modify code
around listEbookReaderProgressByContentIDs and any listUserSortMetrics call to
avoid returning on transient ebook errors and ensure downstream code can handle
an empty ebookProgressMap.
| case "ebook": | ||
| state.Played = ebookProgressMap[item.ContentID].Progress >= 0.9 |
There was a problem hiding this comment.
Nil map panic when ebook progress store is unavailable.
resolveEbookProgressForUserStates (line 159) returns nil, nil when prerequisites are missing (line 166), but line 149 unconditionally accesses ebookProgressMap[item.ContentID] without checking if the map is nil. This will cause a runtime panic when processing ebook items if options.EbookProgressStore is nil.
🛡️ Proposed fix to guard against nil map access
case "ebook":
- state.Played = ebookProgressMap[item.ContentID].Progress >= 0.9
+ if ebookProgressMap != nil {
+ state.Played = ebookProgressMap[item.ContentID].Progress >= 0.9
+ }
default:Or alternatively, ensure resolveEbookProgressForUserStates always returns an empty map instead of nil:
func resolveEbookProgressForUserStates(
ctx context.Context,
options itemUserStateOptions,
profileID string,
contentIDs []string,
) (map[string]EbookReaderProgress, error) {
if options.EbookProgressStore == nil || options.UserID <= 0 || profileID == "" || len(contentIDs) == 0 {
- return nil, nil
+ return map[string]EbookReaderProgress{}, nil
}
return options.EbookProgressStore.ListByContentIDs(ctx, options.UserID, profileID, contentIDs)
}📝 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.
| case "ebook": | |
| state.Played = ebookProgressMap[item.ContentID].Progress >= 0.9 | |
| case "ebook": | |
| if ebookProgressMap != nil { | |
| state.Played = ebookProgressMap[item.ContentID].Progress >= 0.9 | |
| } |
🤖 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/user_state.go` around lines 148 - 149, The code
unconditionally indexes ebookProgressMap in the user-state loop (case "ebook":
state.Played = ebookProgressMap[item.ContentID].Progress >= 0.9) but
resolveEbookProgressForUserStates can return nil; guard against a nil map or
ensure the resolver returns an empty map: either check ebookProgressMap != nil
before indexing and treat missing entries as zero progress, or change
resolveEbookProgressForUserStates to always return a non-nil map (e.g.,
make/return map[string]EbookProgress{} when prerequisites are missing) so the
assignment in the "ebook" case is safe.
| if mediaScope == "ebook" { | ||
| return nil, false, fmt.Errorf("%w: narrator facet is not available for ebook scope", ErrInvalidCatalogRequest) | ||
| } |
There was a problem hiding this comment.
Reject ebook + narrator rules during query validation too.
This makes narrator unsupported for ebook facet search, but validateCatalogOverlayQuery still accepts field: "narrator" when media_scope is "ebook". That leaves /catalog and /catalog/filters* with different contracts for the same scope and allows saved filters the facet APIs will never surface.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/catalog/catalog_resolver.go` around lines 838 - 840,
validateCatalogOverlayQuery currently allows field == "narrator" even when
mediaScope == "ebook"; add a guard in validateCatalogOverlayQuery to reject
queries where field (or facet) is "narrator" and mediaScope == "ebook" by
returning ErrInvalidCatalogRequest (same error used elsewhere) with a clear
message indicating narrator is not available for ebook scope; reference the
mediaScope, field, validateCatalogOverlayQuery, and ErrInvalidCatalogRequest
symbols so the validation logic matches the runtime check you already added.
| WHERE mi.type = 'ebook' | ||
| AND (mi.poster_path IS NULL OR mi.poster_path = '') | ||
| AND mi.last_refreshed IS NULL |
There was a problem hiding this comment.
The sweep becomes one-shot and misses overview-only ebooks.
The batch query only selects poster_path gaps with last_refreshed IS NULL, but the no-folder / no-provider / no-metadata paths all stamp last_refreshed. That skips ebooks that already have a poster but still lack other metadata, and it permanently suppresses retries after any transient empty provider response.
Also applies to: 246-258, 327-332, 507-513
🤖 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/ebooks/enrichment.go` around lines 193 - 195, The SQL sweep
currently limits candidates with "AND mi.last_refreshed IS NULL" in the WHERE
clause (the block beginning "WHERE mi.type = 'ebook' AND (mi.poster_path IS NULL
OR mi.poster_path = '') ..."), which causes overview-only ebooks and
transient-provider-failure cases to be skipped; remove that strict
last_refreshed IS NULL check and instead select rows based on missing/empty
metadata or an explicit retry policy (e.g., replace the condition with something
like "AND (mi.poster_path IS NULL OR mi.poster_path = '' OR mi.overview IS NULL
OR mi.provider IS NULL OR mi.last_refreshed IS NULL OR mi.last_refreshed < now()
- interval 'X')" so records with missing poster or other metadata or older
refresh timestamps are retried; apply the same fix to the other analogous SQL
blocks in enrichment.go that use the same last_refreshed IS NULL predicate.
| func (r *Repo) GetEbookReaderProgressForUser(ctx context.Context, userID int, profileID string) ([]WatchProgressRow, error) { | ||
| rows, err := r.pool.Query(ctx, ` | ||
| SELECT content_id, | ||
| progress::double precision AS position_seconds, | ||
| 1::double precision AS duration_seconds, | ||
| progress >= 0.9 AS completed, | ||
| updated_at | ||
| FROM ebook_reader_progress | ||
| WHERE user_id = $1 AND profile_id = $2`, | ||
| userID, profileID) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("get ebook reader progress: %w", err) | ||
| } | ||
| defer rows.Close() | ||
|
|
||
| var result []WatchProgressRow | ||
| for rows.Next() { | ||
| var wp WatchProgressRow | ||
| if err := rows.Scan(&wp.MediaItemID, &wp.PositionSeconds, &wp.DurationSeconds, &wp.Completed, &wp.UpdatedAt); err != nil { | ||
| return nil, fmt.Errorf("scan ebook reader progress: %w", err) | ||
| } | ||
| result = append(result, wp) | ||
| } | ||
| return result, rows.Err() | ||
| } |
There was a problem hiding this comment.
Missing hidden-items filter for ebook progress.
GetWatchProgressForUser (line 1162) excludes items from user_history_hidden_items, and watchedActivityCTE does the same for the ebook branch (lines 72-79). This method should apply the same filter to ensure hidden ebook progress doesn't influence taste profiles.
Proposed fix
func (r *Repo) GetEbookReaderProgressForUser(ctx context.Context, userID int, profileID string) ([]WatchProgressRow, error) {
rows, err := r.pool.Query(ctx, `
SELECT content_id,
progress::double precision AS position_seconds,
progress >= 0.9 AS completed,
updated_at
FROM ebook_reader_progress
- WHERE user_id = $1 AND profile_id = $2`,
+ WHERE user_id = $1 AND profile_id = $2
+ AND NOT EXISTS (
+ SELECT 1
+ FROM user_history_hidden_items hhi
+ WHERE hhi.user_id = ebook_reader_progress.user_id
+ AND hhi.profile_id = ebook_reader_progress.profile_id
+ AND hhi.media_item_id = ebook_reader_progress.content_id
+ AND ebook_reader_progress.updated_at <= hhi.hidden_before
+ )`,
userID, profileID)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/recommendations/repo.go` around lines 1192 - 1216,
GetEbookReaderProgressForUser is missing the same user_history_hidden_items
exclusion applied elsewhere; update the SQL in GetEbookReaderProgressForUser so
ebook_reader_progress rows for the given userID/profileID exclude hidden content
(same logic used by GetWatchProgressForUser and watchedActivityCTE). Concretely,
adjust the query for Repo.GetEbookReaderProgressForUser to filter out content_id
values present in user_history_hidden_items for the same user_id and profile_id
(either via a NOT IN subquery or a LEFT JOIN ... WHERE
user_history_hidden_items.content_id IS NULL) so hidden ebook progress is not
returned.
| �RCopyright 1990-2009 Adobe Systems Incorporated. | ||
| All rights reserved. | ||
| See ./LICENSE� ETen-B5-H` ^ No newline at end of file |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "Inspect target file size and bytes:"
wc -c web/public/vendor/pdfjs/cmaps/ETenms-B5-H.bcmap
xxd -l 128 web/public/vendor/pdfjs/cmaps/ETenms-B5-H.bcmap
echo
echo "Compare against sibling .bcmap file sizes (sanity baseline):"
fd -e bcmap . web/public/vendor/pdfjs/cmaps --exec wc -c {} \; | sort -n | tail -n 20Repository: Silo-Server/silo-server
Length of output: 217
🏁 Script executed:
#!/bin/bash
set -euo pipefail
TARGET="web/public/vendor/pdfjs/cmaps/ETenms-B5-H.bcmap"
DIR="web/public/vendor/pdfjs/cmaps"
echo "== Target =="
stat -c '%n %s bytes' "$TARGET" 2>/dev/null || true
python3 - <<'PY'
from pathlib import Path
p = Path("web/public/vendor/pdfjs/cmaps/ETenms-B5-H.bcmap")
data = p.read_bytes()
print("target_len", len(data))
print("first_64_hex", data[:64].hex())
print("first_64_ascii_sanitized", ''.join(chr(b) if 32 <= b < 127 else '.' for b in data[:64]))
PY
echo
echo "== Sibling .bcmap sizes (distribution) =="
python3 - <<'PY'
from pathlib import Path
import statistics
d = Path("web/public/vendor/pdfjs/cmaps")
paths = sorted(d.glob("*.bcmap"))
sizes = [p.stat().st_size for p in paths]
print("count", len(paths))
print("min", min(sizes), "max", max(sizes))
for s in sorted(sizes)[:10]:
print("small", s)
print("---")
for s in sorted(sizes)[-10:]:
print("large", s)
print("---")
print("median", statistics.median(sizes))
PY
echo
echo "== Nearest matches by name (ETenms*) =="
ls -l web/public/vendor/pdfjs/cmaps/ETenms* 2>/dev/null || true
echo
echo "== Compare target vs other B5-H CMap bcmap variants (matching suffix) =="
python3 - <<'PY'
from pathlib import Path
d = Path("web/public/vendor/pdfjs/cmaps")
target = "ETenms-B5-H.bcmap"
t = d/target
s_t = t.stat().st_size
matches = []
for p in d.glob("*B5-H.bcmap"):
matches.append((p.name, p.stat().st_size))
matches.sort(key=lambda x: x[1])
print("target_size", s_t)
print("bottom 15:")
for name, sz in matches[:15]:
print(name, sz)
print("top 15:")
for name, sz in matches[-15:]:
print(name, sz)
PYRepository: Silo-Server/silo-server
Length of output: 1408
🏁 Script executed:
#!/bin/bash
set -euo pipefail
TARGET="web/public/vendor/pdfjs/cmaps/ETenms-B5-H.bcmap"
OTHERS=(
"web/public/vendor/pdfjs/cmaps/ETen-B5-H.bcmap"
"web/public/vendor/pdfjs/cmaps/ETenms-B5-V.bcmap"
)
python3 - <<'PY'
from pathlib import Path
files = ["web/public/vendor/pdfjs/cmaps/ETenms-B5-H.bcmap",
"web/public/vendor/pdfjs/cmaps/ETen-B5-H.bcmap",
"web/public/vendor/pdfjs/cmaps/ETenms-B5-V.bcmap"]
keys = [b"begincmap", b"endcmap", b"bfchar", b"bfrange", b"codespacerange"]
for f in files:
p = Path(f)
data = p.read_bytes()
print("==", p.name, "==")
print("len", len(data))
print("hex", data.hex())
# show ascii-ish with non-printables replaced
ascii_s = ''.join(chr(b) if 32 <= b < 127 else '.' for b in data)
print("ascii", ascii_s)
for k in keys:
print(k.decode(), "present" if k in data else "absent")
print()
PYRepository: Silo-Server/silo-server
Length of output: 4644
🏁 Script executed:
TARGET="web/public/vendor/pdfjs/cmaps/ETenms-B5-H.bcmap"
python3 - <<'PY'
from pathlib import Path
p = Path("web/public/vendor/pdfjs/cmaps/ETenms-B5-H.bcmap")
data = p.read_bytes()
print("size_bytes", len(data))
for k in [b"begincmap", b"endcmap", b"codespacerange", b"bfchar", b"bfrange"]:
print(k.decode(), "present" if k in data else "absent")
PYRepository: Silo-Server/silo-server
Length of output: 165
Fix corrupted PDF.js CMap asset (ETenms-B5-H.bcmap)
web/public/vendor/pdfjs/cmaps/ETenms-B5-H.bcmap is only 101 bytes and contains no CMap sections (begincmap, endcmap, codespacerange, bfchar, bfrange), so it can’t be a valid CMap. The sibling ETenms-B5-V.bcmap is also tiny (172 bytes) and missing the same sections. Re-vendor these assets from the exact PDF.js source/version used for this change.
🤖 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/public/vendor/pdfjs/cmaps/ETenms-B5-H.bcmap` around lines 1 - 3, The two
CMap assets ETenms-B5-H.bcmap and ETenms-B5-V.bcmap are corrupted (too small and
missing CMap sections); re-vendor the correct files from the exact PDF.js
release/tag used by this project: download the ETenms-B5-H.bcmap and
ETenms-B5-V.bcmap from that PDF.js source, copy them into the vendor cmaps
location preserving binary encoding, replace the existing files, and commit;
after replacing, verify each file contains CMap markers like begincmap/endcmap,
codespacerange, bfchar/bfrange and that file sizes are substantially larger than
the current 101/172 bytes.
| .textLayer { | ||
| color-scheme: only light; | ||
|
|
||
| position: absolute; |
There was a problem hiding this comment.
Stylelint errors in vendored PDF.js CSS need an explicit lint strategy.
This file currently triggers Stylelint violations, which can block CI. Since it is vendored code, either exclude web/public/vendor/pdfjs/** from Stylelint scope or add file-level disable markers for this asset.
Suggested minimal file-level suppression (if vendor exclusion is not configured)
+/* stylelint-disable */
/* Copyright 2014 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@
}
+/* stylelint-enable */Also applies to: 56-56, 60-61, 118-118, 120-120, 126-126, 130-130
🧰 Tools
🪛 Stylelint (17.12.0)
[error] 19-19: Expected no empty line before declaration (declaration-empty-line-before)
(declaration-empty-line-before)
🤖 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/public/vendor/pdfjs/text_layer_builder.css` at line 19, The vendored CSS
(text_layer_builder.css) is triggering Stylelint errors; either update the
Stylelint config to explicitly exclude the vendor folder pattern
(web/public/vendor/pdfjs/**) or add file-level Stylelint suppression in
text_layer_builder.css by inserting the appropriate top-of-file disable marker
and matching re-enable if needed (e.g., a file-scope disable for all rules),
ensuring you reference text_layer_builder.css and mirror the same treatment for
the other affected vendor files (the other PDF.js files listed in the review).
Source: Linters/SAST tools
| case "narrator": | ||
| if (rule.op === "is") state.narrator = String(rule.value); | ||
| if (rule.op === "is" && normalized.media_scope === "audiobook") { | ||
| state.narrator = String(rule.value); | ||
| } |
There was a problem hiding this comment.
Narrator filters no longer round-trip for library-scoped audiobook queries.
These guards now require an explicit media_scope === "audiobook". For editors that are scoped by libraryType="audiobook[s]" instead, existing narrator rules load as empty and get dropped on save.
Also applies to: 303-304
🤖 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/collections/CollectionGuidedRulesEditor.tsx` around lines
191 - 194, The narrator rule guard is too strict—it's only matching when
normalized.media_scope === "audiobook" so narrator filters don't survive editor
instances scoped via libraryType. Update the condition in the case "narrator"
branch (and the similar check at the later occurrence around the other narrator
handling) to accept library-scoped audiobook editors as well (e.g., allow
normalized.media_scope === "audiobook" OR normalized.libraryType indicates an
audiobook library such as "audiobook" or starting with "audiobook"), so existing
narrator rules load and are preserved on save.
| : card.type === "ebook" | ||
| ? `${Math.round(Math.min(Math.max(progressPercent, 0), 100))}% read` |
There was a problem hiding this comment.
Don't round unfinished ebooks up to 100% read.
Math.round will label any in-progress value at 99.5%+ as complete even though this card is still rendered as a continue-reading item. Floor the percentage, or cap unfinished items at 99 until the backend marks them complete.
🤖 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 135 - 136, The
ebook progress display currently uses Math.round(progressPercent) which can show
100% for in-progress items; change the logic in the ContinueWatchingCard's ebook
branch (the conditional using card.type === "ebook" and variable
progressPercent) to either use Math.floor(Math.max(0, Math.min(progressPercent,
100))) or cap values below 100 at 99 (e.g., compute pct =
Math.min(Math.floor(progressPercent), progressPercent < 100 ? 99 : 100)) so
unfinished ebooks never render as "100% read" until the backend marks them
complete.
| export function getFilterRuleFieldOptions( | ||
| allowPersonalizedFilters = false, | ||
| mediaScope: FilterRuleMediaScope = "all", | ||
| ) { | ||
| return COLLECTION_FIELD_OPTIONS.filter( | ||
| (option) => allowPersonalizedFilters || !option.personalized, | ||
| ).map((option) => { | ||
| if (mediaScope !== "ebook") { | ||
| return option; | ||
| } | ||
| switch (option.value) { | ||
| case "watched": | ||
| return { ...option, label: "Read" }; | ||
| default: | ||
| return option; | ||
| } | ||
| }); | ||
| } |
There was a problem hiding this comment.
Hide unsupported narrator filter option for ebook scope.
Line 52 onward only remaps labels, but Line 252 in internal/catalog/query_definition.go now rejects narrator for media_scope="ebook". Keeping narrator selectable here creates a guaranteed invalid request path in the UI.
Suggested fix
export function getFilterRuleFieldOptions(
allowPersonalizedFilters = false,
mediaScope: FilterRuleMediaScope = "all",
) {
return COLLECTION_FIELD_OPTIONS.filter(
- (option) => allowPersonalizedFilters || !option.personalized,
+ (option) =>
+ (allowPersonalizedFilters || !option.personalized) &&
+ !(mediaScope === "ebook" && option.value === "narrator"),
).map((option) => {
if (mediaScope !== "ebook") {
return option;
}
switch (option.value) {
case "watched":
return { ...option, label: "Read" };
default:
return option;
}
});
}Also applies to: 67-76
🤖 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/FilterRuleEditor.tsx` around lines 42 - 59,
getFilterRuleFieldOptions currently only remaps labels for ebook scope and still
returns COLLECTION_FIELD_OPTIONS entries that have option.value === "narrator",
which produces invalid requests for mediaScope === "ebook"; update the function
to filter out options with value "narrator" when mediaScope === "ebook" (i.e.,
chain a filter like option.value !== "narrator" for that scope) before mapping,
and apply the same change to the other COLLECTION_FIELD_OPTIONS mapping used
later (the block at lines 67-76) so the narrator option is never selectable for
ebook scope.
All-ebook continue sections previously fell through to the horizontal 16:9 wide card; include ebooks in the poster-variant check so book covers render in their natural 2:3 framing. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Move the current-item ring onto the cover artwork with a themed ring-offset color (matching the sidebar profile highlight) and give the scroll container top headroom so the ring is not cut off by overflow-x-auto. Applies to both ebook and audiobook detail rails. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
- Reconcile missing ebook files like video/audio, with real per-root walk failure tracking (failed/unmounted roots are excluded from deletion), symlinked-root support via the shared logical walker, and the empty-root cleanup allowance before any destructive reconciliation. - Create ebook items as 'pending' so enrichment can promote them to 'matched' (backfill migration included), and protect matched items from re-scan clobbering: title/year skipped, people/series fill-empty only. - PDF metadata: scan head + tail windows (non-linearized PDFs keep the Info dict at the end), require proper key delimiters, head values win. - Cap plain .fb2 reads like .fbz entries; drop .md as an ebook format. - gofmt internal/scanner/audiobook.go (pre-existing drift). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
…koff state - Provider errors now record a failure (capped retries) instead of stamping last_refreshed, which permanently excluded items after transient outages. - Unconfigured metadata chains and the scan-window membership race skip the item without stamping or burning a retry. - Failure tracking moves to a new ebook_enrichment_state table, decoupling it from media_items.refresh_failures (shared with metadata refresh debt). - Preserve non-author people credits when persisting enrichment results. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
…reshold - Apply user_history_hidden_items gating (video semantics) to the ebook watched/in-progress filters, progress sort plan, and Continue Reading. - Continue Reading pages past dismissed items via the shared collector and dedupes items across pages (also fixes the video path's latent exposure). - Centralize the 0.9 finished threshold as models.EbookFinishedProgressThreshold with a single SQL-interpolated mirror in catalog. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
…ignals - itemWatchersQuery dedupes to distinct (watcher, item) rows so one binge-watcher can no longer satisfy minWatchers; the eligibility floor now counts distinct accounts rather than profiles. - Hidden-history gating on GetEbookReaderProgressForUser (signal reader). - Ebook reading produces canonical implicit taste signals (weighted like the equivalent movie progress ratio); ebooks join taste-seed candidates. - Stale GetRecentlyAddedItems doc comment corrected. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
…Policy - Serve a CSP on all SPA HTML responses: blob/srcdoc book iframes inherit it, so script-src 'self' 'wasm-unsafe-eval' blocks script execution from malicious book content (sandbox alone is defeated by the WebKit allow-scripts requirement). Threat model documented on the constant. - X-Content-Type-Options: nosniff on frontend, jellycompat, and ebook file responses; MIME resolution can no longer fall through to octet-stream for an admitted ebook file. - Annotation PATCH: presence-aware field semantics (absent keeps, present sets/clears), invariant re-validation on the merged row, and an atomic SELECT ... FOR UPDATE read-merge-write. - Request size caps (413) on progress/config/annotation writes; Content-Disposition via mime.FormatMediaType; hidden-history gating in the shared ebook progress lister; FK-cascade indexes for reader tables. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
- POST/DELETE /watched/{id} accepts ebook content IDs: mark read upserts
progress 1.0 preserving the reader's file/location (or picks the
preferred reader file for never-opened books); mark unread mirrors video
unwatch semantics and deletes the progress row.
- /history/remove accepts ebooks: hides via user_history_hidden_items
without touching the reading position (hidden != unread; next reading
activity resurfaces the book, mirroring video re-watch).
- Access-filter checks match the video branch; shared logic lives in
ebook_read_state.go. Sort metrics/user-state thresholds use the shared
constant; profile-header fallback deduplicated.
Clients: response is {type: "ebook", affected_count: 1, played: bool};
the existing watched SSE event fires.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
- Open-flow race: cancellation checked after every await with full stale-run teardown (no wrong-file progress saves, no leaked views/blob URLs); book.destroy() on cleanup. - Progress: monotonic stale-response guard; visibilitychange flush uses the refresh-capable client, pagehide uses keepalive; per-book cross-format progress documented as deliberate. - Settings: side effects out of the setState updater; local edits no longer clobbered by late server config; pending saves flushed on unmount/pagehide. - TTS: generation token so Stop actually stops (Chromium/Firefox synthetic events); Media Session uninstalled on unmount. - External book links: http(s) only, opened with noopener,noreferrer. - apiBlob 512 MiB guard with a user-facing error; fraction bookmarks navigable; search-result key collisions fixed; dead e-ink code removed; getLibrarySortRelevanceScope deduplicated; md format dropped. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
- Item detail gets a Mark Read/Unread button; card menus drop the ebook gate and share type-aware labels/toasts (also dedupes audiobook wording). - Watched-state invalidation includes the reader progress query key so the Continue button and percent refresh after toggling. - Continue Reading dismiss copy for ebooks; dismissal path now URL-encodes item IDs (ebook content IDs can contain reserved characters). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
🔍 Review & hardening pass — complete (2026-06-10)This branch went through a two-round review (full PR review, then an adversarial security/edge-case pass over both the original code and the first round of fixes). Every finding was fixed in commits Highest-impact fixes
Plus: hidden-history gating across every ebook surface, curated-metadata protection ( VerificationFull Go test suite ✅ · 972 web tests ✅ · production frontend build ✅ · ESLint/Prettier ✅ · Accepted residuals & follow-ups
🤖 Generated with Claude Code |
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
internal/api/handlers/items.go (1)
432-447:⚠️ Potential issue | 🟠 Major | ⚡ Quick winUse the new profile fallback in
/watched/{id}too.This handler still reads the profile only from auth context, so requests that rely on
X-Profile-Idwill 400 before the new ebook branch runs. That makes watched/unwatched inconsistent with therequestProfileID()-backed read paths in the same file.Suggested fix
func (h *ItemsHandler) handleSetWatchedState(w http.ResponseWriter, r *http.Request, played bool) { userID := apimw.GetUserID(r.Context()) - profileID := apimw.GetProfileID(r.Context()) + profileID := requestProfileID(r) id := chi.URLParam(r, "id")🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/api/handlers/items.go` around lines 432 - 447, The handler handleSetWatchedState currently pulls profileID directly via apimw.GetProfileID and returns 400 if missing, which prevents the X-Profile-Id fallback used elsewhere; change the profile retrieval to use the requestProfileID helper (the same helper used by read paths) so requests can fall back to the header value—i.e., replace apimw.GetProfileID(r.Context()) with the call to requestProfileID (and keep the subsequent validation using that returned profileID) so watched/unwatched behaves consistently with other handlers; ensure any downstream logic (resolveWatchedTargets, filter checks) uses this new profileID variable.internal/api/handlers/items_sort_metrics_test.go (1)
166-183:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winMake the fake progress lister enforce user/profile scope.
ListByContentIDsignores theuserIDandprofileIDarguments, so these tests still pass iflistSortMetricsregresses to querying the wrong reader scope. Filtering or asserting on those parameters here would keep the fake aligned withPGEbookReaderProgressStore.ListByContentIDs.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/api/handlers/items_sort_metrics_test.go` around lines 166 - 183, The fake ListByContentIDs implementation ignores the userID and profileID args allowing tests to pass with wrong reader scope; update fakeEbookReaderProgressLister.ListByContentIDs to enforce scope by checking the passed userID and profileID against stored/expected values (or by using a map keyed by userID+profileID+contentID) and only return progress entries when the user/profile match (or return an error if they differ) so it mirrors PGEbookReaderProgressStore.ListByContentIDs behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/api/handlers/ebook_reader_test.go`:
- Around line 127-152: The fake Update implementation only verifies
annotationID; change its signature to name the parameters (e.g., userID,
profileID, contentID) and add checks that s.existing is non-nil and that
s.existing.UserID == userID, s.existing.ProfileID == profileID, and
s.existing.ContentID == contentID (in addition to the existing annotationID
check), returning nil,nil on mismatch so the fake mirrors the real store's
scoped lookup and preserves the authorization boundary exercised by tests.
In `@internal/api/handlers/ebook_reader.go`:
- Around line 650-700: The current logic in ebookReaderFormat lets the filename
extension override the scanned container; change it to prefer the whitelisted
container first and only fall back to the path when the container is empty or
unknown: in ebookReaderFormat call normalizeEbookReaderFormat(container) first
and if it returns a non-empty format return that; otherwise preserve the
existing fallback behavior (still special-case ".fb2.zip" on the path and then
use normalizeEbookReaderFormat(filepath.Ext(path))). Update ebookMimeType and
any callers (e.g., serveEbookInline) to rely on the revised ebookReaderFormat
and keep normalizeEbookReaderFormat unchanged.
In `@internal/scanner/ebook_scan.go`:
- Around line 72-107: The shared visitedPhysicalDirs map in
collectEbookRootScans causes different configured roots that point to the same
physical tree to suppress files for later roots; to fix, stop sharing that map
across logical roots by using a per-root visited map (create a new
map[string]struct{} for each root or clone the global into a per-root copy) and
pass that per-root map into walkLogicalTree for each ebookRootScan; ensure this
change still lets ebookRootScan and reconcileEbookScan operate root-scoped so
seenPaths and reconciliation are correct for each logical root.
---
Outside diff comments:
In `@internal/api/handlers/items_sort_metrics_test.go`:
- Around line 166-183: The fake ListByContentIDs implementation ignores the
userID and profileID args allowing tests to pass with wrong reader scope; update
fakeEbookReaderProgressLister.ListByContentIDs to enforce scope by checking the
passed userID and profileID against stored/expected values (or by using a map
keyed by userID+profileID+contentID) and only return progress entries when the
user/profile match (or return an error if they differ) so it mirrors
PGEbookReaderProgressStore.ListByContentIDs behavior.
In `@internal/api/handlers/items.go`:
- Around line 432-447: The handler handleSetWatchedState currently pulls
profileID directly via apimw.GetProfileID and returns 400 if missing, which
prevents the X-Profile-Id fallback used elsewhere; change the profile retrieval
to use the requestProfileID helper (the same helper used by read paths) so
requests can fall back to the header value—i.e., replace
apimw.GetProfileID(r.Context()) with the call to requestProfileID (and keep the
subsequent validation using that returned profileID) so watched/unwatched
behaves consistently with other handlers; ensure any downstream logic
(resolveWatchedTargets, filter checks) uses this new profileID variable.
🪄 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: 935d9bd3-7252-4f5d-a64c-1a579b3a6eef
📒 Files selected for processing (38)
docs/pr124-ebooks-review-hardening.mdinternal/api/handlers/ebook_read_state.gointernal/api/handlers/ebook_read_state_test.gointernal/api/handlers/ebook_reader.gointernal/api/handlers/ebook_reader_test.gointernal/api/handlers/favorites.gointernal/api/handlers/favorites_history_remove_test.gointernal/api/handlers/items.gointernal/api/handlers/items_sort_metrics_test.gointernal/api/handlers/user_state.gointernal/api/handlers/user_state_test.gointernal/catalog/query_builder.gointernal/catalog/query_builder_test.gointernal/ebooks/enrichment.gointernal/ebooks/enrichment_test.gointernal/jellycompat/web.gointernal/models/ebook_progress.gointernal/recommendations/repo.gointernal/recommendations/repo_test.gointernal/recommendations/taste_signals.gointernal/recommendations/taste_signals_test.gointernal/scanner/audiobook.gointernal/scanner/ebook.gointernal/scanner/ebook_scan.gointernal/scanner/ebook_test.gointernal/scanner/scanner.gointernal/scanner/scanner_test.gointernal/sections/fetcher.gointernal/sections/fetcher_continue_watching_test.gointernal/server/frontend.gointernal/server/frontend_test.gomigrations/sql/20260610071424_add_ebook_reader_fk_indexes.sqlmigrations/sql/20260610080326_backfill_ebook_item_status.sqlmigrations/sql/20260610080327_ebook_enrichment_state.sqlweb/src/api/client.test.tsweb/src/api/client.tsweb/src/components/MediaItemMenu.test.tsxweb/src/components/MediaItemMenu.tsx
✅ Files skipped from review due to trivial changes (4)
- migrations/sql/20260610071424_add_ebook_reader_fk_indexes.sql
- migrations/sql/20260610080327_ebook_enrichment_state.sql
- internal/scanner/audiobook.go
- docs/pr124-ebooks-review-hardening.md
🚧 Files skipped from review as they are similar to previous changes (6)
- internal/api/handlers/user_state_test.go
- internal/scanner/scanner_test.go
- internal/api/handlers/user_state.go
- internal/catalog/query_builder_test.go
- internal/catalog/query_builder.go
- internal/recommendations/repo.go
| func (s *fakeEbookReaderAnnotationStore) Update( | ||
| _ context.Context, | ||
| _ int, | ||
| _ string, | ||
| _ string, | ||
| annotationID string, | ||
| merge func(existing EbookReaderAnnotation) (EbookReaderAnnotation, error), | ||
| ) (*EbookReaderAnnotation, error) { | ||
| if s.err != nil { | ||
| return nil, s.err | ||
| } | ||
| if s.existing == nil || s.existing.ID != annotationID { | ||
| return nil, nil | ||
| } | ||
| existing := *s.existing | ||
| s.mergedFrom = &existing | ||
| s.mergeCalls++ | ||
| merged, err := merge(existing) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| s.updated = &merged | ||
| stored := merged | ||
| s.existing = &stored | ||
| return &merged, nil | ||
| } |
There was a problem hiding this comment.
Match the real store's scoped lookup in the fake Update.
This fake only checks annotationID, so the PATCH tests would still pass if the handler stopped passing userID, profileID, or contentID into Update. Guard those fields here so the test keeps exercising the authorization boundary the PG implementation enforces.
🤖 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/ebook_reader_test.go` around lines 127 - 152, The fake
Update implementation only verifies annotationID; change its signature to name
the parameters (e.g., userID, profileID, contentID) and add checks that
s.existing is non-nil and that s.existing.UserID == userID, s.existing.ProfileID
== profileID, and s.existing.ContentID == contentID (in addition to the existing
annotationID check), returning nil,nil on mismatch so the fake mirrors the real
store's scoped lookup and preserves the authorization boundary exercised by
tests.
| // ebookReaderFormat resolves the whitelisted reader format for a file from | ||
| // its filename extension, falling back to the catalog container when the | ||
| // extension is not a known ebook format. It returns "" when neither identity | ||
| // is whitelisted. isEbookFile admission and ebookMimeType both key off this | ||
| // resolution, so an admitted file always maps to a concrete ebook MIME type | ||
| // and never falls through to application/octet-stream. | ||
| func ebookReaderFormat(path, container string) string { | ||
| if strings.HasSuffix(strings.ToLower(path), ".fb2.zip") { | ||
| return "fbz" | ||
| } | ||
| if format := normalizeEbookReaderFormat(filepath.Ext(path)); format != "" { | ||
| return format | ||
| } | ||
| return normalizeEbookReaderFormat(container) | ||
| } | ||
|
|
||
| // normalizeEbookReaderFormat maps an extension or container value onto the | ||
| // ebook reader format whitelist, returning "" for unknown values. | ||
| func normalizeEbookReaderFormat(value string) string { | ||
| format := strings.TrimPrefix(strings.ToLower(strings.TrimSpace(value)), ".") | ||
| switch format { | ||
| case "epub", "pdf", "mobi", "azw", "azw3", "cbz", "cbr", "fb2", "fbz": | ||
| return format | ||
| default: | ||
| return "" | ||
| } | ||
| } | ||
|
|
||
| func ebookMimeType(path, container string) string { | ||
| switch ebookReaderFormat(path, container) { | ||
| case "epub": | ||
| return "application/epub+zip" | ||
| case "pdf": | ||
| return "application/pdf" | ||
| case "mobi": | ||
| return "application/x-mobipocket-ebook" | ||
| case "azw": | ||
| return "application/vnd.amazon.ebook" | ||
| case "azw3": | ||
| return "application/vnd.amazon.mobi8-ebook" | ||
| case "cbz": | ||
| return "application/vnd.comicbook+zip" | ||
| case "cbr": | ||
| return "application/vnd.comicbook-rar" | ||
| case "fb2": | ||
| return "application/x-fictionbook+xml" | ||
| case "fbz": | ||
| return "application/x-zip-compressed-fb2" | ||
| default: | ||
| return "application/octet-stream" | ||
| } |
There was a problem hiding this comment.
Use the scanned container as the source of truth for served MIME types.
serveEbookInline returns the on-disk bytes, but ebookReaderFormat lets a known filename extension override file.Container. A misnamed PDF stored as book.epub will be served as application/epub+zip, which can break the reader and browser handling for the actual content. Prefer the whitelisted container first, then fall back to the path only when the container is empty or unknown.
Suggested fix
func ebookReaderFormat(path, container string) string {
+ if format := normalizeEbookReaderFormat(container); format != "" {
+ return format
+ }
if strings.HasSuffix(strings.ToLower(path), ".fb2.zip") {
return "fbz"
}
- if format := normalizeEbookReaderFormat(filepath.Ext(path)); format != "" {
- return format
- }
- return normalizeEbookReaderFormat(container)
+ return normalizeEbookReaderFormat(filepath.Ext(path))
}📝 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.
| // ebookReaderFormat resolves the whitelisted reader format for a file from | |
| // its filename extension, falling back to the catalog container when the | |
| // extension is not a known ebook format. It returns "" when neither identity | |
| // is whitelisted. isEbookFile admission and ebookMimeType both key off this | |
| // resolution, so an admitted file always maps to a concrete ebook MIME type | |
| // and never falls through to application/octet-stream. | |
| func ebookReaderFormat(path, container string) string { | |
| if strings.HasSuffix(strings.ToLower(path), ".fb2.zip") { | |
| return "fbz" | |
| } | |
| if format := normalizeEbookReaderFormat(filepath.Ext(path)); format != "" { | |
| return format | |
| } | |
| return normalizeEbookReaderFormat(container) | |
| } | |
| // normalizeEbookReaderFormat maps an extension or container value onto the | |
| // ebook reader format whitelist, returning "" for unknown values. | |
| func normalizeEbookReaderFormat(value string) string { | |
| format := strings.TrimPrefix(strings.ToLower(strings.TrimSpace(value)), ".") | |
| switch format { | |
| case "epub", "pdf", "mobi", "azw", "azw3", "cbz", "cbr", "fb2", "fbz": | |
| return format | |
| default: | |
| return "" | |
| } | |
| } | |
| func ebookMimeType(path, container string) string { | |
| switch ebookReaderFormat(path, container) { | |
| case "epub": | |
| return "application/epub+zip" | |
| case "pdf": | |
| return "application/pdf" | |
| case "mobi": | |
| return "application/x-mobipocket-ebook" | |
| case "azw": | |
| return "application/vnd.amazon.ebook" | |
| case "azw3": | |
| return "application/vnd.amazon.mobi8-ebook" | |
| case "cbz": | |
| return "application/vnd.comicbook+zip" | |
| case "cbr": | |
| return "application/vnd.comicbook-rar" | |
| case "fb2": | |
| return "application/x-fictionbook+xml" | |
| case "fbz": | |
| return "application/x-zip-compressed-fb2" | |
| default: | |
| return "application/octet-stream" | |
| } | |
| func ebookReaderFormat(path, container string) string { | |
| if format := normalizeEbookReaderFormat(container); format != "" { | |
| return format | |
| } | |
| if strings.HasSuffix(strings.ToLower(path), ".fb2.zip") { | |
| return "fbz" | |
| } | |
| return normalizeEbookReaderFormat(filepath.Ext(path)) | |
| } |
🤖 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/ebook_reader.go` around lines 650 - 700, The current
logic in ebookReaderFormat lets the filename extension override the scanned
container; change it to prefer the whitelisted container first and only fall
back to the path when the container is empty or unknown: in ebookReaderFormat
call normalizeEbookReaderFormat(container) first and if it returns a non-empty
format return that; otherwise preserve the existing fallback behavior (still
special-case ".fb2.zip" on the path and then use
normalizeEbookReaderFormat(filepath.Ext(path))). Update ebookMimeType and any
callers (e.g., serveEbookInline) to rely on the revised ebookReaderFormat and
keep normalizeEbookReaderFormat unchanged.
| func collectEbookRootScans(ctx context.Context, folderID int, roots []string) ([]ebookRootScan, error) { | ||
| scans := make([]ebookRootScan, 0, len(roots)) | ||
| visitedPhysicalDirs := make(map[string]struct{}) | ||
| for _, root := range roots { | ||
| if err := ctx.Err(); err != nil { | ||
| return nil, err | ||
| } | ||
| cleanRoot := filepath.Clean(strings.TrimSpace(root)) | ||
| if cleanRoot == "" || cleanRoot == "." { | ||
| continue | ||
| } | ||
| scan := ebookRootScan{root: cleanRoot} | ||
| info, statErr := os.Stat(cleanRoot) | ||
| switch { | ||
| case statErr != nil: | ||
| // Unmounted/missing/permission-broken root: failed, not empty. | ||
| scan.rootErr = fmt.Errorf("stat root: %w", statErr) | ||
| case !info.IsDir(): | ||
| scan.rootErr = fmt.Errorf("root is not a directory after symlink resolution") | ||
| } | ||
| if statErr == nil { | ||
| if err := walkLogicalTree(ctx, cleanRoot, cleanRoot, walkModeEbook, visitedPhysicalDirs, &scan.files, &scan.walkFailures); err != nil { | ||
| return nil, err | ||
| } | ||
| } | ||
| if scan.failed() { | ||
| slog.Warn("ebook scan: root walk incomplete; root excluded from missing-file reconciliation", | ||
| "folder_id", folderID, | ||
| "root", cleanRoot, | ||
| "walk_failures", scan.walkFailures, | ||
| "error", scan.rootErr, | ||
| ) | ||
| } | ||
| scans = append(scans, scan) | ||
| } | ||
| return scans, nil |
There was a problem hiding this comment.
Don't share visitedPhysicalDirs across configured roots when reconciliation is root-scoped.
If two library roots point at the same physical tree (for example, a configured path and a symlink alias), the first walk populates scan.files and the second walk yields zero files because that physical dir is already marked visited. reconcileEbookScan still reconciles the second logical root, though, so its existing rows are absent from seenPaths and get marked missing/deleted even though the files were just indexed through the first root.
Suggested fix
func collectEbookRootScans(ctx context.Context, folderID int, roots []string) ([]ebookRootScan, error) {
scans := make([]ebookRootScan, 0, len(roots))
- visitedPhysicalDirs := make(map[string]struct{})
for _, root := range roots {
+ visitedPhysicalDirs := make(map[string]struct{})
if err := ctx.Err(); err != nil {
return nil, err
}
cleanRoot := filepath.Clean(strings.TrimSpace(root))🤖 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/scanner/ebook_scan.go` around lines 72 - 107, The shared
visitedPhysicalDirs map in collectEbookRootScans causes different configured
roots that point to the same physical tree to suppress files for later roots; to
fix, stop sharing that map across logical roots by using a per-root visited map
(create a new map[string]struct{} for each root or clone the global into a
per-root copy) and pass that per-root map into walkLogicalTree for each
ebookRootScan; ensure this change still lets ebookRootScan and
reconcileEbookScan operate root-scoped so seenPaths and reconciliation are
correct for each logical root.
* docs: define ebook architecture matching audiobooks * docs: plan ebook audiobook-parity implementation * feat: add ebook scanner parser foundation * fix: harden ebook scanner foundation * fix: handle ebook isbn labels * fix: guard ebook subtree scans * feat: scan ebook libraries in core * fix: preserve ebook scan people credits * fix: refresh ebook scan metadata safely * feat: persist ebook series membership * test: cover ebook series persistence decisions * fix: address ebook scanner PR review * docs: clarify ebook foundation PR scope * feat: add ebook metadata enricher * fix: harden ebook poster cache * feat: wire ebook metadata sync task * feat: expose ebook library metadata setup * feat: add ebook catalog scope support * feat: add ebook detail view * feat: label ebook file versions by format * feat: use file-size copy for downloads * feat: use file language in download dialog * test: cover ebook detail authors and downloads * fix: drop narrator credits from ebook scanner merges * fix: align ebook collection filters with book media * fix: drop asin provider ids from ebook enrichment * fix: force ebook people refresh for stale narrators * chore: omit ebook planning docs from branch * feat: add ebook detail related content * feat: add ebook reader file entrypoint * feat: render ebooks with foliate reader * feat: persist ebook reader progress * feat: add ebook reader controls * feat: extract ebook pdf metadata * feat: favor scanner isbn during ebook enrichment * feat: extract fbz ebook metadata * feat: count cbz ebook pages * feat: show ebook file page counts * feat: show ebook download summaries * feat: switch ebook reader files * feat: prefer epub for ebook read action * feat: surface ebook reader progress * feat: sync ebook reader progress cache * feat: hide ebook read action for unsupported files * feat: filter ebook reader file selector * fix: serve fbz ebook archives with reader mime type * fix: detect fbz ebooks from compound filename * fix: authorize fbz ebooks from compound filename * fix: scope ebook catalog facets * fix: reject narrator queries for ebooks * fix: build ebook recommendation text from authors * fix: include ebooks in embedding eligibility * fix: include ebooks in recommendation media mix * fix: include ebooks in recently added recommendations * feat: include ebook progress in recommendation signals * feat: include ebooks in continue watching sections * feat: include ebooks in catalog progress metrics * fix: read ebook isbn from epub metadata * fix: filter ebook asin provider aliases * fix: fall back from unsupported ebook reader files * fix: sort ebook catalogs by reader progress * fix: filter ebook catalogs by reader progress * fix: include ebooks in last watched catalog filters * feat: reflect ebook reader progress in item user state * feat: share ebook progress state across item surfaces * feat: report ebook scan progress * fix: include ebook activity in recommendations * fix: expose ebook reader progress on item detail * fix: support ebook subtree scans * fix: honor profile header for ebook item progress * fix: add ebook library default sections * fix: route ebook continue cards to reader * fix: hide watched toggle for ebooks * fix: route ebook watch tonight cards to reader * fix: route ebook hero actions to reader * fix: detect archive ebook reader formats by filename * feat: cache embedded ebook covers during scan * fix: encode ebook hero reader links * fix: persist non-epub ebook reader progress * fix: scope narrator catalog badges to audiobooks * fix: merge ebook reader progress during item repair * fix: label ebook progress filters as read * fix: show ebook related rails as book covers * fix: remove txt ebook reader support * fix: reject txt ebook reader files * fix: label ebook advanced filters as read * fix: label ebook personalized sorts as read * fix: remove plain text reader loader path * test: cover ebook unread catalog rules * fix: preserve ebook reader library context * fix: link ebook genres with library scope * fix: encode related rail item links * fix: encode catalog card item links * fix: encode hero and continue item links * fix: encode watch tonight item links * fix: encode recommendation and search item links * test: cover ebook scan format set * fix: label ebook search results clearly * fix: make global search prompt media neutral * fix: encode catalog read API ids * fix: encode item API ids * fix: include ebook reader vendor in docker build * fix: make ebook reader build clean * fix: clean ebook embedded descriptions * docs: plan ebook reader shell parity * feat: add ebook reader shell controls * fix: widen ebook scrolled reader flow * fix: remove scrolled reader content width cap * docs: plan ebook reader full parity * feat: persist ebook reader config * feat: add ebook annotations and bookmarks * feat: add ebook reader tools and aids * feat: add ebook advanced reader settings * fix: keep ebook reader panel in viewport * fix: use foliate sizing units for ebook scroll flow * fix: keep ebook settings controls readable * fix: simplify ebook reader settings controls * feat(ebooks): extract local covers during scan (#98) * feat(ebooks): extract local covers during scan * fix(ebooks): read nullable poster paths during cover scan * fix(catalog): coalesce nullable media artwork fields * fix(ebooks): group sibling formats by book identity * fix(ebooks): tolerate legacy ebook metadata encodings * fix(ebooks): decode PDF hex metadata strings * fix(ebooks): harden local cover extraction and format grouping Address review findings on the local cover scan: - Restrict generic sidecar covers (cover.jpg, folder.png, ...) to single-book directories, always accept images named after the book file, and apply exactly one cover per reconcile with sidecar taking precedence over the embedded cover. - Replace the read-then-write poster update with an atomic conditional UPDATE (ItemRepository.SetLocalPoster) so provider/admin artwork is never clobbered by concurrent writers, and refresh locally owned posters when the extracted cover bytes change (thumbhash compare). - Preserve UTF-8 PDF Info strings (including a UTF-8 BOM) instead of forcing everything through Windows-1252; the cp1252 fallback now only applies to non-UTF-8 bytes. - Select EPUB covers by manifest media-type with properties="cover-image" outranking the EPUB2 meta name="cover" id, so XHTML cover pages no longer shadow the real image. - Order CBZ pages naturally (2.jpg before 10.jpg, ch2/ before ch10/) when picking the cover page, via a single O(n) min-scan. - Bump the ebook content group key scheme to version 2 and reprocess rows written under older versions so pre-existing libraries gain sibling-format grouping instead of accumulating duplicates. - Group different formats only (a same-format sibling with colliding sparse metadata stays a separate item) and stop a joining sibling's embedded metadata from overwriting a provider-matched item. - Decode any IANA-labelled OPF/FB2 XML charset (windows-1251, koi8-r, shift_jis, ...) via x/net/html/charset, and wire the charset reader into FB2 parsing which previously had none. - Strip the full .fb2.zip double extension from filename-derived titles and group keys. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: rxwatcher <rxwatcher@users.noreply.github.com> Co-authored-by: Quick <31828688+Quick104@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com> * feat(ebooks): add reader profiles and ruler (#99) * feat(ebooks): extract local covers during scan * fix(ebooks): read nullable poster paths during cover scan * fix(catalog): coalesce nullable media artwork fields * fix(ebooks): group sibling formats by book identity * fix(ebooks): tolerate legacy ebook metadata encodings * fix(ebooks): decode PDF hex metadata strings * feat(ebooks): add reader profiles and ruler * fix(ebooks): address reader ruler and profile review findings - skip renderer setStyles/render when computed styles and attributes are unchanged, so ruler position updates no longer re-style the book view - drag the ruler via a local draft that commits on release, with the surface rect cached at pointer-down - migrate font values persisted before the generic stacks (Inter, Georgia, Merriweather, legacy serif) so the font select never renders blank, with a Custom fallback option for unknown values - make the ruler band click-through and move dragging to a dedicated keyboard-accessible slider handle so links and text selection keep working under the band - share font stacks between options and profiles via READER_FONT_STACKS - surface the active reading profile, move presets to the top of the settings panel, and drop the redundant profile button aria-labels Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(ebooks): resolve prefer-const lint error in readest document lib `pnpm run lint` failed on the branch because `direction` is never reassigned in getDirection; split the destructure so only the reassigned `writingMode` stays mutable. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: rxwatcher <rxwatcher@users.noreply.github.com> Co-authored-by: Quick <31828688+Quick104@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com> * Merge branch 'main' into work/ebooks-reader-base Brings the ebook integration branch up to date with main (audiobook library redesign, continue-watching rework and card affordances, quic-go bump, jellycompat fixes). Conflict resolutions favor main's generalized mechanisms and register ebooks with them: - media scope validation goes through IsValidMediaScope (now including "ebook" alongside main's "video" group scope), in Go and in the web filter/search types - continue-watching uses main's typed rails; reading-type sections pull resume points from ebook_reader_progress and the ebook library default section is wired to ContinueTypeConfig(ContinueTypeReading) - item_repo keeps main's derived select-list machinery (itemColumnExpr) and both poster accessors (GetPoster/SetLocalPoster for ebook covers, GetPosterPath for audiobook covers) - web cards/hero/watch-tonight adopt main's buildMediaPlayHref helpers, which now route ebooks to /reader/ebook and encode content ids; ebook affordances (BookOpen icon, Read verb, percent-read subtitle) carry over onto main's reworked components - LibraryForm ebook support ported into main's refactored useLibraryForm/libraryTypes modules Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(docker): copy foliate-js vendor into Dockerfile.dev frontend stage foliate-js is a file:vendor/foliate-js dependency, so pnpm install needs the vendor directory before the lockfile install layer. The production Dockerfile already copies it; the dev image was missed, breaking make dev-deploy with ENOENT on /app/web/vendor/foliate-js. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(ebooks): render Continue Reading sections as upright poster cards All-ebook continue sections previously fell through to the horizontal 16:9 wide card; include ebooks in the poster-variant check so book covers render in their natural 2:3 framing. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(ui): stop related-rail highlight ring clipping on detail pages Move the current-item ring onto the cover artwork with a themed ring-offset color (matching the sidebar profile highlight) and give the scroll container top headroom so the ring is not cut off by overflow-x-auto. Applies to both ebook and audiobook detail rails. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(scanner): harden ebook scanning against data loss and bad metadata - Reconcile missing ebook files like video/audio, with real per-root walk failure tracking (failed/unmounted roots are excluded from deletion), symlinked-root support via the shared logical walker, and the empty-root cleanup allowance before any destructive reconciliation. - Create ebook items as 'pending' so enrichment can promote them to 'matched' (backfill migration included), and protect matched items from re-scan clobbering: title/year skipped, people/series fill-empty only. - PDF metadata: scan head + tail windows (non-linearized PDFs keep the Info dict at the end), require proper key delimiters, head values win. - Cap plain .fb2 reads like .fbz entries; drop .md as an ebook format. - gofmt internal/scanner/audiobook.go (pre-existing drift). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(ebooks): make enrichment failures non-terminal with dedicated backoff state - Provider errors now record a failure (capped retries) instead of stamping last_refreshed, which permanently excluded items after transient outages. - Unconfigured metadata chains and the scan-window membership race skip the item without stamping or burning a retry. - Failure tracking moves to a new ebook_enrichment_state table, decoupling it from media_items.refresh_failures (shared with metadata refresh debt). - Preserve non-author people credits when persisting enrichment results. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(catalog): gate ebook progress on hidden history and centralize threshold - Apply user_history_hidden_items gating (video semantics) to the ebook watched/in-progress filters, progress sort plan, and Continue Reading. - Continue Reading pages past dismissed items via the shared collector and dedupes items across pages (also fixes the video path's latent exposure). - Centralize the 0.9 finished threshold as models.EbookFinishedProgressThreshold with a single SQL-interpolated mirror in catalog. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(recommendations): correct watcher counting and wire ebook taste signals - itemWatchersQuery dedupes to distinct (watcher, item) rows so one binge-watcher can no longer satisfy minWatchers; the eligibility floor now counts distinct accounts rather than profiles. - Hidden-history gating on GetEbookReaderProgressForUser (signal reader). - Ebook reading produces canonical implicit taste signals (weighted like the equivalent movie progress ratio); ebooks join taste-seed candidates. - Stale GetRecentlyAddedItems doc comment corrected. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(api): harden ebook reader endpoints and serve a Content-Security-Policy - Serve a CSP on all SPA HTML responses: blob/srcdoc book iframes inherit it, so script-src 'self' 'wasm-unsafe-eval' blocks script execution from malicious book content (sandbox alone is defeated by the WebKit allow-scripts requirement). Threat model documented on the constant. - X-Content-Type-Options: nosniff on frontend, jellycompat, and ebook file responses; MIME resolution can no longer fall through to octet-stream for an admitted ebook file. - Annotation PATCH: presence-aware field semantics (absent keeps, present sets/clears), invariant re-validation on the merged row, and an atomic SELECT ... FOR UPDATE read-merge-write. - Request size caps (413) on progress/config/annotation writes; Content-Disposition via mime.FormatMediaType; hidden-history gating in the shared ebook progress lister; FK-cascade indexes for reader tables. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(api): native read-state endpoints for ebooks - POST/DELETE /watched/{id} accepts ebook content IDs: mark read upserts progress 1.0 preserving the reader's file/location (or picks the preferred reader file for never-opened books); mark unread mirrors video unwatch semantics and deletes the progress row. - /history/remove accepts ebooks: hides via user_history_hidden_items without touching the reading position (hidden != unread; next reading activity resurfaces the book, mirroring video re-watch). - Access-filter checks match the video branch; shared logic lives in ebook_read_state.go. Sort metrics/user-state thresholds use the shared constant; profile-header fallback deduplicated. Clients: response is {type: "ebook", affected_count: 1, played: bool}; the existing watched SSE event fires. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(web): harden the ebook reader UI - Open-flow race: cancellation checked after every await with full stale-run teardown (no wrong-file progress saves, no leaked views/blob URLs); book.destroy() on cleanup. - Progress: monotonic stale-response guard; visibilitychange flush uses the refresh-capable client, pagehide uses keepalive; per-book cross-format progress documented as deliberate. - Settings: side effects out of the setState updater; local edits no longer clobbered by late server config; pending saves flushed on unmount/pagehide. - TTS: generation token so Stop actually stops (Chromium/Firefox synthetic events); Media Session uninstalled on unmount. - External book links: http(s) only, opened with noopener,noreferrer. - apiBlob 512 MiB guard with a user-facing error; fraction bookmarks navigable; search-result key collisions fixed; dead e-ink code removed; getLibrarySortRelevanceScope deduplicated; md format dropped. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(web): mark read/unread affordances for ebooks - Item detail gets a Mark Read/Unread button; card menus drop the ebook gate and share type-aware labels/toasts (also dedupes audiobook wording). - Watched-state invalidation includes the reader progress query key so the Continue button and percent refresh after toggling. - Continue Reading dismiss copy for ebooks; dismissal path now URL-encodes item IDs (ebook content IDs can contain reserved characters). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: record the PR #124 review and hardening pass Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: rxwatcher <rxwatcher@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* docs: define ebook architecture matching audiobooks * docs: plan ebook audiobook-parity implementation * feat: add ebook scanner parser foundation * fix: harden ebook scanner foundation * fix: handle ebook isbn labels * fix: guard ebook subtree scans * feat: scan ebook libraries in core * fix: preserve ebook scan people credits * fix: refresh ebook scan metadata safely * feat: persist ebook series membership * test: cover ebook series persistence decisions * fix: address ebook scanner PR review * docs: clarify ebook foundation PR scope * feat: add ebook metadata enricher * fix: harden ebook poster cache * feat: wire ebook metadata sync task * feat: expose ebook library metadata setup * feat: add ebook catalog scope support * feat: add ebook detail view * feat: label ebook file versions by format * feat: use file-size copy for downloads * feat: use file language in download dialog * test: cover ebook detail authors and downloads * fix: drop narrator credits from ebook scanner merges * fix: align ebook collection filters with book media * fix: drop asin provider ids from ebook enrichment * fix: force ebook people refresh for stale narrators * chore: omit ebook planning docs from branch * feat: add ebook detail related content * feat: add ebook reader file entrypoint * feat: render ebooks with foliate reader * feat: persist ebook reader progress * feat: add ebook reader controls * feat: extract ebook pdf metadata * feat: favor scanner isbn during ebook enrichment * feat: extract fbz ebook metadata * feat: count cbz ebook pages * feat: show ebook file page counts * feat: show ebook download summaries * feat: switch ebook reader files * feat: prefer epub for ebook read action * feat: surface ebook reader progress * feat: sync ebook reader progress cache * feat: hide ebook read action for unsupported files * feat: filter ebook reader file selector * fix: serve fbz ebook archives with reader mime type * fix: detect fbz ebooks from compound filename * fix: authorize fbz ebooks from compound filename * fix: scope ebook catalog facets * fix: reject narrator queries for ebooks * fix: build ebook recommendation text from authors * fix: include ebooks in embedding eligibility * fix: include ebooks in recommendation media mix * fix: include ebooks in recently added recommendations * feat: include ebook progress in recommendation signals * feat: include ebooks in continue watching sections * feat: include ebooks in catalog progress metrics * fix: read ebook isbn from epub metadata * fix: filter ebook asin provider aliases * fix: fall back from unsupported ebook reader files * fix: sort ebook catalogs by reader progress * fix: filter ebook catalogs by reader progress * fix: include ebooks in last watched catalog filters * feat: reflect ebook reader progress in item user state * feat: share ebook progress state across item surfaces * feat: report ebook scan progress * fix: include ebook activity in recommendations * fix: expose ebook reader progress on item detail * fix: support ebook subtree scans * fix: honor profile header for ebook item progress * fix: add ebook library default sections * fix: route ebook continue cards to reader * fix: hide watched toggle for ebooks * fix: route ebook watch tonight cards to reader * fix: route ebook hero actions to reader * fix: detect archive ebook reader formats by filename * feat: cache embedded ebook covers during scan * fix: encode ebook hero reader links * fix: persist non-epub ebook reader progress * fix: scope narrator catalog badges to audiobooks * fix: merge ebook reader progress during item repair * fix: label ebook progress filters as read * fix: show ebook related rails as book covers * fix: remove txt ebook reader support * fix: reject txt ebook reader files * fix: label ebook advanced filters as read * fix: label ebook personalized sorts as read * fix: remove plain text reader loader path * test: cover ebook unread catalog rules * fix: preserve ebook reader library context * fix: link ebook genres with library scope * fix: encode related rail item links * fix: encode catalog card item links * fix: encode hero and continue item links * fix: encode watch tonight item links * fix: encode recommendation and search item links * test: cover ebook scan format set * fix: label ebook search results clearly * fix: make global search prompt media neutral * fix: encode catalog read API ids * fix: encode item API ids * fix: include ebook reader vendor in docker build * fix: make ebook reader build clean * fix: clean ebook embedded descriptions * docs: plan ebook reader shell parity * feat: add ebook reader shell controls * fix: widen ebook scrolled reader flow * fix: remove scrolled reader content width cap * docs: plan ebook reader full parity * feat: persist ebook reader config * feat: add ebook annotations and bookmarks * feat: add ebook reader tools and aids * feat: add ebook advanced reader settings * fix: keep ebook reader panel in viewport * fix: use foliate sizing units for ebook scroll flow * fix: keep ebook settings controls readable * fix: simplify ebook reader settings controls * feat(ebooks): extract local covers during scan (#98) * feat(ebooks): extract local covers during scan * fix(ebooks): read nullable poster paths during cover scan * fix(catalog): coalesce nullable media artwork fields * fix(ebooks): group sibling formats by book identity * fix(ebooks): tolerate legacy ebook metadata encodings * fix(ebooks): decode PDF hex metadata strings * fix(ebooks): harden local cover extraction and format grouping Address review findings on the local cover scan: - Restrict generic sidecar covers (cover.jpg, folder.png, ...) to single-book directories, always accept images named after the book file, and apply exactly one cover per reconcile with sidecar taking precedence over the embedded cover. - Replace the read-then-write poster update with an atomic conditional UPDATE (ItemRepository.SetLocalPoster) so provider/admin artwork is never clobbered by concurrent writers, and refresh locally owned posters when the extracted cover bytes change (thumbhash compare). - Preserve UTF-8 PDF Info strings (including a UTF-8 BOM) instead of forcing everything through Windows-1252; the cp1252 fallback now only applies to non-UTF-8 bytes. - Select EPUB covers by manifest media-type with properties="cover-image" outranking the EPUB2 meta name="cover" id, so XHTML cover pages no longer shadow the real image. - Order CBZ pages naturally (2.jpg before 10.jpg, ch2/ before ch10/) when picking the cover page, via a single O(n) min-scan. - Bump the ebook content group key scheme to version 2 and reprocess rows written under older versions so pre-existing libraries gain sibling-format grouping instead of accumulating duplicates. - Group different formats only (a same-format sibling with colliding sparse metadata stays a separate item) and stop a joining sibling's embedded metadata from overwriting a provider-matched item. - Decode any IANA-labelled OPF/FB2 XML charset (windows-1251, koi8-r, shift_jis, ...) via x/net/html/charset, and wire the charset reader into FB2 parsing which previously had none. - Strip the full .fb2.zip double extension from filename-derived titles and group keys. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: rxwatcher <rxwatcher@users.noreply.github.com> Co-authored-by: Quick <31828688+Quick104@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com> * feat(ebooks): add reader profiles and ruler (#99) * feat(ebooks): extract local covers during scan * fix(ebooks): read nullable poster paths during cover scan * fix(catalog): coalesce nullable media artwork fields * fix(ebooks): group sibling formats by book identity * fix(ebooks): tolerate legacy ebook metadata encodings * fix(ebooks): decode PDF hex metadata strings * feat(ebooks): add reader profiles and ruler * fix(ebooks): address reader ruler and profile review findings - skip renderer setStyles/render when computed styles and attributes are unchanged, so ruler position updates no longer re-style the book view - drag the ruler via a local draft that commits on release, with the surface rect cached at pointer-down - migrate font values persisted before the generic stacks (Inter, Georgia, Merriweather, legacy serif) so the font select never renders blank, with a Custom fallback option for unknown values - make the ruler band click-through and move dragging to a dedicated keyboard-accessible slider handle so links and text selection keep working under the band - share font stacks between options and profiles via READER_FONT_STACKS - surface the active reading profile, move presets to the top of the settings panel, and drop the redundant profile button aria-labels Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(ebooks): resolve prefer-const lint error in readest document lib `pnpm run lint` failed on the branch because `direction` is never reassigned in getDirection; split the destructure so only the reassigned `writingMode` stays mutable. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: rxwatcher <rxwatcher@users.noreply.github.com> Co-authored-by: Quick <31828688+Quick104@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com> * Merge branch 'main' into work/ebooks-reader-base Brings the ebook integration branch up to date with main (audiobook library redesign, continue-watching rework and card affordances, quic-go bump, jellycompat fixes). Conflict resolutions favor main's generalized mechanisms and register ebooks with them: - media scope validation goes through IsValidMediaScope (now including "ebook" alongside main's "video" group scope), in Go and in the web filter/search types - continue-watching uses main's typed rails; reading-type sections pull resume points from ebook_reader_progress and the ebook library default section is wired to ContinueTypeConfig(ContinueTypeReading) - item_repo keeps main's derived select-list machinery (itemColumnExpr) and both poster accessors (GetPoster/SetLocalPoster for ebook covers, GetPosterPath for audiobook covers) - web cards/hero/watch-tonight adopt main's buildMediaPlayHref helpers, which now route ebooks to /reader/ebook and encode content ids; ebook affordances (BookOpen icon, Read verb, percent-read subtitle) carry over onto main's reworked components - LibraryForm ebook support ported into main's refactored useLibraryForm/libraryTypes modules Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(docker): copy foliate-js vendor into Dockerfile.dev frontend stage foliate-js is a file:vendor/foliate-js dependency, so pnpm install needs the vendor directory before the lockfile install layer. The production Dockerfile already copies it; the dev image was missed, breaking make dev-deploy with ENOENT on /app/web/vendor/foliate-js. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(ebooks): render Continue Reading sections as upright poster cards All-ebook continue sections previously fell through to the horizontal 16:9 wide card; include ebooks in the poster-variant check so book covers render in their natural 2:3 framing. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(ui): stop related-rail highlight ring clipping on detail pages Move the current-item ring onto the cover artwork with a themed ring-offset color (matching the sidebar profile highlight) and give the scroll container top headroom so the ring is not cut off by overflow-x-auto. Applies to both ebook and audiobook detail rails. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(scanner): harden ebook scanning against data loss and bad metadata - Reconcile missing ebook files like video/audio, with real per-root walk failure tracking (failed/unmounted roots are excluded from deletion), symlinked-root support via the shared logical walker, and the empty-root cleanup allowance before any destructive reconciliation. - Create ebook items as 'pending' so enrichment can promote them to 'matched' (backfill migration included), and protect matched items from re-scan clobbering: title/year skipped, people/series fill-empty only. - PDF metadata: scan head + tail windows (non-linearized PDFs keep the Info dict at the end), require proper key delimiters, head values win. - Cap plain .fb2 reads like .fbz entries; drop .md as an ebook format. - gofmt internal/scanner/audiobook.go (pre-existing drift). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(ebooks): make enrichment failures non-terminal with dedicated backoff state - Provider errors now record a failure (capped retries) instead of stamping last_refreshed, which permanently excluded items after transient outages. - Unconfigured metadata chains and the scan-window membership race skip the item without stamping or burning a retry. - Failure tracking moves to a new ebook_enrichment_state table, decoupling it from media_items.refresh_failures (shared with metadata refresh debt). - Preserve non-author people credits when persisting enrichment results. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(catalog): gate ebook progress on hidden history and centralize threshold - Apply user_history_hidden_items gating (video semantics) to the ebook watched/in-progress filters, progress sort plan, and Continue Reading. - Continue Reading pages past dismissed items via the shared collector and dedupes items across pages (also fixes the video path's latent exposure). - Centralize the 0.9 finished threshold as models.EbookFinishedProgressThreshold with a single SQL-interpolated mirror in catalog. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(recommendations): correct watcher counting and wire ebook taste signals - itemWatchersQuery dedupes to distinct (watcher, item) rows so one binge-watcher can no longer satisfy minWatchers; the eligibility floor now counts distinct accounts rather than profiles. - Hidden-history gating on GetEbookReaderProgressForUser (signal reader). - Ebook reading produces canonical implicit taste signals (weighted like the equivalent movie progress ratio); ebooks join taste-seed candidates. - Stale GetRecentlyAddedItems doc comment corrected. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(api): harden ebook reader endpoints and serve a Content-Security-Policy - Serve a CSP on all SPA HTML responses: blob/srcdoc book iframes inherit it, so script-src 'self' 'wasm-unsafe-eval' blocks script execution from malicious book content (sandbox alone is defeated by the WebKit allow-scripts requirement). Threat model documented on the constant. - X-Content-Type-Options: nosniff on frontend, jellycompat, and ebook file responses; MIME resolution can no longer fall through to octet-stream for an admitted ebook file. - Annotation PATCH: presence-aware field semantics (absent keeps, present sets/clears), invariant re-validation on the merged row, and an atomic SELECT ... FOR UPDATE read-merge-write. - Request size caps (413) on progress/config/annotation writes; Content-Disposition via mime.FormatMediaType; hidden-history gating in the shared ebook progress lister; FK-cascade indexes for reader tables. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(api): native read-state endpoints for ebooks - POST/DELETE /watched/{id} accepts ebook content IDs: mark read upserts progress 1.0 preserving the reader's file/location (or picks the preferred reader file for never-opened books); mark unread mirrors video unwatch semantics and deletes the progress row. - /history/remove accepts ebooks: hides via user_history_hidden_items without touching the reading position (hidden != unread; next reading activity resurfaces the book, mirroring video re-watch). - Access-filter checks match the video branch; shared logic lives in ebook_read_state.go. Sort metrics/user-state thresholds use the shared constant; profile-header fallback deduplicated. Clients: response is {type: "ebook", affected_count: 1, played: bool}; the existing watched SSE event fires. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(web): harden the ebook reader UI - Open-flow race: cancellation checked after every await with full stale-run teardown (no wrong-file progress saves, no leaked views/blob URLs); book.destroy() on cleanup. - Progress: monotonic stale-response guard; visibilitychange flush uses the refresh-capable client, pagehide uses keepalive; per-book cross-format progress documented as deliberate. - Settings: side effects out of the setState updater; local edits no longer clobbered by late server config; pending saves flushed on unmount/pagehide. - TTS: generation token so Stop actually stops (Chromium/Firefox synthetic events); Media Session uninstalled on unmount. - External book links: http(s) only, opened with noopener,noreferrer. - apiBlob 512 MiB guard with a user-facing error; fraction bookmarks navigable; search-result key collisions fixed; dead e-ink code removed; getLibrarySortRelevanceScope deduplicated; md format dropped. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(web): mark read/unread affordances for ebooks - Item detail gets a Mark Read/Unread button; card menus drop the ebook gate and share type-aware labels/toasts (also dedupes audiobook wording). - Watched-state invalidation includes the reader progress query key so the Continue button and percent refresh after toggling. - Continue Reading dismiss copy for ebooks; dismissal path now URL-encodes item IDs (ebook content IDs can contain reserved characters). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: record the PR #124 review and hardening pass Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: rxwatcher <rxwatcher@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Problem
Silo had no ebook support: no way to scan ebook libraries, no metadata/series handling for books, and no way to read them. This branch adds ebooks as a first-class media type with feature parity modeled on the audiobook architecture.
What's included (121 commits)
Scanner & metadata
SetLocalPosterguards atomically in SQL)Reader
ebook_reader_progress), reflected on item detail, continue rails, catalogs, and recommendationsCatalog & discovery integration
ebookmedia scope across catalog queries, filters, badges, sorts (author/series), and facets — with read/unread labeling instead of watch terminologycontinue_type: reading)Migrations:
ebook_series,ebook_reader_progress,ebook_reader_state(timestamped Goose migrations).Approach
Ebooks deliberately mirror the audiobook architecture (see
docs/architecture/): same scanner foundation, same catalog scope mechanics, same section typing. The final merge from main resolved 28 conflicting files by adopting main's generalized mechanisms (IsValidMediaScope, typed continue rails,buildMediaPlayHref, derived select-list machinery initem_repo) and registering ebooks with them rather than keeping branch-local variants.Test plan
go build ./...,go vet ./internal/..., package tests forsections,catalog,scanner,recommendations,api/handlersall passtsc -bclean; ESLint 0 errors; Prettier cleangit merge-treeagainst main is conflict-freeRisks / follow-up
AI-use disclosure
Branch developed with AI assistance; the final main merge resolution, review fixes on #99, and this PR description were done by Claude Code with human direction.
🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Tests
Review & hardening pass (2026-06-10)
This branch received a full two-round review — a complete PR review followed by an adversarial security/edge-case pass — with all findings fixed in commits
36ffea7d..90c45fd8. The complete record lives indocs/pr124-ebooks-review-hardening.md.Security: CSP on all SPA HTML responses blocking script execution from book content (the foliate sandbox alone is defeated by the WebKit
allow-scriptsrequirement);nosniff+ nooctet-streamfallthrough on ebook file serving; external book links restricted to http(s) withnoopener,noreferrer; atomic presence-aware annotation PATCH; request size caps; RFC 5987 Content-Disposition. Verified clean: no IDOR, no path traversal, validated progress input.Reliability: ebook missing-file reconciliation with walk-failure guards and empty-root allowance (an unmounted share can no longer wipe a library); non-terminal enrichment failure backoff in a dedicated state table;
pending→matchedstatus lifecycle with backfill so curated metadata survives re-scans; PDF head+tail metadata scan; FK-cascade indexes.Consistency: hidden-history gating across every ebook progress surface (video semantics); distinct-watcher/distinct-account co-watch counting; ebook reading feeds implicit taste signals; centralized finished threshold; reader open-flow race teardown, ordered progress writes with unload flush, working TTS stop.
Feature completion: native
POST/DELETE /watched/{id}and/history/removefor ebooks plus Mark Read/Unread web UI.Verified: full Go test suite, 972 web tests, production frontend build, ESLint/Prettier,
make verify-local-paths. Branch containsorigin/mainin full (merge-base = main tip) — merges without conflicts.🤖 Reviewed and hardened with Claude Code