Skip to content

feat(subtitles): on-demand AI subtitle translation with live streaming - #27

Merged
Quick104 merged 6 commits into
mainfrom
feat/ai-subtitle-translation
May 30, 2026
Merged

Quick104 merged 6 commits into
mainfrom
feat/ai-subtitle-translation

Conversation

@Quick104

@Quick104 Quick104 commented May 30, 2026 •

Copy link
Copy Markdown
Contributor

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 browser Origin reflects the public host while r.Host is the internal origin, so the realtime websocket (which the live cue streaming rides on) was rejected. It now also accepts the X-Forwarded-Host the proxy forwards.

How

  • Backend 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 job Service: enqueue + idempotency, bounded concurrency (won't starve transcodes), progress/heartbeat, cancellation, and crash recovery. Jobs persist in subtitle_ai_jobs (migration 168). Generated tracks store as downloaded_subtitles.
  • Realtime — new subtitle_ready and subtitle_translation_{started,cues,completed,failed} events plus a per-session notifier in internal/playback.
  • Player — a synthetic "live" track fed by websocket cues; on completion it hands off to the persisted track (selected by downloaded-subtitle id).
  • Admin — a settings card for endpoint / model / max-concurrency.

Review hardening

This branch folds in the fixes from a multi-agent /code-review of the feature:

  • Live → persisted handoff on completion + on the subtitle_ready broadcast (was: viewer stuck on an ephemeral track that vanished on reload, and lost the tail on a mid-stream socket drop).
  • Never persist the live-track sentinel index as a subtitle preference (was: corrupted the saved per-series preference with a nonexistent track).
  • Resume past the last cue instead of a 30s frozen spinner; rebuild on re-translate (was: stale cues mixed in); O(batch) live-cue ingestion (was: O(n²) on the playback hot path).
  • Restore the prior subtitle on failure; only auto-resume if the viewer was playing.
  • Reliability: jobs rooted in the app context (cancelled on shutdown); a heartbeat-based stale-job reaper (multi-instance safe) replaces the table-wide startup reset.

Risks / follow-ups

  • A concurrent second viewer of the same in-flight job gets the finished track via list refresh, not live streaming (streaming is per-session by design).
  • Deferred to separate PRs: extract a shared OpenAI client + SRT parser (currently shaped like the recommendations embedding client / playback SRT→VTT converter); decide the product behavior for re-translating the same source→target (today it can create a second track).
  • Client-visible realtime/API surface — silo-android / silo-apple may want follow-up to consume the new subtitle events (web is handled here).

Testing

  • Backend: go build ./..., go vet, go test ./internal/... (incl. new stale-reaper and SRT round-trip tests) — green.
  • Frontend: tsc -b, eslint, vitest (incl. new realtime-protocol subtitle_ready cases) — green.
  • UI changes (admin card, translate modal, player buffering/track) are not yet captured in screenshots — happy to add.

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

    • AI-powered subtitle translation: on-demand translate jobs (create/status/list/cancel), live streaming of translated cues into the player, buffering UI and automatic track swap.
    • Player UI: “Translate with AI…” menu, translation modal, live synthetic track support.
  • Chores

    • AI Subtitle Translation admin card (enable, endpoint, model, concurrency)
    • AI API key now treated as a sensitive admin setting
  • Tests

    • Added tests for websocket origin, realtime subtitle events, SRT parsing, and service recovery

Review Change Stack

Quick104 and others added 2 commits May 29, 2026 22:40
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]>
@coderabbitai

coderabbitai Bot commented May 30, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 912d77f4-5ed7-44dd-8cda-a71be05c4d14

📥 Commits

Reviewing files that changed from the base of the PR and between 6f9b914 and 95337ec.

📒 Files selected for processing (1)
  • web/src/player/realtime-protocol.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • web/src/player/realtime-protocol.test.ts

📝 Walkthrough

Walkthrough

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

Changes

AI Subtitle Translation Feature

