Skip to content

fix(audiobooks): record Audiobookshelf plays in admin playback history - #2965

Merged
Quick104 merged 1 commit into
Silo-Server:mainfrom
Brady3035:Fix_abs_reporting
Oct 26, 2026
Merged

Quick104 merged 1 commit into
Silo-Server:mainfrom
Brady3035:Fix_abs_reporting

Conversation

@Brady3035

@Brady3035 Brady3035 commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: N/A
Validation tasks: none

Audiobookshelf listening sessions that a client closes normally never show up in the admin Playback History page. Only sessions a client abandons get recorded, because those expire through the native stale-session cleanup, which writes history. Admins see a partial, skewed picture of audiobook listening: clean plays are missing and abandoned ones are present.

POST /abs/api/session/{sid}/close ended the mirrored native playback session with SessionManager.StopSession, which removes the session without running finish hooks. The admin history row is written by the finish hook PlaybackHandler.handleFinishedSession.

Approach

ABS close now ends the native session with FinishSession, the same path jellycompat uses for a finished play, so the existing finish hook records the row. The ABS handler already owns progress (the native session has progress persistence disabled), so the hook writes only the admin history row, not watch progress. The ABS handler's existing live-session sync still clears the row from the live sessions view.

Watch time comes from the native session's measured progress, so it reflects the ABS sync heartbeats rather than the end position.

The existing close test now also checks that the finish hook runs once for the closed session.

Validation

  • gofmt: clean on the changed files.
  • go test ./internal/audiobooks/...: Clean
  • make lint-changed: Clean

Evidence

No before image as nothing was recorded before.

image

Build is 8c90021+dirty

Surface and build: web admin, Playback History, after playing and closing a book in an Audiobookshelf client.

Risks

Plays of multi-file audiobooks record the first file's duration, since the native session is started on the first file while the ABS position covers the whole book. completed can therefore be set early for those books. Abandoned ABS sessions already record history this way through expiry; this change makes it apply to closed sessions too.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.
  • Each test this pull request adds meets "Decide what to test" in CONTRIBUTING.md.
  • The Evidence section shows every change a user can see, or says there is none.

AI Disclosure

  • Harness: Claude (claude.ai app, agent workspace)
  • Tool(s): Claude
  • Model(s): claude-opus-5-5
  • Involvement: AI-assisted
  • Adversarial review: n/a
    🤖 Generated with Claude Code

Note

Run finish hooks on Audiobookshelf session close to record plays in admin history

Changes ABS native-session cleanup so closing a playback session calls FinishSession with the request context instead of StopSession. The finish hooks write the admin playback history row before the existing post-close sync runs.

  • Updates PlaybackSessionManager interface in native_sessions.go: the stop contract is replaced by a context-aware finish contract
  • Keeps the existing not-found warning suppression and immediate sync after a successful close
  • Test renamed to TestHandleSessionCloseFinishesNativePlaybackSession and now asserts a registered finish hook runs exactly once
  • Risk: any caller of PlaybackSessionManager outside this package must switch from the removed StopSession method to FinishSession

Macroscope summarized cedf888.

Closing an Audiobookshelf session stopped its native playback session
without running the session manager's finish hooks, so the play never
reached admin playback history. Only sessions a client abandoned, which
expire through the native stale-session cleanup, were recorded. Closing
now finishes the native session, which records the play the same way a
Jellyfin-compatible stop does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016wJkeovgRDcHgJXkibXhY7
@silo-triage silo-triage Bot added the size/S 0–49 added + deleted lines (all files); change volume, not priority. label Oct 23, 2026
@silo-kody

silo-kody Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@coderabbitai

coderabbitai Bot commented Oct 23, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 5130defa-9ea3-4169-af12-a067334f10bd
📥 Commits

Reviewing files that changed from the base of the PR and between e083e4d and cedf888.

📒 Files selected for processing: 2
  • internal/audiobooks/abs/native_sessions.go
  • internal/audiobooks/abs/native_sessions_test.go

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.

📝 Walkthrough

The ABS playback session manager replaces StopSession with FinishSession, which accepts a context. Closing a session calls the new method. The close test checks that the finish hook records the session ID exactly once.

Changes: ABS session finishing

Layer / File(s) Summary
Finish sessions on close
internal/audiobooks/abs/native_sessions.go, internal/audiobooks/abs/native_sessions_test.go
The manager interface and close path use FinishSession with the request context. The test verifies that closing a session calls the finish hook once with that session ID.

Priority: ➖ Normal

Estimated code review effort: 2 (Simple) | ~8 minutes

Change: Bug fix

Suggested reviewers: quick104

Merge Risk: ⚪ Minimal · up to cedf8

Cleanly closed sessions should now appear in admin playback history. Multi-file books may show Completed early; otherwise, no actionable merge blocker remains.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 2 functions across 2 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title clearly identifies the main change: recording Audiobookshelf plays in admin playback history.
Description check Passed The description directly explains the missing playback-history records, the FinishSession approach, test coverage, validation, evidence, and known risk.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@macroscopeapp

