Skip to content

feat(subtitles): search, download and manage subtitles on v2 - #391

Merged
Quick104 merged 6 commits into
mainfrom
apiv2-stack/43-subtitles-v2
Sep 23, 2026
Merged

Quick104 merged 6 commits into
mainfrom
apiv2-stack/43-subtitles-v2

Conversation

@Quick104

Copy link
Copy Markdown
Contributor

In-player subtitle search now runs entirely on /api/v2: listing stored subtitles, reading provider status, searching, and downloading. A provider download is sent once, and the search menu now handles its three possible outcomes separately.

Problem

SiloAI still sent four subtitle calls to /api/v1 (inventory rows 110-113):

  • GET /api/v1/subtitles/{mediaFileId} (stored subtitles, used by the AI handoff and by search downloads)
  • GET /api/v1/subtitles/providers/status
  • POST /api/v1/subtitles/search
  • POST /api/v1/subtitles/download

The v2 contract differs from v1 in these ways:

  • SubtitleDownloadBody sets additionalProperties: false, has no format, and takes media_file_id as a string. The v1 body would get a 422.
  • StoredSubtitle.id and media_file_id are opaque strings. The player decoded them as Int.
  • Provider status is a capability document (allowed, state, revision). The old model defaulted a missing enabled to true to cover servers that predate the endpoint.
  • downloadSubtitle is non_retryable. The menu showed "Couldn't add that subtitle. Try another result." on every failure, including cases where the server had already stored the subtitle, which invited a duplicate download.

Solution

  • New APIv2Client+Subtitles.swift with subtitleProviderStatus(), storedSubtitles(mediaFileID:auth:), searchSubtitles(_:), and downloadSubtitle(_:auth:). downloadSubtitle moved here from APIv2Client.swift. Each call checks one exact status (200), sends X-Profile-Id when a profile is selected (the contract makes it optional), and runs inside withOwnerFence. Search and download keep the extended timeout. Invalid input is refused before sending: file ID <= 0, or more than 100 languages.
  • IDs fail soft. DownloadedSubtitle.id is now an opaque String. No ID value can fail or trap, and the listing keeps every row in server order. A row that names another file fails the whole listing. The AI handoff still gets an integer result_subtitle_id from its job and compares it as String(resultId); W5-R changes that job model.
  • Stream URLs name the row. The v2 listing leaves out stored rows whose language the server cannot canonicalize, but the stream handler resolves an unpinned ordinal against the full list. A listing position can therefore point at a different row. DownloadedSubtitle.synthesizedDescriptor now appends ?file_id=<file>&downloaded_subtitle_id=<id>, the same shape as the server's DownloadedSubtitleStreamURLV3, so the handler serves the row by ID. A row without a positive integer ID gets no track and the download reports .stored. This applies to search downloads and to the AI handoff.
  • Track ordinals follow the plan, not the listing. The player files a sidecar under its combined ordinal, and a later plan's inventory replaces a local row with the same ordinal. The plan inventory counts every stored row, so after an omitted row a listing position would take an existing downloaded track's slot: the new track would be filed under that track's ID and would not get its own row. DownloadedSubtitleOrdinals now reads each published downloaded row's ordinal from the downloaded_subtitle_id pin on its inventory URL. A published row keeps that ordinal; a row stored since the plan gets the next ordinal past every published track, advanced past earlier unpublished listing rows. It replaces the old baseTrackCount + position.
  • Provider status is available only when allowed && state == "available" && enabled. An unknown state counts as unavailable. A failed probe is not an answer: SubtitleProvidersStore keeps its previous value (initially true), and the next refresh trigger asks again. This is the retryable state that I9 requires; the probe never fails closed.
  • Download outcomes. PlayerViewModel.downloadSearchedSubtitle captures the owner before the first await, downloads for that owner, and re-lists for the same owner. It also re-checks the owner and file before registering the track. It returns SubtitleDownloadOutcome, which SubtitleSearchMenu shows. The mapping from each step to an outcome lives in SubtitleDownloadOutcome.resolve, which takes the download, re-list, owner check and registration as closures so tests can drive it without a player. For .stored and .unconfirmed (holdsResult), the menu remembers the result and will not send it again while the menu is open.
  • Shared classifier. New APIv2DispatchFailure.isUncertain sorts download failures by delegating to the shared APIv2MutationOutcome, so subtitle downloads (and the AI subtitle jobs in W5-R) classify failures the same way as every other v2 write. SubtitleDownloadOutcome.isUnconfirmed adds APIv2SubtitleRequestError.outcomeUnknownOwnerChanged on top.
  • Deleted: the four v1 SiloAI paths, DownloadedSubtitlesResponse, SubtitleDownloadResponse, SubtitleProvidersStatus, the v1 Codable decoders on DownloadedSubtitle and SubtitleSearchResponse, SubtitleDownloadBody.format, and the tests that decoded v1 shapes.

Failure outcomes for POST /api/v2/subtitles/download (non_retryable)

Outcome Cases Behavior
Definite success 200 with a stored row for this file Re-list for the same owner, register and select the track (.added). If the listing, owner, file or handoff context no longer fits, return .stored: "The subtitle was saved but couldn't be turned on now. It will be available the next time you play this video."
Definite success, unusable row 200 whose row names another file .stored with the same copy
Definite failure Refused before sending (owner already replaced, update-required gate, invalid input); transport errors that happen before any bytes leave (cannotConnectToHost, DNS, TLS); any non-2xx answer .failed. Shows the problem detail or the server-update copy when present, otherwise "Couldn't add that subtitle. Try another result." The user may pick the result again.
Uncertain Connection lost or timed out after sending, cancellation, a 2xx other than 200, an unreadable 200 body, or an owner change once dispatch may have begun (APIv2SubtitleRequestError.outcomeUnknownOwnerChanged) .unconfirmed: "Silo couldn't confirm the download. If it was saved, it will be available the next time you play this video." The result is held for as long as the menu stays open and is never resent automatically. The server sends no subtitle_ready broadcast for provider downloads, so a stored subtitle does not appear in the current player; it is listed the next time the file plays.

Search is natural_idempotent, but each search runs a 20–30 s provider fan-out. It isn't retried automatically, and failures show the error text as before.

Validation

  • iOS, tvOS and macOS builds pass on this branch.
  • Focused tests pass on iOS and tvOS: APIv2SubtitleTests, SubtitleSearchModelTests, AIModelDecodingTests, SubtitleAIControllerTests, PlaybackMediaAuthorizationTests, RequestsV2Tests and PlaybackProtocolV3Tests, 0 failures.
  • scripts/ci/check-no-api-v1.sh passes. SiloAI.swift, AIModels.swift, SubtitleProvidersStore.swift and SubtitleSearchModels.swift all fall below their allowlist ceilings; per the stack rules the allowlist is unchanged.
  • The withOwnerFence|sameCredentialIdentity line count in iosApp/iosApp stays at 69.
  • The final stack passed the full suites (iOS 1981 tests, tvOS 1792 tests, 0 failures), the macOS build and the v1 path guard, and every branch in the stack builds on its own.

New StubURLProtocol tests in APIv2SubtitleTests:

  • method, path, X-Profile-Id header and exact body keys for list, search and download
  • provider-status gating across the allowed, state and enabled combinations, and refusal of the v1 shape
  • the store keeping its value when a probe fails
  • opaque IDs kept in server order, and a row for another file refused
  • every download failure sending exactly one request, with each failure sorted as definite or uncertain
  • an owner change before the call refused with nothing sent, and an owner change during the request reported as unknown outcome

New outcome and URL tests in SubtitleSearchModelTests and AIModelDecodingTests:

  • SubtitleDownloadOutcome.resolve: a problem 4xx or a never-sent transport error is .failed; a timeout, a 202 or an owner change after dispatch is .unconfirmed; a 200 row for another file is .stored; none of these re-list. After a 200, a failed re-list, an owner or file change, a row missing from the listing, or a refused registration is .stored; otherwise the row is registered (.added).
  • only .stored and .unconfirmed hold the result in the menu
  • a listing that omits an earlier row still yields a URL pinned to the right row at the plan's ordinal, and that URL passes the player's header-authenticated subtitle query check
  • a published row keeps its inventory ordinal and new rows follow every published ordinal, so no new row takes the slot of a row the listing left out (AIModelDecodingTests)
  • the plan inventory's downloaded rows map to their ordinals by the URL pin, and burn-in-only tracks still count toward the next ordinal (PlaybackProtocolV3Tests)
  • a row without a positive integer ID or file gets no descriptor

