Skip to content

feat(library): read and toggle favorite, watchlist and watched through v2 - #387

Merged
Quick104 merged 3 commits into
mainfrom
apiv2-stack/39-membership-v2
Sep 23, 2026
Merged

Quick104 merged 3 commits into
mainfrom
apiv2-stack/39-membership-v2

Conversation

@Quick104

Copy link
Copy Markdown
Contributor

Problem

Favorite, watchlist and watched still used /api/v1 (inventory rows 64-68):

  • SiloAPI.isFavorite / isInWatchlist (v1 http.exists), toggleFavorite, toggleWatchlist and setWatched.
  • Callers: the card dispatchers added in c23903c (PersonalListSync in PersonalListActions.swift and MediaCardWatchedSync, used by MediaCard, TVMediaCard, EpisodeThumbCard and the Home feed cards), seven mutation sites in ItemDetailViewModel, HomeViewModel.setWatched, and the SectionRow fallback used by Browse and Recommendations.

None of these calls captured an owner, so a tap that finished after a profile or server switch could write that item's state into the new owner's caches. Every failure looked the same: the UI reverted, and detail pages and the SectionRow fallback reported nothing. The v2 writes are all x-silo-retry-safety: non_retryable, so "sent but no answer" needs its own handling. Item detail also sent two existence GETs on every load, even though the v2 detail it already reads returns user_state (audit F28).

Solution

One dispatcher. The new PersonalStateSync (Components/PersonalStateSync.swift) sends each favorite, watchlist or watched change once, under a captured owner, through the existing APIv2Client.setFavoriteMembership / setWatchlistMembership / setWatchedState. Those methods are unchanged: they already assert 204, send X-Profile-Id, fence with withOwnerFence, and are excluded from refresh-and-resend in HTTPClient.shouldAttemptRefresh. After a 204, the dispatcher checks the owner again before any caller writes local state. It returns a PersonalStateOutcome:

Result of the dispatch Outcome Behavior
204 under the captured owner definite success (.applied) Keep the optimistic state. Write back or invalidate the item's caches, favorites, watchlist, history, Home (including a Home read already in flight), recommendations and the library/browse/collection prefixes.
Any non-2xx answer (problem+json or bare status), a decode failure, a refusal before dispatch (gate() update-required, no server URL), or a transport failure that never reached the server (no connection, DNS, cannot connect, TLS handshake) definite failure (.failed) Revert the optimistic state. Report once ("Couldn't Update Item" on cards and detail; Home and the season/episode rows keep their existing alerts). When UpdateRequirement classifies the error (a gate() refusal on a v1-only server, or HTTP 410 client_upgrade_required), every surface instead shows "Update Required" with the server-update or app-update message and no "try again". Log the real cause. Nothing is held, so the next tap sends normally.
Sent with no answer: timeout, connection lost, cancellation, or an unrecognized error uncertain (.held) Revert to the last confirmed state. Record a hold for that owner, flag and item, and show "Change Not Confirmed" with Discard Held Change. It is never re-sent automatically. While held, taps on that flag and item in either direction send nothing and show the same notice. Discarding releases the hold and drops the item's cached state so the next read comes from the server.
Owner changed before dispatch, during the request, or before local apply; or a change to the same flag and item is already in flight nothing applied (.skipped) Revert silently. Nothing is written to the new owner's caches and nothing is reported.

Holds live in memory (PersonalStateHolds). They are keyed with sameCredentialIdentity and cleared on profile switch and sign-out (AuthService.clearPerProfileCaches / clearAllCaches). After a relaunch, the item's state is re-read from the server, which decides what actually landed.

Callers.

  • PersonalListSync and MediaCardWatchedSync now return outcomes. MediaActionFeedback presents both notices for every card and episode rail.
  • ItemDetailViewModel captures the owner when a detail load starts and uses it for every read and write on the page. The favorite, watchlist and watched toggles on the detail page now report failures instead of reverting silently.
  • Season and episode closures in SeriesDetailContent, TVSeriesDetailView, the phone episode rail/carousel and TVEpisodeRail carry outcomes. Their existing "Couldn't Update Watched Status" copy is kept for ordinary failures; a held change adds the discard notice, and an update-required failure uses the shared "Update Required" notice.
  • HomeViewModel.setWatched dispatches through the same path. A held change shows the discard notice instead of actionError.
  • The SectionRow fallback reports through its own MediaActionFeedback.