Layer / File(s) Summary
Configuration and core types
internal/config/config.go, internal/config/db_loader.go, internal/subtitles/ai/config.go, internal/subtitles/ai/engine.go, internal/subtitles/ai/job.go, internal/subtitles/ai/notifier.go, internal/subtitles/ai/repo.go
Configuration and core types: SubtitleAIConfig, SubtitleCue, Translator, Job/JobRequest, JobRepository, and Notifier interface.
Database schema for job persistence
migrations/168_subtitle_ai_jobs.up.sql, migrations/168_subtitle_ai_jobs.down.sql
Adds subtitle_ai_jobs table with idempotency partial index and supporting indexes; down migration drops table if exists.
OpenAI-compatible HTTP client
internal/subtitles/ai/client.go
Chat-completions client with JSON request/response, optional Bearer auth, retries for transport/429/5xx/transient 200 cases, and backoff honoring Retry-After.
SRT subtitle parsing and serialization
internal/subtitles/ai/srt.go, internal/subtitles/ai/srt_test.go
Parse SRT/VTT-like input into cues and serialize cues back to SRT; tolerates BOM, different separators and formats; includes unit tests.
LLM-based cue translator
internal/subtitles/ai/translator.go
Batched LLM translator preserving cue timing, using context neighbors, enforcing JSON-keyed response format and validating per-cue output with retries.
Job persistence and lifecycle
internal/subtitles/ai/repo.go, internal/subtitles/ai/pgrepo.go
Repository interface and Postgres-backed implementation for job CRUD, guarded state transitions, heartbeats, completion/failure, and stale-job reset.
Subtitle AI translation service
internal/subtitles/ai/service.go, internal/subtitles/ai/languages.go, internal/subtitles/ai/service_test.go
Service managing Enqueue/Get/List/Cancel, bounded concurrent execution, job runner with heartbeat and notifier callbacks, source loading, translation, deterministic SRT storage, and recovery reaper. Includes test for immediate stale-job reaping on Recover.
Realtime event types and notifications
internal/playback/realtime.go, internal/playback/subtitle_ready_notifier.go
Adds realtime event names/payloads for subtitle readiness and translation lifecycle; notifier broadcasts readiness and streams per-session translation events.
HTTP handlers and API routing
internal/api/handlers/subtitle_ai.go, internal/api/router.go, internal/api/handlers/subtitle_search.go
SubtitleAIHandler with status/translate/job endpoints, shared media-file authorization helper, router wiring to conditionally enable endpoints and to initialize service/notifier and call Recover.
Proxy and WebSocket origin validation
internal/api/handlers/request_proxy.go, internal/api/handlers/ws_shared.go, internal/api/handlers/ws_shared_test.go, internal/api/handlers/webhook_sync.go
Adds forwardedHost helper, expands WebSocket Origin checks to accept forwarded host, updates webhook base URL logic, and adds tests for origin validation.
Admin settings for API key management
internal/api/handlers/admin.go, web/src/pages/admin-settings/IntegrationsSettings.tsx
Marks subtitle_ai.api_key sensitive server-side; adds admin UI card for configuring Subtitle AI settings and conditionally persisting the API key.
Frontend realtime protocol support
web/src/player/realtime-protocol.ts, web/src/player/realtime-protocol.test.ts, web/src/player/types.ts
Extends realtime event names/envelopes for subtitle-ready and translation lifecycle; adds typed payloads and tests; PlayerSubtitleInfo gains id? and live?.
Frontend player UI and integration
web/src/player/components/PlayerControls.tsx, web/src/player/components/SubtitleMenu.tsx, web/src/player/components/SubtitleTranslateModal.tsx, web/src/player/components/VideoPlayer.tsx, web/src/player/hooks/useSubtitleTracks.ts, web/src/player/hooks/usePlaybackSession.ts
Adds Translate modal and menu item, VideoPlayer live translation state and synthetic track handling, PlayerControls wiring, hooks extended for live cue ingestion and dedupe, and safety for persisting subtitle prefs.
Watch page subtitle preference safety
web/src/player/components/WatchPage.tsx
Prevents persisting invalid subtitle indices when sentinel/synthetic live tracks are selected.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

🐰 I hop through cues and whisper lines,

JSON, SRT, and retry signs,
Jobs take flight and streams unfold,
Live captions bloom in gold,
A tiny patch — the player shines.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/ai-subtitle-translation

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

Comment thread internal/subtitles/ai/service.go Resolved
Comment thread internal/api/router.go Resolved
Comment thread internal/subtitles/ai/service.go Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 10

🧹 Nitpick comments (3)
web/src/player/realtime-protocol.test.ts (1)

107-148: ⚡ Quick win

Add 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 win

