Repository navigation
fix(watchstate): let profiles mark an audiobook listened - #3169
Conversation
|
Caution Review failedThe pull request is closed. No actionable comments were generated in the recent review.
|
| Layer / File(s) | Summary |
|---|---|
Resolve audiobook targets and duration internal/api/handlers/items.go |
Watched-target lookup accepts audiobooks. Manual play duration sums positive file durations by media folder and canonical root, uses the longest total, and falls back to catalog runtime. |
Apply and verify audiobook watched state internal/api/handlers/watch_state_service.go, internal/audiobooks/abs_progress_store.go, internal/userstore/pgstore/progress.go, internal/audiobooks/abs/*, internal/api/handlers/watch_state_unwatch_db_test.go, scripts/ci/db-contracts.txt |
Marking an audiobook watched during a rewatch can record another play. Clearing its resume position returns 404. Audiobookshelf progress deletion clears watched state while retaining history, and progress timestamps are coordinated with history cutoffs. PostgreSQL tests cover access, duration, progress, history, and reset behavior. |
Describe audiobook watched-state behavior contracts/api/v2/openapi.json, docs/architecture/api-contract.md, docs/progress-api.md, internal/apiv2/*, web/src/api/v2/schema.ts |
API descriptions include audiobooks among watched-state targets and rewatch behavior. They also document audiobook duration rules, reset behavior, and the exclusion of audiobooks from clearResumePosition. |
Estimated code review effort: 3 (Moderate) | ~25 minutes
Change: Bug fix
Sequence Diagram(s)
sequenceDiagram
participant ItemsHandler
participant AudiobookFileLookup
participant WatchStateService
ItemsHandler->>AudiobookFileLookup: resolve accessible audiobook durations
AudiobookFileLookup->>ItemsHandler: return duration or lookup error
ItemsHandler->>WatchStateService: set audiobook watched state and duration
Possibly related issues
- Silo-Server/silo-server#1253: The PR adds audiobook watched-state marking, history entries, and progress behavior. The issue’s cross-device and cross-profile progress rule remains unresolved.
- Silo-Server/silo-server#3098: The PR uses the longest accessible copy’s duration for manual audiobook history, addressing a related multi-file duration concern.
- Silo-Server/silo-server#1256: The PR changes the shared audiobook watched-state API used by Web, though the issue’s client validation remains outstanding.
- Silo-Server/silo-server#1254: The PR changes server-side audiobook watched state, progress, history, and access resolution. Resume validation remains unresolved.
Possibly related PRs
- Silo-Server/silo-server#3010: This PR extends the watched-state rewatch behavior added for movies and episodes to audiobooks.
- Silo-Server/silo-server#3013: This PR uses history-preserving watched-state clearing when Audiobookshelf progress is deleted.
- Silo-Server/silo-server#3167: This PR uses accessible audiobook file durations and copy selection for manual history duration.
Suggested labels: api-v2, impact: playback, javascript
Suggested reviewers: blurbery
Merge Risk: 
Minimal · up to fa3cf
-
No actionable merge-blocking issue was identified in the audiobook watched-state changes. Normal merge checks can proceed.
Security architecture risk: 
Low · up to fa3cf
-
The expanded operation preserves item-access checks and profile ownership. The main remaining risk is a narrowly scoped concurrency issue: simultaneous marking and resetting can leave different completion views inconsistent for the same audiobook. No cross-profile access or privilege expansion was identified in the inspected paths.
Retained concerns
- Low · reliability · inferred: Native marking does not participate in the cutoff serialization used by ABS reset. When no committed progress row exists, a native mark can insert progress, reset can commit its cutoff and delete no visible row, and the mark can then insert completion history newer than that cutoff. After commit, cutoff-filtered progress reads hide the progress while completion-history reads restore completion. The expanded audiobook lifecycle therefore has a cross-client reset-convergence gap. The impact is limited to the same profile and audiobook; no authorization bypass is established.
Security review details
-
Security Blast Radius
- inferred — The inspected mutation paths affect the authenticated profile's audiobook progress, completion history, and associated notifications. Their predicates retain user/profile/item scoping; the identified concurrency issue does not establish access to another profile or library.
Trust Boundaries and Controls
- observed — The caller-controlled content ID remains subject to catalog access checks. Native profile selection passes through viewer-access resolution, and the v2 command uses context-derived identity rather than accepting ownership identifiers in its operation input.
Resilience and Maintainability Implications
- observed — ABS session-position updates remain update-only, so they cannot recreate a missing progress row. Reset publishes its success event only after persistence succeeds. The added concurrency test covers an ABS report waiting behind reset, not a native mark inserting a previously absent row.
Pre-merge checks: 
4 · 
1
-
Failed checks: 1 warning Passed checks: 4 passed-
Full details: Description check
-
Explanation
The description states the problem (Mark Listened and Mark as Finished for audiobooks return 404 on POST /api/v2/watched/{id}), the approach (audiobook treated as a single item, duration from accessible files with catalog fallback, ABS reset changes), and validation steps. It is directly related to the changeset, so the check passes.
-
Full details: Docstring Coverage
-
Explanation
Docstring coverage is 55.56% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 9 functions across 9 files. (1 skipped: 1 unsupported.)
Resolution
Write docstrings for the functions missing them to satisfy the coverage threshold.
-
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
| byFolder[file.MediaFolderID] += file.Duration | ||
| longest = max(longest, byFolder[file.MediaFolderID]) |
There was a problem hiding this comment.
Duration overcounting occurs when grouping only by MediaFolderID because scanner.upsertAudiobookMediaItem reuses an existing content ID through findAudiobookDuplicate even for copies with different canonical roots, counting duplicate physical copies in the same library as additional parts. Marking the book listened persists the inflated duration in progress and manual history; sum parts per physical book root within each library, then select the longest copy.
Prompt for LLM
File internal/api/handlers/items.go:
Line 2666 to 2667:
Duration overcounting occurs when grouping only by MediaFolderID because scanner.upsertAudiobookMediaItem reuses an existing content ID through findAudiobookDuplicate even for copies with different canonical roots, counting duplicate physical copies in the same library as additional parts. Marking the book listened persists the inflated duration in progress and manual history; sum parts per physical book root within each library, then select the longest copy.
Talk to Kody by mentioning @kody
Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.
There was a problem hiding this comment.
Fixed in 62bd62d: files are now summed per recording root within a library, and the book counts its longest copy. The Mark Listened test now has a second copy in the same library.
There was a problem hiding this comment.
Thanks—that addresses the reported overcounting: summing per recording root within each library keeps duplicate copies separate, and selecting the longest copy avoids adding them together. The second copy in the same library adds regression coverage for the scenario flagged here.
Based on your description of 62bd62d6b, this suggestion is addressed; I haven’t independently verified the commit.
|
The change is visible: marking an audiobook now succeeds and changes its listened/progress state. The linked evidence is described as web card-menu captures, so it does not show these affected surfaces:
Suggested fix: No code diff is needed; add the missing surface evidence to the linked evidence page. Automated check: Macroscope check run agent (gpt-6-luna). Evidence was not reviewed for correctness. Posted via Macroscope — Visible change evidence |
|
Not adding more captures. The evidence page shows the menu action succeeding and the book's watched state changing. Continue Listening and the Resume/Listen label read that same state, so they follow it. The iOS Mark as Finished result is recorded on Silo-Server/silo-apple#339; iOS needs no change because it calls the same endpoint. |
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
There was a problem hiding this comment.
Actionable comments posted: 2

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:
3665fd8c-bb81-4350-a7f4-798b9f7d55e0
Files selected for processing: 10-
contracts/api/v2/openapi.jsondocs/architecture/api-contract.mddocs/progress-api.mdinternal/api/handlers/items.gointernal/api/handlers/watch_state_service.gointernal/api/handlers/watch_state_unwatch_db_test.gointernal/apiv2/progress.gointernal/apiv2/watch.goscripts/ci/db-contracts.txtweb/src/api/v2/schema.ts
Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.
-
|
The changed
For the major-change rows, the PR description should explain why these C4 paths change and that they need re-validation after merge. Keep the unresolved progress semantics blocked; tvOS also needs #928's control before its UI flow can be re-tested. Suggested fix: Replace the current
Automated check: Macroscope check run agent (gpt-6-luna). No validation was performed. Posted via Macroscope — v1 validation impact |
Quick104
left a comment
There was a problem hiding this comment.
Reviewed 62bd62d6b3535fba1cb02c490142ac65e0e931c9 against 62b1a6e82408eb4be3409255583bf8b0a192a69f. The audiobook regression test passes on the head and fails on the base with not_found. Two additional issues reproduced against PostgreSQL; I am fixing them on this branch.
Note
AI disclosure: gpt-6.1-sol in T3 Code using the Codex provider. Independent review: claude-opus-5-5 in T3 Code.
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
|
Fit: 9/10 · Readiness: 9/10 — ready. Reviewed original head Rebased onto This repairs existing audiobook mark controls at the shared server boundary and reuses the completion transaction. It fits the current correctness work while keeping audiobooks in beta. The verified findings are addressed:
The original PostgreSQL test fails on the PR base with HTTP evidence was refreshed on a sandbox rebuilt from the final source. The restricted profile saves 2400 seconds; ABS reset returns 204, removes native completion, and retains one manual play. Unknown and denied reset targets return 404 and leave zero cutoff rows. The runtime build endpoint reports identity unavailable; matching production source hashes support the rebuild check. The original before capture remains linked, with the separate sandbox runs stated explicitly. Future-history/tick, injected file-error, access-resolver failure, and concurrency cases remain test evidence. No device UI was used. Validated features: the structured passed-case set was empty; rehearsal comments do not establish human acceptance. Re-test audiobook C4 on Web (#1256), iPhone/iPad (Silo-Server/silo-apple#339), tvOS (Silo-Server/silo-apple#340), Android phone/tablet (Silo-Server/silo-android#349), and Android TV (Silo-Server/silo-android#350). Broader C4/C10 acceptance remains blocked by #1253; tvOS also needs Silo-Server/silo-apple#928. No board status or validation results were changed. Existing Apple actions use the shared endpoint. Android has no audiobook mark control on the checked main branch; its validation task records the follow-up. No client contract change is required here. Jellyfin excludes audiobooks from this surface; ABS reset parity is handled here. The public beta audiobook/ABS manual pages do not describe these controls, so no manual issue is needed. The original desktop and phone-width card-menu captures still cover the normal flow. Review method: native gpt-6.1-sol passes plus one independent claude-opus-5-5 round. Kody identified the future-cutoff issue, and CodeRabbit's updated architecture note prompted the final target/concurrency checks; I independently reproduced them and authored the fixes. CodeRabbit withdrew the v1 objection under the documented critical bridge-fix exception; v1 still passes Note AI disclosure: gpt-6.1-sol in T3 Code using the Codex provider. Independent review: claude-opus-5-5 in T3 Code. Rebase onto current |
| if err != nil { | ||
| return fmt.Errorf("abs_progress_store: open user store: %w", err) | ||
| } | ||
| if err := store.ClearWatchedState(ctx, profileID, []string{contentID}, time.Now().UTC()); err != nil { |
There was a problem hiding this comment.
Progress visibility mismatch in internal/audiobooks/abs_progress_store.go occurs after Reset when ClearWatchedState raises hidden_before to the newest retained watched_at and ABSProgressStore.UpsertProgress writes time.Now() without advancing past that cutoff: a future-dated retained play causes subsequent listening or mark-finished progress saved through ABS to appear in ABS but remain filtered out by native GetProgress until that date. Advance updated_at past the cutoff for ABS progress writes, as PostgresUserStore.UpdateProgress already does.
Prompt for LLM
File internal/audiobooks/abs_progress_store.go:
Line 215:
Progress visibility mismatch in internal/audiobooks/abs_progress_store.go occurs after Reset when ClearWatchedState raises hidden_before to the newest retained watched_at and ABSProgressStore.UpsertProgress writes time.Now() without advancing past that cutoff: a future-dated retained play causes subsequent listening or mark-finished progress saved through ABS to appear in ABS but remain filtered out by native GetProgress until that date. Advance updated_at past the cutoff for ABS progress writes, as PostgresUserStore.UpdateProgress already does.
Talk to Kody by mentioning @kody
Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.
There was a problem hiding this comment.
Confirmed against PostgreSQL: after reset covers a future-dated retained play, both an ABS resume report and a finished report are absent from native reads. The new regression fails on 9ebd69854 for both states. I am advancing ABS write timestamps past the shared cutoff and checking session-sync writes too, so a later tick cannot hide the row again. I am fixing this on the branch.
There was a problem hiding this comment.
Thanks for confirming against PostgreSQL. That validates the finding on 9ebd69854 for both resume and finished reports.
Checking session-sync writes is important: every ABS write that refreshes progress must keep updated_at strictly greater than the shared cutoff, so a later tick cannot hide the row again.
The regression should verify native visibility after reset → ABS resume/finished report → session-sync tick, while confirming retained history stays intact. The planned fix addresses the reported issue; it remains open pending the branch changes and passing regression results.
There was a problem hiding this comment.
Fixed in c66561bca. ABS reports and session ticks now advance beyond the shared cutoff; ticks also preserve the existing row timestamp. The PostgreSQL resume/finished cases fail on 9ebd69854 and pass after the fix. An intermediate run also confirmed that fixing reports alone still hid progress on the next session tick, so the regression checks both writes. The original mark/reset cases, all audiobook packages, and changed-line lint pass.
There was a problem hiding this comment.
Thanks for the follow-up. Based on the reported changes and PostgreSQL regression results, this finding is addressed by c66561bca.
Covering both ABS reports and subsequent session ticks closes the visibility gap: progress stays strictly newer than the shared cutoff, and ticks preserve the existing row timestamp rather than moving it backward. The fail-before/pass-after coverage for both resume and finished states directly exercises the reported bug.
I haven’t independently inspected the commit or rerun the tests; this assessment is based on your results.
|
The linked web card-menu evidence covers the Mark Listened state change, but the commits since that evidence review add two user-visible effects it does not show:
Suggested fix: Add these response excerpts or captures to the linked evidence page. Automated check: Macroscope check run agent (gpt-6-luna). Evidence was not reviewed for correctness. Posted via Macroscope — Visible change evidence |
There was a problem hiding this comment.
Actionable comments posted: 1

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:
6387b776-a359-4827-8886-cd5c0334ecc6
Files selected for processing: 5-
docs/progress-api.mdinternal/api/handlers/items.gointernal/api/handlers/watch_state_unwatch_db_test.gointernal/audiobooks/abs_progress_store.goscripts/ci/db-contracts.txt
Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 1 remain after this review.
-
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
POST /api/v2/watched/{id} answered 404 for an audiobook because the
watched-state resolver only knew movies, ebooks, series, seasons and
episodes. It now resolves an audiobook as a leaf sized to the whole
book (the sum of its present files, not the first file or the catalog
runtime), so marking completes it, ends Continue Listening and records
one manual play like a movie, and unmarking clears it. A re-listen in
progress records another play, as a movie rewatch does.
clearResumePosition keeps answering 404 for an audiobook.
Two copies of the same recording in one library share an item, and summing files per library counted the second copy as more parts, doubling the length stored on the manual play. Sum files per recording root and keep the longest copy.
b6e5754 to
fa3cf45
Compare
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
Problem
Related issue: #1253
Validation tasks: changes #1256 C4; changes Silo-Server/silo-apple#339 C4; changes Silo-Server/silo-apple#340 C4; changes Silo-Server/silo-android#349 C4; changes Silo-Server/silo-android#350 C4
Marking an audiobook listened doesn't work. The web card menu offers Mark Listened, and iOS offers Mark as Finished on the audiobook screen. Both call
POST /api/v2/watched/{id}, which answers404 Item not foundfor every audiobook. The web shows an "Item not found" toast and nothing is saved. The watched-state resolver handled movies, series, seasons, episodes and ebooks, but not audiobooks.This change lets the endpoint mark an audiobook listened or unlistened for the acting profile.
Approach
DELETE /api/v2/progress/{id}/position) still answers 404, as documented./watchedshares the handler and accepts audiobooks too. This repairs the broken mark operation under the documented bridge-usability exception; v1 still disables rewatch recording.API descriptions for
markWatched/unmarkWatchedand themark_watched_records_rewatchcapability now name audiobooks;docs/progress-api.mdanddocs/architecture/api-contract.mdmatch. The broader cross-device and cross-profile progress rules for audiobooks remain undecided on #1253. The C4 action paths listed above need re-validation after merge; C4/C10 acceptance remains blocked on that decision, and tvOS also needs Silo-Server/silo-apple#928.Validation
scripts/ci/db-contracts.txt): mark mid-listen, mark during a re-listen, unmark, access-denied 404 and resume-position 404. It failed before the fix withnot_found.go test ./internal/api/handlers/... ./internal/apiv2/..., the handler DB pins,make verify-apiv2-openapi,verify-apiv2-web-types,verify-apiv2-contract,verify-route-inventory: pass.TestAudiobookMarkListenedBoundariesPostgresfailed on the original PR head for restricted-copy duration, file-read failure, and ABS reset. All three cases pass after the review fixes. Additional resume/finished cases failed on9ebd69854when reset covered future-dated history; those reports and subsequent session ticks are now visible to both native and ABS reads. The test is registered in the DB contract gate.c66561bcaand pass after the fix.b6e5754a8, the original mark test, all boundary cases, reset authority tests, all audiobook packages, the PostgreSQL user-store suite, and changed-line lint pass. The full Go/web/database gates were not rerun locally for this last follow-up. CI passes on final headb6e5754a8, including Go tests/lint/integration, database checks, web build/checks, all four web test shards, and the aggregate result. CodeRabbit, Kody, and Evidence checks pass; Macroscope evidence/validation-impact checks were skipped.b6e5754a8source. The restricted profile saves the allowed copy's 2400 seconds; ABS reset clears native completion and retains one manual play. Unknown and denied resets return 404 and leave zero cutoff rows. The build endpoint reports identity unavailable; production source hashes match the rebuilt checkout. Future-history/tick, injected file-error, access-resolver failure and concurrent reset/report cases remain test evidence. No device UI was used.mainat19e98f9a5(headfa3cf458b). The audiobook case now returns the series ID that fix(realtime): name the series on watched and progress events #2504 added toresolveWatchedTargets(empty, as for movies). Every commit builds; handler, v2, audiobook and user-store tests, changed-line lint, and the OpenAPI, web-types, v2 contract, route-inventory and local-path checks pass. PostgreSQL tests run in CI.Evidence
Evidence: https://evidence.siloserver.org/r/silo-server/pr-3169-review/
The linked page retains the original-head HTTP capture and refreshes the final capture at
b6e5754a8with the same synthetic fixture values in a new sandbox. It includes native/ABS responses, SQL history/cutoff reads, and tests that fail before the fixes and pass afterward. It also links the author's original desktop and phone-width card-menu captures (beforee6df1d8ed, after this branch).Risks
The capability
mark_watched_records_rewatchnow also covers audiobooks. A client that reads it to decide whether marking a re-listened book adds a play sees the new behaviour. A transient file-query failure now returns an error instead of recording a fallback duration; the user can retry the mark.Checklist
AI Disclosure
Note
Review fixes by Quick104: gpt-6.1-sol in T3 Code using the Codex provider authored the access, error-handling, ABS reset/access/serialization/timestamp, regression-test, and documentation follow-ups. Independent review: claude-opus-5-5 in T3 Code. Quick104's rebase onto current
main: claude-opus-5-5 in Claude Code (T3 Code). The original author's disclosure below records their implementation and earlier review.Note
Add audiobook support to watched-state marking and ABS reset in watchstate
ItemsHandler.lookupWatchedTargetnow accepts audiobooks, and played audiobook targets get a duration fromaudiobookDurationSeconds, which sums accessible file durations per recording copy, picks the longest group, and falls back to catalog runtime or zero. Unplayed audiobooks skip the duration lookup.ItemsHandler.SetWatchedStateincludes audiobooks in the rewatch condition, so a watched audiobook with a resume position can record another play.ItemsHandler.ClearResumePositionexplicitly rejects audiobooks with 404.Handler.handleDeleteItemProgress) now requires an accessible audiobook and returns 404 for unknown or inaccessible targets.ABSProgressStore.DeleteProgressclears watched state viaClearWatchedStateinstead of deleting the row directly, keeping history behind a cutoff.UpsertProgress,UpdateProgressPosition) now take the shared profile history-cutoff lock (LockHistoryCutoff) and set timestamps at least one second after an item'shidden_beforecutoff.ABSProgressStore.DeleteProgressno longer deletes the progress row directly; checkhandleDeleteItemProgressandDeleteProgressif ABS resets previously expected a raw row deletion. Clearing a resume position now returns 404 for audiobooks.Macroscope summarized fa3cf45.