Reads (F28).

  • ItemDetail gains userState, projected from the v2 detail's user_state. loadDetail sets favorite and watchlist from it and drops the two per-load GETs. An absent user_state keeps the cached value and is not read as all-false.
  • Episodes have no user_state, so the per-episode fan-out and the tvOS series card check use APIv2Client.personalMembership under the page owner.

Expired bearers are renewed before sending. The single-dispatch writes on HTTPClient's refresh exclusion list, these toggles included, never refresh on a 401. On main the toggles used v1 routes that refreshed and retried; on v2, once the access token expired, the first toggle got a 401, reverted, and failed the same way on every retry until an unrelated read refreshed the token. HTTPClient now checks the captured bearer before dispatch on both the scoped and the ordinary path. When it has expired, or expires within the MediaAccessTokenExpiry margin (at most 60 s), the request joins the shared refresh flight and recaptures credentials under the same identity, account and expected-auth checks the 401 path uses, then sends once. Nothing has been sent at that point, so this is safe for non_retryable operations. If no fresh bearer comes back and the old one has expired, the request is not sent and fails with a 401, as the 401 path would. Public auth paths are exempt. This applies to every request through HTTPClient, not just the personal-state writes.

Deleted: SiloAPI.isFavorite, isInWatchlist, toggleFavorite, toggleWatchlist, setWatched (8 v1 path lines out of SiloAPI.swift), and HTTPClient.exists, which only served the v1 existence checks.

Validation

  • iOS, tvOS and macOS builds passed, with no new warnings in touched files.
  • Focused tests passed on iOS and tvOS: PersonalStateSyncTests, CatalogV2Tests, HomeSectionsMutationTests and UpdateRequirementTests.
  • Existing detail and series classes passed on iOS: DetailDismissalNavigationTests, HorizontalMediaRailTests, LibraryDetailScopeTests, SeriesSeasonSelectionTests, SeriesHierarchyLoadingTests and SeriesEpisodeWindowTests. The four of them that build for tvOS passed there too.
  • The new PersonalStateSyncTests run on StubURLProtocol through APIv2TestStub:
    • a 204 sends PUT/DELETE once with X-Profile-Id and applies
    • a problem+json 404 and cannotConnectToHost are definite failures with no hold, and the next tap sends
    • networkConnectionLost on mark-watched is held; later set and clear taps send nothing, another flag or item still sends, and discarding releases the hold
    • a timedOut hold belongs to its profile, and reset() clears it
    • a replaced owner is skipped before dispatch
    • an owner change while the request is in flight applies nothing
    • a second change to the same flag during the first is skipped
    • a 410 client_upgrade_required problem and a gate() refusal on a v1-only server (nothing sent) are definite failures whose notice carries the app-update or server-update message; a 410 with another problem type keeps the generic copy
    • an expired bearer is refreshed before the write is sent once, and when that refresh is rejected no write is sent
    • Home turns a held watched change into the discard notice, not actionError
    • the detail projection carries user_state and leaves it nil when absent
  • scripts/ci/check-no-api-v1.sh passed and scripts/ci/check-no-api-v1.test.sh passed. SiloAPI.swift drops from 57 to 49 v1 lines; the allowlist is not edited (it is a ceiling).
  • Fence lines (withOwnerFence / sameCredentialIdentity) in iosApp/iosApp: 60 before, 62 after.
  • The final stack passed the full suites (iOS 1981 tests and tvOS 1792 tests, 0 failures), the macOS build and the v1 path guard. Every branch in the stack, this one included, builds on its own.
  • Not run: a manual simulator check against a live server, and a rendered check of the new alert.

Risks and follow-ups

  • Behavior change: detail-page toggles, the SectionRow fallback (Browse, Recommendations) and busy/in-flight taps behaved differently before. The first two now show an alert on a definite failure. A tap that collides with a change already in flight is now skipped silently; before, it sent a second request (detail) or showed "Couldn't Update Item" (episode rails).
  • Uncertain means revert: a held change shows the last confirmed state, even though the server may have applied it. The next server read, or Discard, reconciles it. This matches "hold, never auto-replay" in plan §9. Android instead releases the row and lets the next tap re-send (UserItemStatePort.abandonPersonalWrite).
  • Holds are not durable. They do not survive a relaunch, and they are not built on DurableCommandStore, because nothing is queued for later dispatch.
  • Owner capture: cards capture the owner at the tap, not from the read that produced the card. Carrying the list read's owner into the card is a possible follow-up. The detail page uses the owner captured when its load started.
  • Unchanged wire behavior (not verified here): APIv2Client.personalMembership fails to decode a legacy plain-text 404 and does not map it to serverUpdateRequired. Every read in this PR uses try? and keeps the last known value.
  • Pre-dispatch bearer renewal is global. It changes timing for every HTTPClient request whose bearer is about to expire: the request waits for the shared refresh instead of going out and meeting a 401. Only the two personal-state tests above cover it directly.
  • Classifier: PersonalStateSync keeps its own sent/never-sent rules here. W5-E moves them onto the shared APIv2MutationOutcome (added in W5-O), which also holds an undeclared 2xx or an unreadable answer instead of failing it.
  • Test vector left in place: HTTPClientDiagnosticsClassificationTests still lists the /api/v1/favorites/%@ path template. That class belongs to W5-W2 / Z1.
  • Expected conflict: open PR feat(watch-party): add iOS and tvOS rooms and synchronized playback #347 touches SectionRow.swift.

