Skip to content

fix(progress): track resume points independently of watched state - #117

Merged
Quick104 merged 2 commits into
mainfrom
fix/continue-watching-position-model
Jun 9, 2026
Merged

Quick104 merged 2 commits into
mainfrom
fix/continue-watching-position-model

Conversation

@Quick104

@Quick104 Quick104 commented Jun 9, 2026 •

Copy link
Copy Markdown
Contributor

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 latches completed = TRUE one-way and pins position_seconds to the duration, so a rewatch heartbeat can never surface the item again — and any fix that releases the latch erases the watched state that UserData.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:

  1. The time-gap guard is self-defeating. Blocked heartbeats still execute the DO UPDATE, refreshing updated_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).
  2. Position-0 heartbeats un-watch items. The min-resume early return requires position > 0, so an exactly-zero report falls through and releases the latch (the native player's persistProgress has no position > 0 guard, 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:

  • Completion resets position_seconds to 0. Applied in UpdateProgress, SetProgress, SetProgressAt, SetProgressIfNewer, MarkWatched, and MarkProgressBatch (which previously left stale positions behind on conflict). position_seconds > 0 now means exactly "live resume point".
  • completed becomes 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-only GREATEST/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 on position_seconds > 0 in both the Postgres and per-user SQLite stores. The SQLite store also gains the min-resume floor (5%) the Postgres store already had.
  • jellycompat: resumePositionTicks no longer zeroes played items — a rewatch reports Played=true + live PlaybackPositionTicks, the same DTO shape real Jellyfin emits. Watched items naturally report 0 ticks because the row stores 0. IsInProgress drops its !Completed term.
  • Web: the optimistic progress cache mirrors the one-way latch (a rewatch no longer flips the badge off client-side), watchRouteHelpers resumes from any nonzero position instead of forcing played items to 0, EpisodeRow shows the bar on a rewatched episode, and the primary action offers Resume/restart during a rewatch.
  • Audiobooks: ABS surfaces keep today's behavior — finished books report 100% via the completed flag (read-side CASE), and ListContinueListening still excludes finished books.

Migrations

Legacy completed rows have position_seconds pinned to the duration and would surface as phantom resume entries under the new predicate:

  • Postgres: Goose migration 20260609224115_reset_completed_progress_position.sql resets them to 0 (down migration restores the old convention).
  • Per-user SQLite: a one-time data fix gated by PRAGMA user_version (predicate-only idempotence would wipe in-flight rewatch state on every boot, so the version gate is load-bearing).

Testing

  • New internal/userdb lifecycle 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/MarkProgressBatch cancel 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.
  • jellycompat mapping tests updated/extended: played+position-0 → 0 ticks; rewatch → live ticks + Played=true + PlayCount=1.
  • Web tests updated to the new contract (one-way latch in the cache, Resume during rewatch, no-progress default) plus new rewatch cases.
  • go test ./... green; full web suite: all failures remaining are pre-existing on main (verified file-by-file); ESLint 0 errors; changed files Prettier-clean; golangci-lint clean on changed files; make verify-local-paths passes.

Client follow-up (silo-android / silo-apple)

GET /progress and item user_data now report position_seconds = 0 with completed = true for watched items (previously position == duration), and a rewatch reports completed = true with a nonzero position. Clients that derive "watched" from position >= duration, or that hide resume UI whenever played is 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

  • Sub-90% rewatches now keep the item in Continue Watching until finished or dismissed — same as Jellyfin/Plex, and dismissals (fix(jellycompat): hide dismissed and superseded entries from Resume #114 timestamp-keyed) cover the "don't want it there" case.
  • A stale heartbeat from a concurrent/offline session can re-add a watched item to Continue Watching at that session's position. This matches Jellyfin behavior; the watched badge is preserved and dismissal removes it. The previous hard latch "protected" against this only by making all rewatches impossible.

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

    • Added support for resuming rewatches—when rewatching previously completed content, progress is now properly tracked and resumable from where you left off.
  • Bug Fixes

    • Fixed "Resume" and "Continue Watching" logic to correctly handle rewatch scenarios, ensuring the correct playback label displays even for previously watched items being watched again.

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]>
@coderabbitai

coderabbitai Bot commented Jun 9, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

Pull request was closed or merged during review

📝 Walkthrough

Walkthrough

This 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.

Changes

Watched-to-Rewatch Position Semantics

Layer / File(s) Summary
SQLite progress store completion invariant
internal/userdb/progress.go
UpdateProgress, SetProgress, SetProgressAt, SetProgressIfNewer, MarkWatched, and MarkProgressBatch force position_seconds=0 when completed. ListProgress filters in_progress by position_seconds>0 instead of completed=false. Completed flag uses OR-latch (existing OR incoming) during upserts.
SQLite schema migration and version bump
internal/userdb/migrate.go, migrations/sql/20260609224115_reset_completed_progress_position.sql
Schema version incremented from 10 to 11. migrateToV11 resets position_seconds to 0 for legacy completed rows; Down migration restores duration-based position for rollback testing.
Rewatch lifecycle and migration tests
internal/userdb/progress_rewatch_test.go
TestProgressRewatchLifecycle validates completion clears resume, rewatch re-enters in_progress, subsequent completion clears again. TestProgressRewatchGuards covers zero-position resilience, resume-fraction guards, batch consistency. TestMigrateToV11ResetsCompletedPositions confirms migration normalizes legacy rows without affecting active rewatches.
PostgreSQL progress store completion invariant
internal/userstore/pgstore/progress.go
Mirrors SQLite: forces position=0 on completion, filters in_progress by position_seconds>0, applies OR-latch for completed, and enforces zero-position in batch/mark operations.
Audiobooks and conformance suite expectations
internal/audiobooks/abs_progress_store.go, internal/userstore/storetest/suite.go
Audiobooks GetProgress and ListProgressForAudiobooks return progress_pct=1.0 when completed=true. UpsertProgress enforces zero position on completion. Conformance tests expect PositionSeconds=0 for completed rows and MarkWatched assertions.
Catalog query layer filtering
internal/catalog/episode_catalog_entries_executor.go, internal/catalog/nextup_repo.go, internal/catalog/query_builder.go
Query conditions replace completed=FALSE with position_seconds>0 for in_progress CTEs, resumable-episode selection, progress sorting, and episode user-state calculation. All query tests updated to match.
API handlers and DTO mapping
internal/api/handlers/items.go, internal/jellycompat/content_direct.go, internal/jellycompat/mapping.go
Handlers set IsInProgress based solely on position_seconds>0. userDataDTO derives PlaybackPositionTicks and PlayedPercentage from clamped position without played/completed short-circuits. New playedPercentage helper returns 100 for played-at-rest (position=0), else resume fraction. resumePositionTicks replaced by clampResumeSeconds.
DTO mapping test suite
internal/jellycompat/mapping_userdata_test.go
Tests cover played items at rest (position=0, percentage=100), played with rewatch position, completed at rest (position=0, percentage=100), and completed with rewatch position. Percentage clamping validation ensures values ≤100.
History import upsert
internal/historyimport/repo.go
UpsertImportedProgress forces position=0 on completion and uses OR-latch for completed flag during conflict updates.
Frontend progress cache
web/src/hooks/queries/playbackProgressCache.ts, web/src/hooks/queries/playbackProgressCache.test.ts
mergeLeafProgress makes played a one-way latch, clears position on completion, computes is_in_progress solely from position_seconds>0. applyPlaybackProgressToCache preserves completed entries while allowing rewatch resume updates. Test updated for rewatch-with-watched-badge scenario.
Frontend progress bar and resume labels
web/src/components/EpisodeRow.tsx, web/src/components/HeroBanner.tsx
EpisodeRow shows progress bar for nonzero position even on watched items. HeroBanner prioritizes resume decision over played state, enabling "Resume" label for rewatch-in-flight items.
Frontend item detail action bar
web/src/pages/ItemDetail/itemDetailLayout.ts, web/src/pages/ItemDetail/itemDetailLayout.test.ts, web/src/pages/ItemDetail/MovieContent.test.tsx, web/src/pages/ItemDetail/EpisodeContent.test.tsx
resolveLeafPrimaryAction computes progress only when position and duration are positive (undefined otherwise), treats items as in_progress via is_in_progress flag or position_seconds>0. Test fixtures model completed items with position=0; new rewatch-in-flight test cases verify Resume action and restart URL.
Frontend watch route initialization
web/src/pages/watchRouteHelpers.ts
buildWatchPageProps uses position_seconds directly for non-restart requests, removing prior played-based guard and enabling rewatch resume from stored nonzero position.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • Silo-Server/silo-server#41: Both PRs modify next-up/resumable query logic in buildListNextUpQuery by changing which user_watch_progress rows qualify as in-progress candidates (completed=FALSE vs position_seconds>0).
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 30.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: separating resume point tracking from the watched/completed state, which is the core purpose across all file modifications.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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 fix/continue-watching-position-model

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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment thread internal/userdb/schema.go Outdated
// 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Comment thread internal/jellycompat/mapping.go Outdated

if data != nil {
dto.PlaybackPositionTicks = resumePositionTicks(data.PositionSeconds, data.DurationSeconds, data.Played)
dto.PlaybackPositionTicks = resumePositionTicks(data.PositionSeconds, data.DurationSeconds)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

@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: 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 win

Clamp PlayedPercentage from the same sanitized position.

Line 536 and Line 548 now normalize the resume point for PlaybackPositionTicks, but Lines 537-550 still derive PlayedPercentage from the raw stored seconds. A stale row with position > duration will 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 win

Keep the watched latch one-way in the explicit setters.

These UPSERTs still assign completed = excluded.completed, so a rewatch/import write with completed = false clears an item that was already watched. After MarkWatched, a later SetProgressAt(..., 900, ..., false) will drop the played latch instead of preserving it while storing the resume point. Please mirror UpdateProgress's one-way completed merge 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 win

SQLite still misses the 5% resume floor here.

position_seconds > 0 alone will surface tiny imported/synced positions written through SetProgressAt/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 win

Don't let older batch marks erase newer rewatch positions.

watch_progress.position_seconds <> 0 makes this UPSERT fire even when excluded.updated_at is older than the current row. A delayed MarkProgressBatch can therefore zero out a newer rewatch resume point and move updated_at backwards. 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

📥 Commits

Reviewing files that changed from the base of the PR and between 7040fa4 and 1031912.

📒 Files selected for processing (20)
  • internal/api/handlers/items.go
  • internal/audiobooks/abs_progress_store.go
  • internal/jellycompat/content_direct.go
  • internal/jellycompat/mapping.go
  • internal/jellycompat/mapping_userdata_test.go
  • internal/userdb/progress.go
  • internal/userdb/progress_rewatch_test.go
  • internal/userdb/schema.go
  • internal/userstore/pgstore/progress.go
  • internal/userstore/storetest/suite.go
  • migrations/sql/20260609224115_reset_completed_progress_position.sql
  • web/src/components/EpisodeRow.tsx
  • web/src/components/HeroBanner.tsx
  • web/src/hooks/queries/playbackProgressCache.test.ts
  • web/src/hooks/queries/playbackProgressCache.ts
  • web/src/pages/ItemDetail/EpisodeContent.test.tsx
  • web/src/pages/ItemDetail/MovieContent.test.tsx
  • web/src/pages/ItemDetail/itemDetailLayout.test.ts
  • web/src/pages/ItemDetail/itemDetailLayout.ts
  • web/src/pages/watchRouteHelpers.ts

Comment thread internal/userdb/schema.go Resolved
… 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]>
@Quick104

Quick104 commented Jun 9, 2026

Copy link
Copy Markdown
Contributor Author

All review feedback addressed in 7b4b951 (inline threads have individual replies). Responses to the CodeRabbit outside-diff items, which have no inline thread:

  • PlayedPercentage from the clamped position (mapping.go): fixed — both PlaybackPositionTicks and PlayedPercentage now derive from one clampResumeSeconds value, so they can't disagree and the percentage can't exceed 100 for stale over-duration rows. Played items at rest report 100; rewatches report their live fraction. Locked in with assertions in the existing clamp tests.
  • One-way watched latch in the explicit setters (userdb + pgstore): fixed — SetProgress, SetProgressAt, and SetProgressIfNewer merge completed as existing OR excluded in both stores (and the history-import upsert), so the RecordPlaybackStop path and device/import syncs can't clear watched state. Mark-unwatched still releases the latch via ClearProgress/ClearProgressBatch. New subtests cover the stop path and SetProgressIfNewer.
  • MarkProgressBatch zeroing newer rewatch positions: fixed — the extra position_seconds <> 0 branch I'd added to the conflict gate is gone; the position reset now rides the original freshness condition (completed IS DISTINCT FROM TRUE OR updated_at < EXCLUDED.updated_at), so a stale batch can't clobber a live rewatch and updated_at can't move backwards. Covered by a new "stale mark batch" subtest.
  • 5% min-resume floor in the SQLite ListProgress predicate: declining this one. Tiny sub-floor rows can only enter through SetProgressAt/SetProgressIfNewer, which are authoritative import/sync paths that deliberately bypass thresholds — and those rows appeared in Continue Watching under the old completed = FALSE predicate too, so this isn't a behavior change of this PR. The floor is also a server setting (playback.min_resume_threshold), so hardcoding 5% into read predicates (here, the Postgres store, and four catalog queries) would silently diverge from config. Write-time enforcement in UpdateProgress/SetProgress remains the single place the threshold applies. Happy to revisit as a follow-up if sub-floor imports show up in practice.

Verification: go test green across userdb, userstore, jellycompat, catalog, audiobooks, historyimport, watchstate, and api; full web suite unchanged from the pre-existing baseline on main; gofmt/golangci-lint clean on changed files.

@Quick104
Quick104 merged commit f1fcde5 into main Jun 9, 2026
20 of 21 checks passed
@Quick104
Quick104 deleted the fix/continue-watching-position-model branch June 9, 2026 23:44
Quick104 added a commit that referenced this pull request Jun 11, 2026
* 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]>
Quick104 added a commit that referenced this pull request Jun 17, 2026
* 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]>
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.

1 participant