Tighten runtime guards for optional subtitle fields.

label/message optional 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 win

Restrict selectable sources to backend-supported text subtitle formats.

Only excluding live tracks 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

📥 Commits

Reviewing files that changed from the base of the PR and between e15c07d and dba5e4d.

📒 Files selected for processing (38)
  • internal/api/handlers/admin.go
  • internal/api/handlers/request_proxy.go
  • internal/api/handlers/subtitle_ai.go
  • internal/api/handlers/subtitle_search.go
  • internal/api/handlers/webhook_sync.go
  • internal/api/handlers/ws_shared.go
  • internal/api/handlers/ws_shared_test.go
  • internal/api/router.go
  • internal/config/config.go
  • internal/config/db_loader.go
  • internal/playback/realtime.go
  • internal/playback/subtitle_ready_notifier.go
  • internal/subtitles/ai/client.go
  • internal/subtitles/ai/config.go
  • internal/subtitles/ai/engine.go
  • internal/subtitles/ai/job.go
  • internal/subtitles/ai/languages.go
  • internal/subtitles/ai/notifier.go
  • internal/subtitles/ai/pgrepo.go
  • internal/subtitles/ai/repo.go
  • internal/subtitles/ai/service.go
  • internal/subtitles/ai/service_test.go
  • internal/subtitles/ai/srt.go
  • internal/subtitles/ai/srt_test.go
  • internal/subtitles/ai/translator.go
  • migrations/168_subtitle_ai_jobs.down.sql
  • migrations/168_subtitle_ai_jobs.up.sql
  • web/src/pages/admin-settings/IntegrationsSettings.tsx
  • web/src/player/components/PlayerControls.tsx
  • web/src/player/components/SubtitleMenu.tsx
  • web/src/player/components/SubtitleTranslateModal.tsx
  • web/src/player/components/VideoPlayer.tsx
  • web/src/player/components/WatchPage.tsx
  • web/src/player/hooks/usePlaybackSession.ts
  • web/src/player/hooks/useSubtitleTracks.ts
  • web/src/player/realtime-protocol.test.ts
  • web/src/player/realtime-protocol.ts
  • web/src/player/types.ts

Comment thread internal/subtitles/ai/client.go Resolved
Comment thread internal/subtitles/ai/client.go Resolved
Comment thread internal/subtitles/ai/pgrepo.go Resolved
Comment thread internal/subtitles/ai/srt.go Resolved
Comment thread internal/subtitles/ai/translator.go Resolved
Comment thread internal/subtitles/ai/translator.go Resolved
Quick104 and others added 3 commits May 30, 2026 00:19
- 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]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
web/src/player/realtime-protocol.test.ts (2)

150-194: ⚡ Quick win

Verify 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 .name property. 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 value

Clarify 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 started event (line 151) doesn't include a label field, this test is verifying that if the optional label field 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

📥 Commits

Reviewing files that changed from the base of the PR and between ed60b89 and 6f9b914.

📒 Files selected for processing (9)
  • internal/subtitles/ai/client.go
  • internal/subtitles/ai/srt.go
  • internal/subtitles/ai/translator.go
  • web/src/pages/admin-settings/IntegrationsSettings.tsx
  • web/src/player/components/SubtitleMenu.tsx
  • web/src/player/components/VideoPlayer.tsx
  • web/src/player/hooks/useSubtitleTracks.ts
  • web/src/player/realtime-protocol.test.ts
  • web/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]>
@Quick104
Quick104 merged commit 09c1f23 into main May 30, 2026
1 check passed
@Quick104
Quick104 deleted the feat/ai-subtitle-translation branch May 30, 2026 05:00
Quick104 added a commit to thezak48/silo-server that referenced this pull request Jun 7, 2026
…ranslation

feat(subtitles): on-demand AI subtitle translation with live streaming
Quick104 added a commit that referenced this pull request Jun 11, 2026
feat(subtitles): on-demand AI subtitle translation with live streaming
Quick104 added a commit that referenced this pull request Jun 17, 2026
feat(subtitles): on-demand AI subtitle translation with live streaming
Quick104 added a commit that referenced this pull request Jun 17, 2026
feat(subtitles): on-demand AI subtitle translation with live streaming
Pasithea0 added a commit to Pasithea0/silo-server that referenced this pull request Nov 13, 2026
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.
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