Repository navigation
Add AI subtitle translation and metadata language support - #30
Conversation
Add the AI plumbing for silo-server's metadata + subtitle translation features (Milestone 1, Task 1): - AIModels.swift: all AI wire shapes (MetadataAIStatus, SubtitleAIStatus, SubtitleAIQuota, SubtitleJob + envelopes, the translate bodies, DownloadedSubtitlesResponse reusing SubtitleUrl) plus the shared AIJobStatus enum. Tolerant decoders: unknown on_view -> .off, unknown job status -> .pending. Properties stay camelCase (HTTPClient auto-converts snake_case); only SubtitleAIKind.transcribeTranslate carries an explicit raw value. - ContinuumAI.swift: actor facade over HTTPClient.shared mirroring ContinuumAPI's typed-method style, for the native /api/v1 AI endpoints. - AICapabilities.swift: @mainactor @observable singleton caching the two status probes (+ on-demand quota), with failure-tolerant refresh(), reset(), and the gating booleans the UI consumes. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Add the preferred-metadata-language profile setting (Milestone 1, Task 2): - Wire the field: preferredMetadataLanguage on Profile / UpdateProfileBody / UserProfile (+ asUserProfile), encoding as preferred_metadata_language. - ResponseCache.invalidateAllItemMetadata(): flush the item: family + home-sections + recommendations so a language change picks up the server-translated overviews/taglines on the next fetch. - Settings VMs (iOS + tvOS): editorPreferredMetadataLanguage projected from the active profile; a dedicated saveMetadataLanguage() that PUTs the patch, updates the local profile, and on an actual change flushes ResponseCache (+ tvOS ItemDetailCache). The existing subtitle-prefs save path now preserves the metadata language in its local-profile rebuild. - Settings UI: a "Metadata Language" picker row (iOS SubtitleSettingsView; tvOS TVSubtitleSettingsView via TVSettingsPickerSheet) gated on AICapabilities.shared.metadataEnabled, reusing PlaybackLanguageOption.all + a "Library Default" inherit row. - AuthService: AICapabilities.reset() next to the existing cache clears on sign-out + profile-switch, and refresh() after a successful profile select. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Add the on-view "translate this description" affordance (Milestone 1, Task 3): - ItemDetail.pendingTranslationLanguage: set by the server when a description exists but isn't yet in the resolved metadata language. Carried through BOTH field-by-field ItemDetail rebuilds (the iOS ItemDetailViewModel.enrichPlaybackMetadata and the tvOS TVItemDetailView copy) so enrichment never drops it. - DescriptionTranslationCoordinator: @mainactor @observable POST + re-poll driver. POSTs translate-description, then re-fetches itemDetail on a bounded backoff (1,2,3,5,5,5,5,5s) until pendingTranslationLanguage clears, writing each refreshed detail back into the VM + ResponseCache. Single in-flight task; cancel on disappear. - DescriptionTranslationView: small affordance under the synopsis, honoring AICapabilities.metadataOnView (off -> nothing; button -> "Translate"; auto -> fires once). Target language is the item's own pendingTranslationLanguage. - Wired into iOS (PhoneDetailHero belowOverview slot) and tvOS (TVDetailHero belowSynopsis slot) via Movie/Series/Season detail content; the owning ItemDetailViewModel is threaded down so a translated payload re-renders in place. Co-Authored-By: Claude Opus 4.8 <[email protected]>
…on, hero slot cleanup) FIX 1a: AICapabilities gains a generation counter; reset() bumps it and refresh()/refreshQuota() capture+recheck it so a slow probe can't repopulate the next account's capabilities after a sign-out/profile switch. FIX 1b: ContentView refreshes AICapabilities on the authenticated branch and the foreground-retry path (mirroring overlayPrefs), so metadata features appear on a cold relaunch into a restored session. FIX 2: DescriptionTranslationCoordinator bails if the task is cancelled immediately after the itemDetail re-poll await, before apply()/cache write, so a cancelled poll can't clobber the view model/cache with stale data. FIX 3: DescriptionTranslationView adds a per-item autoFiredFor latch so .auto mode fires once per item instead of re-firing on every row re-appear. FIX 4 + 5: Hero slot (belowOverview/belowSynopsis) becomes a generic @ViewBuilder instead of () -> AnyView; the six content structs drop the redundant `let viewModel` property; DescriptionTranslationView is built at the ItemDetailView/TVItemDetailView call sites and .id(detail.contentId)'d so the coordinator resets per item. FIX 6: Coordinator's apply closure typed @mainactor @escaping. FIX 7: AICapabilities header comment repointed from OverlayPrefsStore (ObservableObject) to the PlayerSettings.shared @mainactor @observable precedent. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Milestone 2 of the AI translation plan: prove mid-playback in-memory AI
subtitle cue injection into the libass renderer as a synthetic live track,
driven by a local DEBUG stub (no networking).
- LiveSubtitleTrack: pure value type converting a streamed cue
(start,end,text in absolute media seconds) into the exact FFmpeg rect.ass
*chunk* event body the proven embedded path feeds to ass_process_chunk:
"ReadOrder,Layer,Style,Name,MarginL,MarginR,MarginV,Effect,Text" (Start/End
ride as the startMs/durationMs args, not inline). Same escaping as
VTTToASSConverter (drop {,},\; \n->\N; trim), seconds->ms, dedupe by
(startMs,endMs,escapedText).
- SubtitleTrackIdSpace: third partition aiLiveBase=0x6000_0000 with
makeAILiveTrackId/isAILive/aiLiveOrdinal; isSidecar upper-bounded so the
ranges stay disjoint.
- SubtitleSession: openLive/feedLiveCue/closeLive over the synthetic styled
header; liveSlots set so flushOnSeek skips live tracks (re-feed impossible)
and teardown clears them.
- Both backends route isAILive selection as a no-op before the sidecar
branch (PlayerCore on controlQueue, AVPlayerBackend inline) + live
pass-throughs onto their own SubtitleSession.
- PlayerViewModel: route-agnostic open/feed/close adapters, live-row append,
applyTrackList preserves live rows; DEBUG-only debugStartFakeLiveSubtitles
feeds canned cues at currentTime+ on a timer.
- Tests: LiveSubtitleTrackTests covers chunk format, \n->\N, CRLF, brace/
backslash stripping, dedupe, overlap/out-of-order, seconds->ms (22 cases).
Co-Authored-By: Claude Opus 4.8 <[email protected]>
…pshot, debug timer) Co-Authored-By: Claude Opus 4.8 <[email protected]>
Milestone 3: deliver the in-player AI subtitle suite (translate an existing text track / transcribe audio / transcribe+translate) over polling, matching the Android client. No websocket / live cues yet (that is M4). - AIJobPoller (actor): poll(jobId:fetch:) -> AsyncStream<SubtitleJob> on a ~1.5s cadence, stops on terminal status, cancellable; injected `fetch` closure for headless testing. - SubtitleAIController (@observable @mainactor, owned by PlayerViewModel): POST via ContinuumAI.translateSubtitle -> store activeJob -> drain the poller -> on `completed`, fetch downloadedSubtitles(mediaFileId:), match result_subtitle_id, hand off; quota refresh after ASR jobs. POST omits session_id (poll-only path). - Completion handoff reuses the existing sidecar path: VM resolves the downloaded SubtitleUrl against the server base, seeds pendingSidecarSubtitleTrackId, and registers a SidecarSubtitleDescriptor on the active backend -> appendSidecarTracks appends the PlayerTrack and auto-selects it. - SubtitleTranslateMenu presented from TrackSelectionSheet (iOS sectioned list + tvOS floating panel, gated on AICapabilities): per-source actions (text -> Translate, bitmap PGS/DVD/DVB -> Transcribe, audio -> Transcribe / Transcribe & Translate), target-language picker, quota gauge, in-progress + cancel. - source_index: translate uses track.srcId; transcribe uses the audio index (-1 = default); embedded-text translate deferred; bitmap subs offer transcribe instead of translate. - Tests: AIJobPollerTests (terminal stop per status, progress passthrough, cancellation), AIModelDecodingTests (SubtitleJob/envelopes/quota/status incl. transcribe_translate, omitted optionals, tolerant status). Co-Authored-By: Claude Opus 4.8 <[email protected]>
…OS focus, controller reset
FIX 1 (CRITICAL): the completion handoff bound the wrong server shape. GET
/api/v1/subtitles/{media_file_id} returns the server's DownloadedSubtitle
({id, media_file_id, provider, language, format, release_name, score?,
hearing_impaired?, created_at?}) — NO `index`, NO `url`. Apple decoded it as
[SubtitleUrl] (requires non-optional index+url), so the decode threw, `try?`
swallowed it, and no completed AI track ever appeared. Added a dedicated
DownloadedSubtitle Codable wire model + DownloadedSubtitle.synthesizedDescriptor
helper that builds the SidecarSubtitleDescriptor the way Android's
SubtitleTrackMerge does: combined index = baseTrackCount + position (base =
max non-downloaded combined index + 1, honoring burn-in gaps), stream URL on
the session-scoped /stream/{session}/subtitles/{combined-index}<ext> mount
(verified the server {track} route keys on the COMBINED INDEX, not the DB id),
ext srt/subrip->.vtt, ass/ssa->.ass, pgs->.sup. Match by entry.id ==
resultSubtitleId. Rewrote testDownloadedSubtitlesResponse to the real shape and
added focused synthesis tests.
FIX 2 (HIGH): tvOS focus bleed — the TrackSelectionSheet base panel was not
focus-excluded while SubtitleTranslateMenu was up, so the d-pad escaped behind
it. Added .disabled(showAITranslateMenu) + .opacity(0.28) to the base panel,
mirroring the TVPlayerInfoHUD appearance-dialog precedent. iOS .sheet untouched.
FIX 3 (MEDIUM): added a generation guard to SubtitleAIController (mirroring
AICapabilities) — bumped in reset(), captured before awaits in
submit/drainPoll/handoff/quota-refresh, results discarded on mismatch — so a
stale completion from a previous account/session can't register after a reset.
FIX 4 (MEDIUM): removed the MainActor.assumeIsolated fragility. cleanup() is
now @mainactor and calls subtitleAI.reset() directly; the controller is built
via a lazy @mainactor property with a nonisolated init (closures typed
@mainactor) instead of assumeIsolated. Both targets build green.
FIX 5 (LOW, batch): drainPoll uses the injected api; removed dead
cancelSubtitleAIJob() passthrough; promoted ApplePlaybackRoutePlanner
.siloBitmapSubtitleCodecs to static and referenced it from the menu (kept the
tolerant substring fallback); dropped the redundant MainActor.run / useless
`guard self != nil` in the handoff; gated the AI entry row so it only opens
when there's an actionable source; surfaced a soft failure when the handoff
can't register a track instead of silently dropping it.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
…iming
Apply audited fix list to the AI-subtitle feature after Milestone 4.
- FIX 1 (critical): SubtitleJob.id decoded String but server sends int64
bare → every real 202/poll threw and disabled the pipeline. Tolerant
decode (number or string → String); fixtures re-pointed to integer wire
shape + regression for {"job":{"id":42}} and the ai-42 track-key join.
- FIX 2: poller-wins completion now calls persistedHandoffAlreadyDone so a
dropped socket no longer strands the coordinator in .streaming with an
orphaned synthetic track.
- FIX 3: PlaybackRealtimeClient.unbind() clears unavailabilityListeners;
PlayerViewModel also stores + removes the observer token in cleanup().
- FIX 4: realtimeUnavailableSnapshot defaults to false (optimistic) so a
fast first submit still requests live cues on a healthy socket.
- FIX 5: cue media-time → renderer-tick conversion is now backend-aware
(CoreMedia ticks offset-relative movie time → subtract offset; AVPlayer
ticks absolute media time → no shift), fixing cues rendering early on an
AVPlayer transcode.
- FIX 6: drop dead seek(to:)/currentTime() from LivePlaybackControls + the
production adapter + test fake (coordinator is pause/resume only).
- FIX 7: DRY the 5× liveDriverDidGiveUp+fail couplet into failHandoff(_:).
- FIX 8: supersede teardown uses resume:false to avoid resume-then-repause
flicker; the new job's wasPlaying snapshot decides the final state.
- FIX 9: decode `done` as Int (server progress counter, not Bool); fix the
heartbeat comment/tests (resume gates on !cues.isEmpty).
- FIX 10: new SubtitleAIControllerTests covers the poller-vs-websocket
handoff race (3 orderings): registers exactly once + coordinator reaches
.completed in all paths.
Both targets build; full SiloTests suite green (161 tests).
Co-Authored-By: Claude Opus 4.8 <[email protected]>
…on cleanup Co-Authored-By: Claude Opus 4.8 <[email protected]>
FIX 1 (MEDIUM): record the owned handoff's subtitle id when the persisted track registers (SubtitleAIController.ownedHandoffSubtitleId) and short-circuit handleSubtitleReady on it, so the back-to-back subtitle_ready broadcast for a job the websocket-completed path just registered (which never writes activeJob.resultSubtitleId) is recognized as a self-handoff and skipped — no redundant downloaded-subtitles fetch + register. Cleared on submit/cancel/reset. New SubtitleAIControllerTests dedup cases. FIX 2 (LOW): armDeferredLiveSubtitleClose now closes the previously-pending live track before overwriting the single pending-id slot on a back-to-back completion, so trackA's synthetic row is never orphaned by trackB. FIX 3 (LOW): reset AICapabilities on the server-switch path (ServerRegistry.switchTo) so switching between already-added servers drops the prior server's AI capability/quota probes immediately. FIX 4 (LOW): remove dead code — ContinuumAI.subtitleJobs(mediaFileId:) + SubtitleJobsEnvelope (and its two decoding tests) and SubtitleTrackIdSpace.aiLiveOrdinal(from:). All verified zero call sites. FIX 5 (LOW): hoist the duplicated quota-exhausted footer literal in SubtitleTranslateMenu to a single private static let referenced by both the iOS and tvOS branches. FIX 6 (LOW, cosmetic): drop leftover "FIX N:" dev-comment prefixes (keep prose) and fix the stale __inherit__ reference in TVSettingsViewModel. FIX 7 (MEDIUM, doc-only): document the baseTrackCount non-PGS-bitmap undercount edge at makeSubtitleHandoffContext (server omits non-PGS burn-in tracks from subtitle_urls but still counts them in the downloaded combined index) — graceful soft-fail, robust fix is cross-repo. No logic change. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The Translate-with-AI entry was only added to TrackSelectionSheet, which only the iOS player (MobilePlayerControls) presents. The tvOS player uses TVPlayerInfoHUD, so the affordance never appeared on tvOS. Add it to the HUD's Subtitles tab (SubtitlesPane), reusing the shared SubtitleTranslateMenu as a modal overlay (same idiom as the Appearance dialog). Co-Authored-By: Claude Opus 4.8 <[email protected]>
When a file has many subtitle tracks, the AI entry got buried at the bottom of the (scrolling) Tracks column. Move it to the top of the short, always-visible Options column, wired into that column's d-pad focus order (right-from-track now lands on it). Co-Authored-By: Claude Opus 4.8 <[email protected]>
…racks and add unit tests
- Introduced diagnostics for live AI subtitle rendering in PlayerCore to monitor rendering performance. - Updated PlayerViewModel to manage the state of the live AI subtitle overlay and added functionality to dismiss the "Preparing subtitles" notice. - Refined SubtitleTranslateMenu to streamline the user experience when selecting AI subtitles, including improved language selection and job submission handling. - Enhanced TrackSelectionSheet to integrate the new AI subtitle menu, ensuring a seamless transition when starting subtitle jobs. - Modified LiveSubtitleCoordinator to retract the "Preparing subtitles" notice upon playback resumption. - Improved SubtitleRenderer to accurately report whether cues are being rendered. - Updated TVPlayerInfoHUD and SubtitlesPane to reflect changes in AI subtitle handling and ensure proper HUD dismissal during subtitle job acceptance.
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughAdds AI subtitle networking, live rendering, description translation, subtitle ordering, metadata language settings, player integration, and XCTest coverage. ChangesAI subtitle and translation flow
Estimated code review effort🎯 5 (Critical) | ⏱️ ~150 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 16
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
iosApp/iosApp/Networking/ServerRegistry.swift (1)
186-203: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winMove the AI reset after the server/token retarget.
Line 192 bumps the capability generation before Lines 195-203 switch the URL/profile/token context. A foreground
AICapabilities.refresh()that starts in that gap can capture the new generation, fetch with the old context, then commit stale capabilities for the newly active server.Proposed fix
- await MainActor.run { AICapabilities.shared.reset() } - let entry = entries.first(where: { $0.id == serverId })! defaults.set(entry.url, forKey: "serverUrl") if let pid = entry.profileId { defaults.set(pid, forKey: "profileId") } else { @@ activeServerId = serverId touchLastUsed(serverId) await TokenStore.shared.switchActiveServer(serverId: serverId) + await MainActor.run { AICapabilities.shared.reset() }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@iosApp/iosApp/Networking/ServerRegistry.swift` around lines 186 - 203, Move the AICapabilities reset so it happens after the server context has been fully retargeted. In ServerRegistry’s server-activation flow, update the URL/profile, activeServerId, touchLastUsed, and TokenStore.shared.switchActiveServer first, then call AICapabilities.shared.reset() so refreshes cannot observe a new generation while still using the old server/token context.iosApp/iosApp/Screens/Player/Subtitles/SubtitleSession.swift (1)
160-204: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winClear live-slot state when replacing a live track.
flushOnSeek()now skipsliveSlots, butopenEmbedded/openSidecarreplace the same slot without removing it fromliveSlots. After switching from AI-live to a normal subtitle, seeks can stop flushing that normal track, and late live cues can still feed into the replacement slot.Proposed fix
func openEmbedded( slot: SubtitleSlot, isNativeASS: Bool, extradata: UnsafePointer<UInt8>?, extradataSize: Int ) { cancelFetchTask(for: slot) + withLock { _ = liveSlots.remove(slot) } if isNativeASS { renderer.createTrack( slot: slot, isNativeASS: true, @@ func openSidecar(urlIndex: Int, slot: SubtitleSlot) { guard let descriptor = withLock({ sidecarDescriptors[urlIndex] }) else { Self.logger.warning("openSidecar: no descriptor for index \(urlIndex)") publishStatus(slot: slot, .error("Subtitle track not found")) return } cancelFetchTask(for: slot) + withLock { _ = liveSlots.remove(slot) } publishStatus(slot: slot, .fetching) @@ func feedLiveCue( slot: SubtitleSlot, eventText: String, startMs: Int64, durationMs: Int64 ) { + guard withLock({ liveSlots.contains(slot) }) else { return } renderer.feedChunk( slot: slot, eventText: eventText,Also applies to: 283-294, 369-380
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@iosApp/iosApp/Screens/Player/Subtitles/SubtitleSession.swift` around lines 160 - 204, `openEmbedded(slot:isNativeASS:extradata:extradataSize:)` and `openSidecar(urlIndex:slot:)` replace an existing live subtitle slot but do not clear that slot from `liveSlots`, so `flushOnSeek()` can keep skipping the new track and late live cues may still target it. Update the slot-replacement path in these methods (and any related live-track open helpers noted in the diff) to remove the slot from `liveSlots` before creating the new track, and ensure the state stays consistent whenever a live subtitle is swapped out for a normal subtitle.
🧹 Nitpick comments (2)
iosApp/Tests/SubtitleAIControllerTests.swift (1)
177-181: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win
drainMainQueue()is still a scheduler guess.Eight
Task.yield()calls don't guarantee the detached handoff task has finished, so these race-ordering tests can still flake on a busy runner. Please wait on an explicit signal from the fake register closures / sink instead.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@iosApp/Tests/SubtitleAIControllerTests.swift` around lines 177 - 181, The current `drainMainQueue()` helper in `SubtitleAIControllerTests` is only guessing at scheduler progress with repeated `Task.yield()`, so the tests can still race. Replace that polling approach with an explicit synchronization point tied to the fake register closures or sink used by the test, and have the test await that signal before making assertions. Update the affected test flow around `drainMainQueue()` and the corresponding mock/register callback path so completion is deterministic.iosApp/iosApp/Screens/Player/Subtitles/SubtitleTrackIdentity.swift (1)
55-60: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winEnforce the AI-live ordinal range before OR-ing it into the partition.
Line 58 documents that the ordinal must fit in the low bits, but invalid or negative ordinals would silently collide with other IDs or fall outside
isAILive(_:).Proposed guard
static func makeAILiveTrackId(_ ordinal: Int) -> Int64 { + precondition( + ordinal >= 0 && Int64(ordinal) < (Self.aiLiveBase - Self.sidecarBase), + "AI-live subtitle ordinal is outside the synthetic partition" + ) Self.aiLiveBase | Int64(ordinal) }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@iosApp/iosApp/Screens/Player/Subtitles/SubtitleTrackIdentity.swift` around lines 55 - 60, The AI-live subtitle track ID builder currently ORs any ordinal into the partition without validation, which can produce collisions or IDs that fail isAILive(_:) checks. Update SubtitleTrackIdentity.makeAILiveTrackId(_:) to enforce that the ordinal is non-negative and fits within the low bits reserved below aiLiveBase before combining it, and handle invalid input by rejecting it explicitly rather than returning a malformed ID.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@iosApp/iosApp/Networking/ProfilePrefsStore.swift`:
- Around line 40-64: The hydration flow in ProfilePrefsStore currently returns
immediately from hydrateIfNeeded() when isLoading is true, which lets later
callers miss the in-flight refresh and snapshot nil before
preferredSubtitleLanguage is set. Update hydrateIfNeeded() and refresh() to
share and await a single load task for the active refresh, and revalidate the
result before publishing state so multiple callers observe the same hydration.
Also make sure clear() invalidates any in-flight task so stale fetches cannot
repopulate old profile data after a reset.
In `@iosApp/iosApp/Screens/Detail/DescriptionTranslationCoordinator.swift`:
- Around line 50-60: The cancellation path in DescriptionTranslationCoordinator
is allowing a stale Task to mutate shared state after a newer translation has
started. Update the task lifecycle in `translate(...)`, `cancel()`, and
`run(contentId:targetLanguage:apply:)` so each Task only clears or updates
`task`/`phase` if it is still the current one, and ignore stale completions or
failures from canceled runs. Use the existing `task` property and the
`defer`/result handling inside `run` to guard against overwriting a newer
request’s state.
In `@iosApp/iosApp/Screens/Detail/DescriptionTranslationView.swift`:
- Around line 26-31: The auto-fire latch in DescriptionTranslationView is only
keyed by contentId, so a preferred language change can block a needed second
translation for the same item. Update the auto-firing guard around autoFiredFor
and the `.auto` path in the view so it also includes the target language (for
example, track both contentId and the selected translation language), ensuring
onAppear can trigger again when the preferred metadata language changes while
still preventing duplicate fires for the same item/language pair.
- Around line 102-108: The translation success callback in startTranslation
currently only updates viewModel.detail, so revisit flows can still hydrate
stale data from ResponseCache. Update
DescriptionTranslationView.startTranslation to also persist the refreshed detail
through the shared cache path used by ItemDetailViewModel, ensuring the
translated result is written back whenever coordinator.translate returns. Use
the existing refreshed value and the cache/shared storage symbols already used
by ItemDetailViewModel and ResponseCache so both the local view state and cached
detail stay in sync.
In `@iosApp/iosApp/Screens/Detail/DetailPlaybackFormatting.swift`:
- Around line 210-217: The subtitle sort descriptor in DetailPlaybackFormatting
should also classify CC tracks as hearing-impaired, not just titles containing
“sdh” or “hearing”. Update the SubtitleDisplayOrder.Descriptor construction in
the track sorting logic so isHearingImpaired also returns true when the track’s
normalized subtitle type from subtitleType(_:) is CC, keeping the sort order
aligned with the label semantics.
In `@iosApp/iosApp/Screens/Player/PlaybackRealtimeClient.swift`:
- Around line 85-89: The teardown in `PlaybackRealtimeClient.unbind()` is
removing the only availability subscription, so future loads stop receiving
updates. Update the unbind/teardown flow to preserve the `PlayerViewModel`’s
long-lived subscription token across `beginFreshLoad()` cycles, and only clear
per-bind listeners that are truly temporary; keep `unavailabilityListeners` from
being wiped if it backs the reusable observer used by `PlayerViewModel` and
`subtitleAI`.
In `@iosApp/iosApp/Screens/Player/PlayerViewModel.swift`:
- Around line 4308-4317: `armDeferredLiveSubtitleClose(trackId:)` is pruning an
older deferred live row by calling `closeLiveSubtitleTrackRow(previousId)`, but
that helper always closes `.primary` and can tear down a newer live renderer
that is already active. Update this branch in `PlayerViewModel` to use a
row-only removal path for the stale `previousId` instead of the full close
helper, and keep `closeLiveSubtitleTrackRow(trackId:)` reserved for the actual
active track cleanup.
In `@iosApp/iosApp/Screens/Player/Sheets/SubtitleTranslateMenu.swift`:
- Around line 249-256: The SubtitleTranslateMenu.showsQuota logic is currently
using file-level translationAvailable, which hides the quota UI even when some
offered languages still fall back to transcription. Update showsQuota to reflect
whether any displayed language in canServe(_:) requires ASR/transcription, so
the gauge/footer appears whenever a visible option can consume quota. Keep the
existing capability and audio-track checks, but base the final condition on
per-target transcription need rather than the presence of any translation path.
In `@iosApp/iosApp/Screens/Player/Subtitles/LiveSubtitleCoordinator.swift`:
- Around line 365-378: The `.completed` handling in `LiveSubtitleCoordinator`
currently clears the job and marks the coordinator finished even when
`completed.subtitleId` is nil, which breaks the poller handoff path. Update the
`completed` branch so the job stays recoverable until the persisted handoff is
actually confirmed, or alternatively take an immediate close/restore fallback
when no `subtitleId` is present. Ensure
`sink.closeLiveTrackAfterPersistedSelected(trackKey:)`, `phase`, and
`clearJob()` are only applied in a way that does not prevent
`persistedHandoffAlreadyDone` and `liveDriverDidGiveUp` from completing the
handoff for the nil-`subtitleId` case; add a regression test for
`.completed(trackKey:subtitleId: nil)`.
In `@iosApp/iosApp/Screens/Player/Subtitles/LiveSubtitleTrack.swift`:
- Around line 151-179: The trimming at the end of LiveSubtitleTrack’s subtitle
escaping logic is happening too late, because the newline normalization in the
same block already converts leading/trailing blank lines into literal ASS
breaks. Update the sanitization flow in the method that builds the escaped
subtitle text so any leading/trailing whitespace/newlines are removed before the
loop replaces line endings with "\\N", or otherwise explicitly strip blank lines
before translating them; keep the brace/backslash filtering in place.
- Around line 121-125: The secondsToMs helper in LiveSubtitleTrack should clamp
or saturate the rounded millisecond value before converting to Int64, since a
huge finite Double can still overflow and trap. Update secondsToMs to keep the
existing finite/nonpositive guards, then add an upper bound check on the rounded
ms result and return a safe maximum value instead of casting an out-of-range
number. Use the secondsToMs symbol to locate the conversion path and keep the
method behavior safe for malformed cue timing.
In `@iosApp/iosApp/Screens/Player/Subtitles/SubtitleAIController.swift`:
- Around line 200-205: Fence async quota and completion handoff updates with the
generation token in SubtitleAIController. Bump generation in cancelActiveJob()
and whenever starting/replacing an in-flight job so any previous task becomes
stale, then have refreshQuota() capture the current generation before awaiting
and re-check it before assigning quota. Also apply the same generation guard in
the job handoff/completion paths so a cancelled or superseded request cannot
write into the next request’s UI state.
- Around line 584-643: The completion latch in completePersistedHandoff is being
set too early, so a transient fetch/listing miss can permanently block the other
completion path for the same job. Move the handoffJobId claim so it only happens
once the downloaded subtitle lookup and registration are about to succeed, or
explicitly clear handoffJobId on every soft-failure branch before returning.
Keep the retry behavior consistent for both the websocket and poller paths by
updating completePersistedHandoff and the failure handling around the downloaded
subtitle fetch/resultSubtitleId lookup.
In `@iosApp/iosApp/Screens/Player/tvOS/TVPlayerInfoHUD.swift`:
- Around line 1749-1757: The AI subtitle menu dismissal currently clears
showAITranslateMenu without restoring tvOS focus, which can leave focus on a
removed control. Update the SubtitleTranslateMenu onDismiss path to match the
picker/appearance flows by explicitly returning focus to the .translate control
(using the existing focus state handling in TVPlayerInfoHUD) after setting
showAITranslateMenu to false. Keep the onJobStarted behavior unchanged.
In `@iosApp/iosApp/tvOS/Screens/Settings/TVSettingsViewModel.swift`:
- Around line 243-255: Serialize saves in saveMetadataLanguage() so only one
metadata-language update can be in flight at a time, and ignore stale
completions before mutating activeProfile or prefSaveState. Use the existing
save path in TVSettingsViewModel (including the .onChange-triggered
saveMetadataLanguage flow) to gate concurrent updateProfile calls, and make sure
the unused changed check is used to skip writes when
editorPreferredMetadataLanguage already matches the current profile value.
In `@iosApp/Tests/AIJobPollerTests.swift`:
- Around line 25-43: The timeout helper in AIJobPollerTests has a shared-state
race because the draining Task appends to collected while the task-group
fallback also reads it directly. Update the helper so collected is owned only by
the drain path, or synchronize access through an actor/lock; keep the logic in
the timeout helper and withTaskGroup flow deterministic by returning the
buffered results only from the draining task instead of reading the array from
another task.
---
Outside diff comments:
In `@iosApp/iosApp/Networking/ServerRegistry.swift`:
- Around line 186-203: Move the AICapabilities reset so it happens after the
server context has been fully retargeted. In ServerRegistry’s server-activation
flow, update the URL/profile, activeServerId, touchLastUsed, and
TokenStore.shared.switchActiveServer first, then call
AICapabilities.shared.reset() so refreshes cannot observe a new generation while
still using the old server/token context.
In `@iosApp/iosApp/Screens/Player/Subtitles/SubtitleSession.swift`:
- Around line 160-204: `openEmbedded(slot:isNativeASS:extradata:extradataSize:)`
and `openSidecar(urlIndex:slot:)` replace an existing live subtitle slot but do
not clear that slot from `liveSlots`, so `flushOnSeek()` can keep skipping the
new track and late live cues may still target it. Update the slot-replacement
path in these methods (and any related live-track open helpers noted in the
diff) to remove the slot from `liveSlots` before creating the new track, and
ensure the state stays consistent whenever a live subtitle is swapped out for a
normal subtitle.
---
Nitpick comments:
In `@iosApp/iosApp/Screens/Player/Subtitles/SubtitleTrackIdentity.swift`:
- Around line 55-60: The AI-live subtitle track ID builder currently ORs any
ordinal into the partition without validation, which can produce collisions or
IDs that fail isAILive(_:) checks. Update
SubtitleTrackIdentity.makeAILiveTrackId(_:) to enforce that the ordinal is
non-negative and fits within the low bits reserved below aiLiveBase before
combining it, and handle invalid input by rejecting it explicitly rather than
returning a malformed ID.
In `@iosApp/Tests/SubtitleAIControllerTests.swift`:
- Around line 177-181: The current `drainMainQueue()` helper in
`SubtitleAIControllerTests` is only guessing at scheduler progress with repeated
`Task.yield()`, so the tests can still race. Replace that polling approach with
an explicit synchronization point tied to the fake register closures or sink
used by the test, and have the test await that signal before making assertions.
Update the affected test flow around `drainMainQueue()` and the corresponding
mock/register callback path so completion is deterministic.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: d634fc91-18c4-4d12-b537-b421926d8430
📒 Files selected for processing (63)
iosApp/Tests/AIJobPollerTests.swiftiosApp/Tests/AIModelDecodingTests.swiftiosApp/Tests/DetailVersionSelectionTests.swiftiosApp/Tests/LiveSubtitleCoordinatorTests.swiftiosApp/Tests/LiveSubtitleTrackTests.swiftiosApp/Tests/SubtitleAIControllerTests.swiftiosApp/Tests/SubtitleDisplayOrderTests.swiftiosApp/Tests/SubtitleStreamEventTests.swiftiosApp/iosApp/ContentView.swiftiosApp/iosApp/Networking/AICapabilities.swiftiosApp/iosApp/Networking/AIJobPoller.swiftiosApp/iosApp/Networking/AIModels.swiftiosApp/iosApp/Networking/ContinuumAI.swiftiosApp/iosApp/Networking/Models.swiftiosApp/iosApp/Networking/ProfilePrefsStore.swiftiosApp/iosApp/Networking/ResponseCache.swiftiosApp/iosApp/Networking/ServerRegistry.swiftiosApp/iosApp/Networking/WireFormatModels.swiftiosApp/iosApp/Screens/Auth/AuthService.swiftiosApp/iosApp/Screens/Detail/DescriptionTranslationCoordinator.swiftiosApp/iosApp/Screens/Detail/DescriptionTranslationView.swiftiosApp/iosApp/Screens/Detail/DetailPlaybackFormatting.swiftiosApp/iosApp/Screens/Detail/ItemDetailView.swiftiosApp/iosApp/Screens/Detail/ItemDetailViewModel.swiftiosApp/iosApp/Screens/Detail/MovieDetailContent.swiftiosApp/iosApp/Screens/Detail/Phone/PhoneDetailHero.swiftiosApp/iosApp/Screens/Detail/Phone/PhonePlaybackSelectorRow.swiftiosApp/iosApp/Screens/Detail/SeasonDetailContent.swiftiosApp/iosApp/Screens/Detail/SeriesDetailContent.swiftiosApp/iosApp/Screens/Player/AVPlayerRoute/AVPlayerBackend.swiftiosApp/iosApp/Screens/Player/ApplePlaybackRoutePlanner.swiftiosApp/iosApp/Screens/Player/CoreMedia/PlayerCore.swiftiosApp/iosApp/Screens/Player/PlaybackRealtimeClient.swiftiosApp/iosApp/Screens/Player/PlaybackRealtimeProtocol.swiftiosApp/iosApp/Screens/Player/PlaybackRealtimeSubtitleEvents.swiftiosApp/iosApp/Screens/Player/PlayerViewModel.swiftiosApp/iosApp/Screens/Player/Sheets/SubtitleTranslateMenu.swiftiosApp/iosApp/Screens/Player/Sheets/TrackSelectionSheet.swiftiosApp/iosApp/Screens/Player/Subtitles/LiveSubtitleCoordinator.swiftiosApp/iosApp/Screens/Player/Subtitles/LiveSubtitleTrack.swiftiosApp/iosApp/Screens/Player/Subtitles/SubtitleAIController.swiftiosApp/iosApp/Screens/Player/Subtitles/SubtitleDisplayOrder.swiftiosApp/iosApp/Screens/Player/Subtitles/SubtitleRenderer.swiftiosApp/iosApp/Screens/Player/Subtitles/SubtitleSession.swiftiosApp/iosApp/Screens/Player/Subtitles/SubtitleTrackIdentity.swiftiosApp/iosApp/Screens/Player/tvOS/TVPlayerInfoHUD.swiftiosApp/iosApp/Screens/Profiles/ProfileModels.swiftiosApp/iosApp/Screens/Settings/CardOverlaySettingsView.swiftiosApp/iosApp/Screens/Settings/SettingsView.swiftiosApp/iosApp/Screens/Settings/SettingsViewModel.swiftiosApp/iosApp/Screens/Settings/SubtitleSettingsView.swiftiosApp/iosApp/macOS/MacPlayerOptionsPanel.swiftiosApp/iosApp/tvOS/Screens/Detail/TVDetailHero.swiftiosApp/iosApp/tvOS/Screens/Detail/TVItemDetailView.swiftiosApp/iosApp/tvOS/Screens/Detail/TVMovieDetailView.swiftiosApp/iosApp/tvOS/Screens/Detail/TVPlaybackSelectorRow.swiftiosApp/iosApp/tvOS/Screens/Detail/TVSeasonDetailView.swiftiosApp/iosApp/tvOS/Screens/Detail/TVSeriesDetailView.swiftiosApp/iosApp/tvOS/Screens/Settings/TVCardOverlaySettingsView.swiftiosApp/iosApp/tvOS/Screens/Settings/TVSettingsComponents.swiftiosApp/iosApp/tvOS/Screens/Settings/TVSettingsView.swiftiosApp/iosApp/tvOS/Screens/Settings/TVSettingsViewModel.swiftiosApp/iosApp/tvOS/Screens/Settings/TVSubtitleSettingsView.swift
💤 Files with no reviewable changes (3)
- iosApp/iosApp/Screens/Settings/CardOverlaySettingsView.swift
- iosApp/iosApp/tvOS/Screens/Settings/TVCardOverlaySettingsView.swift
- iosApp/iosApp/Screens/Settings/SettingsView.swift
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@iosApp/iosApp/Networking/ServerRegistry.swift`:
- Around line 197-201: The active-server removal path in remove(serverId:) still
leaves AICapabilities.shared carrying the deleted server’s cached state because
it retargets activeServerId, defaults, and TokenStore without using
switchTo(serverId:). Update remove(serverId:) to either funnel the fallback
retarget through switchTo(serverId:) or explicitly call the same
AICapabilities.shared.reset() after the fallback server context is fully
applied, matching the behavior already added in switchTo(serverId:).
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 23be083e-f287-4cea-a03d-fa1df9f4a431
📒 Files selected for processing (19)
iosApp/Tests/AIJobPollerTests.swiftiosApp/Tests/LiveSubtitleCoordinatorTests.swiftiosApp/Tests/LiveSubtitleTrackTests.swiftiosApp/Tests/SubtitleAIControllerTests.swiftiosApp/iosApp/Networking/ProfilePrefsStore.swiftiosApp/iosApp/Networking/ServerRegistry.swiftiosApp/iosApp/Screens/Detail/DescriptionTranslationCoordinator.swiftiosApp/iosApp/Screens/Detail/DescriptionTranslationView.swiftiosApp/iosApp/Screens/Detail/DetailPlaybackFormatting.swiftiosApp/iosApp/Screens/Player/PlayerViewModel.swiftiosApp/iosApp/Screens/Player/Sheets/SubtitleTranslateMenu.swiftiosApp/iosApp/Screens/Player/Subtitles/LiveSubtitleCoordinator.swiftiosApp/iosApp/Screens/Player/Subtitles/LiveSubtitleTrack.swiftiosApp/iosApp/Screens/Player/Subtitles/SubtitleAIController.swiftiosApp/iosApp/Screens/Player/Subtitles/SubtitleSession.swiftiosApp/iosApp/Screens/Player/Subtitles/SubtitleTrackIdentity.swiftiosApp/iosApp/Screens/Player/tvOS/TVPlayerInfoHUD.swiftiosApp/iosApp/Screens/Settings/SettingsViewModel.swiftiosApp/iosApp/tvOS/Screens/Settings/TVSettingsViewModel.swift
🚧 Files skipped from review as they are similar to previous changes (17)
- iosApp/Tests/AIJobPollerTests.swift
- iosApp/iosApp/Networking/ProfilePrefsStore.swift
- iosApp/iosApp/Screens/Detail/DescriptionTranslationView.swift
- iosApp/iosApp/Screens/Settings/SettingsViewModel.swift
- iosApp/Tests/LiveSubtitleTrackTests.swift
- iosApp/Tests/SubtitleAIControllerTests.swift
- iosApp/iosApp/Screens/Player/Subtitles/LiveSubtitleTrack.swift
- iosApp/iosApp/Screens/Player/tvOS/TVPlayerInfoHUD.swift
- iosApp/iosApp/Screens/Detail/DetailPlaybackFormatting.swift
- iosApp/iosApp/tvOS/Screens/Settings/TVSettingsViewModel.swift
- iosApp/iosApp/Screens/Player/Subtitles/LiveSubtitleCoordinator.swift
- iosApp/iosApp/Screens/Player/Subtitles/SubtitleTrackIdentity.swift
- iosApp/iosApp/Screens/Player/Subtitles/SubtitleAIController.swift
- iosApp/iosApp/Screens/Player/Subtitles/SubtitleSession.swift
- iosApp/iosApp/Screens/Detail/DescriptionTranslationCoordinator.swift
- iosApp/iosApp/Screens/Player/Sheets/SubtitleTranslateMenu.swift
- iosApp/iosApp/Screens/Player/PlayerViewModel.swift
- Pause playback and show the preparing notice as soon as a subtitle AI job is submitted - Track websocket connectivity separately from realtime unavailability - Resume and tear down cleanly on cancel, poll completion, and fallback paths
- Avoid same-language sources by comparing canonical language keys - Keep selected/default fallback when no English source is available
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@iosApp/iosApp/Screens/Player/PlaybackRealtimeClient.swift`:
- Around line 165-170: The initial connectivity emission in
observeConnectivity() can race with queued updates because it is dispatched
separately via MainActor.run, allowing a newer disconnect to be handled first
and then overwritten by the stale snapshot. Make the first snapshot delivery go
through the same serialized path as other connectivity updates in
PlaybackRealtimeClient so observer callbacks are ordered consistently, and
ensure realtimeConnectedSnapshot is updated from that same sequence to avoid
suppressing realtimeDidBecomeUnavailable().
In `@iosApp/Tests/LiveSubtitleCoordinatorTests.swift`:
- Around line 246-255: The cancellation test in LiveSubtitleCoordinatorTests
only checks for one specific .showFailure message, so it can miss other failure
payloads. Tighten testCancelBeforeStartedResumesSubmitPauseWithoutFailure to
assert that sink.calls contains no .showFailure case at all after
cancelActivePresentation(), while still verifying the playCount and phase
expectations using LiveSubtitleCoordinator and the sink spy.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 49256607-6585-4435-a380-6f1d07c9cbac
📒 Files selected for processing (10)
iosApp/Tests/LiveSubtitleCoordinatorTests.swiftiosApp/Tests/SubtitleAIControllerTests.swiftiosApp/iosApp/Networking/ServerRegistry.swiftiosApp/iosApp/Screens/Player/PlaybackRealtimeClient.swiftiosApp/iosApp/Screens/Player/PlayerNoticeOverlay.swiftiosApp/iosApp/Screens/Player/PlayerView.swiftiosApp/iosApp/Screens/Player/PlayerViewModel.swiftiosApp/iosApp/Screens/Player/Sheets/SubtitleTranslateMenu.swiftiosApp/iosApp/Screens/Player/Subtitles/LiveSubtitleCoordinator.swiftiosApp/iosApp/Screens/Player/Subtitles/SubtitleAIController.swift
🚧 Files skipped from review as they are similar to previous changes (6)
- iosApp/iosApp/Networking/ServerRegistry.swift
- iosApp/Tests/SubtitleAIControllerTests.swift
- iosApp/iosApp/Screens/Player/Sheets/SubtitleTranslateMenu.swift
- iosApp/iosApp/Screens/Player/Subtitles/LiveSubtitleCoordinator.swift
- iosApp/iosApp/Screens/Player/Subtitles/SubtitleAIController.swift
- iosApp/iosApp/Screens/Player/PlayerViewModel.swift
- Clamp the iOS player control overlay to the visible player frame - Tighten top bar spacing and glass button sizing to prevent overflow
Summary
Testing
AIJobPoller, AI model decoding, live subtitle coordination/tracks, subtitle stream events, subtitle AI controller behavior, and subtitle display ordering.Summary by CodeRabbit