Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

feat(captions): make captions an independent, transcript-derived layer

Etienne Lescot876e469249ba
diff --git a/.claude/launch.json b/.claude/launch.json
index d237bed95..34c8c2caa 100644
--- a/.claude/launch.json
+++ b/.claude/launch.json
@@ -8,6 +8,19 @@
"port": 5199,
"env": { "NO_ELECTRON": "1" }
},
+ {
+ "name": "desktop-dev",
+ "runtimeExecutable": "npm",
+ "runtimeArgs": ["run", "dev", "--", "--port", "5201", "--strictPort"],
+ "port": 5201,
+ "env": { "NO_ELECTRON": "1" }
+ },
+ {
+ "name": "v4preview",
+ "runtimeExecutable": "node",
+ "runtimeArgs": ["node_modules/vite/bin/vite.js", "--config", "vite.v4preview.config.ts"],
+ "port": 5207
+ },
{
"name": "poc",
"runtimeExecutable": "npx",
diff --git a/electron/ai-edition/caption-translate.test.ts b/electron/ai-edition/caption-translate.test.ts
new file mode 100644
index 000000000..d1c695290
--- /dev/null
+++ b/electron/ai-edition/caption-translate.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from "vitest";
+import { parseTranslationReply } from "./caption-translate";
+
+describe("parseTranslationReply", () => {
+ it("reads a bare JSON array", () => {
+ expect(parseTranslationReply('[{"id":"seg_1","text":"bonjour"}]')).toEqual({
+ seg_1: "bonjour",
+ });
+ });
+
+ it("reads a fenced JSON array", () => {
+ const raw = '```json\n[{"id":"seg_1","text":"bonjour"}]\n```';
+ expect(parseTranslationReply(raw)).toEqual({ seg_1: "bonjour" });
+ });
+
+ it("reads an array buried in a lead-in sentence", () => {
+ const raw = 'Here you go:\n[{"id":"seg_1","text":"bonjour"}]\nHope that helps!';
+ expect(parseTranslationReply(raw)).toEqual({ seg_1: "bonjour" });
+ });
+
+ it("skips entries with a missing or empty text", () => {
+ const raw = '[{"id":"seg_1","text":"bonjour"},{"id":"seg_2","text":" "},{"id":"seg_3"}]';
+ expect(parseTranslationReply(raw)).toEqual({ seg_1: "bonjour" });
+ });
+
+ it("returns nothing when the reply is not a translation at all", () => {
+ expect(parseTranslationReply("I cannot help with that.")).toEqual({});
+ expect(parseTranslationReply('{"id":"seg_1","text":"bonjour"}')).toEqual({});
+ });
+});
diff --git a/electron/ai-edition/caption-translate.ts b/electron/ai-edition/caption-translate.ts
new file mode 100644
index 000000000..03eeb05f8
--- /dev/null
+++ b/electron/ai-edition/caption-translate.ts
@@ -0,0 +1,192 @@
+// Caption translation through the configured chat LLM.
+//
+// This is deliberately NOT part of the agent tool loop: translating subtitles is
+// a pure text transform with no reason to touch the document, so it runs as a
+// one-shot, tool-free call (same shape as `chat-service`'s compaction call) and
+// hands the renderer a plain `segmentId → text` map. The renderer is what writes
+// it into the caption translation layer — the transcript is never modified, here
+// or anywhere downstream.
+//
+// Segments are sent in batches with their ids attached so the model's output can
+// be re-keyed exactly; anything it fails to return is simply left untranslated
+// and shows the original text, which is the honest fallback for a partial run.
+
+import { streamLlm } from "./llm-call";
+
+/** One transcript segment to translate. */
+export interface CaptionTranslateSegment {
+ id: string;
+ text: string;
+}
+
+export interface CaptionTranslateOptions {
+ segments: CaptionTranslateSegment[];
+ /** Target language, as the user named it (e.g. "French", "fr", "Português"). */
+ targetLanguage: string;
+ /** Source language hint from the transcript; "auto" / undefined is fine. */
+ sourceLanguage?: string;
+ provider: string;
+ model: string;
+ apiKey: string;
+ baseUrl?: string;
+ reasoningEffort?: string;
+ accountId?: string;
+ /** Segments per request. Keeps each call small enough to stay reliable while
+ * still giving the model surrounding context to translate coherently. */
+ batchSize?: number;
+ onProgress?: (done: number, total: number) => void;
+ signal?: AbortSignal;
+}
+
+export interface CaptionTranslateResult {
+ success: boolean;
+ /** segmentId → translated text. Partial results are returned on failure too. */
+ segments: Record<string, string>;
+ error?: string;
+}
+
+const DEFAULT_BATCH_SIZE = 40;
+
+const SYSTEM_PROMPT = [
+ "You translate video subtitles.",
+ "You are given a JSON array of subtitle segments, each with an `id` and a `text`.",
+ "Translate every `text` into the requested target language.",
+ "",
+ "Rules:",
+ "- Reply with JSON only: an array of objects with exactly the keys `id` and `text`. No prose, no code fences.",
+ "- Return one entry per input segment, with the SAME `id`. Never merge, split, drop or reorder segments.",
+ "- Keep each translation about as long as the original — these are timed subtitles, not prose.",
+ "- Preserve names, product names, numbers, URLs and code identifiers verbatim.",
+ "- Keep the register and the punctuation style of the original.",
+ "- If a segment is already in the target language, return it unchanged.",
+].join("\n");
+
+function buildUserPrompt(
+ segments: CaptionTranslateSegment[],
+ targetLanguage: string,
+ sourceLanguage?: string,
+): string {
+ const from =
+ sourceLanguage && sourceLanguage !== "auto" ? ` The source language is ${sourceLanguage}.` : "";
+ return [
+ `Translate these subtitle segments into ${targetLanguage}.${from}`,
+ "",
+ JSON.stringify(
+ segments.map((s) => ({ id: s.id, text: s.text })),
+ null,
+ 0,
+ ),
+ ].join("\n");
+}
+
+/**
+ * Pull the JSON array out of a model reply. Models wrap JSON in fences or add a
+ * lead-in sentence often enough that a bare `JSON.parse` is not a fair test of
+ * whether the translation worked — so strip the fence, then fall back to the
+ * outermost bracket pair before giving up.
+ */
+export function parseTranslationReply(raw: string): Record<string, string> {
+ const trimmed = raw.trim();
+ const unfenced = trimmed
+ .replace(/^```(?:json)?\s*/i, "")
+ .replace(/\s*```$/, "")
+ .trim();
+
+ const candidates = [unfenced];
+ const first = unfenced.indexOf("[");
+ const last = unfenced.lastIndexOf("]");
+ if (first >= 0 && last > first) candidates.push(unfenced.slice(first, last + 1));
+
+ for (const candidate of candidates) {
+ try {
+ const parsed: unknown = JSON.parse(candidate);
+ if (!Array.isArray(parsed)) continue;
+ const out: Record<string, string> = {};
+ for (const entry of parsed) {
+ if (!entry || typeof entry !== "object") continue;
+ const { id, text } = entry as { id?: unknown; text?: unknown };
+ if (typeof id === "string" && typeof text === "string" && text.trim()) {
+ out[id] = text.trim();
+ }
+ }
+ if (Object.keys(out).length > 0) return out;
+ } catch {
+ // Try the next candidate.
+ }
+ }
+ return {};
+}
+
+export async function translateCaptionSegments(
+ options: CaptionTranslateOptions,
+): Promise<CaptionTranslateResult> {
+ const segments = options.segments.filter((s) => s.text.trim().length > 0);
+ if (segments.length === 0) return { success: true, segments: {} };
+
+ const batchSize = Math.max(1, options.batchSize ?? DEFAULT_BATCH_SIZE);
+ const out: Record<string, string> = {};
+ let done = 0;
+
+ for (let i = 0; i < segments.length; i += batchSize) {
+ if (options.signal?.aborted) {
+ return { success: false, segments: out, error: "Translation cancelled." };
+ }
+ const batch = segments.slice(i, i + batchSize);
+ let reply = "";
+ try {
+ const result = await streamLlm(
+ {
+ provider: options.provider,
+ model: options.model,
+ apiKey: options.apiKey,
+ baseUrl: options.baseUrl,
+ reasoningEffort: options.reasoningEffort,
+ accountId: options.accountId,
+ signal: options.signal,
+ messages: [
+ { role: "system", content: SYSTEM_PROMPT },
+ {
+ role: "user",
+ content: buildUserPrompt(batch, options.targetLanguage, options.sourceLanguage),
+ },
+ ],
+ },
+ { onTextDelta: (delta) => (reply = `${reply}${delta}`) },
+ );
+ if (!result.success) {
+ return {
+ success: false,
+ segments: out,
+ error: result.error ?? "The model did not return a translation.",
+ };
+ }
+ reply = result.content ?? reply;
+ } catch (error) {
+ return {
+ success: false,
+ segments: out,
+ error: error instanceof Error ? error.message : String(error),
+ };
+ }
+
+ const parsed = parseTranslationReply(reply);
+ if (Object.keys(parsed).length === 0) {
+ return {
+ success: false,
+ segments: out,
+ error: "Could not read the model's reply as translated segments.",
+ };
+ }
+ // Only accept ids we actually asked for — a hallucinated id would otherwise
+ // sit in the translation layer forever, keyed to nothing.
+ for (const segment of batch) {
+ const text = parsed[segment.id];
+ if (typeof text === "string" && text.trim()) out[segment.id] = text.trim();
+ }
+
+ done += batch.length;
+ options.onProgress?.(done, segments.length);
+ }
+
+ return { success: true, segments: out };
+}
diff --git a/electron/ipc/nativeBridge.ts b/electron/ipc/nativeBridge.ts
index 1fe1c8540..d278836b5 100644
--- a/electron/ipc/nativeBridge.ts
+++ b/electron/ipc/nativeBridge.ts
@@ -658,6 +658,15 @@ export function registerNativeBridgeHandlers(context: NativeBridgeContext) {
request.payload.sessionId,
),
);
+ case "captions.translate":
+ return createSuccessResponse(
+ requestId,
+ await aiEditionService.captionsTranslate({
+ segments: request.payload.segments,
+ targetLanguage: request.payload.targetLanguage,
+ sourceLanguage: request.payload.sourceLanguage,
+ }),
+ );
case "timeline.run":
return createSuccessResponse(
requestId,
diff --git a/electron/native-bridge/services/aiEditionService.ts b/electron/native-bridge/services/aiEditionService.ts
index aa80f56c6..1d5933970 100644
--- a/electron/native-bridge/services/aiEditionService.ts
+++ b/electron/native-bridge/services/aiEditionService.ts
@@ -1,6 +1,7 @@
import { documentSchema } from "../../../src/lib/ai-edition/schema";
import type {
AiEditionAssetResult,
+ AiEditionCaptionTranslateResult,
AiEditionChatBudget,
AiEditionChatCompactResult,
AiEditionChatMessage,
@@ -17,6 +18,10 @@ import type {
AiEditionProjectSummary,
AxcutTimelineOperation,
} from "../../../src/native/contracts";
+import {
+ type CaptionTranslateSegment,
+ translateCaptionSegments,
+} from "../../ai-edition/caption-translate";
import type { ChatEventSink } from "../../ai-edition/chat-service";
import type { DocumentService } from "../../ai-edition/document-service";
import type { LlmConfigStore, LlmCredential } from "../../ai-edition/llm-config-store";
@@ -451,4 +456,42 @@ export class AiEditionService {
if (!result) return null;
return result;
}
+
+ /**
+ * Translate transcript segments for the caption layer, using whichever
+ * provider/model the chat is already configured with. Returns a plain
+ * `segmentId → text` map: the caller writes it into the document's caption
+ * translation layer, so nothing here can touch the transcript SSOT.
+ */
+ async captionsTranslate(input: {
+ segments: CaptionTranslateSegment[];
+ targetLanguage: string;
+ sourceLanguage?: string;
+ }): Promise<AiEditionCaptionTranslateResult> {
+ const config = this.options.llmConfig.getConfig();
+ if (!config) {
+ return {
+ success: false,
+ segments: {},
+ error: "No AI provider is configured. Connect one in the agent settings first.",
+ };
+ }
+ const def = PROVIDER_DEFINITIONS.find((d) => d.id === config.provider);
+ const credential = def ? this.options.llmConfig.getCredential(def.id, def.envKeys) : null;
+ const accountId =
+ credential?.entry.kind === "codex" ? (credential.entry.accountId ?? undefined) : undefined;
+
+ const result = await translateCaptionSegments({
+ segments: input.segments,
+ targetLanguage: input.targetLanguage,
+ sourceLanguage: input.sourceLanguage,
+ provider: config.provider,
+ model: config.model,
+ apiKey: credential?.value ?? "",
+ baseUrl: config.baseUrl,
+ reasoningEffort: config.reasoningEffort,
+ accountId,
+ });
+ return { ...result, model: config.model };
+ }
}
diff --git a/src/components/ai-edition/CaptionLayer.tsx b/src/components/ai-edition/CaptionLayer.tsx
new file mode 100644
index 000000000..e74c8ad4f
--- /dev/null
+++ b/src/components/ai-edition/CaptionLayer.tsx
@@ -0,0 +1,93 @@
+// The caption overlay in the preview.
+//
+// Deliberately NOT an `AnnotationOverlay`: a caption has no per-item identity to
+// select, nothing to drag and nothing to resize — its placement comes from the
+// caption settings, which the inspector owns. So this is a plain, pointer-events
+// -none band, which also means it can never steal a click from an annotation
+// sitting underneath it.
+//
+// It mirrors `annotationRenderer.renderText`'s box model (centred band, text
+// vertically centred, per-line background plate, 1.4 line-height) so what the
+// preview shows is what the export writes.
+
+import { useMemo } from "react";
+import {
+ type CaptionCue,
+ type CaptionSettings,
+ captionBackgroundCss,
+ captionBandRect,
+ captionCueAt,
+} from "@/lib/ai-edition/captions";
+
+interface CaptionLayerProps {
+ cues: CaptionCue[];
+ settings: CaptionSettings;
+ /** Playhead in virtual (timeline) seconds — the same clock the cues use. */
+ currentTimeSec: number;
+ containerWidth: number;
+ containerHeight: number;
+}
+
+export function CaptionLayer({
+ cues,
+ settings,
+ currentTimeSec,
+ containerWidth,
+ containerHeight,
+}: CaptionLayerProps) {
+ const currentTimeMs = Math.round(currentTimeSec * 1000);
+ const cue = useMemo(() => captionCueAt(cues, currentTimeMs), [cues, currentTimeMs]);
+
+ if (!settings.enabled || !cue || containerWidth <= 0 || containerHeight <= 0) return null;
+
+ const rect = captionBandRect(settings);
+ const background = captionBackgroundCss(settings);
+
+ return (
+ <div
+ aria-hidden
+ style={{
+ position: "absolute",
+ left: `${rect.x}%`,
+ top: `${rect.y}%`,
+ width: `${rect.width}%`,
+ height: `${rect.height}%`,
+ display: "flex",
+ alignItems: "center",
+ justifyContent:
+ settings.textAlign === "left"
+ ? "flex-start"
+ : settings.textAlign === "right"
+ ? "flex-end"
+ : "center",
+ overflow: "hidden",
+ pointerEvents: "none",
+ // Above every annotation, matching the export's z ordering.
+ zIndex: 60,
+ }}
+ >
+ <span
+ style={{
+ color: settings.color,
+ backgroundColor: background,
+ fontSize: `${settings.fontSize}px`,
+ fontFamily: settings.fontFamily,
+ fontWeight: settings.fontWeight,
+ textAlign: settings.textAlign,
+ lineHeight: 1.4,
+ // `clone` gives each wrapped line its own plate instead of one
+ // ragged box around the whole paragraph — same as the exporter,
+ // which draws the background per line.
+ boxDecorationBreak: "clone",
+ WebkitBoxDecorationBreak: "clone",
+ padding: "0.1em 0.2em",
+ borderRadius: 4,
+ wordBreak: "break-word",
+ whiteSpace: "pre-wrap",
+ }}
+ >
+ {cue.text}
+ </span>
+ </div>
+ );
+}
diff --git a/src/components/ai-edition/CaptionsPane.tsx b/src/components/ai-edition/CaptionsPane.tsx
new file mode 100644
index 000000000..5074d4cd1
--- /dev/null
+++ b/src/components/ai-edition/CaptionsPane.tsx
@@ -0,0 +1,662 @@
+// The Captions facet of the floating inspector.
+//
+// Captions have nothing to do with annotations any more: there is no "generate"
+// step that stamps text onto the timeline, because the caption layer IS the
+// transcript, read through this panel's settings. So every control here changes
+// how the transcript is *shown* — never what it says.
+//
+// The one exception is the translation row, and even that is additive: a
+// translation is stored beside the transcript, keyed by segment id, and picking
+// "Original" goes straight back to the SSOT text.
+
+import { Captions as CaptionsIcon, Languages, Loader2, Trash2 } from "lucide-react";
+import { useMemo, useState } from "react";
+import { useScopedT } from "@/contexts/I18nContext";
+import type { CaptionTextAlign, CaptionVerticalPosition } from "@/lib/ai-edition/captions";
+import { untranslatedSegments } from "@/lib/ai-edition/captions";
+import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
+import { useCaptions } from "@/lib/ai-edition/store/useCaptions";
+import { nativeBridgeClient } from "@/native";
+import styles from "./NewEditorShell.module.css";
+
+/** The families `src/index.css` already loads for on-canvas text — anything else
+ * would render in the preview but fall back to a default in the export canvas. */
+const CAPTION_FONTS = [
+ "Inter",
+ "Geist",
+ "DM Sans",
+ "Plus Jakarta Sans",
+ "Manrope",
+ "Space Grotesk",
+ "Sora",
+ "IBM Plex Sans",
+ "Oswald",
+ "Bebas Neue",
+ "Lora",
+ "Merriweather",
+ "Playfair Display",
+ "Caveat",
+ "Permanent Marker",
+ "Fira Code",
+ "IBM Plex Mono",
+] as const;
+
+const TEXT_COLORS = ["#ffffff", "#f8fafc", "#fde047", "#34d399", "#60a5fa", "#0f172a"] as const;
+const BACKGROUND_COLORS = [
+ "#000000",
+ "#16171d",
+ "#1e293b",
+ "#334155",
+ "#10b981",
+ "#ffffff",
+] as const;
+
+/** Offered as translation targets. Codes double as the storage key. */
+const TRANSLATION_LANGUAGES: ReadonlyArray<{ code: string; label: string }> = [
+ { code: "en", label: "English" },
+ { code: "fr", label: "Français" },
+ { code: "es", label: "Español" },
+ { code: "de", label: "Deutsch" },
+ { code: "it", label: "Italiano" },
+ { code: "pt", label: "Português" },
+ { code: "nl", label: "Nederlands" },
+ { code: "pl", label: "Polski" },
+ { code: "tr", label: "Türkçe" },
+ { code: "ru", label: "Русский" },
+ { code: "ar", label: "العربية" },
+ { code: "hi", label: "हिन्दी" },
+ { code: "ja", label: "日本語" },
+ { code: "ko", label: "한국어" },
+ { code: "zh", label: "中文" },
+];
+
+interface CaptionsPaneProps {
+ /** Runs the local Whisper pipeline for the primary asset — owned by the
+ * shell, which already has the toast + per-asset status plumbing. */
+ onTranscribe: () => void;
+ isTranscribing: boolean;
+}
+
+export function CaptionsPane({ onTranscribe, isTranscribing }: CaptionsPaneProps) {
+ const t = useScopedT("settings");
+ const {
+ settings,
+ translations,
+ cues,
+ hasDocument,
+ hasTranscript,
+ set,
+ setLive,
+ commit,
+ saveTranslation,
+ deleteTranslation,
+ } = useCaptions();
+ const document = useProjectStore((s) => s.document);
+ const saveDocument = useProjectStore((s) => s.saveDocument);
+
+ const [target, setTarget] = useState<string>(TRANSLATION_LANGUAGES[1].code);
+ const [translating, setTranslating] = useState(false);
+ const [translateError, setTranslateError] = useState<string | null>(null);
+
+ // Documents made by the old "generate captions" flow carry caption text as
+ // real annotations. They'd now render *on top of* the derived layer, so the
+ // pane offers to clear them — explicitly, since they are the user's data.
+ const legacyCaptionAnnotations = useMemo(
+ () => (document?.annotations ?? []).filter((a) => a.annotationSource === "auto-caption"),
+ [document],
+ );
+
+ const disabled = !hasDocument;
+ const languageOptions = useMemo(() => Object.values(translations), [translations]);
+
+ const handleTranslate = async () => {
+ const doc = useProjectStore.getState().document;
+ if (!doc) return;
+ const label = TRANSLATION_LANGUAGES.find((l) => l.code === target)?.label ?? target;
+ setTranslating(true);
+ setTranslateError(null);
+ try {
+ // Only the assets actually on the timeline, and only the segments that
+ // aren't translated yet — a re-run after adding footage costs just the new
+ // material instead of the whole video.
+ const assetIds = new Set(doc.timeline.clips.map((c) => c.assetId));
+ let translatedAny = false;
+ for (const transcript of doc.transcripts) {
+ if (!assetIds.has(transcript.assetId)) continue;
+ const pending = untranslatedSegments(transcript, translations, target);
+ if (pending.length === 0) {
+ translatedAny = true;
+ continue;
+ }
+ const result = await nativeBridgeClient.aiEdition.translateCaptions({
+ segments: pending.map((s) => ({ id: s.id, text: s.text })),
+ targetLanguage: label,
+ sourceLanguage: transcript.language,
+ });
+ if (Object.keys(result.segments).length > 0) {
+ await saveTranslation({
+ language: target,
+ label,
+ assetId: transcript.assetId,
+ segments: result.segments,
+ model: result.model,
+ });
+ translatedAny = true;
+ }
+ if (!result.success) {
+ setTranslateError(result.error ?? t("captions.translateFailed"));
+ return;
+ }
+ }
+ if (translatedAny) await set({ language: target, enabled: true });
+ else setTranslateError(t("captions.noTranscript"));
+ } catch (error) {
+ setTranslateError(error instanceof Error ? error.message : String(error));
+ } finally {
+ setTranslating(false);
+ }
+ };
+
+ const clearLegacyCaptionAnnotations = async () => {
+ const doc = useProjectStore.getState().document;
+ if (!doc) return;
+ await saveDocument({
+ ...doc,
+ annotations: doc.annotations.filter((a) => a.annotationSource !== "auto-caption"),
+ });
+ };
+
+ return (
+ <div className={`${styles.pane} ${styles.isActive}`}>
+ <header className={styles.paneHead}>
+ <h2>{t("facets.captions")}</h2>
+ <span style={{ marginLeft: "auto", display: "inline-flex", alignItems: "center", gap: 6 }}>
+ <CaptionsIcon size={14} style={{ color: "var(--muted)" }} />
+ </span>
+ </header>
+ <div className={styles.paneBody} style={{ padding: 0 }}>
+ <div className={styles.paneRow}>
+ <span className="label">{t("captions.show")}</span>
+ <button
+ type="button"
+ className={`${styles.toggle} ${settings.enabled ? styles.isOn : ""}`}
+ aria-pressed={settings.enabled}
+ aria-label={t("captions.show")}
+ disabled={disabled || !hasTranscript}
+ onClick={() => void set({ enabled: !settings.enabled })}
+ />
+ </div>
+
+ {!hasTranscript ? (
+ <div
+ style={{
+ margin: "0 var(--sp-4) 12px",
+ padding: "14px",
+ border: "1px dashed var(--border-hi)",
+ borderRadius: 10,
+ display: "flex",
+ flexDirection: "column",
+ gap: 10,
+ }}
+ >
+ <p style={{ margin: 0, font: "400 12px/1.5 var(--font-body)", color: "var(--muted)" }}>
+ {t("captions.noTranscript")}
+ </p>
+ <button
+ type="button"
+ className={`${styles.btn} ${styles.btnPrimary}`}
+ disabled={disabled || isTranscribing}
+ onClick={onTranscribe}
+ >
+ {isTranscribing ? <Loader2 size={14} className="animate-spin" /> : null}
+ {isTranscribing ? t("captions.transcribing") : t("captions.transcribe")}
+ </button>
+ </div>
+ ) : (
+ <p
+ style={{
+ margin: "0 var(--sp-4) 12px",
+ font: "400 11.5px/1.5 var(--font-body)",
+ color: "var(--meta)",
+ }}
+ >
+ {/* The cue count is only meaningful while the layer is on — deriving
+ cues short-circuits when it's off, so a "0 lines" reading there
+ would say the transcript is empty when it isn't. */}
+ {settings.enabled
+ ? t("captions.derivedFromTranscript", { count: cues.length })
+ : t("captions.hiddenHint")}
+ </p>
+ )}
+
+ {legacyCaptionAnnotations.length > 0 ? (
+ <div
+ style={{
+ margin: "0 var(--sp-4) 12px",
+ padding: "12px 14px",
+ border: "1px solid var(--border)",
+ borderRadius: 10,
+ background: "var(--surface-warm)",
+ display: "flex",
+ flexDirection: "column",
+ gap: 8,
+ }}
+ >
+ <p style={{ margin: 0, font: "400 11.5px/1.5 var(--font-body)", color: "var(--fg-2)" }}>
+ {t("captions.legacyAnnotations", { count: legacyCaptionAnnotations.length })}
+ </p>
+ <button
+ type="button"
+ className={`${styles.btn} ${styles.btnSecondary}`}
+ onClick={() => void clearLegacyCaptionAnnotations()}
+ >
+ <Trash2 size={13} />
+ {t("captions.removeLegacyAnnotations")}
+ </button>
+ </div>
+ ) : null}
+
+ {/* ── Language ───────────────────────────────────────────── */}
+ <div className={styles.sectionLabel}>{t("captions.language")}</div>
+ <div className={styles.paneRow}>
+ <span className="label">{t("captions.displayLanguage")}</span>
+ <select
+ value={settings.language ?? ""}
+ disabled={disabled}
+ onChange={(e) => void set({ language: e.target.value || null })}
+ style={selectStyle}
+ >
+ <option value="">{t("captions.original")}</option>
+ {languageOptions.map((entry) => (
+ <option key={entry.language} value={entry.language}>
+ {entry.label}
+ </option>
+ ))}
+ </select>
+ </div>
+
+ <div
+ style={{
+ margin: "0 var(--sp-4) 12px",
+ display: "flex",
+ alignItems: "center",
+ gap: 8,
+ }}
+ >
+ <select
+ value={target}
+ disabled={disabled || translating}
+ onChange={(e) => setTarget(e.target.value)}
+ style={{ ...selectStyle, flex: 1 }}
+ >
+ {TRANSLATION_LANGUAGES.map((language) => (
+ <option key={language.code} value={language.code}>
+ {language.label}
+ </option>
+ ))}
+ </select>
+ <button
+ type="button"
+ className={`${styles.btn} ${styles.btnSecondary}`}
+ disabled={disabled || translating || !hasTranscript}
+ onClick={() => void handleTranslate()}
+ title={t("captions.translateHint")}
+ >
+ {translating ? <Loader2 size={13} className="animate-spin" /> : <Languages size={13} />}
+ {translating ? t("captions.translating") : t("captions.translate")}
+ </button>
+ </div>
+ {settings.language ? (
+ <button
+ type="button"
+ className={`${styles.btn} ${styles.btnSecondary}`}
+ style={{ margin: "0 var(--sp-4) 12px" }}
+ disabled={disabled}
+ onClick={() => void deleteTranslation(settings.language as string)}
+ >
+ <Trash2 size={13} />
+ {t("captions.deleteTranslation")}
+ </button>
+ ) : null}
+ {translateError ? (
+ <p
+ style={{
+ margin: "0 var(--sp-4) 12px",
+ font: "400 11.5px/1.5 var(--font-body)",
+ color: "var(--danger)",
+ }}
+ >
+ {translateError}
+ </p>
+ ) : null}
+ <p
+ style={{
+ margin: "0 var(--sp-4) 14px",
+ font: "400 11px/1.5 var(--font-body)",
+ color: "var(--meta)",
+ }}
+ >
+ {t("captions.translationIsNonDestructive")}
+ </p>
+
+ {/* ── Text ───────────────────────────────────────────────── */}
+ <div className={styles.sectionLabel}>{t("captions.text")}</div>
+ <div className={styles.paneRow}>
+ <span className="label">{t("captions.font")}</span>
+ <select
+ value={settings.fontFamily}
+ disabled={disabled}
+ onChange={(e) => void set({ fontFamily: e.target.value })}
+ style={selectStyle}
+ >
+ {CAPTION_FONTS.map((font) => (
+ <option key={font} value={font} style={{ fontFamily: font }}>
+ {font}
+ </option>
+ ))}
+ </select>
+ </div>
+ <div className={styles.paneRow}>
+ <span className="label">{t("captions.bold")}</span>
+ <button
+ type="button"
+ className={`${styles.toggle} ${settings.fontWeight === "bold" ? styles.isOn : ""}`}
+ aria-pressed={settings.fontWeight === "bold"}
+ aria-label={t("captions.bold")}
+ disabled={disabled}
+ onClick={() =>
+ void set({ fontWeight: settings.fontWeight === "bold" ? "normal" : "bold" })
+ }
+ />
+ </div>
+ <div className={styles.sliderGrid}>
+ <SliderCell
+ label={t("captions.fontSize")}
+ value={settings.fontSize}
+ min={10}
+ max={90}
+ suffix="px"
+ disabled={disabled}
+ onChange={(v) => setLive({ fontSize: v })}
+ onCommit={() => void commit()}
+ />
+ </div>
+ <div className={styles.sectionLabel}>{t("captions.textColor")}</div>
+ <SwatchRow
+ colors={TEXT_COLORS}
+ value={settings.color}
+ disabled={disabled}
+ onPick={(color) => void set({ color })}
+ label={t("captions.textColor")}
+ />
+
+ {/* ── Background ─────────────────────────────────────────── */}
+ <div className={styles.sectionLabel}>{t("captions.background")}</div>
+ <div className={styles.paneRow}>
+ <span className="label">{t("captions.showBackground")}</span>
+ <button
+ type="button"
+ className={`${styles.toggle} ${settings.backgroundEnabled ? styles.isOn : ""}`}
+ aria-pressed={settings.backgroundEnabled}
+ aria-label={t("captions.showBackground")}
+ disabled={disabled}
+ onClick={() => void set({ backgroundEnabled: !settings.backgroundEnabled })}
+ />
+ </div>
+ {settings.backgroundEnabled ? (
+ <>
+ <SwatchRow
+ colors={BACKGROUND_COLORS}
+ value={settings.backgroundColor}
+ disabled={disabled}
+ onPick={(backgroundColor) => void set({ backgroundColor })}
+ label={t("captions.backgroundColor")}
+ />
+ <div className={styles.sliderGrid}>
+ <SliderCell
+ label={t("captions.backgroundOpacity")}
+ value={Math.round(settings.backgroundOpacity * 100)}
+ min={0}
+ max={100}
+ suffix="%"
+ disabled={disabled}
+ onChange={(v) => setLive({ backgroundOpacity: v / 100 })}
+ onCommit={() => void commit()}
+ />
+ </div>
+ </>
+ ) : null}
+
+ {/* ── Placement ──────────────────────────────────────────── */}
+ <div className={styles.sectionLabel}>{t("captions.position")}</div>
+ <Segmented<CaptionVerticalPosition>
+ value={settings.verticalPosition}
+ disabled={disabled}
+ options={[
+ { value: "top", label: t("captions.positionTop") },
+ { value: "middle", label: t("captions.positionMiddle") },
+ { value: "bottom", label: t("captions.positionBottom") },
+ ]}
+ onChange={(verticalPosition) => void set({ verticalPosition })}
+ />
+ <Segmented<CaptionTextAlign>
+ value={settings.textAlign}
+ disabled={disabled}
+ options={[
+ { value: "left", label: t("captions.alignLeft") },
+ { value: "center", label: t("captions.alignCenter") },
+ { value: "right", label: t("captions.alignRight") },
+ ]}
+ onChange={(textAlign) => void set({ textAlign })}
+ />
+ <div className={styles.sliderGrid}>
+ <SliderCell
+ label={t("captions.verticalOffset")}
+ value={settings.offsetY}
+ min={-45}
+ max={45}
+ suffix="%"
+ disabled={disabled}
+ onChange={(v) => setLive({ offsetY: v })}
+ onCommit={() => void commit()}
+ />
+ <SliderCell
+ label={t("captions.width")}
+ value={settings.width}
+ min={20}
+ max={100}
+ suffix="%"
+ disabled={disabled}
+ onChange={(v) => setLive({ width: v })}
+ onCommit={() => void commit()}
+ />
+ </div>
+
+ {/* ── Line length ────────────────────────────────────────── */}
+ <div className={styles.sectionLabel}>{t("captions.lineLength")}</div>
+ <div className={styles.paneRow}>
+ <span className="label">{t("captions.minWords")}</span>
+ <select
+ value={settings.minWordsPerLine}
+ disabled={disabled}
+ onChange={(e) => void set({ minWordsPerLine: Number(e.target.value) })}
+ style={selectStyle}
+ >
+ {WORD_COUNTS.map((n) => (
+ <option key={n} value={n}>
+ {n}
+ </option>
+ ))}
+ </select>
+ </div>
+ <div className={styles.paneRow} style={{ marginBottom: 16 }}>
+ <span className="label">{t("captions.maxWords")}</span>
+ <select
+ value={settings.maxWordsPerLine}
+ disabled={disabled}
+ onChange={(e) => void set({ maxWordsPerLine: Number(e.target.value) })}
+ style={selectStyle}
+ >
+ {WORD_COUNTS.map((n) => (
+ <option key={n} value={n} disabled={n < settings.minWordsPerLine}>
+ {n}
+ </option>
+ ))}
+ </select>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+const WORD_COUNTS = Array.from({ length: 12 }, (_, i) => i + 1);
+
+const selectStyle: React.CSSProperties = {
+ height: 32,
+ padding: "0 8px",
+ borderRadius: 8,
+ border: "1px solid var(--border)",
+ background: "var(--surface)",
+ color: "var(--fg)",
+ font: "500 12.5px var(--font-body)",
+ maxWidth: 160,
+};
+
+function SwatchRow({
+ colors,
+ value,
+ disabled,
+ onPick,
+ label,
+}: {
+ colors: readonly string[];
+ value: string;
+ disabled?: boolean;
+ onPick: (color: string) => void;
+ label: string;
+}) {
+ return (
+ <div
+ style={{
+ margin: "0 var(--sp-4) 12px",
+ display: "flex",
+ alignItems: "center",
+ gap: 8,
+ flexWrap: "wrap",
+ }}
+ >
+ {colors.map((color) => (
+ <button
+ type="button"
+ key={color}
+ title={color}
+ aria-label={`${label} ${color}`}
+ aria-pressed={value.toLowerCase() === color.toLowerCase()}
+ disabled={disabled}
+ onClick={() => onPick(color)}
+ style={{
+ width: 24,
+ height: 24,
+ borderRadius: "50%",
+ background: color,
+ border:
+ value.toLowerCase() === color.toLowerCase()
+ ? "2px solid var(--accent)"
+ : "1px solid var(--border-hi)",
+ cursor: disabled ? "not-allowed" : "pointer",
+ }}
+ />
+ ))}
+ <input
+ type="color"
+ value={value.startsWith("#") ? value : "#ffffff"}
+ disabled={disabled}
+ aria-label={label}
+ onChange={(e) => onPick(e.target.value)}
+ style={{
+ width: 34,
+ height: 26,
+ padding: 0,
+ border: "1px solid var(--border)",
+ borderRadius: 6,
+ background: "var(--surface)",
+ }}
+ />
+ </div>
+ );
+}
+
+function Segmented<T extends string>({
+ value,
+ options,
+ disabled,
+ onChange,
+}: {
+ value: T;
+ options: ReadonlyArray<{ value: T; label: string }>;
+ disabled?: boolean;
+ onChange: (next: T) => void;
+}) {
+ return (
+ <div className={styles.paneTabs}>
+ {options.map((option) => (
+ <button
+ type="button"
+ key={option.value}
+ className={value === option.value ? styles.isActive : ""}
+ aria-pressed={value === option.value}
+ disabled={disabled}
+ onClick={() => onChange(option.value)}
+ >
+ {option.label}
+ </button>
+ ))}
+ </div>
+ );
+}
+
+function SliderCell({
+ label,
+ value,
+ min,
+ max,
+ step = 1,
+ suffix = "",
+ disabled,
+ onChange,
+ onCommit,
+}: {
+ label: string;
+ value: number;
+ min: number;
+ max: number;
+ step?: number;
+ suffix?: string;
+ disabled?: boolean;
+ onChange: (next: number) => void;
+ onCommit: () => void;
+}) {
+ return (
+ <div className={styles.sliderCell}>
+ <div className="head">
+ <span className="label">{label}</span>
+ <span className="val">
+ {Math.round(value)}
+ {suffix}
+ </span>
+ </div>
+ <input
+ type="range"
+ min={min}
+ max={max}
+ step={step}
+ value={value}
+ disabled={disabled}
+ onChange={(e) => onChange(Number(e.target.value))}
+ onMouseUp={onCommit}
+ onTouchEnd={onCommit}
+ onKeyUp={onCommit}
+ />
+ </div>
+ );
+}
diff --git a/src/components/ai-edition/Modals.tsx b/src/components/ai-edition/Modals.tsx
index b7f74771f..20db96a68 100644
--- a/src/components/ai-edition/Modals.tsx
+++ b/src/components/ai-edition/Modals.tsx
@@ -1878,114 +1878,6 @@ export function SourceTranscriptModal({
);
}
-interface CaptionsModalProps extends BaseModalProps {
- minWords: number;
- maxWords: number;
- onMinWords: (n: number) => void;
- onMaxWords: (n: number) => void;
- onGenerate: () => void;
-}
-
-export function AutoCaptionsModal({
- open,
- onClose,
- minWords,
- maxWords,
- onMinWords,
- onMaxWords,
- onGenerate,
-}: CaptionsModalProps) {
- const t = useScopedT("editor");
- const tc = useScopedT("common");
- return (
- <ModalShell
- open={open}
- onClose={onClose}
- title={t("autoCaptions.dialogTitle")}
- subtitle={t("autoCaptions.dialogDescription")}
- >
- <div style={{ display: "flex", gap: 12 }}>
- <div style={{ display: "flex", flexDirection: "column", gap: 4, flex: 1 }}>
- <label
- style={{
- font: "500 11px/1 var(--font-body)",
- textTransform: "uppercase",
- letterSpacing: "0.06em",
- color: "var(--muted)",
- }}
- >
- {t("autoCaptions.minWords")}
- </label>
- <select
- value={minWords}
- onChange={(e) => onMinWords(Number(e.target.value))}
- style={{
- padding: "8px 10px",
- border: "1px solid var(--border)",
- borderRadius: "6px",
- background: "var(--surface)",
- color: "var(--fg-2)",
- font: "500 13px var(--font-body)",
- }}
- >
- {Array.from({ length: 12 }, (_, i) => i + 1).map((n) => (
- <option key={n} value={n}>
- {t("autoCaptions.wordsCount", { count: n })}
- </option>
- ))}
- </select>
- </div>
- <div style={{ display: "flex", flexDirection: "column", gap: 4, flex: 1 }}>
- <label
- style={{
- font: "500 11px/1 var(--font-body)",
- textTransform: "uppercase",
- letterSpacing: "0.06em",
- color: "var(--muted)",
- }}
- >
- {t("autoCaptions.maxWords")}
- </label>
- <select
- value={maxWords}
- onChange={(e) => onMaxWords(Number(e.target.value))}
- style={{
- padding: "8px 10px",
- border: "1px solid var(--border)",
- borderRadius: "6px",
- background: "var(--surface)",
- color: "var(--fg-2)",
- font: "500 13px var(--font-body)",
- }}
- >
- {Array.from({ length: 12 }, (_, i) => i + 1).map((n) => (
- <option key={n} value={n} disabled={n < minWords}>
- {t("autoCaptions.wordsCount", { count: n })}
- </option>
- ))}
- </select>
- </div>
- </div>
- <div
- style={{
- display: "flex",
- justifyContent: "flex-end",
- gap: 8,
- paddingTop: 12,
- borderTop: "1px solid var(--border-soft)",
- }}
- >
- <button type="button" className={`${styles.btn} ${styles.btnSecondary}`} onClick={onClose}>
- {tc("actions.cancel")}
- </button>
- <button type="button" className={`${styles.btn} ${styles.btnPrimary}`} onClick={onGenerate}>
- {t("autoCaptions.generate")}
- </button>
- </div>
- </ModalShell>
- );
-}
-
export interface ChatHistoryModalProps extends BaseModalProps {
sessions: Array<{ id: string; title: string; messageCount: number; createdAt: string }>;
activeSessionId: string | null;
diff --git a/src/components/ai-edition/NewEditorShell.tsx b/src/components/ai-edition/NewEditorShell.tsx
index 04b247edd..8707b1079 100644
--- a/src/components/ai-edition/NewEditorShell.tsx
+++ b/src/components/ai-edition/NewEditorShell.tsx
@@ -22,7 +22,6 @@ import { useNativePlaybackSync } from "@/native/useNativePlaybackSync";
import { ExportDialog } from "./ExportDialog";
import { LeftPanel } from "./LeftPanel";
import {
- AutoCaptionsModal,
EditClipModal,
NewProjectModal,
OpenProjectModal,
@@ -100,9 +99,6 @@ export function NewEditorShell() {
useUndoRedoShortcuts(() => {
// ponytail: placeholder, wire when undo stack merges with history
});
- const [captionsOpen, setCaptionsOpen] = useState(false);
- const [captionsMinW, setCaptionsMinW] = useState(2);
- const [captionsMaxW, setCaptionsMaxW] = useState(7);
const [copiedClipId, setCopiedClipId] = useState<string | null>(null);
const [projectSummaries, setProjectSummaries] = useState<AiEditionProjectSummary[]>([]);
const seekSeqRef = useRef(0);
@@ -811,77 +807,44 @@ export function NewEditorShell() {
}
}, [tl]);
- const handleCaptions = useCallback(() => {
- if (!document?.project.primaryAssetId) {
- toast.info("Add a video to the project before generating captions.");
- return;
- }
- setCaptionsOpen(true);
- }, [document]);
-
- const handleGenerateCaptions = useCallback(async () => {
+ // Captions are derived from the transcript, so the only caption "action" the
+ // shell still owns is producing that transcript — everything else (styling,
+ // placement, language) is a setting the Captions pane writes directly.
+ const handleTranscribeForCaptions = useCallback(async () => {
const doc = useProjectStore.getState().document;
if (!doc) return;
const assetId = doc.project.primaryAssetId;
if (!assetId) {
- toast.error("Add a video to the project before generating captions.");
+ toast.info("Add a video to the project before transcribing.");
return;
}
+ if (doc.transcripts.some((t) => t.assetId === assetId)) return;
- setCaptionsOpen(false);
+ setIsTranscribing(true);
+ setAssetStatuses((prev) => ({ ...prev, [assetId]: "running" }));
try {
- let transcript = doc.transcript;
- if (!transcript) {
- toast.loading("Transcribing first…", { id: "captions-gen" });
- setAssetStatuses((prev) => ({ ...prev, [assetId]: "running" }));
- try {
- transcript = await transcribeAsset(doc, assetId, {
- onStatus: (s) => toast.loading(`Transcribing: ${s}`, { id: "captions-gen" }),
- });
- toast.dismiss("captions-gen");
- await setTranscript(transcript);
- setAssetStatuses((prev) => {
- const next = { ...prev };
- delete next[assetId];
- return next;
- });
- } catch (err) {
- setAssetStatuses((prev) => ({ ...prev, [assetId]: "failed" }));
- throw err;
- }
- }
-
- const { captionSegmentsToAnnotationRegions } = await import(
- "@/lib/captioning/annotationsFromCaptions"
- );
- toast.loading("Generating captions…", { id: "captions-gen" });
- const segments =
- ((transcript as Record<string, unknown>).segments as Array<Record<string, unknown>>) ?? [];
- const { regions } = captionSegmentsToAnnotationRegions(
- segments as never,
- doc.annotations.length + 1,
- doc.annotations.length + 1,
- {
- minWordsPerCaption: captionsMinW,
- maxWordsPerCaption: captionsMaxW,
- timestampGranularity: "word",
- },
- );
- const latestDoc = useProjectStore.getState().document ?? doc;
- const next = {
- ...latestDoc,
- annotations: [...latestDoc.annotations, ...(regions as never)],
- };
- await saveDocument(next);
- toast.dismiss("captions-gen");
- toast.success(`Added ${regions.length} captions`);
+ toast.loading("Transcribing…", { id: "captions-transcribe" });
+ const transcript = await transcribeAsset(doc, assetId, {
+ onStatus: (s) => toast.loading(`Transcribing: ${s}`, { id: "captions-transcribe" }),
+ });
+ await setTranscript(transcript);
+ setAssetStatuses((prev) => {
+ const next = { ...prev };
+ delete next[assetId];
+ return next;
+ });
+ toast.dismiss("captions-transcribe");
+ toast.success("Transcript ready — captions are live.");
} catch (err) {
- toast.dismiss("captions-gen");
- toast.error("Caption generation failed", {
+ setAssetStatuses((prev) => ({ ...prev, [assetId]: "failed" }));
+ toast.dismiss("captions-transcribe");
+ toast.error("Transcription failed", {
description: err instanceof Error ? err.message : String(err),
});
+ } finally {
+ setIsTranscribing(false);
}
- }, [captionsMinW, captionsMaxW, saveDocument, setTranscript]);
+ }, [setTranscript]);
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
@@ -1264,7 +1227,8 @@ export function NewEditorShell() {
onToggleOpen={() => setInspectorOpen((v) => !v)}
clips={tl.clips}
onEditClip={setEditClipTarget}
- onCaptions={handleCaptions}
+ onTranscribe={() => void handleTranscribeForCaptions()}
+ isTranscribing={isTranscribing}
transcriptProps={transcriptProps}
/>
</>
@@ -1365,15 +1329,6 @@ export function NewEditorShell() {
onChoose={handleConfirmUnsaved}
/>
<ExportDialog open={exportOpen} onClose={() => setExportOpen(false)} document={document} />
- <AutoCaptionsModal
- open={captionsOpen}
- onClose={() => setCaptionsOpen(false)}
- minWords={captionsMinW}
- maxWords={captionsMaxW}
- onMinWords={setCaptionsMinW}
- onMaxWords={setCaptionsMaxW}
- onGenerate={handleGenerateCaptions}
- />
</div>
);
}
diff --git a/src/components/ai-edition/PreviewCanvas.tsx b/src/components/ai-edition/PreviewCanvas.tsx
index 8a32b1fe7..52f2fda22 100644
--- a/src/components/ai-edition/PreviewCanvas.tsx
+++ b/src/components/ai-edition/PreviewCanvas.tsx
@@ -40,6 +40,7 @@ import type {
AxcutZoomRegion,
} from "@/lib/ai-edition/schema";
import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
+import { useCaptions } from "@/lib/ai-edition/store/useCaptions";
import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";
import { resolveActiveCameraTrack } from "@/lib/ai-edition/timeline/camera";
import { createPlaybackClockRef } from "@/lib/ai-edition/timeline/playback-clock";
@@ -53,6 +54,7 @@ import {
import { classifyWallpaper, resolveImageWallpaperUrl } from "@/lib/wallpaper";
import { getCssClipPath } from "@/lib/webcamMaskShapes";
import { AnnotationLayer } from "./AnnotationLayer";
+import { CaptionLayer } from "./CaptionLayer";
import { NativeCompositorOverlay } from "./NativeCompositorOverlay";
import styles from "./NewEditorShell.module.css";
import { type VideoSource, VirtualPreview } from "./VirtualPreview";
@@ -105,6 +107,9 @@ const WEBCAM_SOURCE_SIZE = { width: 960, height: 720 };
export function PreviewCanvas(props: PreviewCanvasProps) {
const te = useScopedT("editor");
const { settings, setLive, commit } = useEditorSettings();
+ // Captions are derived from the transcript, not passed down as regions — the
+ // preview reads them from the same façade the inspector writes to.
+ const { cues: captionCues, settings: captionSettings } = useCaptions();
const document = useProjectStore((s) => s.document);
const assets = document?.assets ?? [];
const frameRef = useRef<HTMLDivElement | null>(null);
@@ -436,6 +441,13 @@ export function PreviewCanvas(props: PreviewCanvasProps) {
onCommit={props.onAnnotationCommit}
/>
) : null}
+ <CaptionLayer
+ cues={captionCues}
+ settings={captionSettings}
+ currentTimeSec={props.currentTimeSec}
+ containerWidth={layout.screenRect.width}
+ containerHeight={layout.screenRect.height}
+ />
</div>
) : null}
{layout?.webcamRect && showWebcamSlot ? (
diff --git a/src/components/ai-edition/v4/FloatingInspector.tsx b/src/components/ai-edition/v4/FloatingInspector.tsx
index 93f491e8d..8d949395e 100644
--- a/src/components/ai-edition/v4/FloatingInspector.tsx
+++ b/src/components/ai-edition/v4/FloatingInspector.tsx
@@ -39,6 +39,7 @@ import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";
import type { useTimeline } from "@/lib/ai-edition/store/useTimeline";
import { coalescedTrimGroups } from "@/lib/ai-edition/timeline/trim-mapping";
import { formatSeconds } from "@/lib/ai-edition/timeline/virtual-preview";
+import { CaptionsPane } from "../CaptionsPane";
import { ColorField } from "../ColorField";
import {
BackgroundPane,
@@ -77,7 +78,10 @@ interface FloatingInspectorProps {
* through a facet body. */
clips: AxcutClip[];
onEditClip: (clip: AxcutClip) => void;
- onCaptions: () => void;
+ /** Runs the transcription the caption layer reads from. Captions are derived
+ * from the transcript, so this is the only caption action the shell owns. */
+ onTranscribe: () => void;
+ isTranscribing: boolean;
transcriptProps: TranscriptProps;
/** Drives the selected-element settings pane (zoom/speed/annotation/trim) —
* takes over the inspector, forcing it open, whenever a timeline region is
@@ -93,7 +97,8 @@ export function FloatingInspector({
onToggleOpen,
clips,
onEditClip,
- onCaptions,
+ onTranscribe,
+ isTranscribing,
transcriptProps,
tl,
}: FloatingInspectorProps) {
@@ -111,7 +116,8 @@ export function FloatingInspector({
) : (
<FacetBody
facet={facet}
- onCaptions={onCaptions}
+ onTranscribe={onTranscribe}
+ isTranscribing={isTranscribing}
onCollapse={onToggleOpen}
transcriptProps={transcriptProps}
/>
@@ -1022,17 +1028,18 @@ const secondaryBtnStyle: React.CSSProperties = {
function FacetBody({
facet,
- onCaptions,
+ onTranscribe,
+ isTranscribing,
onCollapse,
transcriptProps,
}: {
facet: Facet;
- onCaptions: () => void;
+ onTranscribe: () => void;
+ isTranscribing: boolean;
onCollapse: () => void;
transcriptProps: TranscriptProps;
}) {
const te = useScopedT("editor");
- const ts = useScopedT("settings");
// A small collapse affordance floated over the reused pane header.
const collapse = (
<button
@@ -1067,12 +1074,7 @@ function FacetBody({
if (facet === "transcript") return wrap(collapse, <TranscriptPane {...transcriptProps} />);
return wrap(
collapse,
- <SimpleFacet
- title={ts("facets.captions")}
- description={te("inspector.captionsDescription")}
- actionLabel={te("inspector.generateCaptions")}
- onAction={onCaptions}
- />,
+ <CaptionsPane onTranscribe={onTranscribe} isTranscribing={isTranscribing} />,
);
}
@@ -1084,91 +1086,3 @@ function wrap(collapse: React.ReactNode, body: React.ReactNode) {
</div>
);
}
-
-function SimpleFacet({
- title,
- description,
- actionLabel,
- onAction,
- emptyLabel,
-}: {
- title: string;
- description: string;
- actionLabel?: string;
- onAction?: () => void;
- emptyLabel?: string;
-}) {
- return (
- <div style={{ display: "flex", flexDirection: "column", minHeight: 0 }}>
- <header
- style={{
- display: "flex",
- alignItems: "center",
- padding: "14px 16px 12px",
- borderBottom: "1px solid var(--border-soft)",
- flexShrink: 0,
- }}
- >
- <h2
- style={{
- margin: 0,
- fontSize: 14,
- fontWeight: 600,
- color: "var(--fg-emphasis)",
- letterSpacing: "-0.01em",
- }}
- >
- {title}
- </h2>
- </header>
- <div
- style={{
- padding: "16px",
- display: "flex",
- flexDirection: "column",
- gap: 14,
- flex: "1 1 auto",
- minHeight: 0,
- overflowY: "auto",
- scrollbarWidth: "thin",
- scrollbarColor: "var(--border) transparent",
- }}
- >
- <p style={{ margin: 0, fontSize: 12, lineHeight: 1.5, color: "var(--muted)" }}>
- {description}
- </p>
- {emptyLabel ? (
- <div
- style={{
- padding: "20px 16px",
- border: "1px dashed var(--border-hi)",
- borderRadius: 12,
- textAlign: "center",
- color: "var(--muted)",
- fontSize: 12,
- }}
- >
- {emptyLabel}
- </div>
- ) : null}
- {actionLabel && onAction ? (
- <button
- type="button"
- onClick={onAction}
- style={{
- padding: "10px 14px",
- borderRadius: 10,
- border: "1px solid var(--accent)",
- background: "var(--accent)",
- color: "#fff",
- font: "600 13px var(--font-display)",
- cursor: "pointer",
- }}
- >
- {actionLabel}
- </button>
- ) : null}
- </div>
- </div>
- );
-}
diff --git a/src/components/ai-edition/v4/V4Timeline.tsx b/src/components/ai-edition/v4/V4Timeline.tsx
index 3901a1f4d..3f1188bc3 100644
--- a/src/components/ai-edition/v4/V4Timeline.tsx
+++ b/src/components/ai-edition/v4/V4Timeline.tsx
@@ -1097,7 +1097,7 @@ export function V4Timeline({
<button
type="button"
className={styles.tlToolBtn}
- aria-pressed={settings.autoFocusAll}
+ aria-pressed={settings.autoFocusAll}
title={t(
settings.autoFocusAll ? "buttons.autoFocusAllOn" : "buttons.autoFocusAllOff",
)}
diff --git a/src/i18n/locales/en/settings.json b/src/i18n/locales/en/settings.json
index 457994dce..49acd3a99 100644
--- a/src/i18n/locales/en/settings.json
+++ b/src/i18n/locales/en/settings.json
@@ -268,5 +268,45 @@
"restoreSilence": "Restore silence ({{duration}}s)",
"trimSilence": "Trim silence ({{duration}}s)",
"restoreWord": "Restore \"{{word}}\""
+ },
+ "captions": {
+ "show": "Show captions",
+ "noTranscript": "Captions are read from the media transcript. Transcribe this video to turn them on.",
+ "transcribe": "Transcribe video",
+ "transcribing": "Transcribing…",
+ "derivedFromTranscript": "{{count}} caption lines, derived live from the transcript.",
+ "hiddenHint": "Captions come from this media's transcript. Turn them on to see them in the preview and in exports.",
+ "legacyAnnotations": "This project still contains caption annotations from the old captions feature ({{count}}). They render on top of the caption layer.",
+ "removeLegacyAnnotations": "Remove old caption annotations",
+ "language": "Language",
+ "displayLanguage": "Display",
+ "original": "Original (transcript)",
+ "translate": "Translate",
+ "translating": "Translating…",
+ "translateHint": "Translate the transcript with the configured AI provider",
+ "translateFailed": "Translation failed.",
+ "deleteTranslation": "Delete this translation",
+ "translationIsNonDestructive": "Translations are stored beside the transcript, never in it — the original text and its timings stay untouched.",
+ "text": "Text",
+ "font": "Font",
+ "fontSize": "Size",
+ "bold": "Bold",
+ "textColor": "Text color",
+ "background": "Background",
+ "showBackground": "Show background",
+ "backgroundColor": "Background color",
+ "backgroundOpacity": "Opacity",
+ "position": "Position",
+ "positionTop": "Top",
+ "positionMiddle": "Middle",
+ "positionBottom": "Bottom",
+ "alignLeft": "Left",
+ "alignCenter": "Center",
+ "alignRight": "Right",
+ "verticalOffset": "Offset",
+ "width": "Width",
+ "lineLength": "Line length",
+ "minWords": "Min words per line",
+ "maxWords": "Max words per line"
}
}
diff --git a/src/i18n/locales/fr/settings.json b/src/i18n/locales/fr/settings.json
index 39f9ba0e8..b3b47083e 100644
--- a/src/i18n/locales/fr/settings.json
+++ b/src/i18n/locales/fr/settings.json
@@ -268,5 +268,45 @@
"restoreSilence": "Restaurer le silence ({{duration}} s)",
"trimSilence": "Couper le silence ({{duration}} s)",
"restoreWord": "Restaurer « {{word}} »"
+ },
+ "captions": {
+ "show": "Afficher les sous-titres",
+ "noTranscript": "Les sous-titres sont issus de la transcription du média. Transcrivez cette vidéo pour les activer.",
+ "transcribe": "Transcrire la vidéo",
+ "transcribing": "Transcription…",
+ "derivedFromTranscript": "{{count}} lignes de sous-titres, dérivées de la transcription en direct.",
+ "hiddenHint": "Les sous-titres proviennent de la transcription de ce média. Activez-les pour les voir dans l'aperçu et à l'export.",
+ "legacyAnnotations": "Ce projet contient encore des annotations de sous-titres issues de l'ancienne fonctionnalité ({{count}}). Elles s'affichent par-dessus les sous-titres.",
+ "removeLegacyAnnotations": "Supprimer les anciennes annotations",
+ "language": "Langue",
+ "displayLanguage": "Affichage",
+ "original": "Original (transcription)",
+ "translate": "Traduire",
+ "translating": "Traduction…",
+ "translateHint": "Traduire la transcription avec le fournisseur IA configuré",
+ "translateFailed": "La traduction a échoué.",
+ "deleteTranslation": "Supprimer cette traduction",
+ "translationIsNonDestructive": "Les traductions sont stockées à côté de la transcription, jamais dedans — le texte original et ses timings restent intacts.",
+ "text": "Texte",
+ "font": "Police",
+ "fontSize": "Taille",
+ "bold": "Gras",
+ "textColor": "Couleur du texte",
+ "background": "Fond",
+ "showBackground": "Afficher le fond",
+ "backgroundColor": "Couleur du fond",
+ "backgroundOpacity": "Opacité",
+ "position": "Position",
+ "positionTop": "Haut",
+ "positionMiddle": "Milieu",
+ "positionBottom": "Bas",
+ "alignLeft": "Gauche",
+ "alignCenter": "Centre",
+ "alignRight": "Droite",
+ "verticalOffset": "Décalage",
+ "width": "Largeur",
+ "lineLength": "Longueur des lignes",
+ "minWords": "Mots min. par ligne",
+ "maxWords": "Mots max. par ligne"
}
}
diff --git a/src/lib/ai-edition/captions/captions.test.ts b/src/lib/ai-edition/captions/captions.test.ts
new file mode 100644
index 000000000..88ee9a354
--- /dev/null
+++ b/src/lib/ai-edition/captions/captions.test.ts
@@ -0,0 +1,330 @@
+import { describe, expect, it } from "vitest";
+import type { AxcutDocument, AxcutTranscript } from "../schema";
+import { captionCuesToTextRegions, deriveCaptionCues } from "./cues";
+import {
+ captionBackgroundCss,
+ captionBandRect,
+ DEFAULT_CAPTION_SETTINGS,
+ getCaptionSettings,
+ patchCaptionSettings,
+} from "./settings";
+import {
+ getCaptionTranslations,
+ putCaptionTranslation,
+ removeCaptionTranslation,
+ translationCoverage,
+ untranslatedSegments,
+} from "./translations";
+
+function transcript(): AxcutTranscript {
+ return {
+ assetId: "asset-1",
+ language: "en",
+ segments: [
+ {
+ id: "seg_1",
+ kind: "speech",
+ startSec: 0,
+ endSec: 2,
+ text: "hello there friend",
+ wordIds: ["w1", "w2", "w3"],
+ },
+ {
+ id: "seg_2",
+ kind: "speech",
+ startSec: 4,
+ endSec: 6,
+ text: "goodbye now",
+ wordIds: ["w4", "w5"],
+ },
+ ],
+ words: [
+ { id: "w1", segmentId: "seg_1", startSec: 0, endSec: 0.6, text: "hello" },
+ { id: "w2", segmentId: "seg_1", startSec: 0.6, endSec: 1.2, text: "there" },
+ { id: "w3", segmentId: "seg_1", startSec: 1.2, endSec: 2, text: "friend" },
+ { id: "w4", segmentId: "seg_2", startSec: 4, endSec: 5, text: "goodbye" },
+ { id: "w5", segmentId: "seg_2", startSec: 5, endSec: 6, text: "now" },
+ ],
+ };
+}
+
+function doc(overrides: Partial<AxcutDocument> = {}): AxcutDocument {
+ return {
+ schemaVersion: 5,
+ project: {
+ id: "p1",
+ title: "Test",
+ createdAt: "2026-01-01T00:00:00.000Z",
+ updatedAt: "2026-01-01T00:00:00.000Z",
+ primaryAssetId: "asset-1",
+ },
+ assets: [],
+ transcript: null,
+ transcripts: [transcript()],
+ timeline: {
+ clips: [
+ {
+ id: "clip-1",
+ assetId: "asset-1",
+ sourceStartSec: 0,
+ sourceEndSec: 10,
+ timelineStartSec: 0,
+ timelineEndSec: 10,
+ wordRefs: [],
+ origin: "user",
+ reason: "",
+ },
+ ],
+ gaps: [],
+ trimRanges: [],
+ muteRanges: [],
+ speedRanges: [],
+ captionRanges: [],
+ },
+ annotations: [],
+ zoomRanges: [],
+ legacyEditor: null,
+ agent: { pendingQuestions: [], suggestions: [], lastAppliedOperations: [] },
+ preview: { strategy: "seek", revision: 0 },
+ export: { preset: "final-balanced", lastJobId: null },
+ history: { revisions: [] },
+ ...overrides,
+ } as AxcutDocument;
+}
+
+const ON = { ...DEFAULT_CAPTION_SETTINGS, enabled: true };
+
+describe("caption settings", () => {
+ it("defaults to hidden so an existing project doesn't sprout captions on upgrade", () => {
+ expect(getCaptionSettings(doc()).enabled).toBe(false);
+ });
+
+ it("round-trips a patch through the legacyEditor envelope", () => {
+ const next = patchCaptionSettings(doc(), { enabled: true, fontSize: 44, offsetY: -10 });
+ expect(getCaptionSettings(next)).toMatchObject({ enabled: true, fontSize: 44, offsetY: -10 });
+ });
+
+ it("keeps an explicit null language instead of falling back to the default", () => {
+ const translated = patchCaptionSettings(doc(), { language: "fr" });
+ expect(getCaptionSettings(translated).language).toBe("fr");
+ expect(getCaptionSettings(patchCaptionSettings(translated, { language: null })).language).toBe(
+ null,
+ );
+ });
+
+ it("swaps min/max words when they are set the wrong way round", () => {
+ const next = patchCaptionSettings(doc(), { minWordsPerLine: 9, maxWordsPerLine: 3 });
+ expect(getCaptionSettings(next)).toMatchObject({ minWordsPerLine: 3, maxWordsPerLine: 9 });
+ });
+
+ it("keeps the band inside the frame however far the offset is pushed", () => {
+ const rect = captionBandRect({ ...ON, verticalPosition: "bottom", offsetY: 45 });
+ expect(rect.y + rect.height).toBeLessThanOrEqual(100);
+ const top = captionBandRect({ ...ON, verticalPosition: "top", offsetY: -45 });
+ expect(top.y).toBeGreaterThanOrEqual(0);
+ });
+
+ it("folds the opacity into the background colour, and reports 'transparent' when off", () => {
+ expect(
+ captionBackgroundCss({ ...ON, backgroundColor: "#10b981", backgroundOpacity: 0.5 }),
+ ).toBe("rgba(16, 185, 129, 0.5)");
+ expect(captionBackgroundCss({ ...ON, backgroundEnabled: false })).toBe("transparent");
+ });
+});
+
+describe("deriveCaptionCues", () => {
+ it("returns nothing while the layer is hidden", () => {
+ expect(deriveCaptionCues(doc(), DEFAULT_CAPTION_SETTINGS, {})).toEqual([]);
+ });
+
+ it("derives cues from the transcript with no stored caption data", () => {
+ const cues = deriveCaptionCues(doc(), { ...ON, minWordsPerLine: 2, maxWordsPerLine: 3 }, {});
+ expect(cues.length).toBeGreaterThan(0);
+ expect(cues.map((c) => c.text).join(" ")).toContain("hello there");
+ // Timings come from the words, in ms on the ruler.
+ expect(cues[0].startMs).toBe(0);
+ });
+
+ it("maps source time onto the ruler through the clip's in-point", () => {
+ const shifted = doc({
+ timeline: {
+ ...doc().timeline,
+ clips: [
+ {
+ id: "clip-1",
+ assetId: "asset-1",
+ sourceStartSec: 4,
+ sourceEndSec: 10,
+ timelineStartSec: 0,
+ timelineEndSec: 6,
+ wordRefs: [],
+ origin: "user",
+ reason: "",
+ },
+ ],
+ },
+ } as Partial<AxcutDocument>);
+
+ const cues = deriveCaptionCues(shifted, ON, {});
+ // The first two seconds of speech are cut away by the clip in-point; what
+ // survives starts at 4s in the source, i.e. 0s on the ruler.
+ expect(cues).toHaveLength(1);
+ expect(cues[0]).toMatchObject({ startMs: 0, text: "goodbye now" });
+ });
+
+ it("drops cues whose source range no clip plays", () => {
+ const cut = doc({
+ timeline: {
+ ...doc().timeline,
+ clips: [
+ {
+ id: "clip-1",
+ assetId: "asset-1",
+ sourceStartSec: 7,
+ sourceEndSec: 10,
+ timelineStartSec: 0,
+ timelineEndSec: 3,
+ wordRefs: [],
+ origin: "user",
+ reason: "",
+ },
+ ],
+ },
+ } as Partial<AxcutDocument>);
+ expect(deriveCaptionCues(cut, ON, {})).toEqual([]);
+ });
+
+ it("shows the translation for a translated segment and the original for the rest", () => {
+ const translations = {
+ fr: {
+ language: "fr",
+ label: "Français",
+ updatedAt: "2026-01-01T00:00:00.000Z",
+ byAsset: { "asset-1": { seg_1: "bonjour mon ami" } },
+ },
+ };
+ const cues = deriveCaptionCues(doc(), { ...ON, language: "fr" }, translations);
+ const text = cues.map((c) => c.text).join(" | ");
+ expect(text).toContain("bonjour");
+ // seg_2 has no translation, so its original words still play.
+ expect(text).toContain("goodbye");
+ });
+
+ it("keeps the translated line inside its own segment's span", () => {
+ const translations = {
+ fr: {
+ language: "fr",
+ label: "Français",
+ updatedAt: "",
+ byAsset: { "asset-1": { seg_1: "bonjour", seg_2: "au revoir" } },
+ },
+ };
+ const cues = deriveCaptionCues(doc(), { ...ON, language: "fr" }, translations);
+ const second = cues.find((c) => c.text.includes("revoir"));
+ expect(second).toBeDefined();
+ expect(second?.startMs).toBeGreaterThanOrEqual(4000);
+ expect(second?.endMs).toBeLessThanOrEqual(6000);
+ });
+
+ it("never leaves two cues on screen at the same instant", () => {
+ const cues = deriveCaptionCues(doc(), ON, {});
+ for (let i = 1; i < cues.length; i++) {
+ expect(cues[i - 1].endMs).toBeLessThanOrEqual(cues[i].startMs);
+ }
+ });
+});
+
+describe("captionCuesToTextRegions", () => {
+ it("emits plain text regions with no annotationSource marker", () => {
+ const regions = captionCuesToTextRegions(deriveCaptionCues(doc(), ON, {}), ON);
+ expect(regions.length).toBeGreaterThan(0);
+ for (const region of regions) {
+ expect(region.type).toBe("text");
+ expect("annotationSource" in region).toBe(false);
+ expect(region.zIndex).toBeGreaterThan(1000);
+ }
+ });
+
+ it("carries the settings' style onto every region", () => {
+ const settings = {
+ ...ON,
+ color: "#fde047",
+ fontSize: 40,
+ textAlign: "left" as const,
+ backgroundEnabled: false,
+ };
+ const [region] = captionCuesToTextRegions(deriveCaptionCues(doc(), settings, {}), settings);
+ expect(region.style).toMatchObject({
+ color: "#fde047",
+ fontSize: 40,
+ textAlign: "left",
+ backgroundColor: "transparent",
+ });
+ });
+});
+
+describe("caption translations", () => {
+ it("stores a translation without touching the transcript", () => {
+ const before = doc();
+ const after = putCaptionTranslation(before, {
+ language: "fr",
+ label: "Français",
+ assetId: "asset-1",
+ segments: { seg_1: "bonjour" },
+ });
+ expect(after.transcripts).toEqual(before.transcripts);
+ expect(getCaptionTranslations(after).fr.byAsset["asset-1"]).toEqual({ seg_1: "bonjour" });
+ });
+
+ it("merges a second run into the same language layer", () => {
+ let d = putCaptionTranslation(doc(), {
+ language: "fr",
+ label: "Français",
+ assetId: "asset-1",
+ segments: { seg_1: "bonjour" },
+ });
+ d = putCaptionTranslation(d, {
+ language: "fr",
+ label: "Français",
+ assetId: "asset-1",
+ segments: { seg_2: "au revoir" },
+ });
+ expect(getCaptionTranslations(d).fr.byAsset["asset-1"]).toEqual({
+ seg_1: "bonjour",
+ seg_2: "au revoir",
+ });
+ });
+
+ it("reports only the segments still missing a translation", () => {
+ const d = putCaptionTranslation(doc(), {
+ language: "fr",
+ label: "Français",
+ assetId: "asset-1",
+ segments: { seg_1: "bonjour" },
+ });
+ const pending = untranslatedSegments(transcript(), getCaptionTranslations(d), "fr");
+ expect(pending.map((s) => s.id)).toEqual(["seg_2"]);
+ expect(translationCoverage(transcript(), getCaptionTranslations(d), "fr")).toEqual({
+ translated: 1,
+ total: 2,
+ });
+ });
+
+ it("removing a language leaves the transcript and other languages intact", () => {
+ let d = putCaptionTranslation(doc(), {
+ language: "fr",
+ label: "Français",
+ assetId: "asset-1",
+ segments: { seg_1: "bonjour" },
+ });
+ d = putCaptionTranslation(d, {
+ language: "es",
+ label: "Español",
+ assetId: "asset-1",
+ segments: { seg_1: "hola" },
+ });
+ const after = removeCaptionTranslation(d, "fr");
+ expect(Object.keys(getCaptionTranslations(after))).toEqual(["es"]);
+ expect(after.transcripts).toEqual(doc().transcripts);
+ });
+});
diff --git a/src/lib/ai-edition/captions/cues.ts b/src/lib/ai-edition/captions/cues.ts
new file mode 100644
index 000000000..d3ba7401b
--- /dev/null
+++ b/src/lib/ai-edition/captions/cues.ts
@@ -0,0 +1,261 @@
+// Caption cues, derived from the transcript.
+//
+// Captions are a *view* over `document.transcripts` — nothing here is stored.
+// The transcript owns the words and their timings (source time, per asset); the
+// clips decide which of those survive and where they land on the ruler; the
+// caption settings decide how many words share a line. Change any of the three
+// and the cues follow on the next render, with no regeneration step and no
+// stale copy to reconcile.
+//
+// Two coordinate systems meet here:
+// - transcript words / segments: SOURCE seconds, per asset.
+// - cues: VIRTUAL (timeline) ms, what the preview uses.
+// The export path takes the same virtual cues and projects them back to source
+// through `projectRegionsToSourceTime`, exactly like annotations, so preview and
+// export cannot drift apart.
+
+import type { AnnotationRegion } from "@/components/video-editor/types";
+import {
+ dedupeAdjacentCaptionRepeats,
+ finalizeCaptionSegmentsForPlayback,
+ groupTimedCaptionWordsIntoLines,
+ splitMergedCaptionsByWordBounds,
+} from "@/lib/captioning/annotationsFromCaptions";
+import type { CaptionSegment } from "@/lib/captioning/transcribe";
+import type { AxcutClip, AxcutDocument, AxcutTranscript } from "../schema";
+import { type CaptionSettings, captionBackgroundCss, captionBandRect } from "./settings";
+import type { CaptionTranslations } from "./translations";
+
+/** One on-screen caption line, in whichever time base the producer documented. */
+export interface CaptionCue {
+ id: string;
+ startMs: number;
+ endMs: number;
+ text: string;
+}
+
+/** Captions draw above every user annotation so a blur or a sticker can't bury
+ * the subtitle. Well clear of the annotation z-range, which counts up from 1. */
+export const CAPTION_Z_INDEX_BASE = 100_000;
+
+function toCaptionSegments(transcript: AxcutTranscript): CaptionSegment[] {
+ return transcript.words
+ .filter((word) => word.text.trim().length > 0)
+ .map((word) => ({ startSec: word.startSec, endSec: word.endSec, text: word.text }));
+}
+
+function segmentWordsAsCaptionSegments(
+ transcript: AxcutTranscript,
+ segmentId: string,
+): CaptionSegment[] {
+ const segment = transcript.segments.find((s) => s.id === segmentId);
+ if (!segment) return [];
+ const byId = new Map(transcript.words.map((w) => [w.id, w]));
+ return segment.wordIds
+ .map((id) => byId.get(id))
+ .filter((w): w is NonNullable<typeof w> => w !== undefined && w.text.trim().length > 0)
+ .map((w) => ({ startSec: w.startSec, endSec: w.endSec, text: w.text }));
+}
+
+/**
+ * One asset's caption lines in SOURCE seconds.
+ *
+ * Original language: grouped straight from the word timestamps, so a line
+ * starts and ends on real speech.
+ *
+ * Translated language: the translated text replaces the segment's text and is
+ * spread across *the segment's own span* by character weight — a translation
+ * has a different word count and word order, so per-word timings cannot carry
+ * over, but the segment boundary can and does. Segments with no translation yet
+ * fall back to their original words, so a partial translation still plays.
+ */
+export function captionLinesForAsset(
+ transcript: AxcutTranscript,
+ settings: CaptionSettings,
+ translations: CaptionTranslations,
+): CaptionSegment[] {
+ const minWords = settings.minWordsPerLine;
+ const maxWords = settings.maxWordsPerLine;
+
+ // Whisper repeats a phrase across chunk boundaries often enough that raw lines
+ // would stutter on screen; the dedupe + overlap trim are the same pass the old
+ // caption generator ran before writing annotations, kept because the artefact
+ // is in the transcript, not in how it used to be stored.
+ const polish = (lines: CaptionSegment[]) =>
+ finalizeCaptionSegmentsForPlayback(dedupeAdjacentCaptionRepeats(lines));
+
+ if (settings.language === null) {
+ const words = toCaptionSegments(transcript);
+ if (words.length > 0) {
+ return polish(groupTimedCaptionWordsIntoLines(words, minWords, maxWords));
+ }
+ // A transcript with segments but no words (hand-authored / imported) still
+ // deserves captions — split each segment span proportionally instead.
+ return polish(
+ splitMergedCaptionsByWordBounds(
+ transcript.segments
+ .filter((s) => s.text.trim())
+ .map((s) => ({ startSec: s.startSec, endSec: s.endSec, text: s.text })),
+ minWords,
+ maxWords,
+ ),
+ );
+ }
+
+ const translated = translations[settings.language]?.byAsset[transcript.assetId] ?? {};
+ const out: CaptionSegment[] = [];
+ for (const segment of transcript.segments) {
+ const replacement = translated[segment.id];
+ if (typeof replacement === "string" && replacement.trim()) {
+ out.push(
+ ...splitMergedCaptionsByWordBounds(
+ [{ startSec: segment.startSec, endSec: segment.endSec, text: replacement.trim() }],
+ minWords,
+ maxWords,
+ ),
+ );
+ continue;
+ }
+ const words = segmentWordsAsCaptionSegments(transcript, segment.id);
+ if (words.length > 0) {
+ out.push(...groupTimedCaptionWordsIntoLines(words, minWords, maxWords));
+ } else if (segment.text.trim()) {
+ out.push(
+ ...splitMergedCaptionsByWordBounds(
+ [{ startSec: segment.startSec, endSec: segment.endSec, text: segment.text }],
+ minWords,
+ maxWords,
+ ),
+ );
+ }
+ }
+ return polish(out);
+}
+
+/**
+ * Map a source-time span onto the ruler through the clips that play it.
+ *
+ * The inverse of `virtualSpanToSourceSpans` (region-ventilation): a line whose
+ * source range is split across two clips — or played twice by a duplicated clip —
+ * yields one timeline span per covering clip, so the caption appears wherever
+ * its audio actually plays and nowhere else. A span no clip plays yields [].
+ */
+export function sourceSpanToTimelineSpans(
+ assetId: string,
+ startSec: number,
+ endSec: number,
+ clips: AxcutClip[],
+): Array<{ startSec: number; endSec: number }> {
+ const out: Array<{ startSec: number; endSec: number }> = [];
+ for (const clip of clips) {
+ if (clip.assetId !== assetId) continue;
+ const clipSourceEnd = clip.sourceEndSec ?? Number.POSITIVE_INFINITY;
+ const s = Math.max(startSec, clip.sourceStartSec);
+ const e = Math.min(endSec, clipSourceEnd);
+ if (e <= s) continue;
+ out.push({
+ startSec: clip.timelineStartSec + (s - clip.sourceStartSec),
+ endSec: clip.timelineStartSec + (e - clip.sourceStartSec),
+ });
+ }
+ return out;
+}
+
+/**
+ * Every caption cue for the document, in VIRTUAL (timeline) ms.
+ *
+ * Returns [] when the layer is off — the caller doesn't need to check twice, and
+ * "hidden" costs nothing to render.
+ */
+export function deriveCaptionCues(
+ document: AxcutDocument | null | undefined,
+ settings: CaptionSettings,
+ translations: CaptionTranslations,
+): CaptionCue[] {
+ if (!document || !settings.enabled) return [];
+ const clips = document.timeline.clips;
+ if (clips.length === 0) return [];
+
+ const transcripts = new Map(document.transcripts.map((t) => [t.assetId, t]));
+ // A transcript is only projected once per asset even when several clips draw
+ // from it (line grouping is the expensive part, clipping is cheap).
+ const linesByAsset = new Map<string, CaptionSegment[]>();
+ const cues: CaptionCue[] = [];
+ let n = 0;
+
+ for (const assetId of new Set(clips.map((c) => c.assetId))) {
+ const transcript = transcripts.get(assetId);
+ if (!transcript) continue;
+ linesByAsset.set(assetId, captionLinesForAsset(transcript, settings, translations));
+ }
+
+ for (const [assetId, lines] of linesByAsset) {
+ for (const line of lines) {
+ const text = line.text.trim();
+ if (!text) continue;
+ for (const span of sourceSpanToTimelineSpans(assetId, line.startSec, line.endSec, clips)) {
+ const startMs = Math.round(span.startSec * 1000);
+ const endMs = Math.max(Math.round(span.endSec * 1000), startMs + 1);
+ cues.push({ id: `caption-${n++}`, startMs, endMs, text });
+ }
+ }
+ }
+
+ cues.sort((a, b) => a.startMs - b.startMs || a.endMs - b.endMs);
+ // Lines from one asset can't overlap, but two clips playing overlapping
+ // source ranges can put two cues on the same instant. Keep the ruler honest
+ // by ending the earlier one where the later begins.
+ for (let i = 1; i < cues.length; i++) {
+ const prev = cues[i - 1];
+ const cur = cues[i];
+ if (prev.endMs > cur.startMs) prev.endMs = Math.max(prev.startMs + 1, cur.startMs);
+ }
+ return cues;
+}
+
+/** The cue playing at `timeMs`, or null. Ties go to the one that started later,
+ * which is what "the next line has taken over" looks like. */
+export function captionCueAt(cues: CaptionCue[], timeMs: number): CaptionCue | null {
+ let found: CaptionCue | null = null;
+ for (const cue of cues) {
+ if (timeMs >= cue.startMs && timeMs < cue.endMs) found = cue;
+ else if (cue.startMs > timeMs) break;
+ }
+ return found;
+}
+
+/**
+ * Cues as text annotation regions, so the export renderer draws captions through
+ * the exact same text path as annotations (wrapping, background plate,
+ * alignment) instead of a second, subtly-different implementation.
+ *
+ * These regions are synthetic: they are never stored in the document and carry
+ * no `annotationSource` marker, because they are not annotations.
+ */
+export function captionCuesToTextRegions(
+ cues: CaptionCue[],
+ settings: CaptionSettings,
+): AnnotationRegion[] {
+ const rect = captionBandRect(settings);
+ return cues.map((cue, index) => ({
+ id: cue.id,
+ startMs: cue.startMs,
+ endMs: cue.endMs,
+ type: "text" as const,
+ content: cue.text,
+ position: { x: rect.x, y: rect.y },
+ size: { width: rect.width, height: rect.height },
+ style: {
+ color: settings.color,
+ backgroundColor: captionBackgroundCss(settings),
+ fontSize: settings.fontSize,
+ fontFamily: settings.fontFamily,
+ fontWeight: settings.fontWeight,
+ fontStyle: "normal" as const,
+ textDecoration: "none" as const,
+ textAlign: settings.textAlign,
+ textAnimation: "none" as const,
+ },
+ zIndex: CAPTION_Z_INDEX_BASE + index,
+ }));
+}
diff --git a/src/lib/ai-edition/captions/index.ts b/src/lib/ai-edition/captions/index.ts
new file mode 100644
index 000000000..ad26aeac0
--- /dev/null
+++ b/src/lib/ai-edition/captions/index.ts
@@ -0,0 +1,31 @@
+export type { CaptionCue } from "./cues";
+export {
+ CAPTION_Z_INDEX_BASE,
+ captionCueAt,
+ captionCuesToTextRegions,
+ captionLinesForAsset,
+ deriveCaptionCues,
+ sourceSpanToTimelineSpans,
+} from "./cues";
+export type {
+ CaptionSettings,
+ CaptionSettingsPatch,
+ CaptionTextAlign,
+ CaptionVerticalPosition,
+} from "./settings";
+export {
+ CAPTION_BAND_HEIGHT_PCT,
+ captionBackgroundCss,
+ captionBandRect,
+ DEFAULT_CAPTION_SETTINGS,
+ getCaptionSettings,
+ patchCaptionSettings,
+} from "./settings";
+export type { CaptionTranslation, CaptionTranslations } from "./translations";
+export {
+ getCaptionTranslations,
+ putCaptionTranslation,
+ removeCaptionTranslation,
+ translationCoverage,
+ untranslatedSegments,
+} from "./translations";
diff --git a/src/lib/ai-edition/captions/settings.ts b/src/lib/ai-edition/captions/settings.ts
new file mode 100644
index 000000000..08739d3e8
--- /dev/null
+++ b/src/lib/ai-edition/captions/settings.ts
@@ -0,0 +1,216 @@
+// Typed read/write layer over `document.legacyEditor.captions`.
+//
+// Captions are NOT annotations. An annotation is a piece of content the user
+// authored and placed on the timeline; a caption is a *rendering* of the
+// transcript — the transcript stays the single source of truth and this object
+// only says how it should look and where. Nothing here stores caption text.
+//
+// Same envelope + same access pattern as `store/editorSettings.ts` (the
+// `legacyEditor` passthrough blob), so caption settings round-trip through save
+// / load / undo with every other appearance setting and need no schema bump.
+
+import type { AxcutDocument } from "../schema";
+
+/** Vertical anchor of the caption band inside the frame. */
+export type CaptionVerticalPosition = "top" | "middle" | "bottom";
+
+/** Horizontal alignment of the text inside the (always centred) caption band. */
+export type CaptionTextAlign = "left" | "center" | "right";
+
+export interface CaptionSettings {
+ /** Master show/hide for the whole caption layer (preview AND export). */
+ enabled: boolean;
+ /**
+ * Which language to display. `null` = the transcript's own language, i.e. the
+ * SSOT text verbatim. Any other value selects a non-destructive translation
+ * layer (see `translations.ts`) — the transcript is never rewritten.
+ */
+ language: string | null;
+ /** Pixels, in preview-space — same convention as `AnnotationTextStyle.fontSize`
+ * (the exporter rescales it by previewWidth → outputWidth). */
+ fontSize: number;
+ fontFamily: string;
+ fontWeight: "normal" | "bold";
+ color: string;
+ /** When false the text draws straight over the video with no plate behind it. */
+ backgroundEnabled: boolean;
+ /** Hex, no alpha — the alpha comes from `backgroundOpacity`. */
+ backgroundColor: string;
+ /** 0–1. */
+ backgroundOpacity: number;
+ verticalPosition: CaptionVerticalPosition;
+ textAlign: CaptionTextAlign;
+ /** Fine vertical nudge, in % of frame height, applied on top of the anchor. */
+ offsetY: number;
+ /** Caption band width, in % of frame width. */
+ width: number;
+ /** Lower bound on words shown at once. */
+ minWordsPerLine: number;
+ /** Upper bound on words shown at once. */
+ maxWordsPerLine: number;
+}
+
+export const DEFAULT_CAPTION_SETTINGS: CaptionSettings = {
+ enabled: false,
+ language: null,
+ fontSize: 26,
+ fontFamily: "Inter",
+ fontWeight: "bold",
+ color: "#ffffff",
+ backgroundEnabled: true,
+ backgroundColor: "#000000",
+ backgroundOpacity: 0.55,
+ verticalPosition: "bottom",
+ textAlign: "center",
+ offsetY: 0,
+ width: 80,
+ minWordsPerLine: 2,
+ maxWordsPerLine: 7,
+};
+
+/** Band height as a % of frame height. Generous enough for two wrapped lines at
+ * the default size; the renderers clip to it, so it is deliberately not tight. */
+export const CAPTION_BAND_HEIGHT_PCT = 22;
+
+/** Margin between the band and the frame edge for the top/bottom anchors, in %. */
+const CAPTION_EDGE_MARGIN_PCT = 3;
+
+const VERTICAL_POSITIONS: readonly CaptionVerticalPosition[] = ["top", "middle", "bottom"];
+const TEXT_ALIGNS: readonly CaptionTextAlign[] = ["left", "center", "right"];
+
+function isFiniteNumber(value: unknown): value is number {
+ return typeof value === "number" && Number.isFinite(value);
+}
+
+function clamp(value: number, min: number, max: number): number {
+ return Math.min(max, Math.max(min, value));
+}
+
+function readNumber(value: unknown, fallback: number, min: number, max: number): number {
+ return isFiniteNumber(value) ? clamp(value, min, max) : fallback;
+}
+
+function readBoolean(value: unknown, fallback: boolean): boolean {
+ return typeof value === "boolean" ? value : fallback;
+}
+
+function readString(value: unknown, fallback: string): string {
+ return typeof value === "string" && value.length > 0 ? value : fallback;
+}
+
+function readEnum<T extends string>(value: unknown, allowed: readonly T[], fallback: T): T {
+ return typeof value === "string" && (allowed as readonly string[]).includes(value)
+ ? (value as T)
+ : fallback;
+}
+
+function legacyBlob(doc: AxcutDocument | null | undefined): Record<string, unknown> | null {
+ const legacy = doc?.legacyEditor;
+ return typeof legacy === "object" && legacy !== null && !Array.isArray(legacy)
+ ? (legacy as Record<string, unknown>)
+ : null;
+}
+
+function storedCaptions(doc: AxcutDocument | null | undefined): Record<string, unknown> | null {
+ const stored = legacyBlob(doc)?.captions;
+ return typeof stored === "object" && stored !== null && !Array.isArray(stored)
+ ? (stored as Record<string, unknown>)
+ : null;
+}
+
+export function getCaptionSettings(doc: AxcutDocument | null | undefined): CaptionSettings {
+ const raw = storedCaptions(doc);
+ const d = DEFAULT_CAPTION_SETTINGS;
+ if (!raw) return { ...d };
+
+ const minWords = Math.round(readNumber(raw.minWordsPerLine, d.minWordsPerLine, 1, 12));
+ const maxWords = Math.round(readNumber(raw.maxWordsPerLine, d.maxWordsPerLine, 1, 12));
+
+ return {
+ enabled: readBoolean(raw.enabled, d.enabled),
+ // `null` is a meaningful value here ("show the original"), so an explicit
+ // null must survive; only a missing/garbage entry falls back to the default.
+ language: raw.language === null || typeof raw.language === "string" ? raw.language : d.language,
+ fontSize: readNumber(raw.fontSize, d.fontSize, 8, 200),
+ fontFamily: readString(raw.fontFamily, d.fontFamily),
+ fontWeight: readEnum(raw.fontWeight, ["normal", "bold"] as const, d.fontWeight),
+ color: readString(raw.color, d.color),
+ backgroundEnabled: readBoolean(raw.backgroundEnabled, d.backgroundEnabled),
+ backgroundColor: readString(raw.backgroundColor, d.backgroundColor),
+ backgroundOpacity: readNumber(raw.backgroundOpacity, d.backgroundOpacity, 0, 1),
+ verticalPosition: readEnum(raw.verticalPosition, VERTICAL_POSITIONS, d.verticalPosition),
+ textAlign: readEnum(raw.textAlign, TEXT_ALIGNS, d.textAlign),
+ offsetY: readNumber(raw.offsetY, d.offsetY, -45, 45),
+ width: readNumber(raw.width, d.width, 20, 100),
+ minWordsPerLine: Math.min(minWords, maxWords),
+ maxWordsPerLine: Math.max(minWords, maxWords),
+ };
+}
+
+export type CaptionSettingsPatch = Partial<CaptionSettings>;
+
+/** Apply a patch and return the new document. Pure — no persistence. */
+export function patchCaptionSettings(
+ doc: AxcutDocument,
+ patch: CaptionSettingsPatch,
+): AxcutDocument {
+ const next: CaptionSettings = { ...getCaptionSettings(doc), ...patch };
+ return {
+ ...doc,
+ legacyEditor: {
+ ...(legacyBlob(doc) ?? {}),
+ captions: next,
+ } as Record<string, unknown>,
+ };
+}
+
+/** Where the caption band sits in the frame, as annotation-style percentages. */
+export interface CaptionBandRect {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+/**
+ * The band is always horizontally centred — `textAlign` aligns the text *inside*
+ * it, which is how subtitles behave everywhere. Vertical placement is the anchor
+ * preset plus the user's nudge, clamped so the band can never leave the frame.
+ */
+export function captionBandRect(settings: CaptionSettings): CaptionBandRect {
+ const width = clamp(settings.width, 20, 100);
+ const height = CAPTION_BAND_HEIGHT_PCT;
+ const anchorY =
+ settings.verticalPosition === "top"
+ ? CAPTION_EDGE_MARGIN_PCT
+ : settings.verticalPosition === "middle"
+ ? (100 - height) / 2
+ : 100 - height - CAPTION_EDGE_MARGIN_PCT;
+ return {
+ x: (100 - width) / 2,
+ y: clamp(anchorY + settings.offsetY, 0, 100 - height),
+ width,
+ height,
+ };
+}
+
+/** `backgroundColor` + `backgroundOpacity` as one CSS/canvas colour, or
+ * `"transparent"` when the plate is off. */
+export function captionBackgroundCss(settings: CaptionSettings): string {
+ if (!settings.backgroundEnabled) return "transparent";
+ const hex = settings.backgroundColor.replace("#", "");
+ const full =
+ hex.length === 3
+ ? hex
+ .split("")
+ .map((c) => c + c)
+ .join("")
+ : hex;
+ const r = Number.parseInt(full.slice(0, 2), 16);
+ const g = Number.parseInt(full.slice(2, 4), 16);
+ const b = Number.parseInt(full.slice(4, 6), 16);
+ if (!Number.isFinite(r) || !Number.isFinite(g) || !Number.isFinite(b)) {
+ return `rgba(0, 0, 0, ${clamp(settings.backgroundOpacity, 0, 1)})`;
+ }
+ return `rgba(${r}, ${g}, ${b}, ${clamp(settings.backgroundOpacity, 0, 1)})`;
+}
diff --git a/src/lib/ai-edition/captions/translations.ts b/src/lib/ai-edition/captions/translations.ts
new file mode 100644
index 000000000..e51569ccc
--- /dev/null
+++ b/src/lib/ai-edition/captions/translations.ts
@@ -0,0 +1,164 @@
+// Non-destructive translation layer for captions.
+//
+// The rule this module exists to enforce: **the transcript is the SSOT and is
+// never rewritten**. A translation is a side table keyed by transcript segment
+// id — timings, word boundaries and the original text all stay untouched, so
+// switching back to the original language is a no-op read and re-transcribing
+// never silently loses a translation's *timing* (only text whose segment id
+// vanished becomes unused).
+//
+// Keying by segment id (not by caption line) is deliberate: caption lines are a
+// derived, settings-dependent grouping — change "words per line" and every line
+// boundary moves — whereas a segment is a stable unit of the transcript.
+//
+// Stored in the `legacyEditor` passthrough envelope, like `settings.ts`.
+
+import type { AxcutDocument, AxcutTranscript } from "../schema";
+
+export interface CaptionTranslation {
+ /** Language code as chosen by the user, e.g. `"fr"`, `"pt-BR"`. */
+ language: string;
+ /** Human-readable name for the picker, e.g. `"Français"`. */
+ label: string;
+ /** ISO timestamp of the last (re)translation. */
+ updatedAt: string;
+ /** Model that produced it, for provenance in the UI. */
+ model?: string;
+ /** assetId → (transcript segment id → translated text). */
+ byAsset: Record<string, Record<string, string>>;
+}
+
+/** language code → translation. */
+export type CaptionTranslations = Record<string, CaptionTranslation>;
+
+function legacyBlob(doc: AxcutDocument | null | undefined): Record<string, unknown> | null {
+ const legacy = doc?.legacyEditor;
+ return typeof legacy === "object" && legacy !== null && !Array.isArray(legacy)
+ ? (legacy as Record<string, unknown>)
+ : null;
+}
+
+function isPlainObject(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function readStringMap(value: unknown): Record<string, string> {
+ if (!isPlainObject(value)) return {};
+ const out: Record<string, string> = {};
+ for (const [key, entry] of Object.entries(value)) {
+ if (typeof entry === "string") out[key] = entry;
+ }
+ return out;
+}
+
+export function getCaptionTranslations(doc: AxcutDocument | null | undefined): CaptionTranslations {
+ const raw = legacyBlob(doc)?.captionTranslations;
+ if (!isPlainObject(raw)) return {};
+
+ const out: CaptionTranslations = {};
+ for (const [language, entry] of Object.entries(raw)) {
+ if (!isPlainObject(entry)) continue;
+ const byAssetRaw = entry.byAsset;
+ const byAsset: Record<string, Record<string, string>> = {};
+ if (isPlainObject(byAssetRaw)) {
+ for (const [assetId, segments] of Object.entries(byAssetRaw)) {
+ byAsset[assetId] = readStringMap(segments);
+ }
+ }
+ out[language] = {
+ language,
+ label: typeof entry.label === "string" && entry.label ? entry.label : language,
+ updatedAt: typeof entry.updatedAt === "string" ? entry.updatedAt : "",
+ ...(typeof entry.model === "string" ? { model: entry.model } : {}),
+ byAsset,
+ };
+ }
+ return out;
+}
+
+/**
+ * Merge one asset's translated segments into a language layer, creating the
+ * layer if it doesn't exist. Merging (rather than replacing) is what lets a
+ * multi-asset project be translated one asset at a time, and lets a re-run over
+ * a subset of segments patch just those.
+ */
+export function putCaptionTranslation(
+ doc: AxcutDocument,
+ input: {
+ language: string;
+ label: string;
+ assetId: string;
+ segments: Record<string, string>;
+ model?: string;
+ updatedAt?: string;
+ },
+): AxcutDocument {
+ const existing = getCaptionTranslations(doc);
+ const previous = existing[input.language];
+ const merged: CaptionTranslation = {
+ language: input.language,
+ label: input.label || previous?.label || input.language,
+ updatedAt: input.updatedAt ?? new Date().toISOString(),
+ ...(input.model ? { model: input.model } : previous?.model ? { model: previous.model } : {}),
+ byAsset: {
+ ...(previous?.byAsset ?? {}),
+ [input.assetId]: {
+ ...(previous?.byAsset?.[input.assetId] ?? {}),
+ ...input.segments,
+ },
+ },
+ };
+
+ return {
+ ...doc,
+ legacyEditor: {
+ ...(legacyBlob(doc) ?? {}),
+ captionTranslations: { ...existing, [input.language]: merged },
+ } as Record<string, unknown>,
+ };
+}
+
+/** Drop a whole language layer. The transcript is unaffected, by construction. */
+export function removeCaptionTranslation(doc: AxcutDocument, language: string): AxcutDocument {
+ const existing = getCaptionTranslations(doc);
+ if (!(language in existing)) return doc;
+ const { [language]: _dropped, ...rest } = existing;
+ return {
+ ...doc,
+ legacyEditor: {
+ ...(legacyBlob(doc) ?? {}),
+ captionTranslations: rest,
+ } as Record<string, unknown>,
+ };
+}
+
+/**
+ * Segments of `transcript` that have no text yet in `language` — the work list
+ * for a (re)translation run, so an interrupted or extended translation only
+ * costs the missing pieces.
+ */
+export function untranslatedSegments(
+ transcript: AxcutTranscript,
+ translations: CaptionTranslations,
+ language: string,
+): AxcutTranscript["segments"] {
+ const done = translations[language]?.byAsset[transcript.assetId] ?? {};
+ return transcript.segments.filter((segment) => {
+ if (!segment.text.trim()) return false;
+ const existing = done[segment.id];
+ return typeof existing !== "string" || existing.trim().length === 0;
+ });
+}
+
+/** How much of one asset's transcript is covered by a language layer. */
+export function translationCoverage(
+ transcript: AxcutTranscript,
+ translations: CaptionTranslations,
+ language: string,
+): { translated: number; total: number } {
+ const total = transcript.segments.filter((s) => s.text.trim()).length;
+ return {
+ translated: total - untranslatedSegments(transcript, translations, language).length,
+ total,
+ };
+}
diff --git a/src/lib/ai-edition/exporter/documentExporter.ts b/src/lib/ai-edition/exporter/documentExporter.ts
index 0bcfabcf2..48f8b0c5a 100644
--- a/src/lib/ai-edition/exporter/documentExporter.ts
+++ b/src/lib/ai-edition/exporter/documentExporter.ts
@@ -39,6 +39,12 @@ import {
getAspectRatioValue,
getNativeAspectRatioValue,
} from "@/utils/aspectRatioUtils";
+import {
+ captionCuesToTextRegions,
+ deriveCaptionCues,
+ getCaptionSettings,
+ getCaptionTranslations,
+} from "../captions";
import { createId } from "../document/ids";
import { type Interval, normalizeIntervals, primaryAssetDuration } from "../document/timeline";
import type { AxcutAsset, AxcutDocument } from "../schema";
@@ -219,8 +225,18 @@ export async function exportAxcutDocument(
clips,
() => createId("zoom"),
);
+ // Captions are derived from the transcript at export time, never stored — so a
+ // project exported after re-transcribing or after a style change always writes
+ // the captions the editor was showing, with no regeneration step in between.
+ // They ride the annotation text renderer (same wrapping/plate/alignment) and
+ // go through the same virtual→source projection, so preview and file agree.
+ const captionSettings = getCaptionSettings(document);
+ const captionRegions = captionCuesToTextRegions(
+ deriveCaptionCues(document, captionSettings, getCaptionTranslations(document)),
+ captionSettings,
+ );
const annotationRegions = projectRegionsToSourceTime(
- document.annotations as unknown as AnnotationRegion[],
+ [...(document.annotations as unknown as AnnotationRegion[]), ...captionRegions],
clips,
() => createId("ann"),
);
diff --git a/src/lib/ai-edition/exporter/renderPlan.ts b/src/lib/ai-edition/exporter/renderPlan.ts
index e6bf627d3..662853c92 100644
--- a/src/lib/ai-edition/exporter/renderPlan.ts
+++ b/src/lib/ai-edition/exporter/renderPlan.ts
@@ -36,6 +36,12 @@ import {
getAspectRatioValue,
getNativeAspectRatioValue,
} from "@/utils/aspectRatioUtils";
+import {
+ captionCuesToTextRegions,
+ deriveCaptionCues,
+ getCaptionSettings,
+ getCaptionTranslations,
+} from "../captions";
import { type Interval, normalizeIntervals } from "../document/timeline";
import type { AxcutDocument } from "../schema";
import { resolveClipSourceEndSec } from "../timeline/clipDuration";
@@ -319,7 +325,19 @@ export function buildRenderPlan(
// --- Effects (virtual time, pass-through, NO projection) ---
const zoomRegions = document.zoomRanges as unknown as ZoomRegion[];
- const annotationRegions = document.annotations as unknown as AnnotationRegion[];
+ // Captions are derived from the transcript and joined to the annotations here,
+ // because they render through the same text path. They must be part of the plan
+ // (and not only of the legacy config) or the segment-loop renderer would export
+ // a caption-less file — and `isIdentityFastPathEligible` would happily
+ // stream-copy a video whose captions never got drawn.
+ const captionSettings = getCaptionSettings(document);
+ const annotationRegions = [
+ ...(document.annotations as unknown as AnnotationRegion[]),
+ ...captionCuesToTextRegions(
+ deriveCaptionCues(document, captionSettings, getCaptionTranslations(document)),
+ captionSettings,
+ ),
+ ];
const speedRegions = extractLegacyField<SpeedRegion[]>(legacy, "speedRegions", []);
// --- Appearance ---
diff --git a/src/lib/ai-edition/store/useCaptions.ts b/src/lib/ai-edition/store/useCaptions.ts
new file mode 100644
index 000000000..981be3cf8
--- /dev/null
+++ b/src/lib/ai-edition/store/useCaptions.ts
@@ -0,0 +1,128 @@
+// React binding over the caption modules.
+//
+// Same contract as `useEditorSettings`: `set` writes + persists, `setLive`
+// writes only (for sliders), `commit` flushes. The document stays the single
+// source of truth — nothing is cached here.
+
+import { useCallback, useMemo } from "react";
+import {
+ type CaptionCue,
+ type CaptionSettings,
+ type CaptionSettingsPatch,
+ type CaptionTranslations,
+ deriveCaptionCues,
+ getCaptionSettings,
+ getCaptionTranslations,
+ patchCaptionSettings,
+ putCaptionTranslation,
+ removeCaptionTranslation,
+} from "../captions";
+import { useProjectStore } from "./projectStore";
+
+export interface UseCaptionsResult {
+ settings: CaptionSettings;
+ translations: CaptionTranslations;
+ /** Every cue for the current document, in timeline ms. `[]` when hidden. */
+ cues: CaptionCue[];
+ /** True when there's a project loaded — the writers are no-ops otherwise. */
+ hasDocument: boolean;
+ /** True when at least one clip's asset has a transcript to caption. */
+ hasTranscript: boolean;
+ set: (patch: CaptionSettingsPatch) => Promise<void>;
+ setLive: (patch: CaptionSettingsPatch) => void;
+ commit: () => Promise<void>;
+ saveTranslation: (input: {
+ language: string;
+ label: string;
+ assetId: string;
+ segments: Record<string, string>;
+ model?: string;
+ }) => Promise<void>;
+ deleteTranslation: (language: string) => Promise<void>;
+}
+
+export function useCaptions(): UseCaptionsResult {
+ const document = useProjectStore((s) => s.document);
+ const setDocument = useProjectStore((s) => s.setDocument);
+ const saveDocument = useProjectStore((s) => s.saveDocument);
+
+ const settings = useMemo(() => getCaptionSettings(document), [document]);
+ const translations = useMemo(() => getCaptionTranslations(document), [document]);
+ const cues = useMemo(
+ () => deriveCaptionCues(document, settings, translations),
+ [document, settings, translations],
+ );
+
+ const hasTranscript = useMemo(() => {
+ if (!document) return false;
+ const withTranscript = new Set(document.transcripts.map((t) => t.assetId));
+ return document.timeline.clips.some((clip) => withTranscript.has(clip.assetId));
+ }, [document]);
+
+ const set = useCallback(
+ async (patch: CaptionSettingsPatch) => {
+ const doc = useProjectStore.getState().document;
+ if (!doc) return;
+ const next = patchCaptionSettings(doc, patch);
+ setDocument(next);
+ await saveDocument(next);
+ },
+ [setDocument, saveDocument],
+ );
+
+ const setLive = useCallback(
+ (patch: CaptionSettingsPatch) => {
+ const doc = useProjectStore.getState().document;
+ if (!doc) return;
+ setDocument(patchCaptionSettings(doc, patch));
+ },
+ [setDocument],
+ );
+
+ const commit = useCallback(async () => {
+ const doc = useProjectStore.getState().document;
+ if (!doc) return;
+ await saveDocument(doc);
+ }, [saveDocument]);
+
+ const saveTranslation = useCallback<UseCaptionsResult["saveTranslation"]>(
+ async (input) => {
+ const doc = useProjectStore.getState().document;
+ if (!doc) return;
+ const next = putCaptionTranslation(doc, input);
+ setDocument(next);
+ await saveDocument(next);
+ },
+ [setDocument, saveDocument],
+ );
+
+ const deleteTranslation = useCallback(
+ async (language: string) => {
+ const doc = useProjectStore.getState().document;
+ if (!doc) return;
+ // Falling back to the original is the only sane landing spot when the
+ // language currently on screen is the one being deleted.
+ const cleared = removeCaptionTranslation(doc, language);
+ const next =
+ getCaptionSettings(cleared).language === language
+ ? patchCaptionSettings(cleared, { language: null })
+ : cleared;
+ setDocument(next);
+ await saveDocument(next);
+ },
+ [setDocument, saveDocument],
+ );
+
+ return {
+ settings,
+ translations,
+ cues,
+ hasDocument: document !== null,
+ hasTranscript,
+ set,
+ setLive,
+ commit,
+ saveTranslation,
+ deleteTranslation,
+ };
+}
diff --git a/src/lib/captioning/annotationsFromCaptions.test.ts b/src/lib/captioning/annotationsFromCaptions.test.ts
index bbf26fed2..927f6330a 100644
--- a/src/lib/captioning/annotationsFromCaptions.test.ts
+++ b/src/lib/captioning/annotationsFromCaptions.test.ts
@@ -1,10 +1,10 @@
import { describe, expect, it } from "vitest";
import {
- captionSegmentsToAnnotationRegions,
+ dedupeAdjacentCaptionRepeats,
+ finalizeCaptionSegmentsForPlayback,
groupPhraseCaptionSegmentsIntoLines,
groupTimedCaptionWordsIntoLines,
- reconcileAutoCaptionTimelineGaps,
} from "./annotationsFromCaptions";
describe("groupPhraseCaptionSegmentsIntoLines", () => {
@@ -45,23 +45,7 @@ describe("groupPhraseCaptionSegmentsIntoLines", () => {
});
});
-describe("captionSegmentsToAnnotationRegions", () => {
- it("uses raw phrase timing instead of shifting caption boundaries", () => {
- const { regions } = captionSegmentsToAnnotationRegions(
- [
- { startSec: 0, endSec: 0.5, text: "first second" },
- { startSec: 0.62, endSec: 1.2, text: "third fourth" },
- ],
- 1,
- 1,
- { minWordsPerCaption: 2, maxWordsPerCaption: 2, timestampGranularity: "phrase" },
- );
-
- expect(regions).toHaveLength(2);
- expect(regions[0]).toMatchObject({ startMs: 0, endMs: 500 });
- expect(regions[1]).toMatchObject({ startMs: 620, endMs: 1200 });
- });
-
+describe("groupTimedCaptionWordsIntoLines", () => {
it("preserves empty timeline space when word timestamps contain a real pause", () => {
const lines = groupTimedCaptionWordsIntoLines(
[
@@ -79,100 +63,50 @@ describe("captionSegmentsToAnnotationRegions", () => {
expect(lines[1]).toMatchObject({ startSec: 0.7, endSec: 0.98, text: "second caption" });
});
- it("preserves repeated words before grouping in word mode", () => {
- const { regions } = captionSegmentsToAnnotationRegions(
+ it("preserves repeated words instead of collapsing them into one token", () => {
+ const lines = groupTimedCaptionWordsIntoLines(
[
{ startSec: 0, endSec: 0.12, text: "I" },
{ startSec: 0.13, endSec: 0.25, text: "I" },
],
- 1,
- 1,
- { minWordsPerCaption: 2, maxWordsPerCaption: 2, timestampGranularity: "word" },
+ 2,
+ 2,
);
- expect(regions).toHaveLength(1);
- expect(regions[0]).toMatchObject({ content: "I I" });
+ expect(lines).toHaveLength(1);
+ expect(lines[0]).toMatchObject({ text: "I I" });
});
});
-describe("reconcileAutoCaptionTimelineGaps", () => {
- it("does not change regions when the minimum enforced gap is zero", () => {
- const regions = reconcileAutoCaptionTimelineGaps([
- {
- id: "annotation-1",
- startMs: 0,
- endMs: 120,
- type: "text",
- content: "one",
- annotationSource: "auto-caption",
- position: { x: 0, y: 0 },
- size: { width: 10, height: 10 },
- style: {
- color: "#fff",
- backgroundColor: "transparent",
- fontSize: 24,
- fontFamily: "Inter",
- fontWeight: "normal",
- fontStyle: "normal",
- textDecoration: "none",
- textAlign: "center",
- },
- zIndex: 1,
- },
- {
- id: "manual-1",
- startMs: 50,
- endMs: 1000,
- type: "text",
- content: "manual",
- position: { x: 10, y: 10 },
- size: { width: 10, height: 10 },
- style: {
- color: "#fff",
- backgroundColor: "transparent",
- fontSize: 24,
- fontFamily: "Inter",
- fontWeight: "normal",
- fontStyle: "normal",
- textDecoration: "none",
- textAlign: "center",
- },
- zIndex: 2,
- },
- {
- id: "annotation-2",
- startMs: 130,
- endMs: 300,
- type: "text",
- content: "two",
- annotationSource: "auto-caption",
- position: { x: 0, y: 0 },
- size: { width: 10, height: 10 },
- style: {
- color: "#fff",
- backgroundColor: "transparent",
- fontSize: 24,
- fontFamily: "Inter",
- fontWeight: "normal",
- fontStyle: "normal",
- textDecoration: "none",
- textAlign: "center",
- },
- zIndex: 3,
- },
+describe("dedupeAdjacentCaptionRepeats", () => {
+ it("merges the same line repeated across a chunk boundary", () => {
+ const lines = dedupeAdjacentCaptionRepeats([
+ { startSec: 0, endSec: 1, text: "hello there" },
+ { startSec: 0.9, endSec: 1.8, text: "Hello there." },
]);
- expect(regions.find((r) => r.id === "manual-1")).toMatchObject({
- startMs: 50,
- endMs: 1000,
- });
- expect(regions.find((r) => r.id === "annotation-1")).toMatchObject({
- startMs: 0,
- endMs: 120,
- });
- expect(regions.find((r) => r.id === "annotation-2")).toMatchObject({
- startMs: 130,
- endMs: 300,
- });
+ expect(lines).toHaveLength(1);
+ expect(lines[0]).toMatchObject({ startSec: 0, endSec: 1.8 });
+ });
+
+ it("keeps the same line spoken again after a real silence", () => {
+ const lines = dedupeAdjacentCaptionRepeats([
+ { startSec: 0, endSec: 1, text: "hello there" },
+ { startSec: 8, endSec: 9, text: "hello there" },
+ ]);
+
+ expect(lines).toHaveLength(2);
+ });
+});
+
+describe("finalizeCaptionSegmentsForPlayback", () => {
+ it("ends a line where the next one starts so two never show at once", () => {
+ const lines = finalizeCaptionSegmentsForPlayback([
+ { startSec: 0, endSec: 1.5, text: "first" },
+ { startSec: 1, endSec: 2, text: "second" },
+ ]);
+
+ expect(lines[0]!.endSec).toBeCloseTo(1, 5);
+ expect(lines[1]).toMatchObject({ startSec: 1, endSec: 2 });
});
});
diff --git a/src/lib/captioning/annotationsFromCaptions.ts b/src/lib/captioning/annotationsFromCaptions.ts
index c3e22b21d..0e2b84e68 100644
--- a/src/lib/captioning/annotationsFromCaptions.ts
+++ b/src/lib/captioning/annotationsFromCaptions.ts
@@ -1,30 +1,5 @@
-import type { AnnotationRegion, AnnotationTextStyle } from "@/components/video-editor/types";
-
import type { CaptionSegment } from "./transcribe";
-/** Wide lower-third bar; `position.x` is top-left as % of container, so center with (100 - width) / 2. */
-const CAPTION_WIDTH = 92;
-const CAPTION_HEIGHT = 12;
-const CAPTION_BOTTOM_MARGIN = 2;
-
-const CAPTION_POSITION = {
- x: (100 - CAPTION_WIDTH) / 2,
- y: 100 - CAPTION_HEIGHT - CAPTION_BOTTOM_MARGIN,
-};
-
-const CAPTION_SIZE = { width: CAPTION_WIDTH, height: CAPTION_HEIGHT };
-
-const CAPTION_STYLE: AnnotationTextStyle = {
- color: "#ffffff",
- backgroundColor: "rgba(255, 255, 255, 0)",
- fontSize: 24,
- fontFamily: "Inter",
- fontWeight: "normal",
- fontStyle: "normal",
- textDecoration: "none",
- textAlign: "center",
-};
-
/** Nudge caption starts earlier (seconds); Whisper onsets run slightly late. Do not offset ends too, that pulls lines off-screen early. */
const AUTO_CAPTION_START_BIAS_SEC = 0;
@@ -40,9 +15,6 @@ const CAPTION_LINE_END_TAIL_SEC = 0;
/** A real silence between word-level timestamps should start a new caption run. */
const WORD_RUN_BREAK_GAP_SEC = 0.24;
-/** Min time between consecutive caption regions (seconds); keeps a visible gap so blocks don't read as one clip. Small so short pauses survive. */
-const MIN_CAPTION_TIMELINE_GAP_SEC = 0;
-
/** Same text again with almost no gap or overlap; common Whisper/chunk artifact. */
const DEDUPE_SAME_TEXT_MAX_GAP_SEC = 0.55;
@@ -91,7 +63,7 @@ export function collapseSameContentEchoes(segments: CaptionSegment[]): CaptionSe
* Collapse adjacent duplicate lines (overlapping or tiny gap). Does not merge the same phrase
* repeated later in the video when separated by real silence.
*/
-function dedupeAdjacentCaptionRepeats(segments: CaptionSegment[]): CaptionSegment[] {
+export function dedupeAdjacentCaptionRepeats(segments: CaptionSegment[]): CaptionSegment[] {
const sorted = [...segments]
.filter((s) => s.text.trim())
.sort((a, b) => a.startSec - b.startSec || a.endSec - b.endSec);
@@ -114,7 +86,7 @@ function dedupeAdjacentCaptionRepeats(segments: CaptionSegment[]): CaptionSegmen
}
/** Trim only real overlaps. Avoid synthetic lead/lag so caption timing matches model output. */
-function finalizeCaptionSegmentsForPlayback(segments: CaptionSegment[]): CaptionSegment[] {
+export function finalizeCaptionSegmentsForPlayback(segments: CaptionSegment[]): CaptionSegment[] {
const OVERLAP_TRIM_SEC = 0.002;
const sortedRaw = [...segments]
@@ -138,51 +110,6 @@ function finalizeCaptionSegmentsForPlayback(segments: CaptionSegment[]): Caption
return a;
}
-/** Default min gap between auto-caption blocks on the timeline (ms); matches `MIN_CAPTION_TIMELINE_GAP_SEC`. */
-export const DEFAULT_AUTO_CAPTION_MIN_GAP_MS = Math.round(MIN_CAPTION_TIMELINE_GAP_SEC * 1000);
-
-/**
- * Enforce a min gap between consecutive `auto-caption` regions (by start time). Shortens the previous
- * region's end when possible, else shifts the following region later so blocks can't sit completely flush.
- */
-export function reconcileAutoCaptionTimelineGaps(
- regions: AnnotationRegion[],
- minGapMs: number = DEFAULT_AUTO_CAPTION_MIN_GAP_MS,
-): AnnotationRegion[] {
- const gap = Math.max(0, Math.round(minGapMs));
- if (regions.length === 0 || gap === 0) return regions;
-
- const autoCandidates = regions.filter((r) => r.annotationSource === "auto-caption");
- if (autoCandidates.length <= 1) return regions;
-
- const sorted = [...autoCandidates].sort((a, b) => a.startMs - b.startMs || a.endMs - b.endMs);
- const fixed: AnnotationRegion[] = [];
- let prev = { ...sorted[0]! };
- fixed.push(prev);
-
- for (let i = 1; i < sorted.length; i++) {
- let cur = { ...sorted[i]! };
- const minStart = prev.endMs + gap;
-
- if (cur.startMs < minStart) {
- const newPrevEnd = cur.startMs - gap;
- if (newPrevEnd >= prev.startMs + 1) {
- prev = { ...prev, endMs: newPrevEnd };
- fixed[fixed.length - 1] = prev;
- } else {
- const dur = Math.max(1, cur.endMs - cur.startMs);
- cur = { ...cur, startMs: minStart, endMs: minStart + dur };
- }
- }
-
- fixed.push(cur);
- prev = cur;
- }
-
- const fixedById = new Map(fixed.map((r) => [r.id, r]));
- return regions.map((r) => fixedById.get(r.id) ?? r);
-}
-
/** Join phrases that are close in time so the editor does not create dozens of separate overlays. */
export function mergeAdjacentCaptionSegments(
segments: CaptionSegment[],
@@ -540,65 +467,3 @@ function splitOneSegmentByWordBounds(
}
return result;
}
-
-export function captionSegmentsToAnnotationRegions(
- segments: CaptionSegment[],
- startNumericId: number,
- startZIndex: number,
- layout?: CaptionSegmentLayoutOptions,
-): { regions: AnnotationRegion[]; nextNumericId: number; nextZIndex: number } {
- // Don't echo-collapse raw word tokens before grouping: repeated words ("I … I") share a
- // normalized key and would merge spans while keeping only the first token's text.
- const minW = layout?.minWordsPerCaption ?? 2;
- const maxW = layout?.maxWordsPerCaption ?? 7;
- const granularity = layout?.timestampGranularity ?? "word";
-
- const grouped =
- granularity === "phrase"
- ? groupPhraseCaptionSegmentsIntoLines(segments, minW, maxW)
- : groupTimedCaptionWordsIntoLines(segments, minW, maxW);
-
- const dedupedOut = dedupeAdjacentCaptionRepeats(grouped);
- const finalized = finalizeCaptionSegmentsForPlayback(dedupedOut);
-
- let nid = startNumericId;
- let z = startZIndex;
- const regions: AnnotationRegion[] = [];
-
- for (const seg of finalized) {
- const startMs = Math.round(seg.startSec * 1000);
- const endMs = Math.max(Math.round(seg.endSec * 1000), startMs + 1);
- regions.push({
- id: `annotation-${nid++}`,
- startMs,
- endMs,
- type: "text",
- content: seg.text,
- annotationSource: "auto-caption",
- position: { ...CAPTION_POSITION },
- size: { ...CAPTION_SIZE },
- style: { ...CAPTION_STYLE },
- zIndex: z++,
- });
- }
-
- return {
- regions: reconcileAutoCaptionTimelineGaps(regions),
- nextNumericId: nid,
- nextZIndex: z,
- };
-}
-
-export function maxAnnotationNumericId(regions: AnnotationRegion[]): number {
- let max = 0;
- for (const r of regions) {
- const m = /^annotation-(\d+)$/.exec(r.id);
- if (m) max = Math.max(max, Number.parseInt(m[1], 10));
- }
- return max;
-}
-
-export function maxAnnotationZIndex(regions: AnnotationRegion[]): number {
- if (regions.length === 0) return 0;
- return Math.max(...regions.map((r) => r.zIndex));
-}
diff --git a/src/lib/captioning/index.ts b/src/lib/captioning/index.ts
index a34ac20f9..99da5a1f0 100644
--- a/src/lib/captioning/index.ts
+++ b/src/lib/captioning/index.ts
@@ -1,10 +1,9 @@
export type { CaptionSegmentLayoutOptions } from "./annotationsFromCaptions";
export {
- captionSegmentsToAnnotationRegions,
- DEFAULT_AUTO_CAPTION_MIN_GAP_MS,
+ dedupeAdjacentCaptionRepeats,
+ finalizeCaptionSegmentsForPlayback,
groupTimedCaptionWordsIntoLines,
mergeAdjacentCaptionSegments,
- reconcileAutoCaptionTimelineGaps,
splitMergedCaptionsByWordBounds,
} from "./annotationsFromCaptions";
export { extractMono16kFromVideoUrl, MAX_CAPTION_AUDIO_SEC } from "./extractMono16k";
diff --git a/src/native/browserShim.ts b/src/native/browserShim.ts
index d5777f474..fbe2106eb 100644
--- a/src/native/browserShim.ts
+++ b/src/native/browserShim.ts
@@ -585,6 +585,15 @@ function createShimBridgeClient() {
summary: "(browser shim compaction is a no-op)",
});
},
+ // ponytail: no provider credentials in browser mode, so this reports the
+ // same "configure a provider" failure the real bridge would, rather than
+ // inventing fake translations that would land in the document.
+ translateCaptions: () =>
+ Promise.resolve({
+ success: false,
+ segments: {},
+ error: "Caption translation needs the desktop app's AI provider.",
+ }),
},
project: {
getCurrentContext: () =>
diff --git a/src/native/client.ts b/src/native/client.ts
index 3fa9db5d0..a40a5100e 100644
--- a/src/native/client.ts
+++ b/src/native/client.ts
@@ -1,5 +1,6 @@
import {
type AiEditionAssetResult,
+ type AiEditionCaptionTranslateResult,
type AiEditionChatBudget,
type AiEditionChatCompactResult,
type AiEditionChatMessage,
@@ -353,6 +354,19 @@ export const nativeBridgeClient = {
action: "chat.compactNow",
payload: { projectId, sessionId },
}),
+ /** Translate transcript segments for the caption layer through the
+ * configured chat provider. Returns segmentId → translated text; the
+ * caller stores it in the caption translation layer. */
+ translateCaptions: (input: {
+ segments: Array<{ id: string; text: string }>;
+ targetLanguage: string;
+ sourceLanguage?: string;
+ }) =>
+ requireNativeBridgeData<AiEditionCaptionTranslateResult>({
+ domain: "aiEdition",
+ action: "captions.translate",
+ payload: input,
+ }),
runTimelineOperation: (
projectId: string,
sessionId: string,
diff --git a/src/native/contracts.ts b/src/native/contracts.ts
index 5b638e1ec..b8518b6eb 100644
--- a/src/native/contracts.ts
+++ b/src/native/contracts.ts
@@ -313,6 +313,20 @@ export interface AiEditionChatCompactResult {
summary: string;
}
+/**
+ * Result of a caption translation run. `segments` maps TRANSCRIPT SEGMENT ID →
+ * translated text; it is written into the document's caption translation layer,
+ * never back onto the transcript. Partial maps are valid — a run that fails
+ * halfway still returns what it managed to translate.
+ */
+export interface AiEditionCaptionTranslateResult {
+ success: boolean;
+ segments: Record<string, string>;
+ /** Model that produced the translation, for provenance in the UI. */
+ model?: string;
+ error?: string;
+}
+
export type NativeBridgeErrorCode =
| "INVALID_REQUEST"
| "UNSUPPORTED_ACTION"
@@ -644,6 +658,19 @@ export type NativeBridgeRequest =
payload: { projectId: string; sessionId: string };
requestId?: string;
}
+ | {
+ domain: "aiEdition";
+ action: "captions.translate";
+ /** `segments` are TRANSCRIPT segments, sent by id so the reply can be
+ * re-keyed exactly. Stateless: no projectId, and nothing is written to
+ * the document on the main side. */
+ payload: {
+ segments: Array<{ id: string; text: string }>;
+ targetLanguage: string;
+ sourceLanguage?: string;
+ };
+ requestId?: string;
+ }
| {
domain: "aiEdition";
action: "timeline.run";