AI disclosure

Code and description written by Claude Opus 5.5 (claude-opus-5-5) agents in Claude Code (T3 Code), orchestrated by a Claude Code workflow.


Part 39 of 50 in the Apple API v2 stack. Base: apiv2-stack/38-personal-collections-v2. Merge in order from the bottom of the stack. The plan and full index are in PR 01.

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: ca6af9a5-5109-461b-91fc-e4b154d99174

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

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

❤️ Share

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

@greptile-apps greptile-apps 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.

Quick104 has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-23T13:24:21.434978Z a6d7304 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@Quick104

Copy link
Copy Markdown
Contributor Author

Code review summary

Reviewed head: 12e16ce6 (apiv2-stack/39-membership-v2).

Process: an adversarial review of this PR's diff with each candidate finding independently verified before any fix, a simplify pass for medium and larger PRs, and a whole-stack review across contract conformance, authority and failure handling, data integrity, user-visible behavior and cross-PR integration.

Verified findings, all fixed on this branch:

  • minor: Personal-state failure notices drop the error, so update-required answers show "Please try again"
  • whole-stack review: Favorite, watchlist and watched toggles fail every time once the access token has expired
    Refuted or unconfirmed after verification: 1 (not acted on).

Validation: this branch builds on its own for iOS, tvOS and macOS, and its focused tests passed. The completed stack passed the full iOS suite (1981 tests) and tvOS suite (1792 tests) with 0 failures, the macOS build and the v1 path guard. The final stack was also exercised on iOS and tvOS simulators against a v1/v2 bridge server: sign-in (password and QR), restore, browse, search, detail, favorites and watchlist, playback (direct play, transcode, subtitles, stop), audiobooks, downloads with offline playback, settings, requests, profiles, push registration and diagnostics. Server logs showed no /api/v1 request from the new builds except the retained health probe.

Remaining: no open verified findings. Merge in stack order.

Mergeability: 8/10 — conditional. The approach holds up and every verified finding is fixed. Conditions: this PR's CI must pass (it was pending at review time), and the owner still plans a physical-device check of the completed stack.

Review by Claude Opus 5.5 (claude-opus-5-5) agents in Claude Code (T3 Code).

@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: 12e16ce670

ℹ️ 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 on lines +207 to +209
if error is APIv2Error { return .definite }
// Cancellation and anything unrecognized may have left the device.
return .unconfirmed

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 Classify preflight update requirements as definite

When an expired or near-expiry bearer triggers scopedAuthRefreshedBeforeDispatch, the refresh helper can throw UpdateRequirement before the favorite/watchlist/watched request is sent. Because that error is neither HTTPError nor APIv2Error, this fallback classifies it as unconfirmed, records a hold, and shows “Change Not Confirmed” instead of “Update Required”; subsequent taps are then blocked until the user discards the nonexistent mutation. Treat UpdateRequirement as a definite pre-dispatch failure.

Useful? React with 👍 / 👎.

@Quick104
Quick104 force-pushed the apiv2-stack/39-membership-v2 branch from 12e16ce to a6d7304 Compare September 23, 2026 13:19
@Quick104
Quick104 force-pushed the apiv2-stack/38-personal-collections-v2 branch from f6c22f8 to 83b1a84 Compare September 23, 2026 13:19

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

ℹ️ 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 on lines +298 to +299
isFavorite = userState.isFavorite
inWatchlist = userState.inWatchlist

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 Apply played from the v2 user-state payload

