Repository navigation
feat(subtitles): on-demand AI subtitle translation with live streaming - #27
Conversation
The shared WebSocket upgrader rejected handshakes unless the browser's Origin host exactly matched r.Host. Behind a TLS-terminating CDN/proxy that rewrites Host to the internal origin (carrying the public host in X-Forwarded-Host), this comparison always failed and every realtime socket 403'd at the handshake — playback control, events, watch-together rooms, and admin log streaming all share the upgrader. checkWebSocketOrigin now also accepts an Origin matching X-Forwarded-Host, keeping the same-origin CSRF guard intact while supporting proxied deployments. Extract a shared forwardedHost helper (first hop of a multi-proxy list) and reuse it from requestBaseURL, replacing the duplicated inline parse. Also reject opaque (empty-host) origins explicitly. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add server-side AI subtitle translation backed by any OpenAI-compatible chat endpoint (OpenAI, Groq, a local Ollama/llama.cpp server). A viewer picks a source track and target language in the player; the server runs a bounded, resumable job pipeline that translates SRT/VTT cues in batches and streams them back over the realtime websocket so playback pauses, fills in cues near the playhead, and resumes. The finished track is persisted as an ordinary downloaded subtitle, so it reaches every client through the existing subtitle pipeline with no client changes. - Job lifecycle persisted in subtitle_ai_jobs (migration 168): enqueue with idempotency, bounded concurrency, progress/heartbeat, cancellation, and crash recovery. - New realtime events (subtitle_ready + subtitle_translation_*) with a per-session notifier; the player renders a synthetic "live" track fed by websocket cues. Timestamps never leave the server, so timing can't drift. - Admin settings card for endpoint / model / concurrency. Player + lifecycle hardening (from the code review of this feature): - Hand off from the live track to the persisted track on completion (selected by downloaded-subtitle id) and on the subtitle_ready broadcast, so the saved track survives a reload and a mid-stream socket drop. - Never persist the synthetic live-track sentinel index as a subtitle preference; restore the prior selection on failure; only auto-resume playback if the viewer was actually playing. - Resume promptly when the playhead is past the last cue; rebuild the live track on a new job; O(batch) live-cue ingestion instead of O(n^2). Reliability: - Root translation jobs in the application context so shutdown cancels them. - Heartbeat-based stale-job reaper (safe across multiple instances) replaces the table-wide startup reset. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
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: defaults Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughImplements on-demand AI subtitle translation: config, DB schema, OpenAI-compatible client, SRT parsing, LLM translator, job repo and PG implementation, service orchestration (enqueue/dispatch/heartbeat/cancel), HTTP handlers and router wiring, realtime event types and notifier, proxy/Origin handling, admin UI for settings, and frontend player integration for live translated cues. ChangesAI Subtitle Translation Feature
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: dba5e4d185
ℹ️ 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".
There was a problem hiding this comment.
Actionable comments posted: 10
🧹 Nitpick comments (3)
web/src/player/realtime-protocol.test.ts (1)
107-148: ⚡ Quick winAdd tests for
subtitle_translation_*parser branches.The parser added four new event branches, but current tests only cover
subtitle_ready; adding one valid + one invalid case per new event will protect this contract.Suggested test additions
+ it("parses subtitle translation started events", () => { + const event = parsePlaybackRealtimeMessage( + JSON.stringify({ + type: "event", + session_id: "session-1", + name: "subtitle_translation_started", + payload: { + session_id: "session-1", + file_id: 42, + job_id: 99, + track_key: "live:99", + language: "es", + total_cues: 120, + }, + }), + ); + expect(event).not.toBeNull(); + }); + + it("rejects subtitle translation cues events with invalid cues", () => { + const event = parsePlaybackRealtimeMessage( + JSON.stringify({ + type: "event", + session_id: "session-1", + name: "subtitle_translation_cues", + payload: { + session_id: "session-1", + file_id: 42, + job_id: 99, + track_key: "live:99", + cues: [{ start: 1, end: 2 }], + done: 1, + total: 120, + }, + }), + ); + expect(event).toBeNull(); + });🤖 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 `@web/src/player/realtime-protocol.test.ts` around lines 107 - 148, Add unit tests for the four new subtitle_translation_* branches by extending the parsePlaybackRealtimeMessage test suite: for each subtitle_translation_* event name, add one test that passes a well-formed JSON event (with expected payload fields like session_id, file_id, subtitle_id, language, target_language/translation_id as applicable) and asserts the parsed object equals the input, and one test that omits the required identifier (e.g., subtitle_id or translation_id) and asserts parsePlaybackRealtimeMessage returns null; place these tests alongside the existing "parses subtitle ready events" and "rejects subtitle ready events missing the subtitle id" cases so they cover both valid and invalid paths for the new branches.web/src/player/realtime-protocol.ts (1)
252-323: ⚡ Quick winTighten runtime guards for optional subtitle fields.
label/messageoptional fields are currently unchecked, so non-string values can pass type guards and leak invalid shapes downstream.Suggested patch
function isSubtitleReadyPayload(value: unknown): value is PlaybackSubtitleReadyPayload { return ( isRecord(value) && typeof value.session_id === "string" && typeof value.file_id === "number" && typeof value.subtitle_id === "number" && - typeof value.language === "string" + typeof value.language === "string" && + (value.label === undefined || typeof value.label === "string") ); } @@ function isTranslationStartedPayload( value: unknown, ): value is PlaybackSubtitleTranslationStartedPayload { return ( @@ typeof value.job_id === "number" && typeof value.track_key === "string" && typeof value.language === "string" && - typeof value.total_cues === "number" + typeof value.total_cues === "number" && + (value.label === undefined || typeof value.label === "string") ); } @@ function isTranslationCompletedPayload( value: unknown, ): value is PlaybackSubtitleTranslationCompletedPayload { return ( @@ typeof value.track_key === "string" && typeof value.subtitle_id === "number" && - typeof value.language === "string" + typeof value.language === "string" && + (value.label === undefined || typeof value.label === "string") ); } @@ function isTranslationFailedPayload( value: unknown, ): value is PlaybackSubtitleTranslationFailedPayload { return ( @@ typeof value.file_id === "number" && typeof value.job_id === "number" && - typeof value.track_key === "string" + typeof value.track_key === "string" && + (value.message === undefined || typeof value.message === "string") ); }🤖 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 `@web/src/player/realtime-protocol.ts` around lines 252 - 323, The runtime guards must validate optional string fields `label` and `message` so non-strings can't slip through; update the type guards (start with isStreamCue) to include checks like ('label' in value ? typeof value.label === "string" : true) and ('message' in value ? typeof value.message === "string" : true) and then ensure any other guards that accept cues (e.g., isTranslationCuesPayload via value.cues.every(isStreamCue)) rely on the tightened isStreamCue; also add the same optional-string checks in any payload guards that directly accept optional label/message (e.g., isSubtitleReadyPayload, isTranslationStartedPayload, isTranslationCompletedPayload) so optional fields are only allowed when they are strings.web/src/player/components/SubtitleTranslateModal.tsx (1)
33-35: ⚡ Quick winRestrict selectable sources to backend-supported text subtitle formats.
Only excluding
livetracks can still expose non-text/image subtitle tracks that are likely to fail translation requests. Filter the source list to supported text codecs before rendering options.Suggested refactor
+const TRANSLATABLE_CODECS = new Set(["srt", "vtt", "webvtt"]); + export function SubtitleTranslateModal({ @@ - const sourceTracks = useMemo(() => tracks.filter((t) => !t.live), [tracks]); + const sourceTracks = useMemo( + () => + tracks.filter( + (t) => !t.live && (!t.codec || TRANSLATABLE_CODECS.has(t.codec.toLowerCase())), + ), + [tracks], + );Also applies to: 128-133
🤖 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 `@web/src/player/components/SubtitleTranslateModal.tsx` around lines 33 - 35, sourceTracks currently only excludes live tracks which can still include non-text/image codecs that will break translation; update the useMemo that defines sourceTracks to further filter tracks by backend-supported text subtitle formats (e.g., only allow codecs/kinds the backend accepts such as "text/vtt", "text/srt" or tracks with kind === "subtitles"/"captions" and/or mimeType indicating text) before returning the list, and apply the same filter where source options are rendered (the other sourceTracks usage around the block noted at lines ~128-133) so sourceIndex/selectable options only include valid text subtitle sources.
🤖 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 `@internal/subtitles/ai/client.go`:
- Around line 132-133: The warning currently logs raw upstream response content
via the "body" field in the slog.Warn call inside the subtitle AI retry path
(see the slog.Warn call in internal/subtitles/ai/client.go), which may expose
subtitle or model output; remove the "body" field from that log and instead log
only metadata (e.g., attempt, model, status code) or a non-reversible indicator
(e.g., response length or a hash) so no raw response text is written to logs;
update the slog.Warn invocation in the retry branch of the relevant function to
drop the raw respBody and replace it with safe metadata only.
- Around line 101-103: The code currently ignores the error from
io.ReadAll(resp.Body); capture and check that error after calling io.ReadAll and
handle it explicitly: assign like body, err := io.ReadAll(resp.Body), close
resp.Body (preferably via defer earlier or immediately on error), and if err !=
nil log/return/retry as appropriate instead of proceeding with a possibly
truncated respBody. Update all uses of respBody/resp.Body in this block to rely
on the checked body variable and ensure error handling covers cleanup
(resp.Body.Close()) and the function's error/ retry path.
In `@internal/subtitles/ai/pgrepo.go`:
- Around line 104-131: For UpdateProgress, CompleteJob, and FailJob, restrict
the UPDATE to only change jobs in active states by adding "AND status IN
('pending','running')" to each WHERE clause, then inspect the result's
rows-affected (from Exec/CommandTag.RowsAffected()) and treat 0 rows affected as
a benign race (return nil) instead of an error; keep the same returned errors
for actual Exec failures and only swallow/return nil when RowsAffected() == 0.
In `@internal/subtitles/ai/srt.go`:
- Around line 91-96: The parseTimingLine function currently returns parsed start
and end without validating them; update parseTimingLine (the block that calls
parseTimestamp for startField and endField) to reject negative or non-sensical
ranges by checking that both start and end are >= 0 and that start < end, and if
any of these validations fail return a clear error instead of accepting the
values.
In `@internal/subtitles/ai/translator.go`:
- Around line 44-63: Add defensive validation at the start of
LLMTranslator.Translate: check that t.client is not nil and that t.batchSize is
> 0, and return clear errors (e.g., fmt.Errorf("translator has no client") and
fmt.Errorf("invalid batchSize: %d", t.batchSize)) instead of proceeding; this
prevents the nil panic when using t.client later and the infinite loop when
t.batchSize <= 0 (affects Translate and any batching logic using t.batchSize).
- Around line 54-57: Validate that req.TargetLanguage is non-empty before using
languageDisplayName or translationSystemPrompt: check req.TargetLanguage (and
optionally req.SourceLanguage) at the start of the translation routine and
return a clear error (e.g., "target language is required") if it's empty, so you
don't call languageDisplayName(req.TargetLanguage) or build system using
translationSystemPrompt when TargetLanguage is missing.
In `@web/src/pages/admin-settings/IntegrationsSettings.tsx`:
- Around line 473-483: The save function currently persists subtitle_ai settings
regardless of values; update it so when enabled is true you validate
baseUrl.trim() and chatModel.trim() are non-empty and Number(maxConcurrent) > 0
before calling updateSetting.mutateAsync; if validation fails, abort the save
(do not build or Promise.all the updates) and surface an error to the user
(e.g., set a local error state or show a toast). Keep the existing behavior for
apiKey and setApiKey (only push the api_key update when apiKey.trim() !== "")
and still clear the apiKey after successful Promise.all; reference the save
function, variables enabled, baseUrl, chatModel, maxConcurrent, apiKey,
updateSetting.mutateAsync, and setApiKey when making the change.
In `@web/src/player/components/SubtitleMenu.tsx`:
- Around line 304-320: The AI Translate button is shown when tracks.length > 0
but the translate modal only supports non-live sources; update the render
condition so it only shows when there is at least one translatable (non-live)
track: replace the tracks.length > 0 check with a predicate that verifies a
non-live track exists (e.g. tracks.some(t => !t.live) — or use the actual
boolean property your track objects use, like isLive), keeping the other guards
(aiEnabled, mediaFileId, playerConfig) and the same button handlers
(setTranslateOpen, setOpen, menuItemsRef/menuItemIndex).
In `@web/src/player/components/VideoPlayer.tsx`:
- Around line 281-287: The effect that resets live-translation state when
activeFileId changes must also clear the pending resume timer; locate the
useEffect that sets setLiveTranslation, setLiveCues, setTranslationBuffering and
clears translationPauseRef.current and pendingTranslatedSubtitleIdRef.current,
and add logic to clearTimeout for the timer ref (e.g.,
pendingTranslationResumeTimerRef.current) if present and then set that ref to
null so the old 30s callback cannot fire against the new file.
In `@web/src/player/hooks/useSubtitleTracks.ts`:
- Around line 42-45: The dedup is using delay-shifted startTime/endTime so keys
change when the user adjusts delay; instead build the dedup key from the
original source cue times (e.g. parsed.start and parsed.end) and parsed.text
(keep using startTime/endTime to create the VTTCue), update the
seen/seenCueKeysRef logic in useSubtitleTracks to check and store
`${parsed.start}|${parsed.end}|${parsed.text}` before calling track.addCue(new
VTTCue(startTime, endTime, parsed.text)).
---
Nitpick comments:
In `@web/src/player/components/SubtitleTranslateModal.tsx`:
- Around line 33-35: sourceTracks currently only excludes live tracks which can
still include non-text/image codecs that will break translation; update the
useMemo that defines sourceTracks to further filter tracks by backend-supported
text subtitle formats (e.g., only allow codecs/kinds the backend accepts such as
"text/vtt", "text/srt" or tracks with kind === "subtitles"/"captions" and/or
mimeType indicating text) before returning the list, and apply the same filter
where source options are rendered (the other sourceTracks usage around the block
noted at lines ~128-133) so sourceIndex/selectable options only include valid
text subtitle sources.
In `@web/src/player/realtime-protocol.test.ts`:
- Around line 107-148: Add unit tests for the four new subtitle_translation_*
branches by extending the parsePlaybackRealtimeMessage test suite: for each
subtitle_translation_* event name, add one test that passes a well-formed JSON
event (with expected payload fields like session_id, file_id, subtitle_id,
language, target_language/translation_id as applicable) and asserts the parsed
object equals the input, and one test that omits the required identifier (e.g.,
subtitle_id or translation_id) and asserts parsePlaybackRealtimeMessage returns
null; place these tests alongside the existing "parses subtitle ready events"
and "rejects subtitle ready events missing the subtitle id" cases so they cover
both valid and invalid paths for the new branches.
In `@web/src/player/realtime-protocol.ts`:
- Around line 252-323: The runtime guards must validate optional string fields
`label` and `message` so non-strings can't slip through; update the type guards
(start with isStreamCue) to include checks like ('label' in value ? typeof
value.label === "string" : true) and ('message' in value ? typeof value.message
=== "string" : true) and then ensure any other guards that accept cues (e.g.,
isTranslationCuesPayload via value.cues.every(isStreamCue)) rely on the
tightened isStreamCue; also add the same optional-string checks in any payload
guards that directly accept optional label/message (e.g.,
isSubtitleReadyPayload, isTranslationStartedPayload,
isTranslationCompletedPayload) so optional fields are only allowed when they are
strings.
🪄 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: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: b843283c-4a5e-4880-a878-f0340cb87f14
📒 Files selected for processing (38)
internal/api/handlers/admin.gointernal/api/handlers/request_proxy.gointernal/api/handlers/subtitle_ai.gointernal/api/handlers/subtitle_search.gointernal/api/handlers/webhook_sync.gointernal/api/handlers/ws_shared.gointernal/api/handlers/ws_shared_test.gointernal/api/router.gointernal/config/config.gointernal/config/db_loader.gointernal/playback/realtime.gointernal/playback/subtitle_ready_notifier.gointernal/subtitles/ai/client.gointernal/subtitles/ai/config.gointernal/subtitles/ai/engine.gointernal/subtitles/ai/job.gointernal/subtitles/ai/languages.gointernal/subtitles/ai/notifier.gointernal/subtitles/ai/pgrepo.gointernal/subtitles/ai/repo.gointernal/subtitles/ai/service.gointernal/subtitles/ai/service_test.gointernal/subtitles/ai/srt.gointernal/subtitles/ai/srt_test.gointernal/subtitles/ai/translator.gomigrations/168_subtitle_ai_jobs.down.sqlmigrations/168_subtitle_ai_jobs.up.sqlweb/src/pages/admin-settings/IntegrationsSettings.tsxweb/src/player/components/PlayerControls.tsxweb/src/player/components/SubtitleMenu.tsxweb/src/player/components/SubtitleTranslateModal.tsxweb/src/player/components/VideoPlayer.tsxweb/src/player/components/WatchPage.tsxweb/src/player/hooks/usePlaybackSession.tsweb/src/player/hooks/useSubtitleTracks.tsweb/src/player/realtime-protocol.test.tsweb/src/player/realtime-protocol.tsweb/src/player/types.ts
- Heartbeat queued jobs (before the semaphore), not just running ones, so the stale-job reaper can't fail a job that is alive but waiting for a slot (which would otherwise let it resurrect itself on acquire, or admit a duplicate once the partial unique index no longer sees it as active). - Filter the translate modal's source list to the formats the server accepts (text external/downloaded, non-bitmap embedded), so an unsupported source is prevented up front instead of failing the job asynchronously. - Tell a duplicate requester (e.g. a second viewer, or after a reload) that a translation is already in progress instead of silently closing; the finished track still arrives via the subtitle_ready refresh. - Note in the admin card that AI subtitle settings take effect after a restart (the running service snapshots them at construction). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
UpdateProgress/CompleteJob/FailJob now only update a job that is still pending/running, so a job cancelled or reaped as stale can't be resurrected by a late write from its own worker goroutine. Defense-in-depth alongside the queued-job heartbeat fix. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Backend: - client.go: handle the io.ReadAll error on the chat response (retry rather than misparse a truncated read), and stop logging raw upstream response bodies (log byte count instead of subtitle/model text). - srt.go: reject negative/reversed cue time ranges in parseTimingLine. - translator.go: fail fast on a nil client, non-positive batch size, or empty target language instead of panicking / looping. Frontend: - VideoPlayer: clear the pending translation resume timer when the file changes, so a stale 30s callback can't fire against the new media. - useSubtitleTracks: dedup cues on source times, not delay-shifted display times, so adjusting subtitle delay can't re-add the same cue. - SubtitleMenu: only show "Translate with AI" when a translatable (non-live, text/non-bitmap) source exists, matching the modal's filter. - IntegrationsSettings: validate AI settings before saving (non-empty endpoint/model when enabled, positive concurrency) instead of persisting an unusable config. - realtime-protocol: validate optional label/message fields are strings; add parser tests for the subtitle_translation_* events. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
There was a problem hiding this comment.
🧹 Nitpick comments (2)
web/src/player/realtime-protocol.test.ts (2)
150-194: ⚡ Quick winVerify full event structure, not just the name.
The existing test pattern (lines 107-135) validates the entire parsed event structure using
toEqual, but this test only checks the.nameproperty. Shallow assertions reduce test coverage and may miss bugs in payload field parsing (e.g.,job_id,track_key,subtitle_id).✅ Suggested fix for thorough validation
- const started = parsePlaybackRealtimeMessage( - JSON.stringify({ - type: "event", - session_id: "s1", - name: "subtitle_translation_started", - payload: { - session_id: "s1", - file_id: 42, - job_id: 99, - track_key: "ai-99", - language: "es", - total_cues: 120, - }, - }), - ); - expect(started?.name).toBe("subtitle_translation_started"); + const started = parsePlaybackRealtimeMessage( + JSON.stringify({ + type: "event", + session_id: "s1", + name: "subtitle_translation_started", + payload: { + session_id: "s1", + file_id: 42, + job_id: 99, + track_key: "ai-99", + language: "es", + total_cues: 120, + }, + }), + ); + expect(started).toEqual({ + type: "event", + session_id: "s1", + name: "subtitle_translation_started", + payload: { + session_id: "s1", + file_id: 42, + job_id: 99, + track_key: "ai-99", + language: "es", + total_cues: 120, + }, + }); - const completed = parsePlaybackRealtimeMessage( - JSON.stringify({ - type: "event", - session_id: "s1", - name: "subtitle_translation_completed", - payload: { - session_id: "s1", - file_id: 42, - job_id: 99, - track_key: "ai-99", - subtitle_id: 7, - language: "es", - }, - }), - ); - expect(completed?.name).toBe("subtitle_translation_completed"); + const completed = parsePlaybackRealtimeMessage( + JSON.stringify({ + type: "event", + session_id: "s1", + name: "subtitle_translation_completed", + payload: { + session_id: "s1", + file_id: 42, + job_id: 99, + track_key: "ai-99", + subtitle_id: 7, + language: "es", + }, + }), + ); + expect(completed).toEqual({ + type: "event", + session_id: "s1", + name: "subtitle_translation_completed", + payload: { + session_id: "s1", + file_id: 42, + job_id: 99, + track_key: "ai-99", + subtitle_id: 7, + language: "es", + }, + }); - const failed = parsePlaybackRealtimeMessage( - JSON.stringify({ - type: "event", - session_id: "s1", - name: "subtitle_translation_failed", - payload: { session_id: "s1", file_id: 42, job_id: 99, track_key: "ai-99" }, - }), - ); - expect(failed?.name).toBe("subtitle_translation_failed"); + const failed = parsePlaybackRealtimeMessage( + JSON.stringify({ + type: "event", + session_id: "s1", + name: "subtitle_translation_failed", + payload: { session_id: "s1", file_id: 42, job_id: 99, track_key: "ai-99" }, + }), + ); + expect(failed).toEqual({ + type: "event", + session_id: "s1", + name: "subtitle_translation_failed", + payload: { session_id: "s1", file_id: 42, job_id: 99, track_key: "ai-99" }, + });🤖 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 `@web/src/player/realtime-protocol.test.ts` around lines 150 - 194, The test currently only asserts the .name for subtitle translation events; update the "parses subtitle translation started/completed/failed events" test to validate the full parsed event objects returned by parsePlaybackRealtimeMessage (including payload fields like session_id, file_id, job_id, track_key, language, total_cues, subtitle_id) using full equality assertions (e.g., expect(...).toEqual(expectedEvent)) for each of the three cases so the parsing of all payload fields is covered.
234-251: 💤 Low valueClarify that the comment is testing optional field validation.
The comment "A non-string label must fail the started guard" is accurate but could be clearer. Since the valid
startedevent (line 151) doesn't include alabelfield, this test is verifying that if the optionallabelfield is present, it must be a string.📝 Suggested clarity improvement
- // A non-string label must fail the started guard. + // An optional label field, if present, must be a string. const badLabel = parsePlaybackRealtimeMessage(🤖 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 `@web/src/player/realtime-protocol.test.ts` around lines 234 - 251, The test comment is misleading about what it's verifying: update the comment above the parsePlaybackRealtimeMessage test (the case using variable badLabel) to state that this asserts optional field validation for the "subtitle_translation_started" event — i.e., when the optional label field is present it must be a string — so reference the "subtitle_translation_started" started event and parsePlaybackRealtimeMessage/started guard in the comment to clarify intent.
🤖 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.
Nitpick comments:
In `@web/src/player/realtime-protocol.test.ts`:
- Around line 150-194: The test currently only asserts the .name for subtitle
translation events; update the "parses subtitle translation
started/completed/failed events" test to validate the full parsed event objects
returned by parsePlaybackRealtimeMessage (including payload fields like
session_id, file_id, job_id, track_key, language, total_cues, subtitle_id) using
full equality assertions (e.g., expect(...).toEqual(expectedEvent)) for each of
the three cases so the parsing of all payload fields is covered.
- Around line 234-251: The test comment is misleading about what it's verifying:
update the comment above the parsePlaybackRealtimeMessage test (the case using
variable badLabel) to state that this asserts optional field validation for the
"subtitle_translation_started" event — i.e., when the optional label field is
present it must be a string — so reference the "subtitle_translation_started"
started event and parsePlaybackRealtimeMessage/started guard in the comment to
clarify intent.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: 88df9284-5150-4fec-b5a8-89876a78621a
📒 Files selected for processing (9)
internal/subtitles/ai/client.gointernal/subtitles/ai/srt.gointernal/subtitles/ai/translator.goweb/src/pages/admin-settings/IntegrationsSettings.tsxweb/src/player/components/SubtitleMenu.tsxweb/src/player/components/VideoPlayer.tsxweb/src/player/hooks/useSubtitleTracks.tsweb/src/player/realtime-protocol.test.tsweb/src/player/realtime-protocol.ts
🚧 Files skipped from review as they are similar to previous changes (8)
- web/src/pages/admin-settings/IntegrationsSettings.tsx
- web/src/player/realtime-protocol.ts
- internal/subtitles/ai/srt.go
- internal/subtitles/ai/client.go
- internal/subtitles/ai/translator.go
- web/src/player/components/SubtitleMenu.tsx
- web/src/player/hooks/useSubtitleTracks.ts
- web/src/player/components/VideoPlayer.tsx
Use toEqual on the whole parsed envelope (not just .name) for the subtitle_translation_* parser cases so payload-field parsing is covered, and clarify the optional-label validation comment. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ranslation feat(subtitles): on-demand AI subtitle translation with live streaming
feat(subtitles): on-demand AI subtitle translation with live streaming
feat(subtitles): on-demand AI subtitle translation with live streaming
feat(subtitles): on-demand AI subtitle translation with live streaming
The strings this change needs are in Silo-Server/silo-translations#27, which is open: an English-only catalog change waits for the maintainer's translation pass and the release its merge publishes. Until then the catalog is generated from that checkout with scripts/sync-translations --local, so the pin reads local-56f90300dc5c rather than a release version. Re-sync with scripts/sync-translations --version <release> once Silo-Server#27 merges; the only difference then is the pin and the languages that gain the new keys.
What
On-demand AI subtitle translation. A viewer picks a source subtitle track and a target language in the player, and the server translates it via any OpenAI-compatible chat endpoint (OpenAI, Groq, a local Ollama/llama.cpp server). Cues stream back over the realtime websocket — playback pauses, fills in the cues near the playhead, then resumes — and the finished track is persisted as an ordinary downloaded subtitle, so it reaches every client through the existing subtitle pipeline with no client changes.
This branch also carries a small, related fix it depends on:
fix(api): accept forwarded host in websocket origin check. Behind a TLS-terminating CDN/proxy the browserOriginreflects the public host whiler.Hostis the internal origin, so the realtime websocket (which the live cue streaming rides on) was rejected. It now also accepts theX-Forwarded-Hostthe proxy forwards.How
internal/subtitles/ai/— an OpenAI-compatible chat client (retry/backoff,Retry-After), batched SRT/VTT cue translation (only text is sent to the model; timestamps never leave the server, so timing can't drift), and a jobService: enqueue + idempotency, bounded concurrency (won't starve transcodes), progress/heartbeat, cancellation, and crash recovery. Jobs persist insubtitle_ai_jobs(migration168). Generated tracks store asdownloaded_subtitles.subtitle_readyandsubtitle_translation_{started,cues,completed,failed}events plus a per-session notifier ininternal/playback.Review hardening
This branch folds in the fixes from a multi-agent
/code-reviewof the feature:subtitle_readybroadcast (was: viewer stuck on an ephemeral track that vanished on reload, and lost the tail on a mid-stream socket drop).Risks / follow-ups
silo-android/silo-applemay want follow-up to consume the new subtitle events (web is handled here).Testing
go build ./...,go vet,go test ./internal/...(incl. new stale-reaper and SRT round-trip tests) — green.tsc -b,eslint,vitest(incl. newrealtime-protocolsubtitle_readycases) — green.AI use
Built with Claude Code (Opus 4.8): feature implementation, then a multi-agent code review and the hardening fixes above.
🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Chores
Tests