Skip to content

fix(audiobooks): complete playback and catalog parity - #96

Merged
Quick104 merged 8 commits into
mainfrom
work/audiobook-playback-catalog-parity
Jun 9, 2026
Merged

Quick104 merged 8 commits into
mainfrom
work/audiobook-playback-catalog-parity

Conversation

@RXWatcher

@RXWatcher RXWatcher commented Jun 8, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • add shared audiobook playback state so detail pages, hero, and global chrome can reflect active listen/pause state
  • route audiobook hero, continue, Watch Tonight, swipe, and menu actions through audiobook-safe navigation
  • add audiobook catalog sort metadata, section filtering, recommendation inclusion, and listening-specific UI copy
  • migrate default audiobook library continue sections from Continue Watching to Continue Listening

Stack

This PR is stacked on #94 (work/audiobook-fixes-main). Review/merge #94 first; this PR should then rebase cleanly onto main.

Verification

  • go test ./internal/api/handlers ./internal/sections ./internal/recommendations ./internal/config ./internal/scanner ./internal/catalog ./internal/audiobooks/...
  • pnpm --dir web exec tsc --noEmit
  • pnpm --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.ts

Summary by CodeRabbit

  • New Features

    • Added audiobook library support with browsing, searching, and sorting (by author, narrator, or series).
    • Introduced "Continue Listening" sections for audiobook libraries, replacing "Continue Watching."
    • Integrated audiobook playback controls with pause/resume functionality and session-based progress tracking.
    • Added audiobook cover art support with automatic detection from folder images.
    • Included audiobooks in personalized recommendations.
  • Tests

    • Added comprehensive test coverage for audiobook playback, sorting, filtering, and UI components.

@coderabbitai

coderabbitai Bot commented Jun 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This 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 ContinueType model for section semantics (watching/listening/reading), and refactors continue-watching section fetching to type-aware filtering. The frontend introduces a centralized audiobook playback context, session-based streaming, media-agnostic navigation helpers, and audiobook-specific labels in cards, menus, filters, and detail pages. Database migrations enable Audiobookshelf compatibility and update continue-listening section metadata.

Changes

Audiobook platform integration

