Open source CapCut alternative.
TypeScript
feat(site): Cut social captions with preset styles
David Lea1beb457900f
diff --git a/site/src/cut/components/SubtitlesPanel.tsx b/site/src/cut/components/SubtitlesPanel.tsxindex f35a5834..2833f9db 100644--- a/site/src/cut/components/SubtitlesPanel.tsx+++ b/site/src/cut/components/SubtitlesPanel.tsx@@ -1,10 +1,10 @@"use client";import { memo, useEffect, useRef, useState } from "react";-import { AlertCircle, Captions, ChevronDown, Loader2, RefreshCw } from "lucide-react";+import { AlertCircle, Captions, ChevronDown, Loader2, RefreshCw, Sparkles } from "lucide-react";import { Button } from "@/components/ui/button";import { Switch } from "@/components/ui/switch";-import { fmtCueTime } from "@/cut/lib/subtitles";+import { CAPTION_STYLES, fmtCueTime } from "@/cut/lib/subtitles";import { TIMELINE_H_MIN, useEditor } from "@/cut/lib/store";import type { SubtitleCue } from "@/cut/lib/types";import { cn } from "@/lib/utils";@@ -32,13 +32,21 @@ export function SubtitlesPanel() {const error = useEditor((s) => s.subtitleError);const hasCues = subtitles.cues.length > 0;+ const style = subtitles.style ?? "clean";++ const growTimeline = () => {+ const cur = useEditor.getState();+ if (cur.subtitles.cues.length > 0 && cur.timelineH < TIMELINE_H_WITH_SUBS)+ cur.setTimelineH(TIMELINE_H_WITH_SUBS);+ };+const generate = () => {+ void useEditor.getState().generateSubtitles().then(growTimeline);+ };++ const captions = () => {const s = useEditor.getState();- void s.generateSubtitles().then(() => {- const cur = useEditor.getState();- if (cur.subtitles.cues.length > 0 && cur.timelineH < TIMELINE_H_WITH_SUBS)- cur.setTimelineH(TIMELINE_H_WITH_SUBS);- });+ void s.generateCaptions(s.subtitles.style ?? "hook").then(growTimeline);};return (@@ -65,11 +73,11 @@ export function SubtitlesPanel() {</div>{!hasCues ? (- <EmptyState status={status} error={error} onGenerate={generate} />+ <EmptyState status={status} error={error} onGenerate={generate} onCaptions={captions} />) : (<><Transcript cues={subtitles.cues} />- <div className="flex shrink-0 flex-col gap-2 border-t border-border px-4 py-3">+ <div className="flex shrink-0 flex-col gap-2.5 border-t border-border px-4 py-3"><label className="flex items-center justify-between text-xs font-medium">Show<Switch@@ -82,6 +90,45 @@ export function SubtitlesPanel() {}}/></label>++ <div className="flex flex-col gap-1.5">+ <span className="text-[11px] font-semibold tracking-wider text-muted-foreground uppercase">+ Caption style+ </span>+ <div className="flex flex-wrap gap-1.5">+ {Object.values(CAPTION_STYLES).map((cs) => (+ <button+ key={cs.id}+ className={cn(+ "rounded-full border px-2.5 py-1 text-[11px] font-medium transition-colors",+ style === cs.id+ ? "border-primary bg-primary/10 text-primary"+ : "border-border text-muted-foreground hover:text-foreground"+ )}+ onClick={() => useEditor.getState().setSubtitlesView({ style: cs.id })}+ >+ {cs.label}+ </button>+ ))}+ </div>+ <Button+ variant="outline"+ className="sub-social w-full"+ disabled={status === "running"}+ onClick={captions}+ >+ {status === "running" ? (+ <Loader2 className="animate-spin" />+ ) : (+ <Sparkles data-icon="inline-start" />+ )}+ Rewrite for social+ </Button>+ <p className="text-[11px] leading-relaxed text-muted-foreground">+ Punchier lines, a curiosity hook, and a few emoji — timings stay put.+ </p>+ </div>+{status === "running" && (<p className="flex items-center gap-1.5 text-[11px] text-muted-foreground"><Loader2 className="size-3 animate-spin" /> Re-transcribing on this Mac…@@ -101,10 +148,12 @@ function EmptyState({status,error,onGenerate,+ onCaptions,}: {status: string;error: string | null;onGenerate: () => void;+ onCaptions: () => void;}) {const locale = useEditor((s) => s.subtitles.locale ?? "en-US");@@ -163,6 +212,12 @@ function EmptyState({<Captions data-icon="inline-start" />{status === "empty" || status === "error" ? "Try again" : "Generate subtitles"}</Button>+ {status !== "empty" && (+ <Button variant="outline" className="sub-social w-full" onClick={onCaptions}>+ <Sparkles data-icon="inline-start" />+ Social captions+ </Button>+ )}</div>);}diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex ae24c6ce..611959fd 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -239,6 +239,28 @@ export async function runAiTool(};}+ case "captions_generate": {+ const raw = typeof input.style === "string" ? input.style : "hook";+ const style = (["clean", "hook", "punchy"].includes(raw) ? raw : "hook") as+ | "clean"+ | "hook"+ | "punchy";+ await s.generateCaptions(style);+ const cur = useEditor.getState();+ if (cur.subtitleStatus === "error")+ throw new ToolError(cur.subtitleError ?? "Captions failed.");+ if (cur.subtitles.cues.length > 0 && cur.timelineH < 276) cur.setTimelineH(276);+ return {+ status: cur.subtitleStatus,+ cues: cur.subtitles.cues.length,+ style: cur.subtitles.style,+ note:+ cur.subtitleStatus === "empty"+ ? "No speech found — no captions were added to the video."+ : undefined,+ };+ }+case "subtitles_set_view": {const patch: { showOnVideo?: boolean; showOnTimeline?: boolean } = {};if (typeof input.showOnVideo === "boolean") patch.showOnVideo = input.showOnVideo;diff --git a/site/src/cut/server/ai/captions.ts b/site/src/cut/server/ai/captions.tsnew file mode 100644index 00000000..fd70b22f--- /dev/null+++ b/site/src/cut/server/ai/captions.ts@@ -0,0 +1,93 @@+import os from "node:os";+import { query } from "@anthropic-ai/claude-agent-sdk";++// Rewrite plain transcript cues into punchy social-video captions, one-to-one so+// the timings stay put. Runs through the user's own Claude login (no hosted+// models), like the rest of Cut's AI. Any failure falls back to the originals.++export interface CaptionInput {+ start: number;+ end: number;+ text: string;+}++const STYLE_GUIDE: Record<string, string> = {+ clean: "Keep it clear and natural — a light polish, not a rewrite.",+ hook: "Open with a strong curiosity gap that makes people need to keep watching; stay punchy throughout.",+ punchy: "Bold, high-energy phrasing. Make the opening line especially loud and impossible to scroll past.",+};++const MODEL = "claude-haiku-4-5-20251001";++export async function rewriteCaptions(cues: CaptionInput[], style: string): Promise<string[]> {+ const originals = cues.map((c) => c.text);+ const numbered = cues.map((c, i) => `${i + 1}. ${c.text}`).join("\n");+ const guide = STYLE_GUIDE[style] ?? STYLE_GUIDE.clean;+ const prompt = `You rewrite spoken-word transcript lines into short-form social video captions (TikTok / Reels / Shorts).++Rewrite EACH numbered line below. Rules:+- Return EXACTLY ${cues.length} lines — one rewrite per input line, in the same order.+- Preserve the meaning and point of each original line.+- Keep each caption short so it fits inside the vertical video frame — about 3–8 words. It may wrap onto two lines, but must never be so long it would overflow the frame width.+- Sprinkle a few relevant emoji across the whole set — not every line, never more than one per line.+- Line 1 is the opener: make it a scroll-stopping hook.+- ${guide}++Return ONLY a JSON array of ${cues.length} strings. No commentary, no code fence.++Lines:+${numbered}`;++ let text: string;+ try {+ text = await Promise.race([runOnce(prompt), timeout(90_000)]);+ } catch {+ return originals;+ }+ const arr = parseStringArray(text);+ if (!arr || arr.length !== cues.length) return originals;+ return arr.map((s, i) => (s && s.trim() ? s.trim() : originals[i]));+}++function timeout(ms: number): Promise<never> {+ return new Promise((_resolve, reject) => {+ setTimeout(() => reject(new Error("timeout")), ms).unref();+ });+}++async function runOnce(prompt: string): Promise<string> {+ const q = query({+ prompt,+ options: {+ model: MODEL,+ ...(process.env.DONKEY_CUT_CLAUDE+ ? { pathToClaudeCodeExecutable: process.env.DONKEY_CUT_CLAUDE }+ : {}),+ tools: [],+ permissionMode: "dontAsk",+ settingSources: [],+ maxTurns: 1,+ cwd: os.tmpdir(),+ },+ });+ let out = "";+ for await (const msg of q) {+ const m = msg as unknown as { type: string; subtype?: string; result?: unknown };+ if (m.type === "result" && m.subtype === "success" && typeof m.result === "string") {+ out = m.result;+ }+ }+ return out;+}++function parseStringArray(text: string): string[] | null {+ const start = text.indexOf("[");+ const end = text.lastIndexOf("]");+ if (start === -1 || end === -1 || end <= start) return null;+ try {+ const v = JSON.parse(text.slice(start, end + 1)) as unknown;+ return Array.isArray(v) ? v.map((x) => String(x)) : null;+ } catch {+ return null;+ }+}diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex 836147a3..86e3b693 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -175,6 +175,12 @@ export const AI_TOOLS: AiToolDef[] = ["Transcribe the cut on-device (Apple speech) and create subtitle captions. Runs in the background; returns when finished. If no speech is found, no subtitles are added.",inputSchema: obj({ locale: str("BCP-47 locale like en-US (default en-US)") }),},+ {+ name: "captions_generate",+ description:+ "Transcribe (if needed) then rewrite the captions into punchy social-video captions — short lines that fit inside the video frame (they may wrap onto two lines but never overflow), a few emoji, a curiosity-hook opener. style: clean | hook | punchy (default hook). Cue timings are preserved.",+ inputSchema: obj({ style: str("Caption style: clean, hook, or punchy") }),+ },{name: "subtitles_set_view",description: "Toggle subtitles on the video (preview + export burn-in) and/or the timeline cue track.",@@ -302,7 +308,7 @@ Titles burn into the export exactly as previewed.`,"audio-and-subtitles": `# Audio & subtitlesSoundtrack clips: volume 0..1.5, fadeIn/fadeOut seconds (max half the clip), start = timeline position, in/out = trim inside the source. Fades render with ffmpeg afade on export.-Subtitles: subtitles_generate transcribes the current cut fully on-device (Apple speech, macOS 26). Cues are caption-sized (≈38 chars). If no speech exists, no cues are created and nothing renders on the video — never add captions to a speechless video.+Subtitles: subtitles_generate transcribes the current cut fully on-device (Apple speech, macOS 26). Cues are caption-sized (≈38 chars). If no speech exists, no cues are created and nothing renders on the video — never add captions to a speechless video. captions_generate goes further: it rewrites those cues into punchy social captions (emoji, curiosity-hook opener) in a chosen style (clean/hook/punchy), keeping timings — use it when the ask is social/TikTok captions rather than a plain transcript.Editing: update_cue (text or retime), delete_cue. In the panel, Return splits a caption at the cursor onto real word timings; hand-edited text drops its word timings.subtitles_set_view: showOnVideo (preview + export burn-in), showOnTimeline (amber cue track).Caption style is fixed: bold white SF, translucent plate, bottom-center (y≈0.8).`,diff --git a/site/src/cut/server/http/ai.ts b/site/src/cut/server/http/ai.tsindex a5bdc7a5..b756b65e 100644--- a/site/src/cut/server/http/ai.ts+++ b/site/src/cut/server/http/ai.ts@@ -11,6 +11,7 @@ import {unregisterSession,type UIChunkWriter,} from "../ai/bridge";+import { rewriteCaptions } from "../ai/captions";import { AI_SKILL_INDEX, AI_SKILLS, AI_TOOLS, systemPrompt } from "../ai/catalog";import { AI_MODELS } from "../ai/models";@@ -283,6 +284,27 @@ const mcpText = (value: unknown) => ({/** The AI assistant: chat streaming, provider probing, and the MCP bridge. */export const aiApi = {+ /** Rewrite subtitle cues into punchy social captions (one-to-one, timings+ * preserved). Falls back to the originals on any failure. */+ async captions(req: Request) {+ try {+ const { cues, style } = (await req.json()) as {+ cues?: { start: number; end: number; text: string }[];+ style?: string;+ };+ if (!Array.isArray(cues) || cues.length === 0) {+ return Response.json({ error: "No cues to rewrite." }, { status: 400 });+ }+ const texts = await rewriteCaptions(cues, typeof style === "string" ? style : "clean");+ return Response.json({ texts });+ } catch (e) {+ return Response.json(+ { error: e instanceof Error ? e.message : "Could not write captions." },+ { status: 500 }+ );+ }+ },+async chat(req: Request) {const body = (await req.json()) as ChatBody;const base = new URL(req.url).origin;