Skip to content

feat(subtitles): run AI subtitle jobs on v2 - #392

Merged
Quick104 merged 3 commits into
mainfrom
apiv2-stack/44-subtitle-ai-jobs-v2
Sep 23, 2026
Merged

Quick104 merged 3 commits into
mainfrom
apiv2-stack/44-subtitle-ai-jobs-v2

Conversation

@Quick104

Copy link
Copy Markdown
Contributor

The in-player AI subtitle suite (translate, transcribe, transcribe and translate) now runs entirely on /api/v2. Job creation is sent once, and a request with an unknown outcome is held until the user discards it instead of being resent.

Problem

SiloAI still sent five subtitle AI calls to /api/v1 (inventory rows 105-109):

  • GET /api/v1/subtitles/ai/status (capability, read by AICapabilities)
  • GET /api/v1/subtitles/ai/quota (ASR quota gauge)
  • POST /api/v1/subtitles/ai/translate (job creation, from SubtitleAIController)
  • GET /api/v1/subtitles/ai/jobs/{id} (polling)
  • POST /api/v1/subtitles/ai/jobs/{id}/cancel

The v2 contract differs from v1 in these ways:

  • The status is a capability document (allowed, state, revision). The v1 model read only enabled and transcribe_enabled, and defaulted both to false when missing.
  • SubtitleAICreateBody sets additionalProperties: false, takes media_file_id as a string, and requires source_language, target_language and start_position.
  • Job id, media_file_id and result_subtitle_id are strings. The player's SubtitleJob decoded result_subtitle_id as Int, so a non-numeric result ID would fail every poll.
  • createSubtitleAIJob is non_retryable: the server deduplicates active jobs but keeps no replay receipt. The controller showed every failed POST the same way, and the user could tap the language again after a lost receipt and start a second job.

Inventory row 107 lists POST /api/v2/subtitles/ai/jobs as the target. That operation does not exist; this PR uses POST /api/v2/subtitles/ai/translate (createSubtitleAIJob), as the plan corrects.

Solution

  • New APIv2Client+SubtitleAI.swift with subtitleAIStatus(), subtitleAIQuota(), createSubtitle(_:auth:), subtitleJob(id:auth:) and cancelSubtitleJob(id:auth:). Create and cancel moved here from APIv2Client.swift. Each call checks one exact status (200, 202 or 204), sends X-Profile-Id when a profile is selected (optional in the contract), and runs inside withOwnerFence. The subtitle transport in APIv2Client+Subtitles.swift is now shared by both files. Job IDs are percent-encoded as one path segment. Create failures are sorted by the shared APIv2DispatchFailure/APIv2MutationOutcome classifier, with SubtitleCreationError.outcomeUnknown added for an owner change after dispatch.
  • New APIv2SubtitleAIModels.swift holds the wire models. The AI job models moved here from APIv2SubtitleModels.swift. APIv2SubtitleAIStatus and APIv2SubtitleAIQuota decode strictly; the contract requires every field.
  • Capability gating (I9). Translate is offered only when allowed && state == "available" && enabled, and transcription only when allowed && state == "available" && transcribe_enabled. An unknown state counts as unavailable. The existing rule that transcription also needs translation enabled (AICapabilities.transcribeEnabled) is unchanged. A failed status probe no longer clears a known value: AICapabilities keeps the last subtitle status, and the existing foreground and session refreshes ask again.
  • IDs stay opaque. SubtitleJob.resultSubtitleId is now String?. The handoff matches it to the stored-subtitle listing by string, which removes the String(resultId) bridge W5-Q left. Only media_file_id still needs an exact positive integer, because the player addresses files by Int. The websocket completed and subtitle_ready events still carry integer IDs; the controller converts them with String(_:).
  • Owner-bound jobs. The controller captures the owner before sending (SiloAI.captureAuthority()), then polls and cancels for that owner. A poll or cancel for a replaced owner is refused before sending.
  • Send once, hold on unknown outcome. SiloAI.translateSubtitle(_:auth:) records each request by owner (account and profile), file, kind, source index and both languages. The playhead and live session are left out, so a moved playhead cannot turn a lost receipt into a new request. This matches Android's SubtitleAiCreateV2Api.Intent. An identical request whose outcome is unknown is refused with SubtitleCreationError.unresolved and nothing is sent. In the translate menu, the failure panel adds a "Discard held request" button next to "Dismiss" on iOS and tvOS. On tvOS it is a second native focus target; "Dismiss" keeps the initial focus. The hold is process-local, like Android's; it is not an offline queue.
  • Poller give-up. When AIJobPoller stopped after five failed reads in a row, the menu used to stay on "Translating…" indefinitely. For a poll-only job, it now fails with "Silo lost track of this subtitle job. If it finishes, the subtitles will appear in the subtitle list." If the websocket is streaming the job's cues, the controller keeps the live track and lets the websocket settle the job. A completed frame hands off, selects the stored track, and moves the menu to completed. A failed frame fails the job. If the socket drops, the live track hits its 30-second safety timeout, or a completed frame arrives without a subtitle ID, the job fails with the lost-track message. LiveSubtitleCoordinator gains hasLiveTrack and an onSafetyTimeout hook for this.
  • Error copy. A problem response shows its detail (for example the quota message on 429). A 503 without a problem document keeps "AI subtitles aren't available right now. Try again later." An unknown outcome shows "Silo couldn't confirm that the subtitle job started. If it did, the subtitles will appear in the subtitle list when it finishes." A held repeat shows "An earlier request for these subtitles may still be running, so Silo didn't send it again."
  • Deleted: the five v1 SiloAI paths and SiloAI's HTTPClient dependency. Also deleted: the tolerant v1 decoders on SubtitleJob, SubtitleAIStatus and SubtitleAIQuota (now plain domain values built from the v2 models), SubtitleJobEnvelope, TranslateSubtitleBody's Encodable conformance, and the AIModelDecodingTests cases that decoded v1 shapes. Stale /api/v1 comments in AIModels.swift, AICapabilities.swift and SubtitleAIController.swift are updated.

