Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions apps/web/e2e/production-flow.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,32 @@ 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) => {
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();
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);
Expand Down
15 changes: 12 additions & 3 deletions apps/web/src/app/w/[workspaceSlug]/studio/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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 },
Expand Down Expand Up @@ -175,7 +177,7 @@ export default async function StudioPage({
src={videoUrl}
className="w-full rounded-xl"
>
{captionUrl && (
{captionUrl && caption?.format === "WEBVTT" && (
<track kind="captions" src={captionUrl} srcLang="en" label="English" default />
)}
</video>
Expand All @@ -191,6 +193,13 @@ export default async function StudioPage({
accounts={accounts}
/>
)}
{videoUrl && (
<CaptionDownload
key={`${output?.id}:${caption?.storageKey ?? "unavailable"}`}
url={captionUrl}
extension={caption?.format === "SRT" ? "srt" : "vtt"}
/>
)}
<Card>
<CardContent className="space-y-2 p-4">
<h2 className="font-semibold">Workflow history</h2>
Expand Down
35 changes: 35 additions & 0 deletions apps/web/src/components/product/caption-download-state.test.ts
Original file line number Diff line number Diff line change
@@ -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");
});
});
24 changes: 24 additions & 0 deletions apps/web/src/components/product/caption-download-state.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
interface Track {
format: string;
storageKey: string;
}

export function matchingCaptionTrack<T extends Track>(
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.";
}
87 changes: 87 additions & 0 deletions apps/web/src/components/product/caption-download.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
"use client";

import { useEffect, useRef, useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { captionDownloadError } from "./caption-download-state";

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<AbortController | null>(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 (
<div className="space-y-2 text-sm">
{url ? (
<button
type="button"
className="text-primary font-medium underline disabled:opacity-50"
disabled={busy || refreshing}
onClick={() => void download()}
>
{busy ? "Downloading captions…" : `Download Captions (${extension.toUpperCase()})`}
</button>
) : (
<p className="text-muted-foreground">Captions unavailable for this rendered video.</p>
)}
{error && (
<p role="alert" className="text-destructive">
{error}
</p>
)}
{(!url || error || refreshing) && (
<button
type="button"
className="text-primary block underline"
disabled={busy || refreshing}
onClick={() => {
setError("");
startTransition(() => router.refresh());
}}
>
{refreshing ? "Refreshing caption link…" : "Refresh caption link"}
</button>
)}
</div>
);
}
Loading