Skip to content

feat(playback): run video and audiobook sessions and media URLs on v2 - #377

Merged
Quick104 merged 5 commits into
mainfrom
apiv2-stack/29-playback-sessions-v2
Sep 23, 2026
Merged

Quick104 merged 5 commits into
mainfrom
apiv2-stack/29-playback-sessions-v2

Conversation

@Quick104

Copy link
Copy Markdown
Contributor

Problem

Video and audiobook playback still run their sessions on /api/v1/playback: start, replan, route events, progress and stop (SiloAPI.swift rows 79–82 and 84). Against a 1.0 server every one of those calls is refused, so nothing plays.

The media URLs block the switch as well. A v2 start decision names its media as /api/v2/stream/{session} and /api/v2/playback/transcode/{session}/…, and its subtitle and font URLs as /api/v2/stream/{session}/subtitles/…. Main's StreamRequest accepted only unrooted /stream/ and /playback/transcode/ paths and prefixed them with /api/v1. PlaybackMediaAuthorization pinned its source and subtitle scopes to /api/v1, and PlayerViewModel.resolveServerUrl and the downloaded-subtitle descriptor added /api/v1 too (rows 86–88, 131 and PlayerViewModel.swift:6720). Every v2 URL would have been refused.

The v2 operations also need request shapes that v1 never sent: installation_id on every mutation, a sequenced progress sample, a client-minted stop_id and event_id. They answer with exact statuses and receipts that the old calls never checked.

Solution

Review it commit by commit: four feature commits, then a small test cleanup.

  1. Transport (APIv2Client+Playback.swift). Typed wrappers over the fenced playbackRequest:

    • startPlayback accepts only 201.
    • replanPlayback accepts only 200.
    • reportPlaybackRouteEvent accepts only 202, and the receipt must echo the client-minted event_id.
    • updatePlaybackProgress accepts only 200 with applied, replayed or stale_sample.
    • stopPlayback accepts only 200 with stopped for this stop_id, or replayed.

    A non-canonical session id never reaches a path. Start and replan keep the extended timeout. PlaybackSequencedSample drops the timeline_id/item_position fields the server never accepted. The start body drops timeline_id, because the schema sets additionalProperties: false. PlaybackProgressSequence hands out per-session sequence numbers.

  2. Media URLs:

    • StreamRequest accepts only the two /api/v2 media families and uses them as sent. It refuses a relative URL without the /api/v2 root instead of giving it a version.
    • The subtitle-identifier query rule follows the v2 subtitle path.
    • The media and subtitle authorization scopes move to /api/v2.
    • The downloaded-subtitle descriptor is built on /api/v2/stream, and resolveServerUrl no longer adds /api/v1.
    • The v2 font route returns {"items": [...]}, so the ASS font decoder reads that envelope.
    • The /stream/v3 proxy-origin checks are unchanged.
  3. Video callers (PlaybackSessionBridge). The bridge captures the owner before a start and pairs it with the gate's installation in a PlaybackV2SessionAuthority. Replan, route events, progress, stop and the retirement of abandoned sessions all run fenced to that owner.

    • The start keeps its cancellation shield and its one identical resend after a transport failure. A 409 installation_changed still refreshes the capability once and retries with a new playback_attempt_id (W2-A).
    • Progress draws a strictly increasing sequence per session before each request, so the five PlayerViewModel call sites stay ordered.
    • The stop carries the final position as the last sample, which replaces the separate final progress report.
    • A 404 problem or a 409 installation_changed counts as a missing session, and the player renews it.
  4. Audiobook callers (AudioPlayerViewModel). The audiobook player uses the same authority for its start, its session-local progress and its stops. Each session keeps its authority next to it. The start still sends progress_persistence: "client" (D5) and keeps the transport resend.

    • Deletes SiloAPI.startPlaybackV3, replanPlaybackV3, reportPlaybackRouteEventV3, reportPlaybackProgress, stopPlayback and the ProgressReport model.