macroscopeapp Bot commented Oct 23, 2026

Copy link
Copy Markdown

The change is visible: closing an Audiobookshelf session can add a row to the admin Playback History. The Evidence section has only an after capture and does not identify the build or commit for it. Please add before-and-after captures of the same Playback History screen for the same test play, and name the build or commit for each capture.

Automated check: Macroscope check run agent (gpt-6-luna). Evidence was not reviewed for correctness.

Posted via Macroscope — Visible change evidence

@silo-triage silo-triage Bot added bug Something isn't working go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish labels Oct 23, 2026
@Brady3035

Copy link
Copy Markdown
Contributor Author

There are a few more issues with the ABS layer that i'll fix, starting with this one. This should be ready for review

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

Review of cedf888. One finding below, already disclosed in the PR's Risks section and left for the maintainers to decide. The summary comment has the rest.

return
}
if err := h.deps.NativeSessions.StopSession(sessionID); err != nil {
if err := h.deps.NativeSessions.FinishSession(ctx, sessionID); err != nil {

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.

Medium, disclosed, maintainer decision. Every normal close now writes an admin history row, and for a multi-file audiobook that row is wrong. The native session is started on files[0] while ABS syncs set its position to the whole-book currentTime. buildAdminHistoryEntry then uses the first track's Duration and sets completed once the position passes the watched fraction of that track. For a book of 30-minute tracks closed one hour in, the row shows a 30-minute duration, 60 minutes watched, and completed. RecordHistory keeps completed once it is set.

Before this PR only abandoned sessions reached this path, through expiry; now every closed session does. The fix belongs in how the history row gets the book's duration, not in this close call, so it is tracked separately in #3098. Whether to merge this PR first or wait for that fix is a maintainer call. No change is needed here from you.

@Quick104

Copy link
Copy Markdown
Contributor

Review summary for cedf888.

This fixes a real gap: an Audiobookshelf session closed normally ended its native playback session with StopSession, which skips the finish hooks, so only abandoned sessions (reaped by expiry) reached admin Playback History. Switching to FinishSession reuses the hook jellycompat already relies on. The ABS session has progress persistence disabled, so the hook writes only the admin row and leaves watch progress to the ABS handler. No commits were pushed to the branch.

What I checked

  • TestHandleSessionCloseFinishesNativePlaybackSession fails on the base (finish hooks ran for [], want [<id>]) and passes on this head, so it detects the fix.
  • go test ./internal/audiobooks/... passes on this head and on this head merged with current main. The branch merges into main without conflicts. make lint-changed reports 0 issues.
  • The only production finish hook is PlaybackHandler.handleFinishedSession. It runs under context.WithoutCancel, so a client that drops the connection after close doesn't cancel the history write, and the row gets the close request's client IP.
  • A retried close, or a close racing the liveness reaper on the same replica, runs the hooks at most once: FinishSession removes the session under the manager lock. Admin history upserts on session_id, so a copy on another replica cannot add a second row.
  • When the close lands on a replica that doesn't hold the native session, nothing changes from before: FinishSession returns not-found, and the owning replica records the play when it expires the session.
  • A Codex (gpt-6.1-sol) cross-provider round found nothing. Its sandbox couldn't run commands, so it reviewed the diff and the surrounding code passed to it inline, without running tests.

Left for the maintainers

  • Multi-file audiobooks (inline finding, already in the PR's Risks): the row uses the first track's duration against the whole-book position, so it can be marked completed after the first track. This PR makes that apply to every closed session, not just expired ones. Tracked in [bug] Admin Playback History marks multi-file Audiobookshelf plays completed after the first track #3098.
  • Separate, pre-existing: the close endpoint ignores the final sync data Audiobookshelf clients can send in the close body, so the last stretch after the previous sync is missing from resume progress and from this row. Tracked in [bug] Audiobookshelf session close drops the final sync in its request body #3099.
  • Watch time for this row comes from the native session's sampled progress. A listener at speeds above 2x with a long sync interval can have intervals counted as seeks, which lowers played seconds. This is the shared watch-time rule for all clients, not something this PR changes.
  • Macroscope asked for a before capture. The failing base test shows the before state (no finish hook, so no row). Whether a screenshot of the empty history is still wanted is up to the maintainers.

Validated features: none affected. No case on the v1.0 board is recorded as passed. The Audiobookshelf compatibility task (#1247) covers authentication, browsing, playback, and access restrictions, and this change touches none of them. Validation tasks: none is correct.

User manual: unaffected. The Audiobookshelf compatibility and audiobooks pages on siloserver.org don't describe admin Playback History.

Apple and Android: no follow-up. The change is server-side and only affects the admin history row. jellycompat already finishes sessions this way.

Fit: 8/10 · Readiness: 8/10 — conditional

@Quick104
Quick104 merged commit 6628915 into Silo-Server:main Oct 26, 2026
18 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish size/S 0–49 added + deleted lines (all files); change volume, not priority.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants