Repository navigation
feat(subtitles): search, download and manage subtitles on v2 - #391
Conversation
There was a problem hiding this comment.
Quick104 has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan.
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Advanced Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
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. Comment |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Code review summaryReviewed head: 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:
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 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 ( |
There was a problem hiding this comment.
💡 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 } |
There was a problem hiding this comment.
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 👍 / 👎.
c54f706 to
ca67075
Compare
ab1c048 to
5c0bd73
Compare
There was a problem hiding this comment.
💡 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 |
There was a problem hiding this comment.
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 👍 / 👎.
ca67075 to
827f7d3
Compare
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]>
5c0bd73 to
90b2781
Compare
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
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
SiloAIstill 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/statusPOST /api/v1/subtitles/searchPOST /api/v1/subtitles/downloadThe v2 contract differs from v1 in these ways:
SubtitleDownloadBodysetsadditionalProperties: false, has noformat, and takesmedia_file_idas a string. The v1 body would get a 422.StoredSubtitle.idandmedia_file_idare opaque strings. The player decoded them asInt.allowed,state,revision). The old model defaulted a missingenabledtotrueto cover servers that predate the endpoint.downloadSubtitleisnon_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
APIv2Client+Subtitles.swiftwithsubtitleProviderStatus(),storedSubtitles(mediaFileID:auth:),searchSubtitles(_:), anddownloadSubtitle(_:auth:).downloadSubtitlemoved here fromAPIv2Client.swift. Each call checks one exact status (200), sendsX-Profile-Idwhen a profile is selected (the contract makes it optional), and runs insidewithOwnerFence. Search and download keep the extended timeout. Invalid input is refused before sending: file ID<= 0, or more than 100 languages.DownloadedSubtitle.idis now an opaqueString. 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 integerresult_subtitle_idfrom its job and compares it asString(resultId); W5-R changes that job model.DownloadedSubtitle.synthesizedDescriptornow appends?file_id=<file>&downloaded_subtitle_id=<id>, the same shape as the server'sDownloadedSubtitleStreamURLV3, 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.DownloadedSubtitleOrdinalsnow reads each published downloaded row's ordinal from thedownloaded_subtitle_idpin 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 oldbaseTrackCount + position.allowed && state == "available" && enabled. An unknownstatecounts as unavailable. A failed probe is not an answer:SubtitleProvidersStorekeeps its previous value (initiallytrue), and the next refresh trigger asks again. This is the retryable state that I9 requires; the probe never fails closed.PlayerViewModel.downloadSearchedSubtitlecaptures 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 returnsSubtitleDownloadOutcome, whichSubtitleSearchMenushows. The mapping from each step to an outcome lives inSubtitleDownloadOutcome.resolve, which takes the download, re-list, owner check and registration as closures so tests can drive it without a player. For.storedand.unconfirmed(holdsResult), the menu remembers the result and will not send it again while the menu is open.APIv2DispatchFailure.isUncertainsorts download failures by delegating to the sharedAPIv2MutationOutcome, so subtitle downloads (and the AI subtitle jobs in W5-R) classify failures the same way as every other v2 write.SubtitleDownloadOutcome.isUnconfirmedaddsAPIv2SubtitleRequestError.outcomeUnknownOwnerChangedon top.SiloAIpaths,DownloadedSubtitlesResponse,SubtitleDownloadResponse,SubtitleProvidersStatus, the v1Codabledecoders onDownloadedSubtitleandSubtitleSearchResponse,SubtitleDownloadBody.format, and the tests that decoded v1 shapes.Failure outcomes for
POST /api/v2/subtitles/download(non_retryable).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.".storedwith the same copycannotConnectToHost, DNS, TLS); any non-2xx answer.failed. Shows the problemdetailor the server-update copy when present, otherwise "Couldn't add that subtitle. Try another result." The user may pick the result again.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 nosubtitle_readybroadcast 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
APIv2SubtitleTests,SubtitleSearchModelTests,AIModelDecodingTests,SubtitleAIControllerTests,PlaybackMediaAuthorizationTests,RequestsV2TestsandPlaybackProtocolV3Tests, 0 failures.scripts/ci/check-no-api-v1.shpasses.SiloAI.swift,AIModels.swift,SubtitleProvidersStore.swiftandSubtitleSearchModels.swiftall fall below their allowlist ceilings; per the stack rules the allowlist is unchanged.withOwnerFence|sameCredentialIdentityline count iniosApp/iosAppstays at 69.New
StubURLProtocoltests inAPIv2SubtitleTests:X-Profile-Idheader and exact body keys for list, search and downloadNew outcome and URL tests in
SubtitleSearchModelTestsandAIModelDecodingTests: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)..storedand.unconfirmedhold the result in the menuAIModelDecodingTests)PlaybackProtocolV3Tests)Nobody ran the app against a live server, so how the menu shows each outcome on a device is unconfirmed.
Risks and follow-ups
.storedand.unconfirmedholds 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 (StoreSubtitlechecksGetDownloadedSubtitleByContent), so a second download returns the existing row, but it still repeats the upstream provider fetch.GET /api/v2/subtitles/{media_file_id}skips rows whose language failsCanonicalProviderLanguage, while the stream handler resolves an unpinned downloaded ordinal against the unfilteredListDownloadedSubtitles. This PR sidesteps the mismatch by pinningdownloaded_subtitle_idand 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.HTTPClientstill 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 callsingleAttempt(); Apple does not add a per-path exclusion here.SubtitleSearchResultstill uses its tolerant decoder even though the contract requires every field. That decoder came from an earlier PR and is unchanged.String(resultId)bridge inSubtitleAIController.PlayerViewModel.resolveServerUrlprefixes 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