Failure outcomes for POST /api/v2/subtitles/ai/translate (non_retryable)

Outcome Cases Behavior
Definite success 202 whose receipt names the requested file, kind and source index The hold is released. The job is polled for the owner that started it, and the result is handed off as before.
Definite failure Refused before sending (owner already replaced, update-required gate, invalid input); transport errors before any bytes leave (cannotConnectToHost, DNS, TLS); any non-2xx answer (for example 400, 404 for an unknown session, 422, 429 quota, 500, 503) The hold is released. The menu shows the error once (problem detail, server-update copy, or the generic line). The user may tap the language again.
Uncertain Connection lost or timed out after sending, cancellation, a 2xx other than 202, an unreadable 202 body, a receipt for a different file/kind/source, or an owner change once dispatch may have begun (SubtitleCreationError.outcomeUnknown) The request is held and never resent. The menu shows the unconfirmed copy with "Discard held request". Until the user discards it, an identical request fails with unresolved and sends nothing.

Cancel (natural_idempotent) stays best effort, as before: the controller sends it once for the job's owner and ignores its result, because polling decides the final state. The job and quota reads are not retried beyond the poller's existing five-failure budget.

Validation

  • iOS, tvOS and macOS builds pass on this branch.
  • Focused tests pass on iOS and tvOS: APIv2SubtitleTests, AIModelDecodingTests, AIJobPollerTests, SubtitleAIControllerTests, SubtitleSearchModelTests and LiveSubtitleCoordinatorTests, 73 tests each, 0 failures.
  • scripts/ci/check-no-api-v1.sh passes. SiloAI.swift and AIModels.swift no longer contain /api/v1; per the stack rules the allowlist is unchanged.
  • The withOwnerFence|sameCredentialIdentity line count in iosApp/iosApp stays at 69.
  • Mutation checks: releasing the hold on every failure made testCreateHoldsOnlyAnUnknownOutcome, testCreateForAReplacedOwnerIsRefusedOrHeld and testControllerHoldsAnUnknownOutcomeUntilDiscarded fail. Removing the poller give-up handling made testControllerReportsAJobThePollerLostTrackOf fail. Failing the job on every give-up, even with a live track attached, made testWebsocketCompletesAJobThePollerLostTrackOf and testSocketLossFailsAJobThePollerLostTrackOf fail.
  • 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:

  • status: path and profile header, the gating matrix over allowed, state, enabled and transcribe_enabled, and refusal of the v1 shape
  • quota: path and profile header, and refusal of a quota without its counters
  • AICapabilities keeps a known subtitle status when the probe fails
  • create: method, path, profile header and exact body keys; empty languages and session_id for a live transcription
  • create outcomes: every definite failure is released and can be sent again; every uncertain outcome sends exactly one request, refuses the repeat (including one with a moved playhead and new session), still allows a different target language, and sends again after a discard
  • an owner replaced before the call is refused with nothing sent and nothing held; an owner replaced in flight returns outcomeUnknown and holds
  • poll and cancel paths, a snapshot for another job refused, and both refused for a replaced owner with nothing sent
  • controller: an unknown outcome shows the held failure, a repeat tap sends nothing, and discard returns the menu to idle; a poller give-up on a poll-only job ends in .failed after exactly five reads and ends the preparing presentation
  • controller with a live coordinator: after the poller gives up on a streaming job, the live track stays up; a websocket completed frame then registers and selects the stored track and ends in .completed, and a socket drop instead fails the job and closes the live track
  • opaque result IDs (leading zeros, oversized, non-numeric) are kept, an empty one is refused, and an unknown job status decodes as pending

Nobody ran the app against a live server or on a simulator, so the menu's held state and the discard button have not been seen on a device.

