Skip to content

Open source CapCut alternative.

TypeScript

feat(site): chat imports TikTok/YouTube/Reels URLs onto a chat card [rebuild]

David Le4b75b89c612a
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.ts
index 560c540b..56fe00b1 100644
--- a/site/src/cut/lib/aiTools.ts
+++ b/site/src/cut/lib/aiTools.ts
@@ -14,13 +14,12 @@ import {
deleteTemplate,
fetchLibrary,
importLibraryAsset,
- importUrlToLibrary,
moveLibraryAsset,
renameLibraryFolder,
saveAssetToLibrary,
saveTemplate,
} from "./library";
-import { enrichAsset, ensurePeaks, importImage, importStockVideo } from "./media";
+import { enrichAsset, ensurePeaks, importImage, importStockVideo, importUrlMedia } from "./media";
import { refToInlineAudio } from "./refMedia";
import { characterPrompt, stockTitle } from "./stock";
import { STOCK_IMAGES } from "./stockManifest";
@@ -892,6 +891,24 @@ export async function runAiTool(
};
}
+ case "import_url": {
+ const projectId = s.projectId;
+ if (!projectId) throw new ToolError("No project open.");
+ const url = String(input.url ?? "").trim();
+ if (!url) throw new ToolError("A URL is required.");
+ // Captured before the download: the media files under the chat that
+ // asked, even if the user switches threads while it downloads.
+ const chatId = chatOwner();
+ const asset = await importUrlMedia(projectId, url);
+ tagChatAsset(asset.id, chatId);
+ return {
+ assetId: asset.id,
+ name: asset.name,
+ kind: asset.type,
+ duration: round2(asset.duration),
+ };
+ }
+
case "library_list": {
const lib = await fetchLibrary();
return {
@@ -1013,12 +1030,6 @@ export async function runAiTool(
await deleteTemplate(String(input.id ?? ""));
return { deleted: true };
}
- case "import_url": {
- const url = String(input.url ?? "").trim();
- if (!url) throw new ToolError("A URL is required.");
- const a = await importUrlToLibrary(url);
- return { id: a.id, name: a.name, kind: a.type, duration: round2(a.duration) };
- }
default:
throw new ToolError(`Unknown action "${String(input.action)}".`);
}
diff --git a/site/src/cut/lib/media.ts b/site/src/cut/lib/media.ts
index 2292fb3c..5849f875 100644
--- a/site/src/cut/lib/media.ts
+++ b/site/src/cut/lib/media.ts
@@ -208,6 +208,23 @@ export async function importStockVideo(
return asset;
}
+/** Download a media URL (TikTok, YouTube, …) into the project through the
+ * engine's bundled downloader and register it, without placing it on the
+ * timeline. Callers choose where it lands. */
+export async function importUrlMedia(projectId: string, url: string): Promise<MediaAsset> {
+ const res = await apiFetch(`/api/cut/projects/${projectId}/import-url`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ url }),
+ });
+ const body = await apiJson<{ fileName?: string; title?: string }>(res);
+ if (!res.ok || !body.fileName) throw new Error(body.error ?? "Could not import that URL.");
+ const asset = await assetFromProjectFile(projectId, body.fileName, body.title || "Imported clip");
+ 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/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.ts
index 99187797..0e1a62c8 100644
--- a/site/src/cut/server/ai/catalog.ts
+++ b/site/src/cut/server/ai/catalog.ts
@@ -369,6 +369,12 @@ export const AI_TOOLS: AiToolDef[] = [
start: num("Timeline start s (passing it implies add_to_timeline; default when placed: appended at the end)"),
}, ["id"]),
},
+ {
+ name: "import_url",
+ description:
+ "Download a media URL — TikTok, YouTube, Instagram Reels, or a direct video/audio link — with the bundled downloader and import it into the project. Free and local. It lands on a card in this chat, and the user drags it from there to the timeline, Media, or the Library; place it yourself (add_clip) only when they asked for it in the cut. A short clip downloads in seconds; a long video can take a couple of minutes.",
+ inputSchema: obj({ url: str("The page or media URL to download") }, ["url"]),
+ },
{
name: "library_list",
description:
@@ -408,17 +414,16 @@ export const AI_TOOLS: AiToolDef[] = [
{
name: "library_organize",
description:
- "Organize the shared Library: create_folder / rename_folder / delete_folder (a deleted folder's assets drop to the root), move_asset files an asset into a folder (omit folder_id for the root), delete_asset / delete_template remove an item, import_url downloads a media URL into the Library. Deletes are permanent — projects keep their own copies, but delete only what the user explicitly asked to remove.",
+ "Organize the shared Library: create_folder / rename_folder / delete_folder (a deleted folder's assets drop to the root), move_asset files an asset into a folder (omit folder_id for the root), delete_asset / delete_template remove an item. Deletes are permanent — projects keep their own copies, but delete only what the user explicitly asked to remove.",
inputSchema: obj({
action: {
type: "string",
- enum: ["create_folder", "rename_folder", "delete_folder", "move_asset", "delete_asset", "delete_template", "import_url"],
+ enum: ["create_folder", "rename_folder", "delete_folder", "move_asset", "delete_asset", "delete_template"],
description: "The organize operation",
},
name: str("Folder name (create_folder, rename_folder)"),
folder_id: str("Folder id (rename_folder, delete_folder, move_asset destination — omit for root)"),
id: str("Library asset or template id (move_asset, delete_asset, delete_template)"),
- url: str("Media URL to import (import_url)"),
}, ["action"]),
},
{
@@ -711,7 +716,7 @@ subtitles_set_view: showOnVideo (preview + export burn-in), showOnTimeline (ambe
Caption look: the Subtitles panel offers 10 visual presets (clean, hook, punchy, minimal, editorial, typewriter, block, highlight, bubble, neon), a per-word karaoke highlight with accent overrides, and each track's caption drags to a new spot in the preview. No tool sets the look — direct the user to the panel. captions_generate's clean/hook/punchy choice shapes the caption text it writes; the visual preset is separate.`,
"ai-generation": `# Stock media & AI generation
-Two ways to get footage the user doesn't have: bundled stock (local, free) and hosted generation (signed in, spends credits). Prefer stock when it genuinely fits; generate when the shot needs to be specific.
+Three ways to get footage the user doesn't have: bundled stock (local, free), a URL they point at (import_url downloads TikTok / YouTube / Instagram / direct links, free), and hosted generation (signed in, spends credits). Prefer stock when it genuinely fits; generate when the shot needs to be specific.
Stock: stock_search browses the bundled catalogs — footage clips and images in 8 categories plus ~20 UGC talking characters — matching prompts, categories, and tags. stock_add imports an item into the project as a chat card; add_to_timeline:true (or a start) also drops it on the timeline when the user asked. In the UI these live in the Video and Image tabs beside the generators; clicking a stock tile seeds the generate panel with its prompt.
Generation:
- generate_image(prompt, aspect?, resolution?, reference_asset_ids?, add_to_timeline?, index?): the hosted image model renders the prompt at 16:9, 9:16, or 1:1 (default: project aspect) and 1K/2K/4K. The still previews in the chat; placed (add_to_timeline:true or an index) it rides video track 0 as a still clip (8s default, stretchable). Great for a cover/hook frame (index 0), a background, or a b-roll still.
@@ -735,7 +740,8 @@ Project media (\`media\` in editor_state) is every file in the open project. The
- delete_asset removes an asset from the project plus its timeline clips; the media does not come back with undo, so only on an explicit ask, and say what went with it.
The Library is shared across every project: folders, reusable assets, and templates — a template is a saved arrangement (clips, overlays, titles, captions, by reference) that comes back editable.
- library_list browses it; library_add copies an asset into the project (the import step "library"-scope attachments need); template_add re-materializes a template; save_template saves timeline items as one.
-- library_organize handles folders (create/rename/delete), filing (move_asset), deletes (permanent — explicit ask only), and import_url for a media URL.
+- library_organize handles folders (create/rename/delete), filing (move_asset), and deletes (permanent — explicit ask only).
+- import_url downloads a media URL (TikTok, YouTube, Instagram, direct links) into the project as a card in the chat; the user drags it to the timeline, Media, or the Library. Place it with add_clip only when they asked for it in the cut.
Attachments: media files dropped on the chat import into project media by themselves; library attachments wait for library_add.`,
"publish-and-export": `# Publish & export
diff --git a/site/src/cut/server/http/projects.ts b/site/src/cut/server/http/projects.ts
index 194979af..5a8ded16 100644
--- a/site/src/cut/server/http/projects.ts
+++ b/site/src/cut/server/http/projects.ts
@@ -22,6 +22,7 @@ import {
writeProject,
} from "../projects";
import { serveFileRange } from "../serveFile";
+import { importUrlToProject } from "../urlImport";
import { createTranscribeJob, getTranscribeJob, type TranscribeSpec } from "../transcribe";
import { exists } from "../util";
@@ -177,6 +178,17 @@ export const projectsApi = {
return serveFileRange(p, req, { contentType: "video/mp4" });
},
+ /** Download a media URL straight into the project's media folder. */
+ async importUrl(req: Request, { id }: { id: string }) {
+ try {
+ const { url } = (await req.json()) as { url?: string };
+ if (!url) return err("No URL provided.", 400);
+ return Response.json(await importUrlToProject(id, url));
+ } catch (e) {
+ return caught(e, "Could not import that URL.");
+ }
+ },
+
async uploadMedia(req: Request, { id }: { id: string }) {
try {
if (!(await readProject(id))) return err("Project not found.", 404);
diff --git a/site/src/cut/server/http/routes.ts b/site/src/cut/server/http/routes.ts
index 0dacecc0..9881fdfb 100644
--- a/site/src/cut/server/http/routes.ts
+++ b/site/src/cut/server/http/routes.ts
@@ -32,6 +32,7 @@ export const CUT_ROUTES: CutRoute[] = [
{ method: "PUT", path: "/api/cut/projects/:id", handler: (req, p) => projectsApi.put(req, { id: p.id }) },
{ method: "DELETE", path: "/api/cut/projects/:id", handler: (req, p) => projectsApi.remove(req, { id: p.id }) },
{ method: "POST", path: "/api/cut/projects/:id/media", handler: (req, p) => projectsApi.uploadMedia(req, { id: p.id }) },
+ { method: "POST", path: "/api/cut/projects/:id/import-url", handler: (req, p) => projectsApi.importUrl(req, { id: p.id }) },
{ method: "GET", path: "/api/cut/projects/:id/media/:file", handler: (req, p) => projectsApi.serveMedia(req, { id: p.id, file: p.file }) },
{ method: "DELETE", path: "/api/cut/projects/:id/media/:file", handler: (req, p) => projectsApi.removeMedia(req, { id: p.id, file: p.file }) },
{ method: "GET", path: "/api/cut/projects/:id/exports", handler: (req, p) => projectsApi.listExports(req, { id: p.id }) },
diff --git a/site/src/cut/server/urlImport.ts b/site/src/cut/server/urlImport.ts
index ae16a75b..ee30daeb 100644
--- a/site/src/cut/server/urlImport.ts
+++ b/site/src/cut/server/urlImport.ts
@@ -1,13 +1,14 @@
import { spawn } from "node:child_process";
-import { mkdtemp, readdir, rm, stat } from "node:fs/promises";
+import { copyFile, mkdir, mkdtemp, readdir, rm, stat } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
-import { addDownloaded, type LibraryAsset } from "./library";
+import { addDownloaded, type LibraryAsset, type LibrarySource } from "./library";
import { assertLocalRuntime } from "./local-only";
+import { mediaDir, mediaPath as projectMediaPath, readProject } from "./projects";
+import { uniqueName } from "./util";
-// Download a media URL (TikTok, YouTube, Instagram, …) into the shared library
-// with the bundled yt-dlp. The engine finds yt-dlp on its widened PATH exactly
-// like ffmpeg.
+// Download a media URL (TikTok, YouTube, Instagram, …) with the bundled
+// yt-dlp. The engine finds yt-dlp on its widened PATH exactly like ffmpeg.
const MEDIA_EXT = /\.(mp4|mov|m4v|webm|mkv|mp3|m4a|aac|wav|ogg|flac)$/i;
@@ -22,15 +23,25 @@ interface YtMeta {
webpage_url?: string;
}
-export async function importFromUrl(url: string): Promise<LibraryAsset> {
+/** What a finished download hands its consumer: the merged media file (inside
+ * a temp dir the wrapper deletes afterwards) plus what yt-dlp knew about it. */
+interface Downloaded {
+ file: string;
+ title: string;
+ source: LibrarySource;
+}
+
+/** Run one guarded download and hand the file to `consume` before the temp
+ * dir is deleted. The active slot spans the whole operation; mkdtemp runs
+ * inside the try so a failure there still releases the slot (else a rejection
+ * would leak it and, after MAX_ACTIVE failures, brick URL import until
+ * restart). */
+async function withDownload<T>(url: string, consume: (dl: Downloaded) => Promise<T>): Promise<T> {
assertLocalRuntime();
if (!/^https?:\/\//i.test(url.trim())) throw new Error("Enter a valid http(s) URL.");
if (active >= MAX_ACTIVE) {
throw new Error("Too many downloads in progress. Try again in a moment.");
}
- // Count the slot around the whole operation. mkdtemp is inside the try so a
- // failure there still releases the slot (else a rejection would leak it and,
- // after MAX_ACTIVE failures, brick URL import until restart).
active++;
try {
const tmp = await mkdtemp(path.join(os.tmpdir(), "cut-dl-"));
@@ -43,12 +54,15 @@ export async function importFromUrl(url: string): Promise<LibraryAsset> {
names.map(async (n) => ({ n, size: (await stat(path.join(tmp, n))).size }))
);
const file = sized.sort((a, b) => b.size - a.size)[0].n;
- const title = (meta.title || "Imported clip").slice(0, 120);
- return await addDownloaded(path.join(tmp, file), title, {
- url: meta.webpage_url || url.trim(),
- title: meta.title,
- uploader: meta.uploader,
- uploadDate: meta.upload_date,
+ return await consume({
+ file: path.join(tmp, file),
+ title: (meta.title || "Imported clip").slice(0, 120),
+ source: {
+ url: meta.webpage_url || url.trim(),
+ title: meta.title,
+ uploader: meta.uploader,
+ uploadDate: meta.upload_date,
+ },
});
} finally {
void rm(tmp, { recursive: true, force: true });
@@ -58,6 +72,27 @@ export async function importFromUrl(url: string): Promise<LibraryAsset> {
}
}
+/** Download a URL into the shared Library (the Library panel's import box). */
+export async function importFromUrl(url: string): Promise<LibraryAsset> {
+ return withDownload(url, (dl) => addDownloaded(dl.file, dl.title, dl.source));
+}
+
+/** Download a URL straight into a project's media folder (the chat's
+ * import_url tool). Returns the project file name; the client builds and
+ * registers the asset. */
+export async function importUrlToProject(
+ projectId: string,
+ url: string
+): Promise<{ fileName: string; title: string; source: LibrarySource }> {
+ if (!(await readProject(projectId))) throw new Error("Project not found.");
+ return withDownload(url, async (dl) => {
+ await mkdir(mediaDir(projectId), { recursive: true });
+ const dest = await uniqueName(path.basename(dl.file), (n) => projectMediaPath(projectId, n));
+ await copyFile(dl.file, projectMediaPath(projectId, dest));
+ return { fileName: dest, title: dl.title, source: dl.source };
+ });
+}
+
function runYtDlp(url: string, dir: string): Promise<YtMeta> {
return new Promise((resolve, reject) => {
const p = spawn("yt-dlp", [