Skip to content

Open source CapCut alternative.

TypeScript

feat(site): pair the Cut video tab with a stock clip browser

David Lecebdb7154cf5
diff --git a/site/scripts/generate-stock-videos.ts b/site/scripts/generate-stock-videos.ts
new file mode 100644
index 00000000..6ea01783
--- /dev/null
+++ b/site/scripts/generate-stock-videos.ts
@@ -0,0 +1,283 @@
+// Generates the bundled Cut stock-video catalog with the same Veo tier the app
+// uses (veo fast), then writes the typed manifest the editor imports.
+// Idempotent: items whose file already exists are skipped, so re-running fills
+// gaps or picks up new catalog entries only.
+//
+// cd site && ./node_modules/.bin/bun scripts/generate-stock-videos.ts
+//
+// Needs GOOGLE_APPLICATION_CREDENTIALS_JSON (bun auto-loads site/.env) and
+// ffmpeg on PATH for the poster thumbs. Each clip renders at 720p, lands as an
+// mp4 under public/cut-stock-video, and gets a first-frame WebP thumb the
+// browse grid uses.
+//
+// After generation, every clip is tagged: a vision pass looks at the poster
+// frame and extracts the searchable keywords (objects, animals, setting) the
+// editor's search box matches. Tags already in the manifest are reused, so
+// re-running only tags new or untagged clips.
+
+import { spawnSync } from "node:child_process";
+import { existsSync } from "node:fs";
+import { mkdir, readFile, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { GoogleGenAI } from "@google/genai";
+import { JWT } from "google-auth-library";
+import sharp from "sharp";
+
+import type { StockCategory, StockVideoAspect } from "../src/cut/lib/stock";
+
+interface CatalogItem {
+ id: string;
+ category: StockCategory;
+ aspect: StockVideoAspect;
+ /** Rendered length; Veo takes 4, 6, or 8 seconds. */
+ seconds: 4 | 6 | 8;
+ prompt: string;
+}
+
+const MODEL = process.env.GEMINI_VIDEO_MODEL?.trim() || "veo-3.1-fast-generate-001";
+const TAG_MODEL = "gemini-2.5-flash";
+const OUT_DIR = path.join(import.meta.dirname, "..", "public", "cut-stock-video");
+const MANIFEST = path.join(import.meta.dirname, "..", "src", "cut", "lib", "stockVideoManifest.ts");
+// Veo renders take minutes each and quotas are tight; keep the fan-out small.
+const CONCURRENCY = 2;
+const POLL_MS = 10_000;
+/** Longest thumb edge — the browse grid renders tiles well under this. */
+const THUMB_EDGE = 512;
+
+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+
+const clip = (subject: string) =>
+ `Cinematic stock footage: ${subject} Smooth, steady camera motion, natural lighting, realistic color grading. No text, no watermarks, no logos.`;
+
+const animeClip = (subject: string) =>
+ `High-quality anime animation: ${subject} Clean line art, vibrant cel shading, detailed background, smooth motion. No text, no watermarks.`;
+
+const CATALOG: CatalogItem[] = [
+ // Business
+ { id: "business-team-walkthrough", category: "Business", aspect: "16:9", seconds: 6, prompt: clip("a slow tracking shot following a small team walking and talking through a bright modern office, glass walls and plants passing by.") },
+ { id: "business-typing-macro", category: "Business", aspect: "16:9", seconds: 6, prompt: clip("a close-up of hands typing on a laptop at a tidy desk, soft window light, shallow depth of field.") },
+
+ // Nature
+ { id: "nature-coast-aerial", category: "Nature", aspect: "16:9", seconds: 6, prompt: clip("a drone shot rising over a foggy coastline at sunrise, waves rolling onto dark sand far below.") },
+ { id: "nature-forest-rays", category: "Nature", aspect: "9:16", seconds: 6, prompt: clip("sunbeams drifting through tall pines as morning fog moves slowly between the trunks, camera gliding forward at ground level.") },
+
+ // Travel
+ { id: "travel-market-walk", category: "Travel", aspect: "16:9", seconds: 6, prompt: clip("a first-person walk through a lively evening street market, lanterns glowing, vendors and steam from food stalls on both sides.") },
+ { id: "travel-beach-stroll", category: "Travel", aspect: "9:16", seconds: 6, prompt: clip("a traveler walking barefoot along the waterline of a white-sand beach at golden hour, gentle waves washing over their footprints.") },
+
+ // City
+ { id: "city-night-traffic", category: "City", aspect: "16:9", seconds: 6, prompt: clip("an elevated view of city traffic at night, headlight streams and neon reflections on wet asphalt.") },
+ { id: "city-crosswalk-rush", category: "City", aspect: "16:9", seconds: 6, prompt: clip("a busy scramble crosswalk from a high angle, crowds crossing in every direction as the light changes.") },
+
+ // Technology
+ { id: "tech-code-glow", category: "Technology", aspect: "16:9", seconds: 6, prompt: clip("a slow push-in on a developer working at a dual-monitor setup in a dim room, screen glow on their face, code scrolling.") },
+ { id: "tech-robot-assembly", category: "Technology", aspect: "16:9", seconds: 6, prompt: clip("an industrial robot arm assembling components on a clean production line, precise repeated motion, cool white lighting.") },
+
+ // Anime
+ { id: "anime-rain-walk", category: "Anime", aspect: "9:16", seconds: 6, prompt: animeClip("a figure with a glowing umbrella walking toward the viewer down a rain-slicked neon city street at night, puddles rippling.") },
+ { id: "anime-cloud-drift", category: "Anime", aspect: "16:9", seconds: 6, prompt: animeClip("towering summer clouds drifting over a green hillside town by the sea, cherry blossom petals carried on the wind.") },
+
+ // Animal
+ { id: "animal-dog-sprint", category: "Animal", aspect: "16:9", seconds: 6, prompt: clip("a golden retriever sprinting along a beach at sunset in slow motion, sand kicking up, ears flying.") },
+ { id: "animal-flock-sky", category: "Animal", aspect: "16:9", seconds: 6, prompt: clip("a flock of birds wheeling across a pastel dusk sky over still water, reflections mirroring their turns.") },
+
+ // Food & Drink
+ { id: "food-coffee-pour", category: "Food & Drink", aspect: "16:9", seconds: 6, prompt: clip("a slow-motion pour of steamed milk into espresso forming latte art, on a marble counter, steam curling upward.") },
+ { id: "food-pan-sizzle", category: "Food & Drink", aspect: "16:9", seconds: 6, prompt: clip("vegetables tossed in a sizzling wok over a high flame, embers and steam rising, close-up from the side.") },
+];
+
+function makeClient(): { client: GoogleGenAI; authClient: JWT; project: string } {
+ const raw = process.env.GOOGLE_APPLICATION_CREDENTIALS_JSON?.trim();
+ if (!raw) throw new Error("GOOGLE_APPLICATION_CREDENTIALS_JSON is not set (run from site/ so bun loads .env).");
+ const creds = JSON.parse(raw) as { project_id?: string; client_email?: string; private_key?: string; private_key_id?: string };
+ if (!creds.project_id || !creds.client_email || !creds.private_key) {
+ throw new Error("Service account JSON is missing project_id/client_email/private_key.");
+ }
+ const authClient = new JWT({
+ email: creds.client_email,
+ key: creds.private_key,
+ keyId: creds.private_key_id,
+ scopes: ["https://www.googleapis.com/auth/cloud-platform"],
+ });
+ const client = new GoogleGenAI({
+ vertexai: true,
+ location: "global",
+ project: creds.project_id,
+ googleAuthOptions: { authClient },
+ });
+ return { client, authClient, project: creds.project_id };
+}
+
+/** Renders one clip and resolves to its mp4 bytes — polls the long-running
+ * operation, then reads inline bytes or downloads the signed URI. */
+async function generateOne(client: GoogleGenAI, authClient: JWT, item: CatalogItem): Promise<Buffer> {
+ let op = await client.models.generateVideos({
+ model: MODEL,
+ prompt: item.prompt,
+ config: {
+ aspectRatio: item.aspect,
+ durationSeconds: item.seconds,
+ resolution: "720p",
+ generateAudio: true,
+ },
+ });
+ while (!op.done) {
+ await sleep(POLL_MS);
+ op = await client.operations.getVideosOperation({ operation: op });
+ }
+ if (op.error) throw new Error(String(op.error.message ?? "video generation failed"));
+ const video = op.response?.generatedVideos?.[0]?.video;
+ if (video?.videoBytes) return Buffer.from(video.videoBytes, "base64");
+ if (video?.uri) {
+ const token = await authClient.getAccessToken();
+ const res = await fetch(video.uri, { headers: { Authorization: `Bearer ${token.token}` } });
+ if (!res.ok) throw new Error(`could not download the rendered video (${res.status})`);
+ return Buffer.from(await res.arrayBuffer());
+ }
+ throw new Error("no video in response");
+}
+
+/** First frame of the finished mp4 as the grid thumb, via ffmpeg → sharp. */
+async function writeThumb(item: CatalogItem) {
+ const proc = spawnSync(
+ "ffmpeg",
+ ["-v", "error", "-i", path.join(OUT_DIR, `${item.id}.mp4`), "-frames:v", "1", "-f", "image2pipe", "-vcodec", "png", "-"],
+ { maxBuffer: 64 * 1024 * 1024 }
+ );
+ const png = proc.stdout;
+ if (proc.status !== 0 || !png || png.length === 0) {
+ throw new Error(`ffmpeg could not read a poster frame: ${proc.stderr?.toString() ?? "unknown error"}`);
+ }
+ const frame = sharp(png);
+ const { width = 0, height = 0 } = await frame.metadata();
+ const scale = THUMB_EDGE / Math.max(width, height, 1);
+ const thumb = await frame
+ .resize(Math.round(width * scale), Math.round(height * scale))
+ .webp({ quality: 75, smartSubsample: true })
+ .toBuffer();
+ await writeFile(path.join(OUT_DIR, `${item.id}.thumb.webp`), thumb);
+}
+
+/** Vision pass over the poster frame: extracts the concrete, searchable
+ * keywords for what is actually visible — objects, animals, people, setting,
+ * and time/weather. */
+async function tagOne(client: GoogleGenAI, item: CatalogItem): Promise<string[]> {
+ const thumb = await readFile(path.join(OUT_DIR, `${item.id}.thumb.webp`));
+ const response = await client.models.generateContent({
+ model: TAG_MODEL,
+ contents: [
+ {
+ role: "user",
+ parts: [
+ { inlineData: { mimeType: "image/webp", data: thumb.toString("base64") } },
+ {
+ text: "List 10-20 search keywords for everything visible in this image: every distinct object (e.g. tree, dog, cup, laptop), animals, people, the setting (e.g. beach, road, office, forest), and time of day or weather if evident. Lowercase, one or two words each. Respond with a JSON array of strings only.",
+ },
+ ],
+ },
+ ],
+ config: { responseMimeType: "application/json" },
+ });
+ const parsed = JSON.parse(response.text ?? "[]") as unknown;
+ if (!Array.isArray(parsed)) throw new Error("tag response is not an array");
+ const tags = parsed
+ .filter((t): t is string => typeof t === "string")
+ .map((t) => t.trim().toLowerCase())
+ .filter(Boolean);
+ if (tags.length === 0) throw new Error("no tags in response");
+ return [...new Set(tags)];
+}
+
+/** Tags from the current manifest, keyed by id — reused so re-runs only call
+ * the vision model for new or untagged clips. */
+async function existingTags(): Promise<Map<string, string[]>> {
+ const byId = new Map<string, string[]>();
+ try {
+ const { STOCK_VIDEOS } = await import("../src/cut/lib/stockVideoManifest");
+ for (const entry of STOCK_VIDEOS as { id: string; tags?: string[] }[]) {
+ if (entry.tags?.length) byId.set(entry.id, entry.tags);
+ }
+ } catch {
+ // No manifest yet — every clip gets a fresh tagging pass.
+ }
+ return byId;
+}
+
+async function writeManifest(done: Set<string>, tags: Map<string, string[]>) {
+ const entries = CATALOG.filter((c) => done.has(c.id)).map((c) => ({
+ id: c.id,
+ category: c.category,
+ prompt: c.prompt,
+ tags: tags.get(c.id) ?? [],
+ aspect: c.aspect,
+ file: `/cut-stock-video/${c.id}.mp4`,
+ thumb: `/cut-stock-video/${c.id}.thumb.webp`,
+ duration: c.seconds,
+ }));
+ const body = `// Generated by scripts/generate-stock-videos.ts — do not edit by hand.
+import type { StockVideo } from "./stock";
+
+export const STOCK_VIDEOS: StockVideo[] = ${JSON.stringify(entries, null, 2)};
+`;
+ await writeFile(MANIFEST, body);
+}
+
+async function main() {
+ const { client, authClient, project } = makeClient();
+ await mkdir(OUT_DIR, { recursive: true });
+
+ const done = new Set<string>(CATALOG.filter((c) => existsSync(path.join(OUT_DIR, `${c.id}.mp4`))).map((c) => c.id));
+ const todo = CATALOG.filter((c) => !done.has(c.id));
+ console.log(`model=${MODEL} project=${project} existing=${done.size} generating=${todo.length}`);
+
+ let failed = 0;
+ const queue = [...todo];
+ const worker = async () => {
+ for (let item = queue.shift(); item; item = queue.shift()) {
+ for (let attempt = 1; ; attempt++) {
+ try {
+ const video = await generateOne(client, authClient, item);
+ await writeFile(path.join(OUT_DIR, `${item.id}.mp4`), video);
+ await writeThumb(item);
+ done.add(item.id);
+ console.log(`✓ ${item.id} (${item.aspect}, ${item.seconds}s)`);
+ break;
+ } catch (e) {
+ if (attempt >= 2) {
+ failed++;
+ console.error(`✗ ${item.id}: ${e instanceof Error ? e.message : e}`);
+ break;
+ }
+ console.warn(`retrying ${item.id}…`);
+ }
+ }
+ }
+ };
+ await Promise.all(Array.from({ length: CONCURRENCY }, worker));
+
+ // A finished clip can predate its thumb (an interrupted earlier run); fill in
+ // any missing posters before tagging reads them.
+ for (const item of CATALOG) {
+ if (done.has(item.id) && !existsSync(path.join(OUT_DIR, `${item.id}.thumb.webp`))) {
+ await writeThumb(item).catch((e) => console.error(`✗ thumb ${item.id}: ${e instanceof Error ? e.message : e}`));
+ }
+ }
+
+ const tags = await existingTags();
+ for (const item of CATALOG) {
+ if (!done.has(item.id) || tags.has(item.id)) continue;
+ try {
+ tags.set(item.id, await tagOne(client, item));
+ console.log(`✓ tags ${item.id}`);
+ } catch (e) {
+ failed++;
+ console.error(`✗ tags ${item.id}: ${e instanceof Error ? e.message : e}`);
+ }
+ }
+
+ await writeManifest(done, tags);
+ console.log(`manifest: ${done.size}/${CATALOG.length} clips${failed ? `, ${failed} failed` : ""}`);
+ if (failed) process.exitCode = 1;
+}
+
+await main();
diff --git a/site/src/cut/components/GeneratePanel.tsx b/site/src/cut/components/GeneratePanel.tsx
index 9d07fcbd..c38f4a0f 100644
--- a/site/src/cut/components/GeneratePanel.tsx
+++ b/site/src/cut/components/GeneratePanel.tsx
@@ -1,46 +1,40 @@
"use client";
-import { useState } from "react";
import { Film, Loader2, Plus, Sparkles, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
-import {
- addRefOnce,
- collectRefs,
- sameRef,
- useRefCandidates,
- useAssetDrop,
- type AssetRef,
-} from "@/cut/lib/assetRef";
+import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
+import { collectRefs, useRefCandidates, useAssetDrop } from "@/cut/lib/assetRef";
import { signInUrl, useGenerate, useSignedIn, type GenerateJob } from "@/cut/lib/generate";
import { useEditor } from "@/cut/lib/store";
import { useLocalPref } from "@/cut/lib/uiState";
+import { useVideoGen } from "@/cut/lib/videoGen";
import { cn } from "@/lib/utils";
import { MentionTextarea, RefChips } from "./AssetRefs";
+import { GeneratedAssetMenu } from "./GeneratedAssetMenu";
-// AI video generation (Veo). Image generation lives in the stock browser's
-// flyover — see StockImagesPanel / ImageGenFlyover.
+// The generate-video panel: an always-on column in the Video tab, sitting left
+// of the stock-clip browser. Clicking a stock tile loads its saved prompt here.
//
// A visual reference (dragged in or @name-mentioned) seeds the render: Veo
// takes one input image, so the first reference's picture becomes the start
// frame.
-const chip = (active: boolean) =>
+// Segmented pill group, same language as the platform switcher in PlatformPreview.
+const segGroup = "flex gap-0.5 rounded-full border border-border bg-card p-0.5 shadow-xs";
+const segButton = (active: boolean) =>
cn(
- "rounded-full border px-2.5 py-1 text-[11px] font-medium transition-colors",
- active
- ? "border-primary bg-primary/10 text-primary"
- : "border-border text-muted-foreground hover:text-foreground"
+ "rounded-full px-2.5 py-[3px] text-[11px] font-medium transition-colors",
+ active ? "bg-foreground text-background" : "text-muted-foreground hover:text-foreground"
);
export function GenerateVideoPanel({ projectId }: { projectId: string }) {
const signedIn = useSignedIn();
const allJobs = useGenerate((s) => s.jobs);
const jobs = allJobs.filter((j) => j.projectId === projectId && j.kind === "video");
- const [prompt, setPrompt] = useState("");
- const [refs, setRefs] = useState<AssetRef[]>([]);
+ const { prompt, refs } = useVideoGen();
const candidates = useRefCandidates();
const { active: dropActive, attachTarget, targetProps } = useAssetDrop((ref) => {
- if (ref.kind !== "audio") setRefs((prev) => addRefOnce(prev, ref));
+ if (ref.kind !== "audio") useVideoGen.getState().addRef(ref);
});
const [tier, setTier] = useLocalPref<"fast" | "high">(
"cut-gen-tier",
@@ -59,14 +53,13 @@ export function GenerateVideoPanel({ projectId }: { projectId: string }) {
void useGenerate
.getState()
.generateVideo(projectId, text, { tier, durationSeconds: seconds, refs: all });
- setPrompt("");
- setRefs([]);
+ useVideoGen.getState().openWith("");
};
return (
<>
<div className="flex h-12 shrink-0 items-center justify-between pr-2.5 pl-4">
- <span className="text-sm font-semibold tracking-tight">Video</span>
+ <span className="text-sm font-semibold tracking-tight">Generate video</span>
</div>
<div
@@ -83,7 +76,7 @@ export function GenerateVideoPanel({ projectId }: { projectId: string }) {
)}
<RefChips
refs={refs}
- onRemove={(ref) => setRefs((prev) => prev.filter((r) => !sameRef(r, ref)))}
+ onRemove={(ref) => useVideoGen.getState().removeRef(ref)}
className="shrink-0"
peekSide="bottom"
/>
@@ -91,7 +84,7 @@ export function GenerateVideoPanel({ projectId }: { projectId: string }) {
className="gen-prompt min-h-[88px] w-full shrink-0 resize-y rounded-lg border border-input bg-transparent px-2.5 py-2 text-[12.5px] leading-relaxed outline-none focus:border-ring"
placeholder="A drone shot rising over a foggy coastline at sunrise… Drop media in or type @ to reference it."
value={prompt}
- onChange={setPrompt}
+ onChange={(v) => useVideoGen.getState().setPrompt(v)}
candidates={candidates}
submitKey="mod-enter"
menuSide="bottom"
@@ -99,16 +92,26 @@ export function GenerateVideoPanel({ projectId }: { projectId: string }) {
/>
<div className="flex shrink-0 items-center justify-between gap-2">
- <div className="flex gap-1.5">
+ <div className={segGroup}>
{[4, 6, 8].map((s) => (
- <button key={s} className={chip(seconds === s)} onClick={() => setSeconds(s)}>
+ <button
+ key={s}
+ className={segButton(seconds === s)}
+ aria-pressed={seconds === s}
+ onClick={() => setSeconds(s)}
+ >
{s}s
</button>
))}
</div>
- <div className="flex gap-1.5">
+ <div className={segGroup}>
{(["fast", "high"] as const).map((t) => (
- <button key={t} className={chip(tier === t)} onClick={() => setTier(t)}>
+ <button
+ key={t}
+ className={segButton(tier === t)}
+ aria-pressed={tier === t}
+ onClick={() => setTier(t)}
+ >
{t === "fast" ? "Fast" : "Best"}
</button>
))}
@@ -180,7 +183,7 @@ function JobRow({ job }: { job: GenerateJob }) {
)}
>
{job.status === "running" && "Rendering…"}
- {job.status === "done" && "In your media"}
+ {job.status === "done" && "Ready — drag it in or press +"}
{job.status === "error" && (job.error ?? "Failed.")}
</div>
</div>
@@ -193,14 +196,27 @@ function JobRow({ job }: { job: GenerateJob }) {
<Plus className="size-3.5" />
</button>
)}
- {job.status !== "running" && (
- <button
- title="Dismiss"
- className="grid size-6 shrink-0 place-items-center rounded-full text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100 hover:text-foreground"
- onClick={() => useGenerate.getState().dismiss(job.id)}
- >
- <Trash2 className="size-3.5" />
- </button>
+ {job.status === "done" && asset ? (
+ <GeneratedAssetMenu
+ asset={asset}
+ projectId={job.projectId}
+ triggerClassName="grid size-6 shrink-0 place-items-center rounded-full text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100 data-popup-open:opacity-100 hover:text-foreground"
+ after={
+ <DropdownMenuItem onClick={() => useGenerate.getState().dismiss(job.id)}>
+ <Trash2 /> Dismiss
+ </DropdownMenuItem>
+ }
+ />
+ ) : (
+ job.status !== "running" && (
+ <button
+ title="Dismiss"
+ className="grid size-6 shrink-0 place-items-center rounded-full text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100 hover:text-foreground"
+ onClick={() => useGenerate.getState().dismiss(job.id)}
+ >
+ <Trash2 className="size-3.5" />
+ </button>
+ )
)}
</div>
);
diff --git a/site/src/cut/components/Lightbox.tsx b/site/src/cut/components/Lightbox.tsx
index 55d6966f..bf577360 100644
--- a/site/src/cut/components/Lightbox.tsx
+++ b/site/src/cut/components/Lightbox.tsx
@@ -4,7 +4,7 @@ import { useEffect, useState } from "react";
import { Check, Copy, Loader2, Plus, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useLightbox } from "@/cut/lib/lightbox";
-import { importImage } from "@/cut/lib/media";
+import { importImage, importStockVideo } from "@/cut/lib/media";
import { useEditor } from "@/cut/lib/store";
// The image lightbox: the bigger version of a stock or generated image, with
@@ -41,7 +41,10 @@ export function Lightbox() {
if (item.assetId) {
useEditor.getState().addClipFromAsset(item.assetId);
} else {
- const asset = await importImage(projectId, { url: item.src, name: item.name });
+ // A stock clip imports as footage; a stock image bakes into a still.
+ const asset = item.playable
+ ? await importStockVideo(projectId, { url: item.src, name: item.name })
+ : await importImage(projectId, { url: item.src, name: item.name });
useEditor.getState().addClipFromAsset(asset.id);
}
setAddedSrc(item.src);
@@ -70,13 +73,24 @@ export function Lightbox() {
</button>
{item.isVideo ? (
- <video
- muted
- playsInline
- preload="metadata"
- src={`${item.src}#t=0.1`}
- className="block max-h-[75vh] w-full object-contain"
- />
+ item.playable ? (
+ <video
+ controls
+ autoPlay
+ loop
+ playsInline
+ src={item.src}
+ className="block max-h-[75vh] w-full bg-black object-contain"
+ />
+ ) : (
+ <video
+ muted
+ playsInline
+ preload="metadata"
+ src={`${item.src}#t=0.1`}
+ className="block max-h-[75vh] w-full object-contain"
+ />
+ )
) : (
// eslint-disable-next-line @next/next/no-img-element -- static/project image, client-only page
<img
diff --git a/site/src/cut/components/SidePanel.tsx b/site/src/cut/components/SidePanel.tsx
index 6658e9a9..852c93aa 100644
--- a/site/src/cut/components/SidePanel.tsx
+++ b/site/src/cut/components/SidePanel.tsx
@@ -45,6 +45,8 @@ import { buildDragGhost, FolderCrumb, FolderShelf } from "./desktopFolders";
import { GenerateVideoPanel } from "./GeneratePanel";
import { ImageGenPanel } from "./ImageGenPanel";
import { StockImagesPanel } from "./StockImagesPanel";
+import { StockVideosPanel } from "./StockVideosPanel";
+import { STOCK_VIDEOS } from "@/cut/lib/stockVideoManifest";
import { LibraryCard } from "./LibraryView";
// Drag a library clip onto a folder tile to file it (side panel, single card).
@@ -80,7 +82,15 @@ export function SidePanel({
// Clicking a reference token anywhere jumps here: switch to the tab that
// owns the asset; the matching card scrolls into view and flashes.
useRevealEffect((ref) => {
- setTab(ref.scope === "project" ? "media" : ref.scope === "library" ? "library" : "image");
+ setTab(
+ ref.scope === "project"
+ ? "media"
+ : ref.scope === "library"
+ ? "library"
+ : STOCK_VIDEOS.some((v) => v.id === ref.id)
+ ? "video"
+ : "image"
+ );
});
return (
@@ -124,16 +134,20 @@ export function SidePanel({
})}
</div>
- {tab === "image" ? (
- // The Image tab is two columns: the generate-image input on the left,
+ {tab === "image" || tab === "video" ? (
+ // The generate tabs are two columns: the generate input on the left,
// the stock reference browser on the right. Clicking a stock tile loads
// its prompt into the generate panel beside it.
<>
<div className="flex w-[252px] min-h-0 shrink-0 flex-col border-r border-border">
- <ImageGenPanel projectId={projectId} />
+ {tab === "image" ? (
+ <ImageGenPanel projectId={projectId} />
+ ) : (
+ <GenerateVideoPanel projectId={projectId} />
+ )}
</div>
<div className="flex w-[264px] min-h-0 shrink-0 flex-col">
- <StockImagesPanel />
+ {tab === "image" ? <StockImagesPanel /> : <StockVideosPanel />}
</div>
</>
) : (
@@ -141,7 +155,6 @@ export function SidePanel({
{tab === "media" && (
<MediaPanel projectId={projectId} onImport={onImport} importing={importing} />
)}
- {tab === "video" && <GenerateVideoPanel projectId={projectId} />}
{tab === "library" && <LibraryPanel projectId={projectId} />}
{tab === "audio" && <AudioPanel projectId={projectId} importing={importing} />}
{tab === "subtitles" && <SubtitlesPanel />}
diff --git a/site/src/cut/components/StockVideosPanel.tsx b/site/src/cut/components/StockVideosPanel.tsx
new file mode 100644
index 00000000..882842df
--- /dev/null
+++ b/site/src/cut/components/StockVideosPanel.tsx
@@ -0,0 +1,239 @@
+"use client";
+
+import { useRef, useState } from "react";
+import { ChevronLeft, ChevronRight, Maximize2, Search } from "lucide-react";
+import { clearRefDrag, refFromStockVideo, setRefDragData } from "@/cut/lib/assetRef";
+import { useLightbox } from "@/cut/lib/lightbox";
+import { useRevealEffect, useRevealFlash } from "@/cut/lib/refReveal";
+import { useVideoGen } from "@/cut/lib/videoGen";
+import { STOCK_CATEGORIES, type StockVideo } from "@/cut/lib/stock";
+import { STOCK_VIDEOS } from "@/cut/lib/stockVideoManifest";
+import { formatTime } from "@/cut/lib/time";
+import { cn } from "@/lib/utils";
+import { CopyRefButton, RefHandlePill } from "./AssetRefs";
+
+/** A readable title from a stock id, e.g. "nature-waves" → "Nature Waves". */
+const titleFromId = (id: string) =>
+ id.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
+
+// The Video tab's reference browser: a searchable catalog of AI-generated stock
+// clips. Every clip carries the prompt that made it — clicking one loads that
+// prompt into the generate panel beside it to edit and render on the user's
+// account. Videos the user generates show up in that panel, not here.
+
+type View = "all" | (typeof STOCK_CATEGORIES)[number];
+
+const chip = (active: boolean) =>
+ cn(
+ "shrink-0 rounded-full px-2 py-0.5 text-[10px] font-medium transition-colors",
+ active ? "bg-primary/15 text-primary" : "bg-muted text-muted-foreground hover:text-foreground"
+ );
+
+export function StockVideosPanel() {
+ const [view, setView] = useState<View>("all");
+ const [query, setQuery] = useState("");
+
+ // Only categories the catalog actually covers get a chip.
+ const categories = STOCK_CATEGORIES.filter((c) => STOCK_VIDEOS.some((v) => v.category === c));
+
+ // A revealed stock clip may sit behind a category view — open its category
+ // so the tile is on screen to flash.
+ useRevealEffect((ref) => {
+ if (ref.scope !== "stock") return;
+ const item = STOCK_VIDEOS.find((v) => v.id === ref.id);
+ if (!item) return;
+ setView(item.category);
+ setQuery("");
+ });
+
+ const q = query.trim().toLowerCase();
+ const matches = (item: StockVideo) =>
+ !q ||
+ item.prompt.toLowerCase().includes(q) ||
+ item.category.toLowerCase().includes(q) ||
+ item.tags.some((t) => t.includes(q));
+
+ const stock = STOCK_VIDEOS.filter(matches);
+
+ return (
+ <>
+ <div className="flex h-12 shrink-0 items-center pr-2.5 pl-2.5">
+ <span className="flex min-w-0 items-center gap-1 text-sm font-semibold tracking-tight">
+ {view !== "all" && (
+ <button
+ title="All stock videos"
+ className="grid size-6 shrink-0 place-items-center rounded-md text-muted-foreground hover:text-foreground"
+ onClick={() => setView("all")}
+ >
+ <ChevronLeft className="size-4" />
+ </button>
+ )}
+ <span className={cn("truncate", view === "all" && "pl-1.5")}>
+ {view === "all" ? "Stock Videos" : view}
+ </span>
+ </span>
+ </div>
+
+ <div className="flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto px-3.5 pb-4">
+ {STOCK_VIDEOS.length === 0 ? (
+ <p className="text-[11px] leading-relaxed text-muted-foreground">
+ No stock videos are bundled yet.
+ </p>
+ ) : (
+ <>
+ <label className="flex shrink-0 items-center gap-2 rounded-lg border border-input px-2.5 py-1.5 focus-within:border-ring">
+ <Search className="size-3.5 shrink-0 text-muted-foreground" />
+ <input
+ className="w-full bg-transparent text-[12px] outline-none placeholder:text-muted-foreground"
+ placeholder="Search…"
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ />
+ </label>
+
+ <div className="flex shrink-0 flex-wrap gap-1">
+ <button className={chip(view === "all")} onClick={() => setView("all")}>
+ All
+ </button>
+ {categories.map((c) => (
+ <button key={c} className={chip(view === c)} onClick={() => setView(c)}>
+ {c}
+ </button>
+ ))}
+ </div>
+
+ {view === "all" ? (
+ <>
+ {categories.map((c) => {
+ const items = stock.filter((v) => v.category === c);
+ if (items.length === 0) return null;
+ return (
+ <section key={c} className="shrink-0">
+ <SectionHead
+ title={c}
+ onViewAll={items.length > 6 ? () => setView(c) : undefined}
+ />
+ <div className="grid grid-cols-2 gap-1.5">
+ {items.slice(0, 6).map((v) => (
+ <StockTile key={v.id} item={v} />
+ ))}
+ </div>
+ </section>
+ );
+ })}
+ {stock.length === 0 && <Empty />}
+ </>
+ ) : (
+ (() => {
+ const items = stock.filter((v) => v.category === view);
+ return items.length > 0 ? (
+ <div className="grid grid-cols-2 gap-1.5">
+ {items.map((v) => (
+ <StockTile key={v.id} item={v} />
+ ))}
+ </div>
+ ) : (
+ <Empty />
+ );
+ })()
+ )}
+ </>
+ )}
+ </div>
+ </>
+ );
+}
+
+function SectionHead({ title, onViewAll }: { title: string; onViewAll?: () => void }) {
+ return (
+ <div className="mb-1.5 flex items-center justify-between">
+ <span className="text-[12px] font-semibold">{title}</span>
+ {onViewAll && (
+ <button
+ className="flex items-center gap-0.5 text-[11px] text-muted-foreground hover:text-foreground"
+ onClick={onViewAll}
+ >
+ View all
+ <ChevronRight className="size-3" />
+ </button>
+ )}
+ </div>
+ );
+}
+
+/** A stock clip: hover plays it, clicking loads its saved prompt into the
+ * generate panel, and it drags as a video ref (chat attachment, generation
+ * start frame, timeline drop). */
+function StockTile({ item }: { item: StockVideo }) {
+ const videoRef = useRef<HTMLVideoElement>(null);
+ const { flash, attachReveal } = useRevealFlash("stock", item.id);
+ return (
+ <div
+ ref={attachReveal}
+ className={cn(
+ "group relative overflow-hidden rounded-lg",
+ flash && "ring-2 ring-[#0a84ff] ring-offset-1"
+ )}
+ onMouseEnter={() => {
+ void videoRef.current?.play().catch(() => {});
+ }}
+ onMouseLeave={() => {
+ const v = videoRef.current;
+ if (v) {
+ v.pause();
+ v.currentTime = 0;
+ }
+ }}
+ >
+ <button
+ title={item.prompt}
+ className="block w-full outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ draggable
+ onDragStart={(e) => setRefDragData(e, refFromStockVideo(item))}
+ onDragEnd={clearRefDrag}
+ onClick={() => useVideoGen.getState().openWith(item.prompt)}
+ >
+ <video
+ ref={videoRef}
+ src={item.file}
+ poster={item.thumb}
+ preload="none"
+ muted
+ loop
+ playsInline
+ className="aspect-[16/10] w-full bg-muted object-cover"
+ />
+ </button>
+ <span className="pointer-events-none absolute right-1 bottom-1 rounded-[5px] bg-black/65 px-1 py-px font-mono text-[9.5px] text-white tabular-nums">
+ {formatTime(item.duration)}
+ </span>
+ <RefHandlePill
+ token={`@${item.id}`}
+ className="absolute bottom-1 left-1 opacity-0 transition-opacity group-hover:opacity-100"
+ />
+ <div className="absolute top-1 right-1 flex gap-1 opacity-0 transition-opacity group-hover:opacity-100">
+ <button
+ title="Expand"
+ className="grid size-5 place-items-center rounded-full bg-black/45 text-white hover:bg-black/65"
+ onClick={() =>
+ useLightbox.getState().open({
+ src: item.file,
+ isVideo: true,
+ playable: true,
+ name: titleFromId(item.id),
+ prompt: item.prompt,
+ assetId: null,
+ })
+ }
+ >
+ <Maximize2 className="size-3" />
+ </button>
+ <CopyRefButton name={item.id} />
+ </div>
+ </div>
+ );
+}
+
+function Empty() {
+ return <p className="text-[11px] text-muted-foreground">No matches.</p>;
+}
diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsx
index 5c0f699a..9ed09b2c 100644
--- a/site/src/cut/components/Timeline.tsx
+++ b/site/src/cut/components/Timeline.tsx
@@ -22,7 +22,7 @@ import {
import { draggingRef, hasRefDrag, refFromAsset, startPointerRefDrag, type AssetRef } from "@/cut/lib/assetRef";
import { importLibraryAsset, saveTemplate } from "@/cut/lib/library";
import { startDrag } from "@/cut/lib/drag";
-import { ensurePeaks, importImage } from "@/cut/lib/media";
+import { ensurePeaks, importImage, importStockVideo } from "@/cut/lib/media";
import { clipLen, clipSpeed, getClipSpans, projectDuration, TIMELINE_H_MAX, useEditor } from "@/cut/lib/store";
import type { VideoTrackPlacement } from "@/cut/lib/store";
import { formatTime, formatTimecode } from "@/cut/lib/time";
@@ -147,6 +147,15 @@ function draggingStill(e: React.DragEvent): AssetRef | null {
return ref?.kind === "image" ? ref : null;
}
+/** The stock-clip ref being dragged (a stock video tile), null for any other
+ * drag — project and library videos carry their own MIMEs and are handled
+ * first. On the timeline it imports into the project and lands as footage. */
+function draggingStockVideo(e: React.DragEvent): AssetRef | null {
+ if (!hasRefDrag(e)) return null;
+ const ref = draggingRef();
+ return ref?.scope === "stock" && ref.kind === "video" ? ref : null;
+}
+
/** Insertion slot for a new clip dropped at time `t`: it lands before the
* first span whose midpoint is past `t` (spans.length = at the very end).
* Exported for the Editor's OS-file drops onto the timeline. */
@@ -469,6 +478,8 @@ export function Timeline() {
if (!asset || !isBaseType(asset.type)) return null;
return { duration: asset.type === "image" ? STILL_SECONDS : asset.duration };
}
+ const stockVideo = draggingStockVideo(e);
+ if (stockVideo) return { duration: stockVideo.duration ?? 0 };
return draggingStill(e) ? { duration: STILL_SECONDS } : null;
};
@@ -498,6 +509,7 @@ export function Timeline() {
const lib = draggingLibrary();
const libId = draggedLibraryId(e);
const still = draggingStill(e);
+ const stockVideo = draggingStockVideo(e);
const projectId = useEditor.getState().projectId;
clearAssetDrag();
if (libId && lib && isBaseType(lib.type) && projectId) {
@@ -512,6 +524,12 @@ export function Timeline() {
useEditor.getState().addVideoFromAsset(id, place, t);
return;
}
+ if (stockVideo && projectId) {
+ void importStockVideo(projectId, { url: stockVideo.url, name: stockVideo.name })
+ .then((vid) => useEditor.getState().addVideoFromAsset(vid.id, place, t))
+ .catch(() => {});
+ return;
+ }
if (still && projectId) {
void importImage(projectId, still)
.then((img) => useEditor.getState().addVideoFromAsset(img.id, place, t))
@@ -563,17 +581,21 @@ export function Timeline() {
onDragOver={(e) => {
const isLib = hasLibraryDrag(e);
const still = draggingStill(e);
- if (!hasAssetDrag(e) && !isLib && !still) return;
+ const stockVideo = draggingStockVideo(e);
+ if (!hasAssetDrag(e) && !isLib && !still && !stockVideo) return;
e.preventDefault();
e.dataTransfer.dropEffect = "copy";
// Preview where a video would land; audio drops free-form. Library and
- // image drags carry their own shape since they aren't in the project yet.
+ // stock drags carry their own shape since they aren't in the project yet.
let type: "video" | "audio" | "image" | undefined;
let duration = 0;
if (isLib) {
const lib = draggingLibrary();
type = lib?.type;
duration = lib?.duration ?? 0;
+ } else if (stockVideo) {
+ type = "video";
+ duration = stockVideo.duration ?? 0;
} else if (still) {
type = "video";
duration = STILL_SECONDS;
@@ -611,6 +633,7 @@ export function Timeline() {
const lib = draggingLibrary();
const libId = draggedLibraryId(e);
const still = draggingStill(e);
+ const stockVideo = draggingStockVideo(e);
const projectId = useEditor.getState().projectId;
clearAssetDrag();
if (libId && lib && projectId) {
@@ -629,7 +652,15 @@ export function Timeline() {
return;
}
- // An image ref imports as a still, then snaps into the base-track slot.
+ // A stock clip imports as footage, an image ref as a still, then each
+ // snaps into the base-track slot.
+ if (stockVideo && projectId) {
+ e.preventDefault();
+ void importStockVideo(projectId, { url: stockVideo.url, name: stockVideo.name })
+ .then((asset) => placeAssetAt(asset.id, "video", t))
+ .catch(() => {});
+ return;
+ }
if (still && projectId) {
e.preventDefault();
void importImage(projectId, still)
diff --git a/site/src/cut/lib/assetRef.ts b/site/src/cut/lib/assetRef.ts
index 07e6215a..5ab82436 100644
--- a/site/src/cut/lib/assetRef.ts
+++ b/site/src/cut/lib/assetRef.ts
@@ -3,8 +3,9 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type React from "react";
import { fetchLibrary, libraryMediaUrl, type LibraryAsset } from "./library";
-import type { StockImage } from "./stock";
+import type { StockImage, StockVideo } from "./stock";
import { STOCK_IMAGES } from "./stockManifest";
+import { STOCK_VIDEOS } from "./stockVideoManifest";
import { useEditor } from "./store";
import type { MediaAsset } from "./types";
@@ -68,6 +69,15 @@ export const refFromStock = (i: StockImage): AssetRef => ({
url: i.file,
});
+export const refFromStockVideo = (v: StockVideo): AssetRef => ({
+ scope: "stock",
+ id: v.id,
+ name: v.id,
+ kind: "video",
+ url: v.file,
+ duration: v.duration,
+});
+
export const sameRef = (a: AssetRef, b: AssetRef) => a.scope === b.scope && a.id === b.id;
export const addRefOnce = (list: AssetRef[], ref: AssetRef): AssetRef[] =>
@@ -279,6 +289,7 @@ export function useRefCandidates(): AssetRef[] {
...project,
...lib.map(refFromLibrary),
...STOCK_IMAGES.map(refFromStock),
+ ...STOCK_VIDEOS.map(refFromStockVideo),
]) {
const key = ref.name.toLowerCase();
if (seen.has(key)) continue;
diff --git a/site/src/cut/lib/lightbox.ts b/site/src/cut/lib/lightbox.ts
index c5665b44..cd01fb40 100644
--- a/site/src/cut/lib/lightbox.ts
+++ b/site/src/cut/lib/lightbox.ts
@@ -2,7 +2,7 @@
import { create } from "zustand";
-// The image lightbox: a full-screen preview opened from a stock tile or a
+// The media lightbox: a full-screen preview opened from a stock tile or a
// generated image. Held in its own store so any tile can open it and a single
// overlay (mounted once in the editor) renders it.
@@ -11,6 +11,9 @@ export interface LightboxItem {
src: string;
/** Generated stills are 8s videos — render the poster frame, not an <img>. */
isVideo: boolean;
+ /** True for real footage (a stock clip): play it with controls instead of
+ * showing the poster frame. */
+ playable?: boolean;
name: string;
/** The generation prompt, when known. */
prompt: string;
diff --git a/site/src/cut/lib/media.ts b/site/src/cut/lib/media.ts
index da4c2a0b..60981731 100644
--- a/site/src/cut/lib/media.ts
+++ b/site/src/cut/lib/media.ts
@@ -181,6 +181,29 @@ export async function importImage(
return asset;
}
+/** Store a fetchable video (a stock clip) in the project's media as a regular
+ * video asset and register it, without placing it on the timeline. Callers
+ * choose where it lands. */
+export async function importStockVideo(
+ projectId: string,
+ video: { url: string; name: string }
+): Promise<MediaAsset> {
+ const dl = await fetch(video.url);
+ if (!dl.ok) throw new Error("Could not read the video.");
+ const blob = await dl.blob();
+ const file = new File([blob], video.url.split("/").pop() || "video.mp4", {
+ type: blob.type || "video/mp4",
+ });
+ const asset = await importFileToProject(projectId, file);
+ if (!asset) throw new Error("Could not add the video.");
+ asset.name = video.name;
+ // Like a stock image, it lands where the caller places it, not in Media.
+ asset.origin = "stock";
+ useEditor.getState().addAsset(asset);
+ void enrichAsset(asset);
+ return asset;
+}
+
/** Build a runtime asset for a media file the engine already wrote into the
* project folder (freeze frames, AI generations) — probe metadata, no upload. */
export async function assetFromProjectFile(
diff --git a/site/src/cut/lib/stock.ts b/site/src/cut/lib/stock.ts
index e8b7a7f2..558494b6 100644
--- a/site/src/cut/lib/stock.ts
+++ b/site/src/cut/lib/stock.ts
@@ -1,8 +1,10 @@
-// The bundled stock-image catalog: AI-generated stills that ship with the site
-// (files under public/cut-stock, manifest in stockManifest.ts). Each entry keeps
-// the exact prompt that produced it — clicking a stock image copies that prompt
-// into the generate flyover for the user to edit and re-render on their account.
-// Regenerate or extend the set with `bun scripts/generate-stock-images.ts`.
+// The bundled stock catalogs: AI-generated stills and clips that ship with the
+// site (files under public/cut-stock and public/cut-stock-video, manifests in
+// stockManifest.ts and stockVideoManifest.ts). Each entry keeps the exact
+// prompt that produced it — clicking a stock tile copies that prompt into the
+// generate panel beside it for the user to edit and re-render on their account.
+// Regenerate or extend the sets with `bun scripts/generate-stock-images.ts`
+// and `bun scripts/generate-stock-videos.ts`.
export type StockAspect = "16:9" | "9:16" | "1:1";
@@ -21,6 +23,26 @@ export interface StockImage {
thumb: string;
}
+/** Veo renders landscape and portrait only — no square video. */
+export type StockVideoAspect = "16:9" | "9:16";
+
+export interface StockVideo {
+ id: string;
+ category: StockCategory;
+ /** The generation prompt, saved verbatim — the editable starting point. */
+ prompt: string;
+ /** Vision-extracted keywords for the visible content (objects, setting,
+ * subjects) — what the search box matches beyond the prompt text. */
+ tags: string[];
+ aspect: StockVideoAspect;
+ /** Site-relative mp4 URL (under /cut-stock-video/) — playback, refs, timeline. */
+ file: string;
+ /** Poster-frame thumbnail URL for the browse grid. */
+ thumb: string;
+ /** Rendered length in seconds. */
+ duration: number;
+}
+
export const STOCK_CATEGORIES = [
"Business",
"Nature",
diff --git a/site/src/cut/lib/stockVideoManifest.ts b/site/src/cut/lib/stockVideoManifest.ts
new file mode 100644
index 00000000..3dffe48b
--- /dev/null
+++ b/site/src/cut/lib/stockVideoManifest.ts
@@ -0,0 +1,4 @@
+// Generated by scripts/generate-stock-videos.ts — do not edit by hand.
+import type { StockVideo } from "./stock";
+
+export const STOCK_VIDEOS: StockVideo[] = [];
diff --git a/site/src/cut/lib/videoGen.ts b/site/src/cut/lib/videoGen.ts
new file mode 100644
index 00000000..5e826c31
--- /dev/null
+++ b/site/src/cut/lib/videoGen.ts
@@ -0,0 +1,30 @@
+"use client";
+
+import { create } from "zustand";
+import { addRefOnce, sameRef, type AssetRef } from "./assetRef";
+
+// The generate-video panel's state, shared between the stock-video browser
+// (which loads a stock clip's saved prompt into it on click) and the always-on
+// generate panel that sits beside the browser in the Video tab.
+
+interface VideoGenState {
+ prompt: string;
+ /** Visual references attached to the next generation (dragged in or picked
+ * via @name mentions resolved on send). */
+ refs: AssetRef[];
+ /** Load a starting prompt into the panel (a stock clip's saved prompt, or
+ * "" for a blank generation). Resets any attached references. */
+ openWith: (prompt: string) => void;
+ setPrompt: (prompt: string) => void;
+ addRef: (ref: AssetRef) => void;
+ removeRef: (ref: AssetRef) => void;
+}
+
+export const useVideoGen = create<VideoGenState>((set) => ({
+ prompt: "",
+ refs: [],
+ openWith: (prompt) => set({ prompt, refs: [] }),
+ setPrompt: (prompt) => set({ prompt }),
+ addRef: (ref) => set((s) => ({ refs: addRefOnce(s.refs, ref) })),
+ removeRef: (ref) => set((s) => ({ refs: s.refs.filter((r) => !sameRef(r, ref)) })),
+}));