From cb52b9351a6213bcbd78d66a5f769d83b6b794af Mon Sep 17 00:00:00 2001
From: Darun Ramalingam
Date: Mon, 23 Nov 2026 23:04:23 -0600
Subject: [PATCH 1/3] feat(studio): download matching caption track (D10)
---
.../src/app/w/[workspaceSlug]/studio/page.tsx | 15 +++-
.../product/caption-download-state.test.ts | 35 ++++++++
.../product/caption-download-state.ts | 24 ++++++
.../components/product/caption-download.tsx | 83 +++++++++++++++++++
4 files changed, 154 insertions(+), 3 deletions(-)
create mode 100644 apps/web/src/components/product/caption-download-state.test.ts
create mode 100644 apps/web/src/components/product/caption-download-state.ts
create mode 100644 apps/web/src/components/product/caption-download.tsx
diff --git a/apps/web/src/app/w/[workspaceSlug]/studio/page.tsx b/apps/web/src/app/w/[workspaceSlug]/studio/page.tsx
index d68bad8..c5e04ca 100644
--- a/apps/web/src/app/w/[workspaceSlug]/studio/page.tsx
+++ b/apps/web/src/app/w/[workspaceSlug]/studio/page.tsx
@@ -5,6 +5,8 @@ import { scriptSchema, type ScriptOutput } from "@contentforge/ai";
import { LocalObjectStorageProvider, localStorageRoot } from "@contentforge/media";
import { Badge, Card, CardContent } from "@contentforge/ui";
import { PageHeading } from "@/components/product/page-heading";
+import { CaptionDownload } from "@/components/product/caption-download";
+import { matchingCaptionTrack } from "@/components/product/caption-download-state";
import { ActionButton, RecordForm, ScheduleForm } from "@/components/product/workflow-actions";
import { ScriptEditor } from "@/components/product/script-editor";
import { getWorkspaceContext } from "@/server/services/workspace-context";
@@ -112,9 +114,9 @@ export default async function StudioPage({
const videoUrl = output
? await storage.createSignedDownloadUrl(output.storageKey, 3600)
: undefined;
- const caption = saved?.captionTracks.find((t) => t.format === "WEBVTT");
+ const caption = matchingCaptionTrack(output?.storageKey, saved?.captionTracks ?? []);
const captionUrl = caption
- ? await storage.createSignedDownloadUrl(caption.storageKey, 3600)
+ ? await storage.createSignedDownloadUrl(caption.storageKey, 3600).catch(() => undefined)
: undefined;
const versions = await prisma.contentVersion.findMany({
where: { workspaceId: ctx.workspace.id, contentItemId: content.id },
@@ -175,7 +177,7 @@ export default async function StudioPage({
src={videoUrl}
className="w-full rounded-xl"
>
- {captionUrl && (
+ {captionUrl && caption?.format === "WEBVTT" && (
)}
@@ -191,6 +193,13 @@ export default async function StudioPage({
accounts={accounts}
/>
)}
+ {videoUrl && (
+
+ )}
Workflow history
diff --git a/apps/web/src/components/product/caption-download-state.test.ts b/apps/web/src/components/product/caption-download-state.test.ts
new file mode 100644
index 0000000..de469bf
--- /dev/null
+++ b/apps/web/src/components/product/caption-download-state.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from "vitest";
+import { captionDownloadError, matchingCaptionTrack } from "./caption-download-state";
+
+describe("matchingCaptionTrack", () => {
+ const video = "workspace/run-1/video-digest.mp4";
+ const vtt = { format: "WEBVTT", storageKey: "workspace/run-1/captions.vtt" };
+ const srt = { format: "SRT", storageKey: "workspace/run-1/captions.srt" };
+
+ it("prefers WebVTT and falls back to SRT for the same render", () => {
+ expect(matchingCaptionTrack(video, [srt, vtt])).toEqual(vtt);
+ expect(matchingCaptionTrack(video, [srt])).toEqual(srt);
+ });
+
+ it("rejects captions overwritten by a different workflow", () => {
+ const newer = { format: "WEBVTT", storageKey: "workspace/run-2/captions.vtt" };
+ expect(matchingCaptionTrack(video, [newer])).toBeUndefined();
+ expect(matchingCaptionTrack(video, [newer, srt])).toEqual(srt);
+ });
+
+ it("rejects different workspace, prefix collisions, missing or malformed output", () => {
+ expect(matchingCaptionTrack("other/run-1/video-digest.mp4", [vtt])).toBeUndefined();
+ expect(matchingCaptionTrack("workspace/run-10/video-digest.mp4", [vtt])).toBeUndefined();
+ expect(matchingCaptionTrack(undefined, [vtt])).toBeUndefined();
+ expect(matchingCaptionTrack("workspace/video.mp4", [vtt])).toBeUndefined();
+ expect(matchingCaptionTrack(video, [])).toBeUndefined();
+ });
+});
+
+describe("captionDownloadError", () => {
+ it("gives actionable messages for expired or missing signed media", () => {
+ expect(captionDownloadError(403)).toContain("expired");
+ expect(captionDownloadError(404)).toContain("unavailable");
+ expect(captionDownloadError(500)).toContain("retry");
+ });
+});
diff --git a/apps/web/src/components/product/caption-download-state.ts b/apps/web/src/components/product/caption-download-state.ts
new file mode 100644
index 0000000..e62d372
--- /dev/null
+++ b/apps/web/src/components/product/caption-download-state.ts
@@ -0,0 +1,24 @@
+interface Track {
+ format: string;
+ storageKey: string;
+}
+
+export function matchingCaptionTrack(
+ videoKey: string | undefined,
+ tracks: readonly T[],
+): T | undefined {
+ // Both outputs are stored under workspaceId/workflowRunId by the production worker.
+ // CaptionTrack rows are reused across runs, so scriptId or generationJobId is not enough.
+ const prefix = videoKey?.match(/^([^/]+\/[^/]+)\/video-[^/]+\.mp4$/)?.[1];
+ if (!prefix) return undefined;
+ return (
+ tracks.find((t) => t.format === "WEBVTT" && t.storageKey === `${prefix}/captions.vtt`) ??
+ tracks.find((t) => t.format === "SRT" && t.storageKey === `${prefix}/captions.srt`)
+ );
+}
+
+export function captionDownloadError(status: number): string {
+ if (status === 403) return "The caption link expired or is invalid. Refresh the link and retry.";
+ if (status === 404) return "The caption file is unavailable. Refresh the link and retry.";
+ return "Could not download captions. Please retry.";
+}
diff --git a/apps/web/src/components/product/caption-download.tsx b/apps/web/src/components/product/caption-download.tsx
new file mode 100644
index 0000000..ae4a6bd
--- /dev/null
+++ b/apps/web/src/components/product/caption-download.tsx
@@ -0,0 +1,83 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import { useRouter } from "next/navigation";
+import { captionDownloadError } from "./caption-download-state";
+
+export function CaptionDownload({
+ url,
+ extension,
+}: {
+ url?: string;
+ extension: "srt" | "vtt";
+}) {
+ const router = useRouter();
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState("");
+ const request = useRef(null);
+
+ useEffect(() => () => request.current?.abort(), []);
+
+ async function download() {
+ if (!url || request.current) return;
+ const controller = new AbortController();
+ request.current = controller;
+ setBusy(true);
+ setError("");
+ try {
+ const response = await fetch(url, { cache: "no-store", signal: controller.signal });
+ if (!response.ok) throw new Error(captionDownloadError(response.status));
+ const blob = await response.blob();
+ if (controller.signal.aborted) return;
+ if (!blob.size) throw new Error("The caption file is empty. Refresh the link and retry.");
+ const objectUrl = URL.createObjectURL(blob);
+ const link = document.createElement("a");
+ link.href = objectUrl;
+ link.download = `contentforge-captions.${extension}`;
+ document.body.appendChild(link);
+ try {
+ link.click();
+ } finally {
+ link.remove();
+ setTimeout(() => URL.revokeObjectURL(objectUrl), 1000);
+ }
+ } catch (err) {
+ if (!controller.signal.aborted)
+ setError(err instanceof Error ? err.message : "Could not download captions. Please retry.");
+ } finally {
+ request.current = null;
+ if (!controller.signal.aborted) setBusy(false);
+ }
+ }
+
+ return (
+
+ {url ? (
+
+ ) : (
+
Captions unavailable for this rendered video.
+ )}
+ {error && (
+
+ {error}
+
+ )}
+ {(!url || error) && (
+
+ )}
+
+ );
+}
From 42f9a8475efa3af064d20eff51fba986dbbb3cd4 Mon Sep 17 00:00:00 2001
From: Darun Ramalingam
Date: Mon, 23 Nov 2026 23:06:27 -0600
Subject: [PATCH 2/3] fix(studio): stabilize caption downloads and cover
expired links in browser
---
apps/web/e2e/production-flow.spec.ts | 24 +++++++++++++++++++
.../src/app/w/[workspaceSlug]/studio/page.tsx | 2 +-
.../components/product/caption-download.tsx | 24 +++++++++++--------
3 files changed, 39 insertions(+), 11 deletions(-)
diff --git a/apps/web/e2e/production-flow.spec.ts b/apps/web/e2e/production-flow.spec.ts
index b21a477..055d2a2 100644
--- a/apps/web/e2e/production-flow.spec.ts
+++ b/apps/web/e2e/production-flow.spec.ts
@@ -92,6 +92,30 @@ test("new campaign becomes an approved, published video with stored analytics",
await page.getByText("Open content in the studio", { exact: true }).click();
const video = page.getByLabel("Rendered content preview");
await expect(video).toBeVisible();
+ const captionButton = page.getByRole("button", { name: "Download Captions (VTT)" });
+ const captionUrl = await video.locator("track").getAttribute("src");
+ expect(captionUrl).toBeTruthy();
+ // Simulate an expired signed link without changing the persisted render.
+ const expiredCaption = (url: URL) =>
+ url.pathname === "/api/storage" && url.searchParams.get("key")?.endsWith("/captions.vtt") === true;
+ await page.route(expiredCaption, (route) => route.fulfill({ status: 403 }));
+ await captionButton.click();
+ await expect(page.getByRole("alert").filter({ hasText: "caption link expired" })).toBeVisible();
+ await page.unroute(expiredCaption);
+ await page.getByRole("button", { name: "Refresh caption link" }).click();
+ await expect(captionButton).toBeEnabled();
+ const [captions] = await Promise.all([page.waitForEvent("download"), captionButton.click()]);
+ expect(captions.suggestedFilename()).toBe("contentforge-captions.vtt");
+ expect(await captions.failure()).toBeNull();
+ const captionStream = await captions.createReadStream();
+ const chunks: Buffer[] = [];
+ for await (const chunk of captionStream) chunks.push(Buffer.from(chunk));
+ const downloadedCaptions = Buffer.concat(chunks).toString("utf8");
+ expect(downloadedCaptions).toMatch(/^WEBVTT/);
+ const refreshedCaptionUrl = await video.locator("track").getAttribute("src");
+ const captionResponse = await request.get(refreshedCaptionUrl!);
+ expect(captionResponse.ok()).toBe(true);
+ expect(downloadedCaptions).toBe(await captionResponse.text());
await expect
.poll(() => video.evaluate((el: HTMLVideoElement) => el.readyState))
.toBeGreaterThanOrEqual(1);
diff --git a/apps/web/src/app/w/[workspaceSlug]/studio/page.tsx b/apps/web/src/app/w/[workspaceSlug]/studio/page.tsx
index c5e04ca..5bb5ecf 100644
--- a/apps/web/src/app/w/[workspaceSlug]/studio/page.tsx
+++ b/apps/web/src/app/w/[workspaceSlug]/studio/page.tsx
@@ -195,7 +195,7 @@ export default async function StudioPage({
)}
{videoUrl && (
diff --git a/apps/web/src/components/product/caption-download.tsx b/apps/web/src/components/product/caption-download.tsx
index ae4a6bd..cbd168e 100644
--- a/apps/web/src/components/product/caption-download.tsx
+++ b/apps/web/src/components/product/caption-download.tsx
@@ -1,18 +1,18 @@
"use client";
-import { useEffect, useRef, useState } from "react";
+import { useEffect, useRef, useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { captionDownloadError } from "./caption-download-state";
-export function CaptionDownload({
- url,
- extension,
-}: {
+interface CaptionDownloadProps {
url?: string;
extension: "srt" | "vtt";
-}) {
+}
+
+export function CaptionDownload({ url, extension }: CaptionDownloadProps) {
const router = useRouter();
const [busy, setBusy] = useState(false);
+ const [refreshing, startTransition] = useTransition();
const [error, setError] = useState("");
const request = useRef(null);
@@ -56,7 +56,7 @@ export function CaptionDownload({
)}
- {(!url || error) && (
+ {(!url || error || refreshing) && (
)}
From 4437f4542be61c305bb29c60ad6203e6fb42db79 Mon Sep 17 00:00:00 2001
From: Darun Ramalingam
Date: Mon, 23 Nov 2026 23:06:53 -0600
Subject: [PATCH 3/3] style(test): simplify caption route predicate
---
apps/web/e2e/production-flow.spec.ts | 6 ++++--
1 file changed, 4 insertions(+), 2 deletions(-)
diff --git a/apps/web/e2e/production-flow.spec.ts b/apps/web/e2e/production-flow.spec.ts
index 055d2a2..a324a9b 100644
--- a/apps/web/e2e/production-flow.spec.ts
+++ b/apps/web/e2e/production-flow.spec.ts
@@ -96,8 +96,10 @@ test("new campaign becomes an approved, published video with stored analytics",
const captionUrl = await video.locator("track").getAttribute("src");
expect(captionUrl).toBeTruthy();
// Simulate an expired signed link without changing the persisted render.
- const expiredCaption = (url: URL) =>
- url.pathname === "/api/storage" && url.searchParams.get("key")?.endsWith("/captions.vtt") === true;
+ const expiredCaption = (url: URL) => {
+ const key = url.searchParams.get("key");
+ return url.pathname === "/api/storage" && Boolean(key?.endsWith("/captions.vtt"));
+ };
await page.route(expiredCaption, (route) => route.fulfill({ status: 403 }));
await captionButton.click();
await expect(page.getByRole("alert").filter({ hasText: "caption link expired" })).toBeVisible();