Risks and follow-ups

  • Plan §9 treats any non-2xx answer as a definite failure, so a 500 or 503 from the create handler releases the hold. Android is stricter: it holds on 408 and 5xx. The server deduplicates active jobs, so a resend after a 5xx that did create a job normally returns that job instead of starting a second one.
  • A request cancelled while its POST is in flight (the menu's Cancel during "Preparing", or a player reset) counts as uncertain. SiloAI keeps that hold, so the same language fails with the held message until the user discards it.
  • The hold is process-local and keyed by the credential generation, so it ends at app exit or sign-out. A relaunch can resend a request whose earlier outcome was unknown; the server's active-job deduplication is the remaining protection.
  • live_delivery_attached: false (for example a deduplicated job) is not handled beyond the existing receipt check. The controller stays in the poll-only flow it already uses when realtime is unavailable, so the player waits for the poller to finish.
  • The session_id sent with a live transcription comes from the v2 playback session that W2-B (PR 29) introduced. Nobody checked against a live server that BindTranslation accepts it.
  • The websocket subtitle events still carry integer IDs; the playback lane owns that model.
  • After the poller gives up on a job that is already streaming, only the websocket can settle it. If the socket stays connected but never sends completed or failed, the menu stays on "Translating…" while the live cues play. The coordinator's safety timer covers only the wait for the first cue.

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 44 of 50 in the Apple API v2 stack. Base: apiv2-stack/43-subtitles-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: 73bcdd4d-c91c-4ee9-b0dc-f828712c0aa1

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:25:01.619081Z 5b65565 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: 27dac38a (apiv2-stack/44-subtitle-ai-jobs-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: Poller give-up now tears down a live websocket subtitle stream that is still working
  • minor: PR body is missing the required AI disclosure section

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: 5b65565fdb

ℹ️ 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 +54 to +58
} catch HTTPError.authorityChanged, HTTPError.requestIdentityChanged {
// `requestIdentityChanged` is raised both just before the bytes
// leave and after the response arrives, so it cannot prove the
// job was never started.
throw SubtitleCreationError.outcomeUnknown

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 Distinguish owner changes that occur before dispatch

Use a dispatch record or the existing APIv2OwnerChangedBeforeDispatch mechanism before converting every ownership error to .outcomeUnknown. If the profile or credential changes after the initial check on line 40 but before withOwnerFence or requestData dispatches any bytes, those preflight checks throw authorityChanged/requestIdentityChanged; this catch then incorrectly holds the request as possibly started, blocking a safe retry until the user manually discards it.

Useful? React with 👍 / 👎.

@Quick104
Quick104 force-pushed the apiv2-stack/43-subtitles-v2 branch from 5c0bd73 to 90b2781 Compare September 23, 2026 13:45
Base automatically changed from apiv2-stack/43-subtitles-v2 to main September 23, 2026 13:45
Quick104 and others added 3 commits September 23, 2026 09:45
The player's AI subtitle suite still called five /api/v1 routes for the
capability, the ASR quota, job creation, polling and cancel. Creation is
non_retryable on v2, and the controller showed every failed POST the
same way, so a lost receipt could be resent and start a second job.

SiloAI now reads the capability and quota from /api/v2/subtitles/ai/status
and /quota, starts jobs with POST /api/v2/subtitles/ai/translate, and polls
and cancels through /api/v2/subtitles/ai/jobs/{job_id}. The capability is
on only when the viewer is allowed and the state is available; a failed
probe keeps the last value. Jobs are polled and cancelled for the owner
that started them, and job and result IDs stay opaque strings.

A create whose outcome is unknown (connection lost after sending, an owner
change once dispatch could have begun, or an unusable 2xx receipt) is held
per owner, file and job. An identical request is refused without being sent
until the user picks "Discard held request" in the menu. A server answer or
a request that never left releases it. When the poller gives up, the menu
now says the job may still finish instead of showing progress forever.

The v1 methods, the tolerant v1 decoders for SubtitleJob, SubtitleAIStatus
and SubtitleAIQuota, SubtitleJobEnvelope and their decoding tests are gone.

Stack-PR: W5-R
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Stack-PR: W5-R
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
When five job reads failed in a row, the controller failed the job even
while the websocket was still streaming its cues. That closed the live
track, restored the old selection, and dropped the websocket completed
frame, so the finished track was never selected.

Now a poller give-up fails the job only when no live track is attached.
With one attached, the controller keeps the live track and lets the
websocket settle the job: a completed frame hands off, selects the stored
track and moves the menu to completed; a failed frame fails it. If the
socket drops, the live track times out, or a completed frame carries no
subtitle ID after the give-up, the job fails with the lost-track message.

Stack-PR: W5-R
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@Quick104
Quick104 force-pushed the apiv2-stack/44-subtitle-ai-jobs-v2 branch from 5b65565 to 6e408ef 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 2b2a319 into main Sep 23, 2026
3 checks passed
@Quick104
Quick104 deleted the apiv2-stack/44-subtitle-ai-jobs-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