Harvested from apiv2-legacy: only the idea of a per-session sequence counter and a stable stop_id for resends. None of its code was copied. It has no v1 fallback, timelines, owner-loss or 202 draining, and no PlaybackMutationCoordinator/Store.

Update required: when the recorded verdict says the server is v1-only, playbackRequest's gate throws APIv2Error.serverUpdateRequired, and the capability gate maps it to the server-update terminal failure (W2-A). Both reach the player through localizedDescription and reach the audiobook player through ErrorState, which F5 maps.

Failure outcomes

Operation (retry safety) Definite success Definite failure Uncertain (sent, no response)
Start (domain_identity) 201 decision; the plan is staged until Aether commits it Problem or non-201: the error is shown once and logged. 409 installation_changed: capability refresh, then one start with a new attempt id One identical resend with the same playback_attempt_id, which the server replays. If that also fails, the error is shown. A start cancelled by the caller is still shielded, and anything it allocated is retired
Replan (domain_identity) 200 decision; staged as before Problem or non-200: the existing recovery path handles it (terminal after the attempt limit) Not resent. The player treats it as a failed replan
Route event (non_retryable) 202 with the echoed event_id Logged and dropped, including 429 Dropped; never resent
Progress (domain_identity) applied, replayed or stale_sample Video: a 404 problem or 409 installation_changed means the session is missing, and the player renews it. Anything else is a transient failure, logged and counted. Audiobook: every failure, including 404 and 409 installation_changed, is logged and the session is not renewed; the next 10-second tick sends a new sample, and durable progress still goes through APIv2Client.syncProgress (W2-S) Dropped; the next periodic sample carries a higher sequence and supersedes it
Stop (domain_identity) stopped with this stop_id, or replayed Logged. The server ends the session at its idle timeout One resend with the same stop_id, which the server records once. If that also fails, it is logged

Playback session mutations are live, interactive and not journaled, so an uncertain outcome is never held. Start and stop resend once only because the server keys them on playback_attempt_id and stop_id.

Validation

  • iOS, tvOS and macOS builds passed on this branch.
  • The full iOS and tvOS suites passed on the lane before the stack was assembled, with only the two environment-gated Aether live-fixture tests skipped.
  • scripts/ci/check-no-api-v1.sh passed. The v1 match counts drop in SiloAPI.swift, StreamRequest.swift, PlaybackMediaAuthorization.swift, PlaybackSessionBridge.swift, PlayerViewModel.swift, AIModels.swift and the playback and media tests.
  • The count of lines in iosApp/iosApp that name withOwnerFence or sameCredentialIdentity is unchanged (64). Every new mutation goes through the fenced playbackRequest.
  • PlaybackSessionTransportTests (new, on StubURLProtocol) covers the exact body and single accepted status of each operation, the route-event echo check, progress outcomes, refusal of a stop receipt for another stop or a draining outcome, 404 and 409 problems, non-canonical session ids never leaving the device, a stop for a replaced profile never being sent, and per-session sequencing.
  • PlaybackMediaAuthorizationTests and the StreamRequest cases in AetherPlaybackBoundaryTests now use v2 paths and assert that the unrooted and other-version forms are refused.
  • The fixture-based tests decode the server's published v2 decision (playback_start_opaque_ids.json) through APIv2PlaybackDecision instead of the v1-shaped decision_response.json. That fixture is deleted along with the unused native-decision_response.json.
  • The missing-session and font-envelope tests are rewritten for v2. RotatingMediaOrigin serves the v2 paths and font envelope.
  • The final stack passed the full suites (iOS 1981 tests and tvOS 1792 tests, 0 failures), the macOS build and the v1 path guard, and every branch in the stack builds on its own.
  • Not run: the plan's manual checks (direct play, HLS, subtitle sidecar, quality change, stop then resume, and audiobook play, kill and relaunch on three platforms against a live server). No server was exercised end to end.