Layer / File(s) Summary
Platform defaults and database migrations
migrations/sql/20260608183000_*.sql, migrations/sql/20260608210000_*.sql, migrations/sql/20260608224625_*.sql
SQL migrations enable Audiobookshelf compatibility by default, rename continue-watching to continue-listening for audiobook library sections, and conditionally insert a home-scoped continue-listening section with continue_type JSON config.
Backend sort metrics and recommendation inclusion
internal/api/handlers/items.go, internal/recommendations/personal.go, internal/recommendations/repo.go, internal/recommendations/accuracy_test.go
Item sort API adds author/narrator/series fields for audiobooks. Recommendation queries now include audiobooks in cold-start (taste seed, taste profile, recently added) and supplement candidate sets.
Scanner routing and sidecar cover application
internal/scanner/audiobook_cover.go, internal/scanner/audiobook_cover_test.go, internal/scanner/audiobook_scan.go
Scanner applies optional sidecar cover caching and metadata updates during audiobook reconciliation. Covers are discovered by filename pattern, size-validated, cached, and poster path is persisted with optional thumbhash.
Poster path query and COALESCE columns
internal/catalog/item_repo.go
ItemRepository.GetPosterPath queries poster path for metadata lookup. Nullable string columns return empty strings instead of NULLs via COALESCE to avoid JSON null handling issues.
Continue-type domain model and helpers
internal/sections/continue_type.go
Introduces ContinueType string type (watching/listening/reading) with JSON parsing that prefers continue_type, falls back to filter_type/media_scope, and provides item-type matching and next-up eligibility checks.
Section defaults and recipe presets
internal/sections/defaults.go, internal/sections/defaults_test.go, internal/sections/recipes/library_staples.go, internal/sections/recipes/library_staples_test.go
DefaultHomeSections/DefaultLibrarySectionsForType use ContinueTypeConfig for typed sections. Continue-watching recipe exposes two presets with watching/listening default params. Tests assert continue-type parsing and audiobook library seeding.
Section config validation and next-up insertion
internal/api/handlers/sections.go, internal/api/handlers/sections_test.go
validateSectionConfig accepts audiobook filter type and continue types. injectNextUpSection inserts Next Up after contiguous continue-watching rows instead of after the first. Tests verify validation and insertion ordering.
Section repository continue-listening insertion
internal/sections/repo.go
EnsureHomeContinueListeningSection finds or inserts a home-scoped continue-listening section, calculating insertion position after the first watching continue row. Shifts subsequent home section positions and creates the section with fixed metadata.
Continue-watching fetcher and dismissal filtering
internal/sections/fetcher.go, internal/sections/fetcher_continue_watching_test.go
fetchContinueWatchingSection derives continue type from config, loads dismissals once, paginates progress resolution, and filters via centralised matchesContinueWatchingFilter. Tests cover audiobook/ebook/video type matching and continue-type parsing.
Playback session state and progress persistence control
internal/playback/session.go, internal/api/handlers/playback.go, internal/api/handlers/playback_test.go
Session adds DisableProgressPersistence flag and SetProgressPersistenceDisabled method. Handler checks the flag on start playback, and persistProgress/persistStopAndHistory/scrobbling respect the flag. Test verifies progress is not persisted when disabled.
Audiobook playback context provider and player callbacks
web/src/pages/audiobooks/player/audiobookPlaybackContext.tsx, web/src/pages/audiobooks/player/AudiobookPlayer.tsx, web/src/App.tsx, web/src/components/AdminLayout.tsx, web/src/components/Layout.tsx
AudiobookPlaybackProvider manages global playback state (active request, controls, visibility). AudiobookPlayer exports AudiobookPlayerStatus/AudiobookPlayerControls callbacks for state reporting. App/Layout/AdminLayout integrate provider tree and use background bar visibility.
Audiobook playback hook with session streaming and realtime
web/src/pages/audiobooks/player/useAudiobookPlayback.ts, web/src/pages/audiobooks/player/useAudiobookPlayback.test.ts
useAudiobookPlayback manages server playback session lifecycle (POST start, keepalive progress, DELETE cleanup), builds tokenized stream URLs, wires realtime commands (pause/unpause/seek/stop), and invokes optional onStopRequested callback. Tests verify session flow, realtime handling, and chapter/sleep behavior.
Player stream URL builder
web/src/player/stream-url.ts, web/src/player/hooks/usePlaybackSession.ts, web/src/lib/mediaNavigation.test.ts
buildPlayerStreamUrl constructs tokenized URLs with optional seek parameters. usePlaybackSession and player hooks use this helper for all stream/subtitle URL generation.
Media navigation helpers
web/src/lib/mediaNavigation.ts, web/src/lib/mediaNavigation.test.ts
buildItemHref routes to /item/{contentId}, buildMediaPlayHref routes movie/episode to /watch/{contentId} and audiobook to /item/{contentId}?play=1, isVideoWatchHref detects watch URLs. Tests cover all media types.
Continue watching card and hero banner routing
web/src/components/ContinueWatchingCard.tsx, web/src/components/ContinueWatchingCard.test.tsx, web/src/components/HeroBanner.tsx, web/src/components/HeroBanner.test.tsx
ContinueWatchingCard and HeroBanner use buildMediaPlayHref/buildItemHref for audiobook routing and libraryId passing. HeroBanner integrates playback context to show play/pause/resume states for active audiobooks. Tests verify link generation, label computation, and pause handler.
Watch tonight and swipe card audiobook support
web/src/components/WatchTonightCard.tsx, web/src/components/WatchTonightCard.test.tsx, web/src/components/watchtonight/CardStack.tsx, web/src/components/watchtonight/CardStack.test.ts, web/src/components/watchtonight/SwipeCard.tsx
WatchTonightCard uses buildMediaPlayHref and conditionally renders "Listen" verb. CardStack exports playTargetForSwipeCard to route audiobooks via navigate instead of playback controller. CardActions accepts playLabel prop. Tests verify routing and label behavior.
Item card sort metadata and media item menu
web/src/components/ItemCard.tsx, web/src/components/ItemCard.test.tsx, web/src/components/MediaItemMenu.tsx, web/src/components/MediaItemMenu.test.tsx, web/src/components/SectionItemCard.tsx
SortMeta component displays author/narrator/series from sort_metrics. MediaItemMenu treats audiobook as leaf type with listening-specific labels ("Listen from Beginning", "Mark Listened"). MediaItemMenu supports optional libraryId prop. Tests cover audiobook sort fields and menu label generation.
Audiobook detail page and chapters integration
web/src/pages/ItemDetail/AudiobookContent.tsx, web/src/pages/ItemDetail/AudiobookContent.test.tsx, web/src/pages/audiobooks/components/ChaptersSection.tsx, web/src/pages/audiobooks/components/ChaptersSection.test.tsx
AudiobookContent refactored to use centralized playback context instead of local state, with auto-play from query param, play/pause icons, and dynamic resume labels. ChaptersSection shows "listening" status instead of "playing". Tests verify playback actions and chapter highlighting.
Catalog filters and active filter badges
web/src/components/catalog/CatalogFiltersPanel.tsx, web/src/components/catalog/catalogFilterBadges.ts, web/src/components/catalog/catalogFilterBadges.test.ts
CatalogFiltersPanel computes isAudiobookLibrary flag and passes it to badge calculation. getActiveFilterBadges renders "Listening: listened/unlistened" for audiobooks and "Watch: watched" for other types. Tests verify audiobook vs non-audiobook label rendering.
Collection editor and section editor UI
web/src/components/collections/CollectionGuidedRulesEditor.tsx, web/src/components/RecipeGallery/RecipeParamFields.tsx, web/src/components/sections/EditableSectionRows.tsx, web/src/components/sections/SectionEditorDrawer.test.ts
CollectionGuidedRulesEditor shows "Listening Status"/"Listened"/"Unlistened" labels for audiobook libraries. RecipeParamFields renders ContinueTypeParamField for continue-watching recipe. EditableSectionRows shows resume badge. Tests verify section payload preservation and label generation.
Home dismissal toast and library seeding
web/src/hooks/queries/homeDismissals.ts, web/src/hooks/queries/homeDismissals.test.ts, internal/api/handlers/libraries.go
Home dismissal toast uses mediaType to distinguish "Removed from Continue Listening" for audiobooks. Library creation calls EnsureHomeContinueListeningSection to seed audiobook-specific sections. Tests verify toast messaging and dismissal behavior.
Config parsing for audiobook media scope
internal/sections/types.go, web/src/api/types.ts
ParseConfigFilters accepts "audiobook" media scope. BrowseItemSortMetrics interface adds author/narrator/series_name optional fields.

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()
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • Silo-Server/silo-server#26: Both PRs extend the catalog/item "sort metrics" pipeline in internal/api/handlers/items.go—main PR adds author/narrator/series_name audiobook sort fields and routes new audiobook-specific queries, while retrieved PR #26 refactors listSortMetrics infrastructure to compute and attach per-item sort_metrics.
  • Silo-Server/silo-server#48: Both PRs touch web/src/App.tsx provider tree wiring around RealtimeEventsProvider—main PR wraps it with AudiobookPlaybackProvider, retrieved PR refactors realtime UI reactivity, so provider ordering and component interaction may overlap.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch work/audiobook-playback-catalog-parity