Nobody ran the app against a live server, so how the menu shows each outcome on a device is unconfirmed.

Risks and follow-ups

  • The .stored and .unconfirmed holds last only while the menu is open. After the menu is reopened, the same result can be downloaded again. The server deduplicates stored subtitles by content (StoreSubtitle checks GetDownloadedSubtitleByContent), so a second download returns the existing row, but it still repeats the upstream provider fetch.
  • Server note (not filed): GET /api/v2/subtitles/{media_file_id} skips rows whose language fails CanonicalProviderLanguage, while the stream handler resolves an unpinned downloaded ordinal against the unfiltered ListDownloadedSubtitles. This PR sidesteps the mismatch by pinning downloaded_subtitle_id and taking ordinals from the plan inventory, but any client that builds unpinned ordinals from the v2 listing can get the wrong subtitle. One gap remains on Apple: a row stored after the plan and left out of the listing still shifts the server's later ordinals, so a track registered after it can carry a different ordinal than the next plan publishes. The content stays right because of the pin; the menu can show that track twice after the next replan.
  • HTTPClient still replays a request once after a 401 and a successful token refresh. A 401 means the server rejected the request before running it, so the download is still sent at most once to the handler. Android marks the call singleAttempt(); Apple does not add a per-path exclusion here.
  • SubtitleSearchResult still uses its tolerant decoder even though the contract requires every field. That decoder came from an earlier PR and is unchanged.
  • W5-R, next in this lane, moves the subtitle AI job model to string IDs. It can then drop the String(resultId) bridge in SubtitleAIController.
  • How PlayerViewModel.resolveServerUrl prefixes the /stream/... path belongs to the playback lane and is unchanged here; this PR only adds the row pin to the path's query.

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 43 of 50 in the Apple API v2 stack. Base: apiv2-stack/42-metadata-ai-v2. Merge in order from the bottom of the stack. The plan and full index are in PR 01.

🤖 Generated with Claude Code

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

@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: 5f281328-62bf-40c7-9624-898621af8f3e

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.