Risks and follow-ups

  • Intermediate commits are not independently shippable. After commit 2, media URLs expect v2 while the callers still start on v1. The PR is meant to land as a whole.
  • Expected conflicts with open PRs:
  • Still v1 after this PR: the playback control socket (row 85), which moves in W2-D.
  • Replan after an installation change: a 409 installation_changed on replan counts as a missing session, like a 404, and the video player renews the session at the observed position. It becomes a terminal error only when renewal is not possible: there is no prior load request, or the player is disposed.
  • Route-event 409: the server can return 409 on route events although the OpenAPI document omits it (S7). The client logs it like any other refusal.
  • Non-integer file ids: APIv2PlaybackDecision.legacy() refuses a non-integer file id. The server sends integer strings today. If that changes, a start that allocated a session and then failed to decode would leave that session until the idle timeout.
  • HTTPClient refresh exclusion: replan and route events are excluded from 401 refresh-and-resend in HTTPClient.shouldAttemptRefresh (unchanged by this PR), so a replan made with an expired token fails instead of refreshing.

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 29 of 50 in the Apple API v2 stack. Base: apiv2-stack/28-playback-capabilities-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: 7769b576-43bb-418f-a79f-57e4756e6614

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:46:24.581912Z 6b2151c 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: 5c233a7f (apiv2-stack/29-playback-sessions-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: PR body says a 409 installation_changed on replan becomes a failed replan, but the code renews the session

Note: Runtime validation found that changing quality while an external subtitle is selected makes the server replan fail ("subtitle track unavailable in the effective file version"), and the retry drops the quality choice. main has the same behavior, so it is a follow-up, not a regression from this PR.

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

@Quick104
Quick104 force-pushed the apiv2-stack/29-playback-sessions-v2 branch from 5c233a7 to c425351 Compare September 23, 2026 13:19
@Quick104
Quick104 force-pushed the apiv2-stack/28-playback-capabilities-v2 branch from 6375069 to 83820f0 Compare September 23, 2026 13:40
Base automatically changed from apiv2-stack/28-playback-capabilities-v2 to main September 23, 2026 13:40
Quick104 and others added 5 commits September 23, 2026 09:40
Video and audiobook playback start, replan, report progress, report route
events and stop through /api/v1/playback. The v2 operations need a
different body for every mutation (installation_id everywhere, a sequenced
progress sample, a client-minted stop_id and event_id) and answer with
exact statuses and receipts that the v1 calls never checked.

This first slice adds the typed v2 transport in APIv2Client+Playback.swift:
startPlayback (201), replanPlayback (200), reportPlaybackRouteEvent (202,
the receipt must echo the event id), updatePlaybackProgress (200 with
applied, replayed or stale_sample) and stopPlayback (200 with stopped for
this stop_id, or replayed). Every call runs through playbackRequest, which
fences the captured owner, and a non-canonical session id never reaches a
path. Start and replan keep the extended timeout the v1 calls used.

PlaybackSequencedSample drops the timeline_id and item_position fields the
server never accepted, and PlaybackProgressSequence hands out the per-session
sequence numbers. The start body drops timeline_id, which the schema's
additionalProperties: false would refuse. Callers switch in the following
commits.

Stack-PR: W2-B
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…pace

A v2 playback decision names its media as /api/v2/stream/{session} and
/api/v2/playback/transcode/{session}/..., and its subtitle and font URLs
as /api/v2/stream/{session}/subtitles/.... The header-authenticated
branch of StreamRequest accepted only /stream/ and /playback/transcode/
paths and prefixed them with /api/v1, so every v2 URL would have been
refused, and PlaybackMediaAuthorization pinned its source and subtitle
scopes to /api/v1.

StreamRequest now accepts only the two /api/v2 media families and uses
them as sent. A relative URL without the /api/v2 root is refused instead
of being assigned a version, and the subtitle-identifier query rule
matches the v2 subtitle path. The media and subtitle authorization scopes
move to /api/v2. The downloaded-subtitle descriptor is built on
/api/v2/stream, and PlayerViewModel.resolveServerUrl no longer adds
/api/v1 to a relative path. The /stream/v3 proxy-origin checks are
unchanged.

The v2 font bundle route answers with the collection envelope
{"items": [...]}, so the ASS font decoder reads that shape.

Tests move to the v2 paths, and the fixture-based tests decode the
server's published v2 start decision (playback_start_opaque_ids.json)
through APIv2PlaybackDecision instead of the v1-shaped
decision_response.json, which is deleted with the unused
native-decision_response.json.

Stack-PR: W2-B
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The video player started, replanned, reported progress and route events
for, and stopped its sessions through /api/v1/playback. v2 needs the
server's installation id on every mutation, a sequenced progress sample,
and a stop that names itself with a stop_id.

PlaybackSessionBridge now captures the owner before a start and pairs it
with the installation from the capability gate in a
PlaybackV2SessionAuthority. Every later request of the session (replan,
route events, progress, stop, and the retirement of abandoned sessions)
runs fenced to that owner through the typed v2 client. The start keeps
its cancellation shield and its one identical resend after a transport
failure, and a 409 installation_changed still refreshes the capability
and starts again with a new attempt id.

Progress draws a strictly increasing sequence per server session before
each request, so samples from the five player call sites stay ordered.
The stop now carries the final position as the session's last sample,
which replaces the separate final progress report, and resends the same
stop_id once after a transport failure. A session counts as missing on a
404 problem or on 409 installation_changed; the player renews it either
way.

The audiobook player keeps its v1 terminal-start report until the next
commit switches it.

Stack-PR: W2-B
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The audiobook player started, reported progress for and stopped its
per-file sessions through /api/v1/playback.

It now captures the owner before each start and runs the start, the
session-local progress samples and every stop under a
PlaybackV2SessionAuthority, the same way the video player does. The start
still sends progress_persistence "client", keeps its one identical resend
after a transport failure, and starts again with a new attempt id after a
409 installation_changed. Progress samples draw a per-session sequence.
Each session's authority is kept next to the session itself, so a
superseded or failed part is stopped under the installation and owner it
was started with.

Durable audiobook resume still goes through SiloAPI.syncProgress; its
move to POST /api/v2/sync/progress belongs to the sync/progress change.

Deletes SiloAPI.startPlaybackV3, replanPlaybackV3,
reportPlaybackRouteEventV3, reportPlaybackProgress and stopPlayback, the
ProgressReport model, and the bridge's temporary v1 terminal-start report.

Stack-PR: W2-B
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Stack-PR: W2-B
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@Quick104
Quick104 force-pushed the apiv2-stack/29-playback-sessions-v2 branch from c425351 to 6b2151c Compare September 23, 2026 13:41
@Quick104
Quick104 merged commit 7a05523 into main Sep 23, 2026
3 checks passed
@Quick104
Quick104 deleted the apiv2-stack/29-playback-sessions-v2 branch September 23, 2026 13:41

@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: 6b2151c4d1

ℹ️ 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 +1567 to +1571
let response = try await SiloAPI.shared.apiV2Client.replanPlayback(
sessionID: currentSessionId,
request,
installationID: authority.installationID,
auth: authority.owner

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 Refresh credentials before failing v2 replans

When the access token expires during playback, this newly migrated v2 request receives a 401 and immediately terminates the replan—and the player subsequently surfaces a terminal playback error—because HTTPClient.shouldAttemptRefresh explicitly excludes POST paths ending in /replan (HTTPClient.swift:1902-1907) and this wrapper performs no retry. The previous v1 replan was not covered by that exclusion. Since each request carries a stable replan_request_id and replanPlayback documents that the server replays the committed decision for that identity, refresh and resend can be performed safely instead of breaking quality changes, track changes, seek reanchors, or recovery after a token expires.

Useful? React with 👍 / 👎.

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