Repository navigation
fix(progress): track resume points independently of watched state - #117
Conversation
Re-watching a finished item never re-entered Continue Watching: completion
latched completed = TRUE one-way, pinned position_seconds to the duration,
and the resume query filtered on completed = FALSE — so a rewatch heartbeat
could never surface the item again (and releasing the latch would have
erased the watched state clients display).
Adopt the Jellyfin invariant instead of guard heuristics:
- Completion resets position_seconds to 0 (UpdateProgress, SetProgress,
SetProgressAt, SetProgressIfNewer, MarkWatched, MarkProgressBatch), so
position_seconds > 0 now means "live resume point".
- completed stays a pure one-way watched latch; rewatch heartbeats re-enter
Continue Watching through plain GREATEST/MAX while the watched flag and
PlayCount survive (matching Plex and Jellyfin master).
- ListProgress("in_progress") keys on position_seconds > 0 in both stores;
the SQLite store also gains the min-resume floor the Postgres store had.
- jellycompat reports Played=true with live PositionTicks during a rewatch
(resumePositionTicks no longer zeroes played items) — the DTO shape real
Jellyfin emits since jellyfin/jellyfin#15762.
- Web mirrors the latch (playbackProgressCache), resumes rewatches at their
stored position, and shows progress bars on rewatched episodes.
- ABS audiobook surfaces keep today's behavior: finished books report 100%
via the completed flag and Continue Listening still excludes them.
- Migrations reset legacy completed rows (position pinned to duration) to
0: a Goose migration for Postgres and a user_version-gated one-time fix
for the per-user SQLite DBs.
Replaces the guard-based approach of #109, whose restart detection
(50% fraction + 60s time gap) could never release the latch for immediate
rewatches (blocked heartbeats refreshed updated_at, re-arming the gap) and
un-watched items on position-0 heartbeats.
Co-Authored-By: Claude Fable 5 <[email protected]>
|
Caution Review failedPull request was closed or merged during review 📝 WalkthroughWalkthroughThis PR refactors watched-item completion semantics across the full stack. Completed media items now store position_seconds=0 (no resume point), while rewatches store nonzero position with completed=true. The in_progress indicator switches from completed=false to position_seconds>0. Changes span SQLite/PostgreSQL stores, schema migration, API handlers, DTOs, catalog queries, frontend cache/components, and comprehensive test coverage. ChangesWatched-to-Rewatch Position Semantics
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 10319123b8
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| // Continue Watching predicate). One-time data fixes can't be made idempotent | ||
| // by predicate alone — re-running this UPDATE on every boot would wipe the | ||
| // resume point of any rewatch in flight — so the version gate is required. | ||
| const userSchemaVersionCompletedPositionReset = 1 |
There was a problem hiding this comment.
Bump the SQLite data-fix version past current schema
For any existing per-user SQLite DB, runMigrations has already set PRAGMA user_version to the current schema version (10), so this gate at 1 makes migrateCompletedProgressPositionReset return without resetting legacy completed rows. Those rows still have position_seconds = duration_seconds, and the new ListProgress("in_progress") predicate is position_seconds > 0, so already-watched items will be surfaced as phantom resume entries after upgrade until each row is rewritten.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 7b4b951 — good catch, this was the most important finding. The data fix is now migrateToV11 in the existing versioned runMigrations chain (schemaVersion bumped to 11), so existing DBs at v10 run the reset exactly once and fresh DBs short-circuit as before. The standalone gate (which would also have rewound user_version) is gone. Covered by TestMigrateToV11ResetsCompletedPositions, which seeds a v10 DB with a legacy row, runs the migration, then verifies a rewatch survives a re-run.
| return { | ||
| played, | ||
| is_in_progress: positionSeconds > 0 && !played, | ||
| is_in_progress: positionSeconds > 0, |
There was a problem hiding this comment.
Clear optimistic resume state when playback completes
When a playback snapshot reports the end of an item (positionSeconds >= durationSeconds), played becomes true but position_seconds remains nonzero and this line marks the item as still in progress. Until the server refetch arrives, the detail/watch caches can show a completed item as resumable (and with the new primary-action logic offer Resume at the end) instead of mirroring the server invariant that completed rows store position 0.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 7b4b951 — the optimistic cache now mirrors the completion invariant: when a snapshot reaches the duration, played latches, position_seconds zeroes, and is_in_progress drops, in both the leaf user-data merge and the progress-list entry update. So the detail page shows Play (not Resume-at-end) during the window before the server refetch.
| if duration > 0 && position/duration > userstore.WatchedFraction(thresholds.WatchedPct) { | ||
| completed = true | ||
| position = duration // match MarkWatched() — reset so no stale resume point | ||
| position = 0 // match MarkWatched() — completed rows hold no resume point |
There was a problem hiding this comment.
Preserve watched latch when SetProgress stores a rewatch
When a watched item is rewatched and then stopped before the watched threshold, RecordPlaybackStop calls SetProgress, completed remains false, and the upsert below still assigns completed = excluded.completed. That normal stop path therefore clears the watched latch for the item instead of keeping completed one-way, so the watched badge/state is lost as soon as the user exits a partial rewatch.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 7b4b951 — confirmed: RecordPlaybackStop persists via SetProgress, so a partial rewatch stop cleared the latch. completed is now one-way (existing OR excluded) in SetProgress, SetProgressAt, and SetProgressIfNewer in both stores; mark-unwatched still releases it via ClearProgress/ClearProgressBatch. New subtests cover the stop path and SetProgressIfNewer.
| last_file_id, last_resolution, last_hdr, last_codec_video, last_edition_key | ||
| FROM user_watch_progress | ||
| WHERE user_id = $1 AND profile_id = $2 AND completed = FALSE | ||
| WHERE user_id = $1 AND profile_id = $2 AND position_seconds > 0 |
There was a problem hiding this comment.
Normalize completed imports before using position as resume
This new predicate assumes every completed writer has reset position_seconds to 0, but the history import repository still forces completed imports to positionSeconds = durationSeconds before upserting (internal/historyimport/repo.go lines 872-873). Any completed item imported after this migration will satisfy position_seconds > 0 and show up in Continue Watching as a phantom resume entry until another path rewrites it.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 7b4b951 — UpsertImportedProgress now normalizes completed imports to position 0 and its on-conflict merge is one-way for completed, matching the userstore writers.
| PositionSeconds: progress.PositionSeconds, | ||
| DurationSeconds: progress.DurationSeconds, | ||
| IsInProgress: !progress.Completed && progress.PositionSeconds > 0, | ||
| IsInProgress: progress.PositionSeconds > 0, |
There was a problem hiding this comment.
Propagate the new in-progress test to catalog queries
This handler now treats any position_seconds > 0 row as in-progress, including rewatch rows that still have completed = TRUE, but several catalog SQL predicates still require uwp.completed = FALSE (for example internal/catalog/query_builder.go lines 957 and 1350, and internal/catalog/episode_catalog_entries_executor.go line 566). As a result, rewatched items appear in Continue Watching via ListProgress but are omitted from smart-collection in_progress filters and progress sorting until the item is manually unwatched.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 7b4b951 — dropped completed = FALSE from the smart-collection in_progress filter and the progress-sort ratio in query_builder.go, and the episode progress CTE in episode_catalog_entries_executor.go. Also caught two sites beyond the ones listed: both next-up predicates in nextup_repo.go (the eligible-series in-progress gate and the in-progress episode scan) now key on position_seconds > 0 too. Test expectations updated.
|
|
||
| if data != nil { | ||
| dto.PlaybackPositionTicks = resumePositionTicks(data.PositionSeconds, data.DurationSeconds, data.Played) | ||
| dto.PlaybackPositionTicks = resumePositionTicks(data.PositionSeconds, data.DurationSeconds) |
There was a problem hiding this comment.
Report watched percentage from the latch, not resume point
With completed rows now storing position_seconds = 0, this path still computes PlayedPercentage from the resume position, so a fully watched item is sent to Jellyfin clients as Played=true with PlayedPercentage=0. That regresses clients that render progress from the Jellyfin DTO: completed items should report 100% (or otherwise derive the value from the played latch) while only active rewatches should use the nonzero resume percentage.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 7b4b951 — PlayedPercentage and PlaybackPositionTicks are now derived from the same clamped position (new playedPercentage helper): a played item at rest reports 100 (matching the old model's client-visible value) and a rewatch in flight reports its live fraction. Tests assert 100-at-rest, the live rewatch fraction, and that the percentage can never exceed 100 for stale over-duration rows.
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (4)
internal/jellycompat/mapping.go (1)
536-550:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winClamp
PlayedPercentagefrom the same sanitized position.Line 536 and Line 548 now normalize the resume point for
PlaybackPositionTicks, but Lines 537-550 still derivePlayedPercentagefrom the raw stored seconds. A stale row withposition > durationwill now emit inconsistent user data: ticks are clamped to EOF while percentage can still exceed 100. Please compute both fields from the same clamped value, and lock it in with an assertion in the existing clamp tests.🤖 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/jellycompat/mapping.go` around lines 536 - 550, The PlayedPercentage is being computed from raw PositionSeconds while PlaybackPositionTicks is computed from a clamped value via resumePositionTicks, causing percentages >100 for stale rows; fix by deriving a single clamped position value (e.g., clampedSeconds) using the same normalization logic you use for resumePositionTicks (or add/consume a resumePositionSeconds helper) and use that clampedSeconds to compute PlayedPercentage for both the data and progress branches (use data.DurationSeconds/progress.DurationSeconds to guard division by zero), and update the existing clamp tests to assert that PlayedPercentage never exceeds 100 and matches the clamped position used for PlaybackPositionTicks.internal/userdb/progress.go (3)
63-71:⚠️ Potential issue | 🟠 Major | ⚡ Quick winKeep the watched latch one-way in the explicit setters.
These UPSERTs still assign
completed = excluded.completed, so a rewatch/import write withcompleted = falseclears an item that was already watched. AfterMarkWatched, a laterSetProgressAt(..., 900, ..., false)will drop the played latch instead of preserving it while storing the resume point. Please mirrorUpdateProgress's one-waycompletedmerge here, and in the Postgres mirror.Also applies to: 101-109, 138-147
🤖 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/userdb/progress.go` around lines 63 - 71, The UPSERT in internal/userdb/progress.go currently overwrites the watched latch by setting completed = excluded.completed; change this to a one-way merge that preserves any existing true value (e.g. completed = watch_progress.completed OR excluded.completed) so a later write with completed=false won't clear a previously-watched item; apply the same change in the Postgres mirror and in the other two UPSERT sites referenced (the blocks corresponding to SetProgressAt/SetProgress and the Postgres equivalents) to match UpdateProgress's one-way completed merge and keep MarkWatched semantics.
323-341:⚠️ Potential issue | 🟠 Major | ⚡ Quick winSQLite still misses the 5% resume floor here.
position_seconds > 0alone will surface tiny imported/synced positions written throughSetProgressAt/SetProgressIfNewer. The PR summary calls out a SQLite-specific min-resume floor, but this predicate does not enforce it. Add the same duration-based threshold here so Continue Watching does not repopulate with 1-2 second rows.🤖 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/userdb/progress.go` around lines 323 - 341, The WHERE clause in internal/userdb/progress.go building the query string for Continue Watching (the variable query) only filters by position_seconds > 0 and misses the SQLite 5% resume floor; update that WHERE clause to also require the position meets the 5%-of-duration floor (e.g., add a predicate such as "AND (position_seconds * 20) >= duration_seconds" or an equivalent expression using GREATEST/MAX) so tiny 1–2s imported positions are excluded; adjust no args are needed since this is a column-only expression and keep the rest of the query (and the args slice) unchanged.
213-223:⚠️ Potential issue | 🟠 Major | ⚡ Quick winDon't let older batch marks erase newer rewatch positions.
watch_progress.position_seconds <> 0makes this UPSERT fire even whenexcluded.updated_atis older than the current row. A delayedMarkProgressBatchcan therefore zero out a newer rewatch resume point and moveupdated_atbackwards. The non-zero-position branch needs the same freshness guard as the timestamp branch.🤖 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/userdb/progress.go` around lines 213 - 223, The UPSERT in the MarkProgressBatch SQL (the tx.Exec INSERT ... ON CONFLICT block) currently has "OR watch_progress.position_seconds <> 0" which lets an older batch overwrite a newer rewatch position; modify the WHERE clause so the non-zero-position branch also requires the incoming row to be newer (i.e. add a freshness guard comparing excluded.updated_at and watch_progress.updated_at). Concretely, change the position clause to require "watch_progress.position_seconds <> 0 AND watch_progress.updated_at < excluded.updated_at" (or equivalent "AND excluded.updated_at > watch_progress.updated_at") so a stale batch cannot zero out a later resume point.
🤖 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/audiobooks/abs_progress_store.go`:
- Around line 41-47: The read-side logic expects completed rows to have
position_seconds = 0 but the write-side still persists row.CurrentSeconds when
row.IsFinished is true; update the write paths (notably the UpsertProgress
function and the other upsert/update that also writes position_seconds) to
normalize completed rows by writing position_seconds = 0 whenever row.IsFinished
(or row.Completed) is true, while preserving position_seconds only for
non-finished rows so completed entries cannot leak into position-based resume
queries.
In `@internal/userdb/schema.go`:
- Around line 296-325: The PR is using userSchemaVersionCompletedPositionReset =
1 which causes migrateCompletedProgressPositionReset to return early on DBs
already at user_version >= 9 (set elsewhere by
migratePlaybackSettingsToDeviceScope), so the completed rows never get
normalized; update the sentinel to a new version number above the current max
user_version (pick a value >9) and bump the constant
userSchemaVersionCompletedPositionReset accordingly so
migrateCompletedProgressPositionReset runs on existing DBs, keeping the rest of
the function (the UPDATE and PRAGMA user_version write) unchanged; references:
userSchemaVersionCompletedPositionReset and
migrateCompletedProgressPositionReset (and note
migratePlaybackSettingsToDeviceScope reads PRAGMA user_version elsewhere).
---
Outside diff comments:
In `@internal/jellycompat/mapping.go`:
- Around line 536-550: The PlayedPercentage is being computed from raw
PositionSeconds while PlaybackPositionTicks is computed from a clamped value via
resumePositionTicks, causing percentages >100 for stale rows; fix by deriving a
single clamped position value (e.g., clampedSeconds) using the same
normalization logic you use for resumePositionTicks (or add/consume a
resumePositionSeconds helper) and use that clampedSeconds to compute
PlayedPercentage for both the data and progress branches (use
data.DurationSeconds/progress.DurationSeconds to guard division by zero), and
update the existing clamp tests to assert that PlayedPercentage never exceeds
100 and matches the clamped position used for PlaybackPositionTicks.
In `@internal/userdb/progress.go`:
- Around line 63-71: The UPSERT in internal/userdb/progress.go currently
overwrites the watched latch by setting completed = excluded.completed; change
this to a one-way merge that preserves any existing true value (e.g. completed =
watch_progress.completed OR excluded.completed) so a later write with
completed=false won't clear a previously-watched item; apply the same change in
the Postgres mirror and in the other two UPSERT sites referenced (the blocks
corresponding to SetProgressAt/SetProgress and the Postgres equivalents) to
match UpdateProgress's one-way completed merge and keep MarkWatched semantics.
- Around line 323-341: The WHERE clause in internal/userdb/progress.go building
the query string for Continue Watching (the variable query) only filters by
position_seconds > 0 and misses the SQLite 5% resume floor; update that WHERE
clause to also require the position meets the 5%-of-duration floor (e.g., add a
predicate such as "AND (position_seconds * 20) >= duration_seconds" or an
equivalent expression using GREATEST/MAX) so tiny 1–2s imported positions are
excluded; adjust no args are needed since this is a column-only expression and
keep the rest of the query (and the args slice) unchanged.
- Around line 213-223: The UPSERT in the MarkProgressBatch SQL (the tx.Exec
INSERT ... ON CONFLICT block) currently has "OR watch_progress.position_seconds
<> 0" which lets an older batch overwrite a newer rewatch position; modify the
WHERE clause so the non-zero-position branch also requires the incoming row to
be newer (i.e. add a freshness guard comparing excluded.updated_at and
watch_progress.updated_at). Concretely, change the position clause to require
"watch_progress.position_seconds <> 0 AND watch_progress.updated_at <
excluded.updated_at" (or equivalent "AND excluded.updated_at >
watch_progress.updated_at") so a stale batch cannot zero out a later resume
point.
🪄 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: 9ea2e5d3-f5c5-4152-8737-2431ad5b8976
📒 Files selected for processing (20)
internal/api/handlers/items.gointernal/audiobooks/abs_progress_store.gointernal/jellycompat/content_direct.gointernal/jellycompat/mapping.gointernal/jellycompat/mapping_userdata_test.gointernal/userdb/progress.gointernal/userdb/progress_rewatch_test.gointernal/userdb/schema.gointernal/userstore/pgstore/progress.gointernal/userstore/storetest/suite.gomigrations/sql/20260609224115_reset_completed_progress_position.sqlweb/src/components/EpisodeRow.tsxweb/src/components/HeroBanner.tsxweb/src/hooks/queries/playbackProgressCache.test.tsweb/src/hooks/queries/playbackProgressCache.tsweb/src/pages/ItemDetail/EpisodeContent.test.tsxweb/src/pages/ItemDetail/MovieContent.test.tsxweb/src/pages/ItemDetail/itemDetailLayout.test.tsweb/src/pages/ItemDetail/itemDetailLayout.tsweb/src/pages/watchRouteHelpers.ts
… writers/readers Review fixes for the position-based watch-progress model: - The per-user SQLite data fix is now migrateToV11 in the existing versioned runMigrations chain (schemaVersion 11). The previous standalone PRAGMA gate compared against 1, but existing DBs already sit at user_version 10, so the reset never ran for them — and the gate would have rewound the version. Fresh DBs short-circuit to the current version as before. - `completed` is now one-way across every playback/sync writer: SetProgress (the RecordPlaybackStop path — stopping a rewatch below the watched threshold no longer clears the watched state), SetProgressAt, SetProgressIfNewer (both stores), and the history import upsert, which also stops pinning completed imports to position = duration. Mark-unwatched still releases the latch via ClearProgress/ClearProgressBatch. - MarkProgressBatch regains its freshness guard: a delayed batch mark carrying an old timestamp can no longer zero a newer rewatch resume point (the position-reset now rides the original updated_at check). - Catalog read paths align with the new in-progress definition (position_seconds > 0, completed-agnostic): smart-collection in_progress filter, progress sort ratio, episode progress CTE, and both next-up predicates. - jellycompat derives PlayedPercentage and PlaybackPositionTicks from the same clamped position; a played item at rest reports 100 (as the old model did) while a rewatch reports its live fraction. - ABS audiobook UpsertProgress stores position 0 on finish so finished books can't surface as phantom resume entries; re-listens still move position forward from 0 with the latch intact. - The web optimistic cache zeroes the resume point on completion, mirroring the server invariant until the refetch lands. Co-Authored-By: Claude Fable 5 <[email protected]>
|
All review feedback addressed in 7b4b951 (inline threads have individual replies). Responses to the CodeRabbit outside-diff items, which have no inline thread:
Verification: |
* fix(progress): track resume points independently of watched state
Re-watching a finished item never re-entered Continue Watching: completion
latched completed = TRUE one-way, pinned position_seconds to the duration,
and the resume query filtered on completed = FALSE — so a rewatch heartbeat
could never surface the item again (and releasing the latch would have
erased the watched state clients display).
Adopt the Jellyfin invariant instead of guard heuristics:
- Completion resets position_seconds to 0 (UpdateProgress, SetProgress,
SetProgressAt, SetProgressIfNewer, MarkWatched, MarkProgressBatch), so
position_seconds > 0 now means "live resume point".
- completed stays a pure one-way watched latch; rewatch heartbeats re-enter
Continue Watching through plain GREATEST/MAX while the watched flag and
PlayCount survive (matching Plex and Jellyfin master).
- ListProgress("in_progress") keys on position_seconds > 0 in both stores;
the SQLite store also gains the min-resume floor the Postgres store had.
- jellycompat reports Played=true with live PositionTicks during a rewatch
(resumePositionTicks no longer zeroes played items) — the DTO shape real
Jellyfin emits since jellyfin/jellyfin#15762.
- Web mirrors the latch (playbackProgressCache), resumes rewatches at their
stored position, and shows progress bars on rewatched episodes.
- ABS audiobook surfaces keep today's behavior: finished books report 100%
via the completed flag and Continue Listening still excludes them.
- Migrations reset legacy completed rows (position pinned to duration) to
0: a Goose migration for Postgres and a user_version-gated one-time fix
for the per-user SQLite DBs.
Replaces the guard-based approach of #109, whose restart detection
(50% fraction + 60s time gap) could never release the latch for immediate
rewatches (blocked heartbeats refreshed updated_at, re-arming the gap) and
un-watched items on position-0 heartbeats.
Co-Authored-By: Claude Fable 5 <[email protected]>
* fix(progress): address review — migration gate, one-way latch, missed writers/readers
Review fixes for the position-based watch-progress model:
- The per-user SQLite data fix is now migrateToV11 in the existing
versioned runMigrations chain (schemaVersion 11). The previous
standalone PRAGMA gate compared against 1, but existing DBs already
sit at user_version 10, so the reset never ran for them — and the
gate would have rewound the version. Fresh DBs short-circuit to the
current version as before.
- `completed` is now one-way across every playback/sync writer:
SetProgress (the RecordPlaybackStop path — stopping a rewatch below
the watched threshold no longer clears the watched state),
SetProgressAt, SetProgressIfNewer (both stores), and the history
import upsert, which also stops pinning completed imports to
position = duration. Mark-unwatched still releases the latch via
ClearProgress/ClearProgressBatch.
- MarkProgressBatch regains its freshness guard: a delayed batch mark
carrying an old timestamp can no longer zero a newer rewatch resume
point (the position-reset now rides the original updated_at check).
- Catalog read paths align with the new in-progress definition
(position_seconds > 0, completed-agnostic): smart-collection
in_progress filter, progress sort ratio, episode progress CTE, and
both next-up predicates.
- jellycompat derives PlayedPercentage and PlaybackPositionTicks from
the same clamped position; a played item at rest reports 100 (as the
old model did) while a rewatch reports its live fraction.
- ABS audiobook UpsertProgress stores position 0 on finish so finished
books can't surface as phantom resume entries; re-listens still move
position forward from 0 with the latch intact.
- The web optimistic cache zeroes the resume point on completion,
mirroring the server invariant until the refetch lands.
Co-Authored-By: Claude Fable 5 <[email protected]>
---------
Co-authored-by: Claude Fable 5 <[email protected]>
* fix(progress): track resume points independently of watched state
Re-watching a finished item never re-entered Continue Watching: completion
latched completed = TRUE one-way, pinned position_seconds to the duration,
and the resume query filtered on completed = FALSE — so a rewatch heartbeat
could never surface the item again (and releasing the latch would have
erased the watched state clients display).
Adopt the Jellyfin invariant instead of guard heuristics:
- Completion resets position_seconds to 0 (UpdateProgress, SetProgress,
SetProgressAt, SetProgressIfNewer, MarkWatched, MarkProgressBatch), so
position_seconds > 0 now means "live resume point".
- completed stays a pure one-way watched latch; rewatch heartbeats re-enter
Continue Watching through plain GREATEST/MAX while the watched flag and
PlayCount survive (matching Plex and Jellyfin master).
- ListProgress("in_progress") keys on position_seconds > 0 in both stores;
the SQLite store also gains the min-resume floor the Postgres store had.
- jellycompat reports Played=true with live PositionTicks during a rewatch
(resumePositionTicks no longer zeroes played items) — the DTO shape real
Jellyfin emits since jellyfin/jellyfin#15762.
- Web mirrors the latch (playbackProgressCache), resumes rewatches at their
stored position, and shows progress bars on rewatched episodes.
- ABS audiobook surfaces keep today's behavior: finished books report 100%
via the completed flag and Continue Listening still excludes them.
- Migrations reset legacy completed rows (position pinned to duration) to
0: a Goose migration for Postgres and a user_version-gated one-time fix
for the per-user SQLite DBs.
Replaces the guard-based approach of #109, whose restart detection
(50% fraction + 60s time gap) could never release the latch for immediate
rewatches (blocked heartbeats refreshed updated_at, re-arming the gap) and
un-watched items on position-0 heartbeats.
Co-Authored-By: Claude Fable 5 <[email protected]>
* fix(progress): address review — migration gate, one-way latch, missed writers/readers
Review fixes for the position-based watch-progress model:
- The per-user SQLite data fix is now migrateToV11 in the existing
versioned runMigrations chain (schemaVersion 11). The previous
standalone PRAGMA gate compared against 1, but existing DBs already
sit at user_version 10, so the reset never ran for them — and the
gate would have rewound the version. Fresh DBs short-circuit to the
current version as before.
- `completed` is now one-way across every playback/sync writer:
SetProgress (the RecordPlaybackStop path — stopping a rewatch below
the watched threshold no longer clears the watched state),
SetProgressAt, SetProgressIfNewer (both stores), and the history
import upsert, which also stops pinning completed imports to
position = duration. Mark-unwatched still releases the latch via
ClearProgress/ClearProgressBatch.
- MarkProgressBatch regains its freshness guard: a delayed batch mark
carrying an old timestamp can no longer zero a newer rewatch resume
point (the position-reset now rides the original updated_at check).
- Catalog read paths align with the new in-progress definition
(position_seconds > 0, completed-agnostic): smart-collection
in_progress filter, progress sort ratio, episode progress CTE, and
both next-up predicates.
- jellycompat derives PlayedPercentage and PlaybackPositionTicks from
the same clamped position; a played item at rest reports 100 (as the
old model did) while a rewatch reports its live fraction.
- ABS audiobook UpsertProgress stores position 0 on finish so finished
books can't surface as phantom resume entries; re-listens still move
position forward from 0 with the latch intact.
- The web optimistic cache zeroes the resume point on completion,
mirroring the server invariant until the refetch lands.
Co-Authored-By: Claude Fable 5 <[email protected]>
---------
Co-authored-by: Claude Fable 5 <[email protected]>
Problem
Re-watching an already-finished item never re-enters Continue Watching. The row is built from
ListProgress(profileID, "in_progress")(WHERE completed = FALSE), but completion latchescompleted = TRUEone-way and pinsposition_secondsto the duration, so a rewatch heartbeat can never surface the item again — and any fix that releases the latch erases the watched state thatUserData.Played, play counts, and the web watched badge are derived from.#109 attacked this with restart-detection heuristics (50% position fraction + 60s time gap) inside the upsert. Review found two confirmed defects in that mechanism:
DO UPDATE, refreshingupdated_at— so the 60s gap is measured against the last heartbeat (~10s cadence), not against completion. Once one qualifying heartbeat lands inside the window, the latch can never release for the rest of the session and the rewatch's progress is silently discarded (reproduced with a clock-pinned test: a 10-minute episode restarted 30s after finishing stayed completed through 4+ minutes of heartbeats).position > 0, so an exactly-zero report falls through and releases the latch (the native player'spersistProgresshas noposition > 0guard, unlike the jellycompat path). Opening a watched movie and backing out cleared its watched state.Approach
Adopt the invariant Jellyfin uses (and Plex achieves structurally via
viewCount/viewOffset), which makes restart detection unnecessary:position_secondsto 0. Applied inUpdateProgress,SetProgress,SetProgressAt,SetProgressIfNewer,MarkWatched, andMarkProgressBatch(which previously left stale positions behind on conflict).position_seconds > 0now means exactly "live resume point".completedbecomes a pure one-way watched latch. Playback never clears it; only mark-unwatched does. A rewatch heartbeat lands on a 0-position row and re-enters Continue Watching through the existing forward-onlyGREATEST/MAX— no CASE branches, no clock math, no race windows. The watched badge and PlayCount survive the rewatch, matching Plex and Jellyfin master (Fix watched status resetting on re-watch jellyfin/jellyfin#15762; Jellyfin ≤10.11 cleared Played on rewatch start and walked that back).ListProgress("in_progress")keys onposition_seconds > 0in both the Postgres and per-user SQLite stores. The SQLite store also gains the min-resume floor (5%) the Postgres store already had.resumePositionTicksno longer zeroes played items — a rewatch reportsPlayed=true+ livePlaybackPositionTicks, the same DTO shape real Jellyfin emits. Watched items naturally report 0 ticks because the row stores 0.IsInProgressdrops its!Completedterm.watchRouteHelpersresumes from any nonzero position instead of forcing played items to 0,EpisodeRowshows the bar on a rewatched episode, and the primary action offers Resume/restart during a rewatch.completedflag (read-sideCASE), andListContinueListeningstill excludes finished books.Migrations
Legacy completed rows have
position_secondspinned to the duration and would surface as phantom resume entries under the new predicate:20260609224115_reset_completed_progress_position.sqlresets them to 0 (down migration restores the old convention).PRAGMA user_version(predicate-only idempotence would wipe in-flight rewatch state on every boot, so the version gate is load-bearing).Testing
internal/userdblifecycle tests: watch → complete (position 0, latched) → rewatch (re-enters in_progress, watched survives) → complete again; position-0 heartbeat is a no-op on watched items; sub-5% heartbeats discarded;MarkWatched/MarkProgressBatchcancel stale resume points; import paths normalize completed positions to 0; the userdb migration resets legacy rows and the version gate preserves in-flight rewatches across re-init.Played=true+PlayCount=1.go test ./...green; full web suite: all failures remaining are pre-existing onmain(verified file-by-file); ESLint 0 errors; changed files Prettier-clean;golangci-lintclean on changed files;make verify-local-pathspasses.Client follow-up (silo-android / silo-apple)
GET /progressand itemuser_datanow reportposition_seconds = 0withcompleted = truefor watched items (previously position == duration), and a rewatch reportscompleted = truewith a nonzero position. Clients that derive "watched" fromposition >= duration, or that hide resume UI wheneverplayedis true, need the same one-way-latch treatment as the web app. Jellyfin-protocol clients need no changes — the new shape matches real Jellyfin.Risks
Replaces #109 — see the review there for the full analysis. Thanks @d3v1l1989 for the diagnosis and test scaffolding that motivated this.
AI-use disclosure: implemented and tested with Claude (Claude Code), reviewed by the maintainer.
🤖 Generated with Claude Code
Summary by CodeRabbit
Release Notes
New Features
Bug Fixes