@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:08.474305Z 5c0bd73 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: ab1c0489 (apiv2-stack/43-subtitles-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:

  • major: The v2 stored-subtitle listing leaves out rows, so a track's listing position no longer matches the server's combined subtitle index
  • minor: The unconfirmed-download copy and the PR body rely on a subtitle_ready broadcast that the server never sends for provider downloads
  • minor: No tests cover the new download-outcome mapping in the view model or the menu's send-once hold

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: ab1c04895c

ℹ️ 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".

let state: String
let allowed: Bool

var isAvailable: Bool { allowed && state == "available" && enabled }

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 Preserve why provider search is unavailable

When the capability returns allowed: false while providers are enabled and the state is available, this collapses the viewer-specific denial into the same false used for an unconfigured server. SubtitleProvidersStore retains only that Boolean, and PlayerViewModel.subtitleSearchUnavailableReason consequently tells the user “Not set up on this server,” which is incorrect for this valid response. Preserve enough capability state to distinguish viewer access from provider configuration in the disabled-row message.

Useful? React with 👍 / 👎.

@Quick104
Quick104 force-pushed the apiv2-stack/42-metadata-ai-v2 branch from c54f706 to ca67075 Compare September 23, 2026 13:19
@Quick104
Quick104 force-pushed the apiv2-stack/43-subtitles-v2 branch from ab1c048 to 5c0bd73 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: 5c0bd73309

ℹ️ 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".

/// later ordinals; the URL pin keeps the content right in that case.
func ordinal(at position: Int, in listing: [DownloadedSubtitle]) -> Int {
if let ordinal = published[listing[position].id] { return ordinal }
return next + listing[..<position].filter { published[$0.id] == nil }.count

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 Refresh the plan before assigning new subtitle ordinals

When a stored row omitted from the v2 listing is created after the active V3 plan but before a visible download, this calculation assigns the visible row next, while the server's complete inventory assigns the hidden row next and the visible row next + 1. After a replan, the locally registered track ID therefore collides with a different subtitle in the authoritative inventory, so the picker can label or select the wrong track; pinning the stream URL preserves the bytes but not the track identity. Refresh the complete plan or obtain the server-assigned ordinal before registering such post-plan rows.

Useful? React with 👍 / 👎.

@Quick104
Quick104 force-pushed the apiv2-stack/42-metadata-ai-v2 branch from ca67075 to 827f7d3 Compare September 23, 2026 13:44
Base automatically changed from apiv2-stack/42-metadata-ai-v2 to main September 23, 2026 13:45
Quick104 and others added 6 commits September 23, 2026 09:45
The in-player subtitle search still listed stored subtitles, read the
provider status, searched and downloaded through /api/v1. The v1 download
body sent `format` and an integer media_file_id, which the v2 contract
rejects, and the stored-subtitle IDs were decoded as integers although v2
sends opaque strings.

Move all four calls to /api/v2 in a new APIv2Client+Subtitles extension.
Stored-subtitle IDs stay opaque strings in the player, so no ID can fail a
listing; the listing keeps server order because a row's position fixes its
combined track index, and a row for another file fails the listing instead
of shifting later tracks. The provider status gates on allowed, state
available and enabled. The download is non_retryable: it is sent once for
the owner captured before the first await, and the menu now tells a stored
subtitle, a definite failure and an unknown outcome apart and never resends
the last. The unknown-outcome classifier moves out of the requests feature
so both features share it. The v1 methods, envelopes, provider-status model
and v1 decode tests are removed.

Stack-PR: W5-Q
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Merge the two catch clauses that both map an owner change during a
provider download to outcomeUnknownOwnerChanged.

Stack-PR: W5-Q
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The v2 stored-subtitle listing skips rows whose language the server cannot
canonicalize, but the stream handler resolves an unpinned downloaded
ordinal against the full stored list. After a skipped row, the synthesized
URL fetched another subtitle's content, or a 404, under the new track's
label.

The descriptor now appends file_id and downloaded_subtitle_id, matching the
server's DownloadedSubtitleStreamURLV3, so the handler serves the row by ID.
The ordinal stays for display and de-duplication only. A row without a
positive integer ID or file yields no descriptor, which the callers already
treat as "stored, not added now".

Stack-PR: W5-Q
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Two gaps in the provider download flow. The unconfirmed copy said the
subtitle may still appear in the list, but the server sends no
subtitle_ready broadcast for provider downloads, so it never appears in the
current player. And the mapping from each download step to an outcome, plus
the menu's rule for holding a result, had no tests.

The outcome mapping moves into SubtitleDownloadOutcome.resolve, which takes
the download, re-list, owner check and registration as closures; the player
supplies the real ones. The menu's hold rule and copy move onto the outcome
(holdsResult, message). Tests now cover .failed, .unconfirmed and .stored
for each case, and the unconfirmed copy says the subtitle will be available
the next time the video plays.

Stack-PR: W5-Q
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The v2 stored-subtitle listing leaves out rows whose language the server
cannot canonicalize, while the plan's subtitle inventory counts every
stored row. The player filed a new downloaded or AI-generated track under
baseTrackCount + listing position, so after an omitted row the new track
took an existing downloaded track's ordinal: it was filed under that
track's ID instead of getting its own row, and the next plan could not
match it.

DownloadedSubtitleOrdinals now reads each published downloaded row's
ordinal from the downloaded_subtitle_id pin on its inventory URL. A
published row keeps that ordinal; a row stored since the plan gets the
next ordinal past every published track, advanced past earlier
unpublished listing rows. The stream URL still pins the row by ID, so
content does not depend on the ordinal.

Stack-PR: W5-Q
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…assifier

APIv2DispatchFailure carried its own copy of the never-sent URLError list
and status rules. It now delegates to APIv2MutationOutcome, so subtitle
downloads (and the AI subtitle jobs built on it) sort failures the same
way as every other v2 write.

Stack-PR: W5-Q
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@Quick104
Quick104 force-pushed the apiv2-stack/43-subtitles-v2 branch from 5c0bd73 to 90b2781 Compare September 23, 2026 13:45
@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 0860218 into main Sep 23, 2026
3 of 6 checks passed
@Quick104
Quick104 deleted the apiv2-stack/43-subtitles-v2 branch September 23, 2026 13:45
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