Repository navigation
fix(audiobooks): complete playback and catalog parity - #96
Conversation
📝 WalkthroughWalkthroughThis PR integrates audiobook support across the backend and frontend. The backend adds audiobook sort metrics (author/narrator/series), includes audiobooks in recommendations and scanner pipelines, introduces a ChangesAudiobook platform integration
Sequence Diagram(s)sequenceDiagram
participant User as User/Client
participant Frontend as React Components
participant PlaybackCtx as AudiobookPlaybackProvider
participant Player as AudiobookPlayer
participant Session as PlaybackSession
participant API as Backend API
User->>Frontend: Click "Listen Book"
Frontend->>PlaybackCtx: startPlayback({ contentId, ... })
PlaybackCtx->>Player: render with activeRequest
Player->>API: POST /playback/start (with disable_progress_persistence)
API->>Session: Create session, SetProgressPersistenceDisabled
Session-->>API: Return sessionId, streamUrl
API-->>Player: Return session
Player->>Player: Play audio stream via sessionId
Player-->>PlaybackCtx: onPlaybackStateChange (status)
PlaybackCtx-->>Frontend: Update currentTime/playing state
Frontend->>Frontend: Render play/pause icon, resume label
User->>Frontend: Click pause link
Frontend->>PlaybackCtx: toggleActivePlayback()
PlaybackCtx->>Player: controls.togglePlay()
Player->>Player: audio.pause()
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
|
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (4)
web/src/pages/ItemDetail/AudiobookContent.tsx (1)
185-191: ⚡ Quick winRefactor auto-play effect to satisfy React exhaustive-deps rules.
The
useEffectcallsopenPlayer(line 190) without including it or its dependencies in the deps array. While thehandledPlayParamRefguard prevents issues in practice, this violates React Hooks rules and will trigger ESLint warnings witheslint-plugin-react-hooks.Recommended fix — wrap
openPlayerinuseCallback:+ const openPlayer = useCallback((atSeconds: number) => { - function openPlayer(atSeconds: number) { audiobookPlayback?.startPlayback({ contentId: item.content_id, title: item.title, author, narrator, posterUrl: item.poster_url, files, initialPositionSeconds: atSeconds, }); - } + }, [audiobookPlayback, item.content_id, item.title, author, narrator, item.poster_url, files]);Then add
openPlayerto the effect's dependency array on line 191.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/pages/ItemDetail/AudiobookContent.tsx` around lines 185 - 191, The effect is calling openPlayer but not listing it in deps, violating exhaustive-deps; wrap openPlayer in useCallback (capturing any external values it uses, e.g., resumeSeconds, hasProgress, searchParams if referenced) so it becomes stable, then add openPlayer to the useEffect dependency array alongside files.length, hasProgress, resumeSeconds, and searchParams; keep the handledPlayParamRef guard as-is.web/src/pages/audiobooks/player/AudiobookPlayer.tsx (1)
59-74: ⚖️ Poor tradeoffConsider throttling or debouncing the playback state callback.
This
useEffectfires on everycurrentTimeupdate, which occurs frequently during playback (potentially multiple times per second). Each call triggersonPlaybackStateChange, which updates state in the parent provider and causes downstream re-renders. If consumers perform expensive work in response to these updates, this could create performance issues.Consider either:
- Throttling
currentTimeupdates (e.g., emit at most once per second)- Using a ref for high-frequency values and only emitting status changes for discrete events (play/pause/seek)
- Documenting that
onPlaybackStateChangemust be memoized/lightweight🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/pages/audiobooks/player/AudiobookPlayer.tsx` around lines 59 - 74, The useEffect calling onPlaybackStateChange on every playback.currentTime update floods consumers; modify the AudiobookPlayer to throttle emissions (e.g., only call onPlaybackStateChange at most once per second) or switch to a hybrid approach: keep high-frequency currentTime in a ref and only emit via onPlaybackStateChange for discrete events (play/pause/seek) and throttled time updates. Locate the effect that references useEffect and onPlaybackStateChange (and the playback object: playback.currentTime, playback.duration, playback.playing, playback.hasFile) and implement a throttling timer or debounce logic (or use a stable ref and trigger onPlaybackStateChange from a setInterval) so parent updates happen at a lower rate while still emitting immediate discrete state changes.web/src/pages/audiobooks/player/audiobookPlaybackContext.tsx (1)
53-56: ⚡ Quick winEvery playback request forces a full player remount.
Incrementing
requestKeyon line 55 causes theAudiobookPlayercomponent to fully remount (line 86 usesrequestKeyin the key), even when the user restarts the same audiobook. This discards any internal player state (buffered data, network connections) and could cause a noticeable delay when toggling playback or restarting.If the remount is intentional to ensure clean state, consider documenting this behavior. Otherwise, consider only incrementing
requestKeywhencontentIdchanges:setActiveRequest((previous) => ({ ...input, - requestKey: (previous?.requestKey ?? 0) + 1, + requestKey: previous?.contentId === input.contentId + ? (previous.requestKey ?? 0) + : (previous?.requestKey ?? 0) + 1, }));🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/pages/audiobooks/player/audiobookPlaybackContext.tsx` around lines 53 - 56, The current setActiveRequest call always increments requestKey causing AudiobookPlayer to remount on every playback request; change the update logic in setActiveRequest (the function that sets activeRequest/requestKey) to only increment requestKey when the content identifier changes (compare previous?.contentId or previous?.contentId vs input.contentId) and otherwise keep the existing requestKey so the AudiobookPlayer (which uses requestKey as its key) won't unmount on restarts of the same audiobook; preserve spreading of input and ensure requestKey is initialized when previous is undefined.web/src/lib/mediaNavigation.test.ts (1)
5-11: ⚡ Quick winConsider expanding test coverage for routing logic.
The test suite currently verifies only the podcast fallback case. Adding tests for the primary routing paths (movie/episode →
/watch/, audiobook →/item/withplay=1) and parameter handling (libraryId,restart) would strengthen confidence in the utility's correctness with minimal effort.📋 Example test cases to add
describe("buildMediaPlayHref", () => { + it("routes movies to video watch with libraryId", () => { + expect(buildMediaPlayHref({ contentId: "movie-1", type: "movie", libraryId: 7 })).toBe( + "/watch/movie-1?libraryId=7", + ); + }); + + it("routes audiobooks to item detail with play flag", () => { + expect(buildMediaPlayHref({ contentId: "book-1", type: "audiobook" })).toBe( + "/item/book-1?play=1", + ); + }); + + it("includes restart parameter when provided", () => { + expect(buildMediaPlayHref({ contentId: "ep-1", type: "episode", restart: true })).toBe( + "/watch/ep-1?restart=1", + ); + }); + it("routes podcasts to item detail instead of video watch", () => {🤖 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/lib/mediaNavigation.test.ts` around lines 5 - 11, Add additional unit tests for buildMediaPlayHref to cover primary routing and parameter handling: add cases asserting that types "movie" and "episode" produce "/watch/{contentId}" (including restart=true mapping to "?t=0" or proper query), that type "audiobook" routes to "/item/{contentId}" with "play=1" query, and that optional params like libraryId are preserved in the generated href; reference the existing mediaNavigation.test.ts describe block and include individual it() cases for each scenario (movie, episode, audiobook, libraryId, restart) to expand coverage.
🤖 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/scanner/audiobook_cover.go`:
- Around line 132-137: The loop that populates byName currently accepts any
non-directory DirEntry allowing symlinks; update the checks in the entries loop
(the one that writes the byName map) to skip non-regular files and symlinks by
verifying DirEntry.Type()/Mode indicates a regular file (e.g. use
entry.Type().IsRegular() or entry.Info().Mode().IsRegular() and skip if
entry.Type()&os.ModeSymlink != 0), and apply the same guard before
opening/reading sidecar files in the later loop (the block around lines 154-159)
so you never follow symlinks or process non-regular files when building/reading
byName.
In `@internal/sections/fetcher.go`:
- Around line 2805-2815: The matchesContinueWatchingFilter function currently
returns false in its default case causing all items to be filtered out for
unknown filterType; change the behavior so unknown or legacy FilterType values
do not drop items—modify matchesContinueWatchingFilter to treat unrecognized
filterType as a pass-through (return true) so continue-watching sections remain
populated when FilterType is non-empty, and optionally add a debug log noting
the unknown filterType for visibility; ensure references to FilterType usage
(where FilterType is checked before calling matchesContinueWatchingFilter) are
left intact.
In `@migrations/sql/20260608183000_enable_audiobookshelf_compat_default.sql`:
- Around line 1-25: The migration currently force-enables the audiobookshelf
compatibility flag by setting server_settings.value = 'true' for any row with
key = 'audiobookshelf_compat.enabled' whose stored value is
blank/0/false/no/off; instead only set it to 'true' when the key is
missing/blank or when it can be inferred from the legacy audiobooks.enabled
kill-switch (i.e., preserve explicit disables). Update the Up statement to: 1)
insert a 'true' row only when there is no existing row for key =
'audiobookshelf_compat.enabled' or when its value is truly empty/NULL (not when
it equals an explicit false-like string), or 2) set to 'true' only for rows
derived from audiobooks.enabled being absent/false via a join/subquery; ensure
the Down reverses the insert only if it was created by this migration and do not
overwrite rows where audiobookshelf_compat.enabled was explicitly set to 'false'
by an operator; refer to audiobookshelf_compat.enabled, audiobooks.enabled,
Service.ABSCompatEnabled(), GetString() and cmd/silo/main.go to validate
behavior.
In `@web/src/pages/audiobooks/player/audiobookPlaybackContext.tsx`:
- Around line 46-52: The current startPlayback creates a synthetic active state
(setActive({... duration: 0, playing: false ...})) which causes UI flashes;
update startPlayback to avoid setting a fake active immediately — either
setActive(null) and wait for AudiobookPlayer.onPlaybackStateChange to populate
active, or initialize setActive using real values from the input (use
input.initialPositionSeconds and input.item.audiobook.total_duration_seconds) so
duration and playing are accurate; change the logic in startPlayback and any
callers that expect immediate active to handle null or the accurate initial
values.
---
Nitpick comments:
In `@web/src/lib/mediaNavigation.test.ts`:
- Around line 5-11: Add additional unit tests for buildMediaPlayHref to cover
primary routing and parameter handling: add cases asserting that types "movie"
and "episode" produce "/watch/{contentId}" (including restart=true mapping to
"?t=0" or proper query), that type "audiobook" routes to "/item/{contentId}"
with "play=1" query, and that optional params like libraryId are preserved in
the generated href; reference the existing mediaNavigation.test.ts describe
block and include individual it() cases for each scenario (movie, episode,
audiobook, libraryId, restart) to expand coverage.
In `@web/src/pages/audiobooks/player/audiobookPlaybackContext.tsx`:
- Around line 53-56: The current setActiveRequest call always increments
requestKey causing AudiobookPlayer to remount on every playback request; change
the update logic in setActiveRequest (the function that sets
activeRequest/requestKey) to only increment requestKey when the content
identifier changes (compare previous?.contentId or previous?.contentId vs
input.contentId) and otherwise keep the existing requestKey so the
AudiobookPlayer (which uses requestKey as its key) won't unmount on restarts of
the same audiobook; preserve spreading of input and ensure requestKey is
initialized when previous is undefined.
In `@web/src/pages/audiobooks/player/AudiobookPlayer.tsx`:
- Around line 59-74: The useEffect calling onPlaybackStateChange on every
playback.currentTime update floods consumers; modify the AudiobookPlayer to
throttle emissions (e.g., only call onPlaybackStateChange at most once per
second) or switch to a hybrid approach: keep high-frequency currentTime in a ref
and only emit via onPlaybackStateChange for discrete events (play/pause/seek)
and throttled time updates. Locate the effect that references useEffect and
onPlaybackStateChange (and the playback object: playback.currentTime,
playback.duration, playback.playing, playback.hasFile) and implement a
throttling timer or debounce logic (or use a stable ref and trigger
onPlaybackStateChange from a setInterval) so parent updates happen at a lower
rate while still emitting immediate discrete state changes.
In `@web/src/pages/ItemDetail/AudiobookContent.tsx`:
- Around line 185-191: The effect is calling openPlayer but not listing it in
deps, violating exhaustive-deps; wrap openPlayer in useCallback (capturing any
external values it uses, e.g., resumeSeconds, hasProgress, searchParams if
referenced) so it becomes stable, then add openPlayer to the useEffect
dependency array alongside files.length, hasProgress, resumeSeconds, and
searchParams; keep the handledPlayParamRef guard as-is.
🪄 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: c44393af-add8-4f13-a13d-89e5cf52f557
📥 Commits
Reviewing files that changed from the base of the PR and between 24d2103 and eb698ca882b540296efbe43b8101ea65f59d876c.
📒 Files selected for processing (55)
internal/api/handlers/items.gointernal/api/handlers/sections.gointernal/audiobooks/enrichment.gointernal/audiobooks/enrichment_test.gointernal/audiobooks/service.gointernal/audiobooks/service_test.gointernal/catalog/detail.gointernal/catalog/detail_audiobook_test.gointernal/config/db_loader.gointernal/config/db_loader_test.gointernal/recommendations/accuracy_test.gointernal/recommendations/personal.gointernal/recommendations/repo.gointernal/scanner/audiobook_cover.gointernal/scanner/audiobook_cover_test.gointernal/scanner/audiobook_scan.gointernal/scanner/audiobook_test.gointernal/scanner/scanner.gointernal/sections/fetcher.gointernal/sections/fetcher_continue_watching_test.gointernal/sections/types.gomigrations/sql/20260607161414_add_audiobookshelf_compat_enabled.sqlmigrations/sql/20260608183000_enable_audiobookshelf_compat_default.sqlmigrations/sql/20260608210000_audiobook_continue_listening_section_title.sqlweb/src/App.tsxweb/src/api/types.tsweb/src/components/AdminLayout.tsxweb/src/components/ContinueWatchingCard.test.tsxweb/src/components/ContinueWatchingCard.tsxweb/src/components/HeroBanner.test.tsxweb/src/components/HeroBanner.tsxweb/src/components/ItemCard.test.tsxweb/src/components/ItemCard.tsxweb/src/components/Layout.tsxweb/src/components/MediaItemMenu.test.tsxweb/src/components/MediaItemMenu.tsxweb/src/components/SectionItemCard.tsxweb/src/components/WatchTonightCard.test.tsxweb/src/components/WatchTonightCard.tsxweb/src/components/WatchTonightDialog.tsxweb/src/components/catalog/CatalogFiltersPanel.tsxweb/src/components/catalog/catalogFilterBadges.test.tsweb/src/components/catalog/catalogFilterBadges.tsweb/src/components/collections/CollectionGuidedRulesEditor.tsxweb/src/components/watchtonight/CardStack.test.tsweb/src/components/watchtonight/CardStack.tsxweb/src/components/watchtonight/SwipeCard.tsxweb/src/lib/mediaNavigation.test.tsweb/src/lib/mediaNavigation.tsweb/src/pages/ItemDetail/AudiobookContent.test.tsxweb/src/pages/ItemDetail/AudiobookContent.tsxweb/src/pages/audiobooks/components/ChaptersSection.test.tsxweb/src/pages/audiobooks/components/ChaptersSection.tsxweb/src/pages/audiobooks/player/AudiobookPlayer.tsxweb/src/pages/audiobooks/player/audiobookPlaybackContext.tsx
c6c50e7 to
2eb996c
Compare
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (2)
web/src/components/sections/EditableSectionRows.tsx (1)
35-44: 💤 Low valueClean label derivation with fallback for legacy configs.
The helper correctly maps explicit
continue_typevalues and falls back to inferring "Listening" from audiobook-related config fields for older sections.📝 Optional: Add explanatory comment for fallback logic
function continueTypeLabel(config?: Record<string, unknown>): string | null { const value = config?.continue_type; if (value === "listening") return "Listening"; if (value === "watching") return "Watching"; if (value === "reading") return "Reading"; + // Fallback: infer from media_scope/filter_type for sections created before continue_type was added if (config?.filter_type === "audiobook" || config?.media_scope === "audiobook") { return "Listening"; } return null; }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/src/components/sections/EditableSectionRows.tsx` around lines 35 - 44, The function continueTypeLabel(config?: Record<string, unknown>) correctly maps continue_type values and falls back to audiobook inference, but add a short explanatory comment above the function (or above the audiobook fallback branch referencing config.filter_type and config.media_scope) that explains why we infer "Listening" for legacy audiobook configs and that the function returns string | null for unknown types; keep the comment concise and mention the legacy fields (continue_type, filter_type, media_scope) so future readers understand the fallback logic.internal/catalog/item_repo.go (1)
41-43: ⚖️ Poor tradeoffRemove the nil check for consistency and correct error semantics.
This nil check is inconsistent with all other methods in
ItemRepository(e.g.,GetByID,GetOriginalLanguage,GetByIDs) which don't guard against nil receiver/pool. Additionally, returningErrItemNotFoundwhen the repository is invalid is semantically incorrect — that error should indicate "the item doesn't exist in the database," not "the repository wasn't initialized properly."In idiomatic Go, a nil receiver panic is acceptable and clearly signals a programming error. If nil-safety is truly required here, it should either use a distinct error type or be applied consistently across all repository methods.
♻️ Recommended fix: remove the nil check
func (r *ItemRepository) GetPosterPath(ctx context.Context, contentID string) (string, error) { - if r == nil || r.pool == nil { - return "", ErrItemNotFound - } var posterPath string if err := r.pool.QueryRow(ctx, `🤖 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 41 - 43, Remove the nil check "if r == nil || r.pool == nil { return "", ErrItemNotFound }" from this ItemRepository method so behavior matches other methods (GetByID, GetOriginalLanguage, GetByIDs); do not convert an uninitialized repository into ErrItemNotFound—allow a nil receiver panic to surface as a programming error (or apply a consistent nil-safety policy everywhere), and ensure only actual "item not found" cases return ErrItemNotFound.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/sections/fetcher.go`:
- Around line 507-513: The code takes the address of the range variable field
entry.UpdatedAt (used when setting meta.ProgressUpdatedAt) which can lead to all
entries sharing the same pointer; make a local copy of entry.UpdatedAt before
taking its address (similar to how position and duration are handled) and assign
meta.ProgressUpdatedAt = &localCopy. Update the assignment near
episodeMeta[entry.MediaItemID] / meta.ProgressUpdatedAt so it uses the new local
variable instead of &entry.UpdatedAt.
In `@internal/sections/repo.go`:
- Around line 465-468: The existing-section detection SQL in
internal/sections/repo.go is only checking config->>'filter_type' = 'audiobook'
while ParseContinueType also treats config->>'media_scope' = 'audiobook' as
listening; update the AND clause (the query used to detect existing sections) to
include OR config->>'media_scope' = 'audiobook' so legacy listening configs are
matched (keep the rest of the conditional logic the same and reference this
change near the query that contains config->>'continue_type' = $2 and
config->>'filter_type').
In `@migrations/sql/20260608224625_home_continue_listening_split.sql`:
- Around line 10-19: The migration currently only tags library-scoped
continue_watching rows as listening when ps.title = 'Continue Listening',
causing other audiobook library rows without continue_type to be left unmodified
and later misclassified as watching; remove the title gate so the first UPDATE
targets all library continue_watching rows lacking continue_type for audiobook
folders (keep the join to media_folders mf, the lower(mf.type) IN
('audiobook','audiobooks') check, the ps.section_type = 'continue_watching'
condition, the NOT (ps.config ? 'continue_type') guard, and the ps.scope =
'library' / ps.library_id = mf.id linkage, and continue to set ps.config =
ps.config || '{"continue_type":"listening"}'::jsonb and updated_at = NOW()).
---
Nitpick comments:
In `@internal/catalog/item_repo.go`:
- Around line 41-43: Remove the nil check "if r == nil || r.pool == nil { return
"", ErrItemNotFound }" from this ItemRepository method so behavior matches other
methods (GetByID, GetOriginalLanguage, GetByIDs); do not convert an
uninitialized repository into ErrItemNotFound—allow a nil receiver panic to
surface as a programming error (or apply a consistent nil-safety policy
everywhere), and ensure only actual "item not found" cases return
ErrItemNotFound.
In `@web/src/components/sections/EditableSectionRows.tsx`:
- Around line 35-44: The function continueTypeLabel(config?: Record<string,
unknown>) correctly maps continue_type values and falls back to audiobook
inference, but add a short explanatory comment above the function (or above the
audiobook fallback branch referencing config.filter_type and config.media_scope)
that explains why we infer "Listening" for legacy audiobook configs and that the
function returns string | null for unknown types; keep the comment concise and
mention the legacy fields (continue_type, filter_type, media_scope) so future
readers understand the fallback logic.
🪄 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: 324102cb-bdb6-4274-848a-1dfe44afca03
📥 Commits
Reviewing files that changed from the base of the PR and between eb698ca882b540296efbe43b8101ea65f59d876c and f05563768b176be6a688148a04ae93863762d370.
📒 Files selected for processing (21)
internal/api/handlers/libraries.gointernal/api/handlers/sections.gointernal/api/handlers/sections_test.gointernal/catalog/item_repo.gointernal/scanner/audiobook_cover.gointernal/scanner/audiobook_cover_test.gointernal/sections/continue_type.gointernal/sections/defaults.gointernal/sections/defaults_test.gointernal/sections/fetcher.gointernal/sections/fetcher_continue_watching_test.gointernal/sections/recipes/library_staples.gointernal/sections/recipes/library_staples_test.gointernal/sections/repo.gomigrations/sql/20260608224625_home_continue_listening_split.sqlweb/src/components/ContinueWatchingCard.tsxweb/src/components/RecipeGallery/RecipeParamFields.tsxweb/src/components/sections/EditableSectionRows.tsxweb/src/components/sections/SectionEditorDrawer.test.tsweb/src/hooks/queries/homeDismissals.test.tsweb/src/hooks/queries/homeDismissals.ts
✅ Files skipped from review due to trivial changes (2)
- web/src/components/sections/SectionEditorDrawer.test.ts
- internal/api/handlers/sections_test.go
🚧 Files skipped from review as they are similar to previous changes (3)
- internal/api/handlers/sections.go
- internal/scanner/audiobook_cover.go
- internal/scanner/audiobook_cover_test.go
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
internal/scanner/audiobook_cover.go (1)
92-99: 💤 Low valueConsider using the returned path for better error context.
The
pathreturn value fromfindSidecarAudiobookCover(line 96) is ignored. WhenfindSidecarAudiobookCoverreturns an error, that error already includes the path fromreadSidecarAudiobookCover, but explicitly including it here would make the call site clearer for future maintenance.📝 Suggested improvement
- cover, _, err := findSidecarAudiobookCover(folderPath) + cover, coverPath, err := findSidecarAudiobookCover(folderPath) if err != nil || len(cover) == 0 { + if err != nil && coverPath != "" { + err = fmt.Errorf("reading sidecar cover %s: %w", coverPath, err) + } return err }🤖 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/audiobook_cover.go` around lines 92 - 99, In applyAudiobookSidecarCover, use the path returned from findSidecarAudiobookCover instead of discarding it: capture the returned path (e.g., path) and when returning an error wrap or annotate it with that path for clearer context (for example return fmt.Errorf("findSidecarAudiobookCover %s: %w", path, err)) and likewise when cover is empty return an error mentioning the path; update the function so the unique symbol applyAudiobookSidecarCover uses the path from findSidecarAudiobookCover for all error returns.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@web/src/pages/audiobooks/player/AudiobookPlayer.tsx`:
- Around line 75-130: The effect can schedule a timer that closes over the old
onPlaybackStateChange, causing stale-callback invocations; fix by storing the
latest onPlaybackStateChange in a ref (e.g., playbackStateCallbackRef) and
always calling playbackStateCallbackRef.current(...) inside emit instead of the
prop directly, update that ref whenever onPlaybackStateChange changes (via a
small useEffect or assignment), and ensure emit/timeout uses the ref so pending
timers invoke the current callback; keep existing refs lastPlaybackStateEmitRef
and playbackStateTimerRef logic but replace direct uses of onPlaybackStateChange
with the ref-backed callback to avoid stale closures.
---
Nitpick comments:
In `@internal/scanner/audiobook_cover.go`:
- Around line 92-99: In applyAudiobookSidecarCover, use the path returned from
findSidecarAudiobookCover instead of discarding it: capture the returned path
(e.g., path) and when returning an error wrap or annotate it with that path for
clearer context (for example return fmt.Errorf("findSidecarAudiobookCover %s:
%w", path, err)) and likewise when cover is empty return an error mentioning the
path; update the function so the unique symbol applyAudiobookSidecarCover uses
the path from findSidecarAudiobookCover for all error returns.
🪄 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: 1c23da08-1795-4b7c-bb04-b982b6f2f353
📥 Commits
Reviewing files that changed from the base of the PR and between f05563768b176be6a688148a04ae93863762d370 and dfcb2b2.
📒 Files selected for processing (66)
internal/api/handlers/items.gointernal/api/handlers/libraries.gointernal/api/handlers/playback.gointernal/api/handlers/playback_test.gointernal/api/handlers/sections.gointernal/api/handlers/sections_test.gointernal/catalog/item_repo.gointernal/playback/session.gointernal/recommendations/accuracy_test.gointernal/recommendations/personal.gointernal/recommendations/repo.gointernal/scanner/audiobook_cover.gointernal/scanner/audiobook_cover_test.gointernal/scanner/audiobook_scan.gointernal/sections/continue_type.gointernal/sections/defaults.gointernal/sections/defaults_test.gointernal/sections/fetcher.gointernal/sections/fetcher_continue_watching_test.gointernal/sections/recipes/library_staples.gointernal/sections/recipes/library_staples_test.gointernal/sections/repo.gointernal/sections/types.gomigrations/sql/20260608183000_enable_audiobookshelf_compat_default.sqlmigrations/sql/20260608210000_audiobook_continue_listening_section_title.sqlmigrations/sql/20260608224625_home_continue_listening_split.sqlweb/src/App.tsxweb/src/api/types.tsweb/src/components/AdminLayout.tsxweb/src/components/ContinueWatchingCard.test.tsxweb/src/components/ContinueWatchingCard.tsxweb/src/components/HeroBanner.test.tsxweb/src/components/HeroBanner.tsxweb/src/components/ItemCard.test.tsxweb/src/components/ItemCard.tsxweb/src/components/Layout.tsxweb/src/components/MediaItemMenu.test.tsxweb/src/components/MediaItemMenu.tsxweb/src/components/RecipeGallery/RecipeParamFields.tsxweb/src/components/SectionItemCard.tsxweb/src/components/WatchTonightCard.test.tsxweb/src/components/WatchTonightCard.tsxweb/src/components/WatchTonightDialog.tsxweb/src/components/catalog/CatalogFiltersPanel.tsxweb/src/components/catalog/catalogFilterBadges.test.tsweb/src/components/catalog/catalogFilterBadges.tsweb/src/components/collections/CollectionGuidedRulesEditor.tsxweb/src/components/sections/EditableSectionRows.tsxweb/src/components/sections/SectionEditorDrawer.test.tsweb/src/components/watchtonight/CardStack.test.tsweb/src/components/watchtonight/CardStack.tsxweb/src/components/watchtonight/SwipeCard.tsxweb/src/hooks/queries/homeDismissals.test.tsweb/src/hooks/queries/homeDismissals.tsweb/src/lib/mediaNavigation.test.tsweb/src/lib/mediaNavigation.tsweb/src/pages/ItemDetail/AudiobookContent.test.tsxweb/src/pages/ItemDetail/AudiobookContent.tsxweb/src/pages/audiobooks/components/ChaptersSection.test.tsxweb/src/pages/audiobooks/components/ChaptersSection.tsxweb/src/pages/audiobooks/player/AudiobookPlayer.tsxweb/src/pages/audiobooks/player/audiobookPlaybackContext.tsxweb/src/pages/audiobooks/player/useAudiobookPlayback.test.tsweb/src/pages/audiobooks/player/useAudiobookPlayback.tsweb/src/player/hooks/usePlaybackSession.tsweb/src/player/stream-url.ts
✅ Files skipped from review due to trivial changes (3)
- web/src/components/collections/CollectionGuidedRulesEditor.tsx
- web/src/pages/audiobooks/components/ChaptersSection.tsx
- internal/sections/recipes/library_staples_test.go
🚧 Files skipped from review as they are similar to previous changes (44)
- web/src/components/WatchTonightCard.test.tsx
- migrations/sql/20260608210000_audiobook_continue_listening_section_title.sql
- internal/scanner/audiobook_scan.go
- web/src/components/WatchTonightDialog.tsx
- web/src/components/catalog/CatalogFiltersPanel.tsx
- web/src/components/Layout.tsx
- web/src/components/ItemCard.test.tsx
- web/src/components/SectionItemCard.tsx
- web/src/lib/mediaNavigation.test.ts
- internal/recommendations/personal.go
- internal/api/handlers/libraries.go
- web/src/hooks/queries/homeDismissals.ts
- web/src/pages/audiobooks/components/ChaptersSection.test.tsx
- web/src/components/ContinueWatchingCard.test.tsx
- web/src/components/catalog/catalogFilterBadges.ts
- web/src/App.tsx
- internal/sections/types.go
- web/src/components/sections/SectionEditorDrawer.test.ts
- web/src/components/catalog/catalogFilterBadges.test.ts
- web/src/components/RecipeGallery/RecipeParamFields.tsx
- web/src/components/sections/EditableSectionRows.tsx
- internal/recommendations/accuracy_test.go
- internal/sections/fetcher_continue_watching_test.go
- web/src/components/HeroBanner.test.tsx
- internal/api/handlers/items.go
- internal/api/handlers/sections.go
- web/src/lib/mediaNavigation.ts
- web/src/components/ItemCard.tsx
- web/src/components/WatchTonightCard.tsx
- web/src/components/MediaItemMenu.tsx
- web/src/components/ContinueWatchingCard.tsx
- web/src/pages/ItemDetail/AudiobookContent.tsx
- internal/sections/defaults_test.go
- web/src/components/watchtonight/CardStack.test.ts
- internal/sections/continue_type.go
- internal/sections/recipes/library_staples.go
- internal/sections/fetcher.go
- web/src/components/watchtonight/SwipeCard.tsx
- web/src/pages/audiobooks/player/audiobookPlaybackContext.tsx
- internal/sections/defaults.go
- web/src/components/HeroBanner.tsx
- internal/api/handlers/sections_test.go
- web/src/components/watchtonight/CardStack.tsx
- internal/recommendations/repo.go
| useEffect(() => { | ||
| if (!onPlaybackStateChange) { | ||
| return; | ||
| } | ||
|
|
||
| const status: AudiobookPlayerStatus = { | ||
| contentId, | ||
| playing: playback.playing, | ||
| currentTime: playback.currentTime, | ||
| duration: playback.duration, | ||
| hasFile: playback.hasFile, | ||
| }; | ||
| const last = lastPlaybackStateEmitRef.current; | ||
| const statusChanged = | ||
| !last || | ||
| last.playing !== status.playing || | ||
| last.duration !== status.duration || | ||
| last.hasFile !== status.hasFile; | ||
| const now = Date.now(); | ||
|
|
||
| const emit = () => { | ||
| lastPlaybackStateEmitRef.current = { | ||
| emittedAt: Date.now(), | ||
| duration: status.duration, | ||
| hasFile: status.hasFile, | ||
| playing: status.playing, | ||
| }; | ||
| onPlaybackStateChange(status); | ||
| }; | ||
|
|
||
| if (!last || statusChanged || now - last.emittedAt >= 1000) { | ||
| if (playbackStateTimerRef.current != null) { | ||
| window.clearTimeout(playbackStateTimerRef.current); | ||
| playbackStateTimerRef.current = null; | ||
| } | ||
| emit(); | ||
| return; | ||
| } | ||
|
|
||
| if (playbackStateTimerRef.current == null) { | ||
| playbackStateTimerRef.current = window.setTimeout( | ||
| () => { | ||
| playbackStateTimerRef.current = null; | ||
| emit(); | ||
| }, | ||
| Math.max(0, 1000 - (now - last.emittedAt)), | ||
| ); | ||
| } | ||
| }, [ | ||
| contentId, | ||
| onPlaybackStateChange, | ||
| playback.currentTime, | ||
| playback.duration, | ||
| playback.hasFile, | ||
| playback.playing, | ||
| ]); |
There was a problem hiding this comment.
Stale closure: onPlaybackStateChange can be invoked with old reference.
The effect schedules a timer that closes over emit, which closes over the onPlaybackStateChange prop. If the parent changes onPlaybackStateChange while the timer is pending, the effect re-runs but skips scheduling a new timer (line 114 condition), leaving the old timer to fire with the stale callback. This can cause state updates in unmounted components or other lifecycle issues.
🔒 Recommended fix: store callback in a ref
+ const onPlaybackStateChangeRef = useRef(onPlaybackStateChange);
+ useEffect(() => {
+ onPlaybackStateChangeRef.current = onPlaybackStateChange;
+ }, [onPlaybackStateChange]);
+
useEffect(() => {
- if (!onPlaybackStateChange) {
+ if (!onPlaybackStateChangeRef.current) {
return;
}
const status: AudiobookPlayerStatus = {
contentId,
playing: playback.playing,
currentTime: playback.currentTime,
duration: playback.duration,
hasFile: playback.hasFile,
};
const last = lastPlaybackStateEmitRef.current;
const statusChanged =
!last ||
last.playing !== status.playing ||
last.duration !== status.duration ||
last.hasFile !== status.hasFile;
const now = Date.now();
const emit = () => {
lastPlaybackStateEmitRef.current = {
emittedAt: Date.now(),
duration: status.duration,
hasFile: status.hasFile,
playing: status.playing,
};
- onPlaybackStateChange(status);
+ onPlaybackStateChangeRef.current?.(status);
};
if (!last || statusChanged || now - last.emittedAt >= 1000) {
if (playbackStateTimerRef.current != null) {
window.clearTimeout(playbackStateTimerRef.current);
playbackStateTimerRef.current = null;
}
emit();
return;
}
if (playbackStateTimerRef.current == null) {
playbackStateTimerRef.current = window.setTimeout(
() => {
playbackStateTimerRef.current = null;
emit();
},
Math.max(0, 1000 - (now - last.emittedAt)),
);
}
}, [
contentId,
- onPlaybackStateChange,
playback.currentTime,
playback.duration,
playback.hasFile,
playback.playing,
]);🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@web/src/pages/audiobooks/player/AudiobookPlayer.tsx` around lines 75 - 130,
The effect can schedule a timer that closes over the old onPlaybackStateChange,
causing stale-callback invocations; fix by storing the latest
onPlaybackStateChange in a ref (e.g., playbackStateCallbackRef) and always
calling playbackStateCallbackRef.current(...) inside emit instead of the prop
directly, update that ref whenever onPlaybackStateChange changes (via a small
useEffect or assignment), and ensure emit/timeout uses the ref so pending timers
invoke the current callback; keep existing refs lastPlaybackStateEmitRef and
playbackStateTimerRef logic but replace direct uses of onPlaybackStateChange
with the ref-backed callback to avoid stale closures.
* fix(audiobooks): complete playback and catalog parity * fix(web): allow podcast continue targets * fix(audiobooks): use folder sidecar covers during scan * fix(audiobooks): read nullable poster paths during cover scan * feat(home): split continue listening sections * fix(catalog): coalesce nullable media artwork fields * feat(playback): surface audiobook sessions in admin activity * fix(audiobooks): address playback review feedback --------- Co-authored-by: rxwatcher <[email protected]> Co-authored-by: Quick <[email protected]>
* fix(audiobooks): complete playback and catalog parity * fix(web): allow podcast continue targets * fix(audiobooks): use folder sidecar covers during scan * fix(audiobooks): read nullable poster paths during cover scan * feat(home): split continue listening sections * fix(catalog): coalesce nullable media artwork fields * feat(playback): surface audiobook sessions in admin activity * fix(audiobooks): address playback review feedback --------- Co-authored-by: rxwatcher <[email protected]> Co-authored-by: Quick <[email protected]>
Summary
Stack
This PR is stacked on #94 (
work/audiobook-fixes-main). Review/merge #94 first; this PR should then rebase cleanly ontomain.Verification
go test ./internal/api/handlers ./internal/sections ./internal/recommendations ./internal/config ./internal/scanner ./internal/catalog ./internal/audiobooks/...pnpm --dir web exec tsc --noEmitpnpm --dir web exec vitest run src/components/WatchTonightCard.test.tsx src/pages/audiobooks/components/ChaptersSection.test.tsx src/components/catalog/catalogFilterBadges.test.ts src/components/catalog/CatalogFiltersPanel.test.tsx src/pages/ItemDetail/AudiobookContent.test.tsx src/components/HeroBanner.test.tsx src/components/watchtonight/CardStack.test.ts src/components/ItemCard.test.tsx src/components/ContinueWatchingCard.test.tsx src/components/MediaItemMenu.test.tsx src/components/collections/CollectionGuidedRulesEditor.test.tsx src/pages/audiobooks/player/MiniBar.test.tsx src/pages/audiobooks/player/useAudiobookPlayback.test.tsSummary by CodeRabbit
New Features
Tests