When a detail response contains user_state.played but omits user_data—a payload shape this commit's testDetailProjectionCarriesTheViewersFlags explicitly accepts—this block copies only favorite and watchlist. The later isWatched = enriched.userData?.played ?? false therefore renders a watched item as unwatched and makes the next toggle request the wrong state. Apply userState.played as well and preserve it through playback-metadata enrichment.

Useful? React with 👍 / 👎.

Comment on lines +205 to +207
// Every APIv2Error is either a refusal before dispatch (`gate()`) or a
// decoded server answer.
if error is APIv2Error { return .definite }

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 Hold mutations after unexpected successful statuses

If a mutation is applied but the server or an intermediary returns an unexpected 2xx status such as 200 instead of 204, the API methods throw APIv2Error.httpStatus, and this blanket branch classifies it as definite. The caller then releases the mutation and permits another send even though the server may already have acted; the repository's shared APIv2MutationOutcome correctly treats unexpected 2xx statuses as uncertain for this reason. Classify those statuses as unconfirmed rather than definite.

Useful? React with 👍 / 👎.

@Quick104
Quick104 force-pushed the apiv2-stack/38-personal-collections-v2 branch from 83b1a84 to 08038f1 Compare September 23, 2026 13:43
Quick104 and others added 3 commits September 23, 2026 09:43
…h v2

Favorite, watchlist and watched still went through /api/v1. The card
dispatchers from c23903c (PersonalListSync, MediaCardWatchedSync), item
detail, Home and SectionRow each called SiloAPI with no captured owner, and
every failure was treated the same way: revert and, in most places, say
nothing. Item detail also made two extra existence GETs on every load even
though the v2 detail read already returns user_state (F28).

All six writes now go through one dispatcher, PersonalStateSync, which calls
the existing APIv2Client membership and watched methods under a captured
owner. Every v2 write here is non_retryable, so the dispatcher sorts each
result into the plan's failure model:
- a 204 under the same owner is applied, and callers invalidate their caches
  (including in-flight Home reads);
- a server answer or a request that never connected is a definite failure:
  revert, report once, log the cause;
- a request that was sent but got no answer is held for its owner, item and
  flag. It is never re-sent, later taps report the hold, and "Discard Held
  Change" releases it and drops the item's cached state;
- an owner change or a second in-flight change to the same flag is skipped
  and applies nothing locally.
Holds are cleared on profile switch and sign-out.

Item detail reads favorite and watchlist from the v2 detail's user_state.
The episode and tvOS series checks, which have no user_state, use the v2
membership GET under the page's owner. The v1 SiloAPI methods and the
now-unused HTTPClient.exists helper are deleted.

Stack-PR: W5-M
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
A favorite, watchlist or watched write refused because the server is
v1-only (gate() reports serverUpdateRequired) or because the server no
longer accepts this app (HTTP 410 client_upgrade_required) showed "Your
change wasn't saved. Please try again." Retrying can never succeed there,
and the detail-page toggles and season watched alerts now surface that
failure.

PersonalStateOutcome.failed and PersonalStateNotice.failed now carry the
UpdateRequirement classified from the error. The notice shows "Update
Required" with the server-update or app-update message, and the series
watched alerts on iOS and tvOS route an update-required failure to that
notice instead of "Please check your connection and try again."

Stack-PR: W5-M
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Favorite, watchlist and watched toggles (and the other single-dispatch
writes on the refresh exclusion list) never refresh on a 401. Once the
access token expired, the first such toggle got a 401, reverted, and
failed the same way on every retry until some unrelated read happened to
refresh the token. On main these toggles used v1 routes that refreshed
and retried.

HTTPClient now checks the captured bearer before dispatch on both the
scoped and the ordinary path. When it has expired or expires within the
margin MediaAccessTokenExpiry uses (at most 60 s), it joins the shared
refresh flight and recaptures credentials under the same identity,
account and expected-auth checks the 401 path uses, then sends once.
Nothing has been sent at that point, so this is safe for non_retryable
operations. When no fresh bearer comes back and the old one has expired,
the request is not sent and fails with a 401 as the 401 path would.

Stack-PR: W5-M
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Base automatically changed from apiv2-stack/38-personal-collections-v2 to main September 23, 2026 13:43
@Quick104
Quick104 force-pushed the apiv2-stack/39-membership-v2 branch from a6d7304 to 5453ca8 Compare September 23, 2026 13:44
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@Quick104
Quick104 merged commit 4ebd278 into main Sep 23, 2026
3 of 6 checks passed
@Quick104
Quick104 deleted the apiv2-stack/39-membership-v2 branch September 23, 2026 13:44
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