Base automatically changed from work/audiobook-fixes-main to main June 8, 2026 22:17

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (4)
web/src/pages/ItemDetail/AudiobookContent.tsx (1)

185-191: ⚡ Quick win

Refactor auto-play effect to satisfy React exhaustive-deps rules.

The useEffect calls openPlayer (line 190) without including it or its dependencies in the deps array. While the handledPlayParamRef guard prevents issues in practice, this violates React Hooks rules and will trigger ESLint warnings with eslint-plugin-react-hooks.

Recommended fix — wrap openPlayer in useCallback:

+ 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 openPlayer to 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 tradeoff

Consider throttling or debouncing the playback state callback.

This useEffect fires on every currentTime update, which occurs frequently during playback (potentially multiple times per second). Each call triggers onPlaybackStateChange, 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 currentTime updates (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 onPlaybackStateChange must 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 win

Every playback request forces a full player remount.

Incrementing requestKey on line 55 causes the AudiobookPlayer component to fully remount (line 86 uses requestKey in 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 requestKey when contentId changes:

  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 win

Consider 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/ with play=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.go
  • internal/api/handlers/sections.go
  • internal/audiobooks/enrichment.go
  • internal/audiobooks/enrichment_test.go
  • internal/audiobooks/service.go
  • internal/audiobooks/service_test.go
  • internal/catalog/detail.go
  • internal/catalog/detail_audiobook_test.go
  • internal/config/db_loader.go
  • internal/config/db_loader_test.go
  • internal/recommendations/accuracy_test.go
  • internal/recommendations/personal.go
  • internal/recommendations/repo.go
  • internal/scanner/audiobook_cover.go
  • internal/scanner/audiobook_cover_test.go
  • internal/scanner/audiobook_scan.go
  • internal/scanner/audiobook_test.go
  • internal/scanner/scanner.go
  • internal/sections/fetcher.go
  • internal/sections/fetcher_continue_watching_test.go
  • internal/sections/types.go
  • migrations/sql/20260607161414_add_audiobookshelf_compat_enabled.sql
  • migrations/sql/20260608183000_enable_audiobookshelf_compat_default.sql
  • migrations/sql/20260608210000_audiobook_continue_listening_section_title.sql
  • web/src/App.tsx
  • web/src/api/types.ts
  • web/src/components/AdminLayout.tsx
  • web/src/components/ContinueWatchingCard.test.tsx
  • web/src/components/ContinueWatchingCard.tsx
  • web/src/components/HeroBanner.test.tsx
  • web/src/components/HeroBanner.tsx
  • web/src/components/ItemCard.test.tsx
  • web/src/components/ItemCard.tsx
  • web/src/components/Layout.tsx
  • web/src/components/MediaItemMenu.test.tsx
  • web/src/components/MediaItemMenu.tsx
  • web/src/components/SectionItemCard.tsx
  • web/src/components/WatchTonightCard.test.tsx
  • web/src/components/WatchTonightCard.tsx
  • web/src/components/WatchTonightDialog.tsx
  • web/src/components/catalog/CatalogFiltersPanel.tsx
  • web/src/components/catalog/catalogFilterBadges.test.ts
  • web/src/components/catalog/catalogFilterBadges.ts
  • web/src/components/collections/CollectionGuidedRulesEditor.tsx
  • web/src/components/watchtonight/CardStack.test.ts
  • web/src/components/watchtonight/CardStack.tsx
  • web/src/components/watchtonight/SwipeCard.tsx
  • web/src/lib/mediaNavigation.test.ts
  • web/src/lib/mediaNavigation.ts
  • web/src/pages/ItemDetail/AudiobookContent.test.tsx
  • web/src/pages/ItemDetail/AudiobookContent.tsx
  • web/src/pages/audiobooks/components/ChaptersSection.test.tsx
  • web/src/pages/audiobooks/components/ChaptersSection.tsx
  • web/src/pages/audiobooks/player/AudiobookPlayer.tsx
  • web/src/pages/audiobooks/player/audiobookPlaybackContext.tsx

Comment thread internal/scanner/audiobook_cover.go Resolved
Comment thread internal/sections/fetcher.go Resolved
@RXWatcher
RXWatcher force-pushed the work/audiobook-playback-catalog-parity branch from c6c50e7 to 2eb996c Compare June 8, 2026 23:07

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (2)
web/src/components/sections/EditableSectionRows.tsx (1)

35-44: 💤 Low value

Clean label derivation with fallback for legacy configs.

The helper correctly maps explicit continue_type values 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 tradeoff

Remove 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, returning ErrItemNotFound when 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.go
  • internal/api/handlers/sections.go
  • internal/api/handlers/sections_test.go
  • internal/catalog/item_repo.go
  • internal/scanner/audiobook_cover.go
  • internal/scanner/audiobook_cover_test.go
  • internal/sections/continue_type.go
  • internal/sections/defaults.go
  • internal/sections/defaults_test.go
  • internal/sections/fetcher.go
  • internal/sections/fetcher_continue_watching_test.go
  • internal/sections/recipes/library_staples.go
  • internal/sections/recipes/library_staples_test.go
  • internal/sections/repo.go
  • migrations/sql/20260608224625_home_continue_listening_split.sql
  • web/src/components/ContinueWatchingCard.tsx
  • web/src/components/RecipeGallery/RecipeParamFields.tsx
  • web/src/components/sections/EditableSectionRows.tsx
  • web/src/components/sections/SectionEditorDrawer.test.ts
  • web/src/hooks/queries/homeDismissals.test.ts
  • web/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

Comment thread internal/sections/fetcher.go Resolved
Comment thread internal/sections/repo.go Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
internal/scanner/audiobook_cover.go (1)

92-99: 💤 Low value

Consider using the returned path for better error context.

The path return value from findSidecarAudiobookCover (line 96) is ignored. When findSidecarAudiobookCover returns an error, that error already includes the path from readSidecarAudiobookCover, 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.go
  • internal/api/handlers/libraries.go
  • internal/api/handlers/playback.go
  • internal/api/handlers/playback_test.go
  • internal/api/handlers/sections.go
  • internal/api/handlers/sections_test.go
  • internal/catalog/item_repo.go
  • internal/playback/session.go
  • internal/recommendations/accuracy_test.go
  • internal/recommendations/personal.go
  • internal/recommendations/repo.go
  • internal/scanner/audiobook_cover.go
  • internal/scanner/audiobook_cover_test.go
  • internal/scanner/audiobook_scan.go
  • internal/sections/continue_type.go
  • internal/sections/defaults.go
  • internal/sections/defaults_test.go
  • internal/sections/fetcher.go
  • internal/sections/fetcher_continue_watching_test.go
  • internal/sections/recipes/library_staples.go
  • internal/sections/recipes/library_staples_test.go
  • internal/sections/repo.go
  • internal/sections/types.go
  • migrations/sql/20260608183000_enable_audiobookshelf_compat_default.sql
  • migrations/sql/20260608210000_audiobook_continue_listening_section_title.sql
  • migrations/sql/20260608224625_home_continue_listening_split.sql
  • web/src/App.tsx
  • web/src/api/types.ts
  • web/src/components/AdminLayout.tsx
  • web/src/components/ContinueWatchingCard.test.tsx
  • web/src/components/ContinueWatchingCard.tsx
  • web/src/components/HeroBanner.test.tsx
  • web/src/components/HeroBanner.tsx
  • web/src/components/ItemCard.test.tsx
  • web/src/components/ItemCard.tsx
  • web/src/components/Layout.tsx
  • web/src/components/MediaItemMenu.test.tsx
  • web/src/components/MediaItemMenu.tsx
  • web/src/components/RecipeGallery/RecipeParamFields.tsx
  • web/src/components/SectionItemCard.tsx
  • web/src/components/WatchTonightCard.test.tsx
  • web/src/components/WatchTonightCard.tsx
  • web/src/components/WatchTonightDialog.tsx
  • web/src/components/catalog/CatalogFiltersPanel.tsx
  • web/src/components/catalog/catalogFilterBadges.test.ts
  • web/src/components/catalog/catalogFilterBadges.ts
  • web/src/components/collections/CollectionGuidedRulesEditor.tsx
  • web/src/components/sections/EditableSectionRows.tsx
  • web/src/components/sections/SectionEditorDrawer.test.ts
  • web/src/components/watchtonight/CardStack.test.ts
  • web/src/components/watchtonight/CardStack.tsx
  • web/src/components/watchtonight/SwipeCard.tsx
  • web/src/hooks/queries/homeDismissals.test.ts
  • web/src/hooks/queries/homeDismissals.ts
  • web/src/lib/mediaNavigation.test.ts
  • web/src/lib/mediaNavigation.ts
  • web/src/pages/ItemDetail/AudiobookContent.test.tsx
  • web/src/pages/ItemDetail/AudiobookContent.tsx
  • web/src/pages/audiobooks/components/ChaptersSection.test.tsx
  • web/src/pages/audiobooks/components/ChaptersSection.tsx
  • web/src/pages/audiobooks/player/AudiobookPlayer.tsx
  • web/src/pages/audiobooks/player/audiobookPlaybackContext.tsx
  • web/src/pages/audiobooks/player/useAudiobookPlayback.test.ts
  • web/src/pages/audiobooks/player/useAudiobookPlayback.ts
  • web/src/player/hooks/usePlaybackSession.ts
  • web/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

Comment on lines +75 to +130
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,
]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

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.

@Quick104
Quick104 merged commit e522c6a into main Jun 9, 2026
3 checks passed
@Quick104
Quick104 deleted the work/audiobook-playback-catalog-parity branch June 9, 2026 01:55
Quick104 added a commit that referenced this pull request Jun 11, 2026
* 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]>
Quick104 added a commit that referenced this pull request Jun 17, 2026
* 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants