Open source CapCut alternative.
TypeScript
feat(site): connect the hosted Cut client to the local engine
David Lea3fe998ac2b4
diff --git a/site/src/cut/components/AiPanel.tsx b/site/src/cut/components/AiPanel.tsxindex b0ee43e1..0f2a6f49 100644--- a/site/src/cut/components/AiPanel.tsx+++ b/site/src/cut/components/AiPanel.tsx@@ -32,7 +32,7 @@ import {DropdownMenuSeparator,DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";-import { apiFetch, apiUrl } from "@/cut/lib/api";+import { apiFetch, engineReady } from "@/cut/lib/api";import { buildAiContext } from "@/cut/lib/aiContext";import { runAiTool } from "@/cut/lib/aiTools";import { draggedAssetId, hasAssetDrag, setAssetDragData } from "@/cut/lib/assetDrag";@@ -129,7 +129,7 @@ export function AiPanel({ onClose }: { onClose: () => void }) {useEffect(() => {let alive = true;- void apiFetch("/api/ai/models")+ void apiFetch("/api/cut/ai/models").then((r) => r.json()).then((d: ModelsInfo) => alive && setInfo(d)).catch(() => {});@@ -357,8 +357,12 @@ function ChatSession({const transport = useMemo(() =>new DefaultChatTransport({- api: apiUrl("/api/ai/chat"),- prepareSendMessagesRequest: ({ messages }) => ({+ // The engine origin is discovered asynchronously; await it per request+ // (not at mount) so an early send still targets the local engine rather+ // than the hosted origin, where the Cut APIs 404. engineReady memoizes,+ // so only the first request pays for discovery.+ prepareSendMessagesRequest: async ({ messages }) => ({+ api: `${await engineReady()}/api/cut/ai/chat`,body: {messages,model: modelRef.current,@@ -386,7 +390,7 @@ function ChatSession({// server-side bridge (which is holding the provider's tool call open).void (async () => {const post = (payload: Record<string, unknown>) =>- apiFetch("/api/ai/tool-result", {+ apiFetch("/api/cut/ai/tool-result", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({diff --git a/site/src/cut/components/AppSidebar.tsx b/site/src/cut/components/AppSidebar.tsxindex 7399f653..43446a67 100644--- a/site/src/cut/components/AppSidebar.tsx+++ b/site/src/cut/components/AppSidebar.tsx@@ -32,7 +32,7 @@ export function AppSidebar() {const create = async () => {setBusy(true);try {- const res = await apiFetch("/api/projects", {+ const res = await apiFetch("/api/cut/projects", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ name: name.trim() || "Untitled" }),diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsxindex 453fed57..1c9f0761 100644--- a/site/src/cut/components/Editor.tsx+++ b/site/src/cut/components/Editor.tsx@@ -34,7 +34,7 @@ export function Editor({ projectId }: { projectId: string }) {});}, [projectId]);- // Autosave: debounce document changes into PUT /api/projects/<id>.+ // Autosave: debounce document changes into PUT /api/cut/projects/<id>.useEffect(() => {let timer: ReturnType<typeof setTimeout> | null = null;let last = serializeDoc(useEditor.getState());@@ -45,7 +45,7 @@ export function Editor({ projectId }: { projectId: string }) {if (!s.loaded || s.projectId !== projectId) return;s.setSaveState("saving");try {- const res = await apiFetch(`/api/projects/${projectId}`, {+ const res = await apiFetch(`/api/cut/projects/${projectId}`, {method: "PUT",headers: { "Content-Type": "application/json" },body: JSON.stringify(serializeDoc(s)),diff --git a/site/src/cut/components/PlatformPreview.tsx b/site/src/cut/components/PlatformPreview.tsxindex fd82c66b..a205aed2 100644--- a/site/src/cut/components/PlatformPreview.tsx+++ b/site/src/cut/components/PlatformPreview.tsx@@ -67,7 +67,7 @@ export function PlatformPreviewDialog({return () => window.removeEventListener("keydown", onKey);}, [onClose]);- const url = apiUrl(`/api/projects/${projectId}/exports/${encodeURIComponent(item.file)}`);+ const url = apiUrl(`/api/cut/projects/${projectId}/exports/${encodeURIComponent(item.file)}`);const handle = publish.handle.trim().replace(/^@+/, "") || "you";const caption = publish.caption.trim();const tagsLine = normalizeTags(publish.tags);diff --git a/site/src/cut/components/ProjectsHome.tsx b/site/src/cut/components/ProjectsHome.tsxindex f395e3e1..dc00228a 100644--- a/site/src/cut/components/ProjectsHome.tsx+++ b/site/src/cut/components/ProjectsHome.tsx@@ -39,7 +39,7 @@ import {DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";import { Input } from "@/components/ui/input";-import { apiFetch, engineOrigin } from "@/cut/lib/api";+import { apiFetch } from "@/cut/lib/api";import { formatTime } from "@/cut/lib/time";import { mediaUrl, type ProjectSummary } from "@/cut/lib/types";import { cn } from "@/lib/utils";@@ -83,7 +83,7 @@ export function ProjectsHome() {const refresh = useCallback(async () => {try {- const res = await apiFetch("/api/projects");+ const res = await apiFetch("/api/cut/projects");if (!res.ok) throw new Error(String(res.status));setProjects((await res.json()) as ProjectSummary[]);setEngineDown(false);@@ -98,10 +98,18 @@ export function ProjectsHome() {void refresh();}, [refresh]);+ // While the engine is unreachable, keep probing so the page springs to life+ // the moment it starts.+ useEffect(() => {+ if (!engineDown) return;+ const t = setInterval(() => void refresh(), 3000);+ return () => clearInterval(t);+ }, [engineDown, refresh]);+const create = async () => {setBusy(true);try {- const res = await apiFetch("/api/projects", {+ const res = await apiFetch("/api/cut/projects", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ name: name.trim() || "Untitled" }),@@ -117,7 +125,7 @@ export function ProjectsHome() {if (!renaming) return;setBusy(true);try {- await apiFetch(`/api/projects/${renaming.id}`, {+ await apiFetch(`/api/cut/projects/${renaming.id}`, {method: "PUT",headers: { "Content-Type": "application/json" },body: JSON.stringify({ name: name.trim() || renaming.name }),@@ -133,7 +141,7 @@ export function ProjectsHome() {if (!deleting) return;setBusy(true);try {- await apiFetch(`/api/projects/${deleting.id}`, { method: "DELETE" });+ await apiFetch(`/api/cut/projects/${deleting.id}`, { method: "DELETE" });setDeleting(null);await refresh();} finally {@@ -178,21 +186,28 @@ export function ProjectsHome() {<Unplug className="size-7 text-muted-foreground" /></div><h1 className="text-lg font-semibold tracking-tight">- Can’t reach Donkey Cut on this Mac+ Donkey Cut works with the Donkey app</h1><p className="text-sm text-muted-foreground">- Donkey Cut does all its work locally. Start it on this Mac- {engineOrigin() ? ` (${engineOrigin()})` : ""}, then try again.+ Everything runs locally on your Mac. Install Donkey — or open it+ if it’s already installed — and this page connects+ automatically.</p>- <Button- onClick={() => {- setEngineDown(false);- setProjects(null);- void refresh();- }}- >- Try again- </Button>+ <div className="flex items-center gap-2">+ <Button onClick={() => window.open("https://donkeyuse.com", "_blank")}>+ Get Donkey for Mac+ </Button>+ <Button+ variant="ghost"+ onClick={() => {+ setEngineDown(false);+ setProjects(null);+ void refresh();+ }}+ >+ Try again+ </Button>+ </div></div></div>) : projects === null ? (diff --git a/site/src/cut/components/SidePanel.tsx b/site/src/cut/components/SidePanel.tsxindex e8a49328..dcc10c25 100644--- a/site/src/cut/components/SidePanel.tsx+++ b/site/src/cut/components/SidePanel.tsx@@ -156,7 +156,7 @@ function MediaPanel({useEffect(() => {if (exportOpen) return;let alive = true;- void apiFetch(`/api/projects/${projectId}/exports`)+ void apiFetch(`/api/cut/projects/${projectId}/exports`).then((r) => (r.ok ? (r.json() as Promise<ExportItem[]>) : [])).then((list) => alive && setExports(list)).catch(() => {});@@ -225,7 +225,7 @@ function MediaPanel({mutedplaysInlinepreload="metadata"- src={`${apiUrl(`/api/projects/${projectId}/exports/${encodeURIComponent(it.file)}`)}#t=0.1`}+ src={`${apiUrl(`/api/cut/projects/${projectId}/exports/${encodeURIComponent(it.file)}`)}#t=0.1`}className="h-11 w-[25px] shrink-0 rounded-[4px] bg-black object-cover"/><span className="min-w-0 flex-1">diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex cd06fab2..f9253813 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -181,7 +181,7 @@ export async function runAiTool(const t = clamp(isNum(input.t) ? input.t : s.currentTime, 0, Math.max(0, total - 0.001));const span = spans.find((sp) => t >= sp.start && t < sp.start + sp.len) ?? spans[spans.length - 1];const srcTime = span.clip.in + (t - span.start);- const res = await apiFetch(`/api/projects/${projectId}/freeze`, {+ const res = await apiFetch(`/api/cut/projects/${projectId}/freeze`, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({diff --git a/site/src/cut/lib/api.ts b/site/src/cut/lib/api.tsindex 0d9d6dc9..dd272095 100644--- a/site/src/cut/lib/api.ts+++ b/site/src/cut/lib/api.ts@@ -2,25 +2,75 @@// localhost) the page and the engine share an origin, so paths stay relative.// Served from the hosted domain (cut.donkeyuse.com) the page is just static// html/js — the Cut APIs are switched off on that host — so every API call-// targets the engine running on this Mac at 127.0.0.1 instead. Loopback is a-// trustworthy origin, so the https page may call it; the engine's proxy grants-// the hosted origin CORS (see src/proxy.ts).-const DEFAULT_ENGINE = "http://127.0.0.1:3000";+// targets the engine running on this Mac instead. Loopback is a trustworthy+// origin, so the https page may call it; the engine grants the hosted origin+// CORS (see src/proxy.ts).+//+// The engine is found by probing its health endpoint across candidate ports:+// the downloadable engine's dedicated port first, then the dev server's 3000.+// The first healthy origin wins and is remembered for the session.+import { DEFAULT_ENGINE_PORT } from "./ports";++const ENGINE_PORTS = [DEFAULT_ENGINE_PORT, 3000];+const PROBE_TIMEOUT_MS = 1200;const isLocalHost = (hostname: string) =>hostname === "localhost" || hostname === "127.0.0.1" || hostname.endsWith(".localhost");-/** "" when the page is served by the engine itself; the engine's origin when- * the page came from the hosted domain. Override via localStorage key- * "cut-engine-origin" when the engine runs on a non-default port. */+let resolvedOrigin: string | null = null; // "" = same origin+let resolving: Promise<string> | null = null;++function candidates(): string[] {+ // Manual override for unusual setups, e.g. an engine on a custom port.+ const saved = localStorage.getItem("cut-engine-origin");+ return [...(saved ? [saved] : []), ...ENGINE_PORTS.map((p) => `http://127.0.0.1:${p}`)];+}++async function probe(origin: string): Promise<boolean> {+ try {+ const res = await fetch(`${origin}/api/cut/engine/health`, {+ signal: AbortSignal.timeout(PROBE_TIMEOUT_MS),+ });+ return res.ok;+ } catch {+ return false;+ }+}++/** Resolve (and memoize) the engine origin; throws when no engine answers so+ * callers surface the "start Donkey Cut on this Mac" state. A failed attempt+ * is not memoized — the next call probes again. */+export function engineReady(): Promise<string> {+ if (resolvedOrigin !== null) return Promise.resolve(resolvedOrigin);+ resolving ??= (async () => {+ if (typeof window === "undefined" || isLocalHost(window.location.hostname)) {+ resolvedOrigin = "";+ return "";+ }+ for (const c of candidates()) {+ if (await probe(c)) {+ resolvedOrigin = c;+ return c;+ }+ }+ throw new Error("No Donkey Cut engine is reachable on this Mac.");+ })().finally(() => {+ resolving = null;+ });+ return resolving;+}++/** The engine origin as currently known ("" while same-origin or unresolved).+ * URLs built from it are correct once any apiFetch has succeeded. */export function engineOrigin(): string {- if (typeof window === "undefined") return "";- if (isLocalHost(window.location.hostname)) return "";- return localStorage.getItem("cut-engine-origin") ?? DEFAULT_ENGINE;+ return resolvedOrigin ?? "";}/** Absolute-or-relative URL for an engine API path. */export const apiUrl = (path: string) => `${engineOrigin()}${path}`;-/** fetch() against the engine. */-export const apiFetch = (path: string, init?: RequestInit) => fetch(apiUrl(path), init);+/** fetch() against the engine, resolving it first. */+export async function apiFetch(path: string, init?: RequestInit) {+ const base = await engineReady();+ return fetch(`${base}${path}`, init);+}diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.tsindex bc2416d9..c8b1aee7 100644--- a/site/src/cut/lib/exportClient.ts+++ b/site/src/cut/lib/exportClient.ts@@ -128,7 +128,7 @@ export function startExport();onProgress("Starting encoder", 0);- const res = await apiFetch("/api/export", { method: "POST", body: form });+ const res = await apiFetch("/api/cut/export", { method: "POST", body: form });const body = (await res.json()) as { id?: string; error?: string };if (!res.ok || !body.id) throw new Error(body.error ?? "Export failed to start.");jobId = body.id;@@ -137,7 +137,7 @@ export function startExport(for (;;) {if (canceled) throw new Error("Export canceled.");await new Promise((r) => setTimeout(r, 400));- const st = await apiFetch(`/api/export/${jobId}`);+ const st = await apiFetch(`/api/cut/export/${jobId}`);const status = (await st.json()) as {status: string;progress: number;@@ -154,7 +154,7 @@ export function startExport(onProgress("Done", 1);const a = document.createElement("a");- a.href = apiUrl(`/api/export/${jobId}/file`);+ a.href = apiUrl(`/api/cut/export/${jobId}/file`);a.download = outName;document.body.appendChild(a);a.click();@@ -166,7 +166,7 @@ export function startExport(done,cancel: () => {canceled = true;- if (jobId) void apiFetch(`/api/export/${jobId}`, { method: "DELETE" });+ if (jobId) void apiFetch(`/api/cut/export/${jobId}`, { method: "DELETE" });},};}diff --git a/site/src/cut/lib/library.ts b/site/src/cut/lib/library.tsindex 8dee33cb..9c102639 100644--- a/site/src/cut/lib/library.ts+++ b/site/src/cut/lib/library.ts@@ -17,10 +17,10 @@ export interface LibraryAsset {}export const libraryMediaUrl = (fileName: string) =>- apiUrl(`/api/library/media/${encodeURIComponent(fileName)}`);+ apiUrl(`/api/cut/library/media/${encodeURIComponent(fileName)}`);export async function fetchLibrary(): Promise<LibraryAsset[]> {- const res = await apiFetch("/api/library");+ const res = await apiFetch("/api/cut/library");if (!res.ok) throw new Error("Could not load the library.");return (await res.json()) as LibraryAsset[];}@@ -28,14 +28,14 @@ export async function fetchLibrary(): Promise<LibraryAsset[]> {export async function uploadToLibrary(file: File): Promise<LibraryAsset> {const form = new FormData();form.append("file", file, file.name);- const res = await apiFetch("/api/library", { method: "POST", body: form });+ const res = await apiFetch("/api/cut/library", { method: "POST", body: form });const body = (await res.json()) as LibraryAsset & { error?: string };if (!res.ok) throw new Error(body.error ?? "Upload failed.");return body;}export async function deleteFromLibrary(id: string) {- const res = await apiFetch(`/api/library/${id}`, { method: "DELETE" });+ const res = await apiFetch(`/api/cut/library/${id}`, { method: "DELETE" });if (!res.ok) throw new Error("Could not delete.");}@@ -44,7 +44,7 @@ export async function addLibraryAssetToProject(projectId: string,lib: LibraryAsset): Promise<MediaAsset> {- const res = await apiFetch("/api/library/use", {+ const res = await apiFetch("/api/cut/library/use", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ assetId: lib.id, projectId }),@@ -71,7 +71,7 @@ export async function addLibraryAssetToProject(/** Copy a project asset into the shared library for reuse. */export async function saveAssetToLibrary(projectId: string, asset: MediaAsset) {- const res = await apiFetch("/api/library/save", {+ const res = await apiFetch("/api/cut/library/save", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ projectId, fileName: asset.fileName, name: asset.name }),diff --git a/site/src/cut/lib/media.ts b/site/src/cut/lib/media.tsindex 9e9e214c..03ec09bf 100644--- a/site/src/cut/lib/media.ts+++ b/site/src/cut/lib/media.ts@@ -35,7 +35,7 @@ export async function importFileToProject(const form = new FormData();form.append("file", file, file.name);- const res = await apiFetch(`/api/projects/${projectId}/media`, {+ const res = await apiFetch(`/api/cut/projects/${projectId}/media`, {method: "POST",body: form,});diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.tsindex 70de0890..de3fdcf2 100644--- a/site/src/cut/lib/store.ts+++ b/site/src/cut/lib/store.ts@@ -225,7 +225,7 @@ export const useEditor = create<EditorState>((set, get) => {exportOpen: false,});try {- const [res, ui] = await Promise.all([apiFetch(`/api/projects/${id}`), loadUiState(id)]);+ const [res, ui] = await Promise.all([apiFetch(`/api/cut/projects/${id}`), loadUiState(id)]);if (!res.ok) throw new Error("This project no longer exists.");const doc = (await res.json()) as ProjectDoc;const assets: MediaAsset[] = doc.assets.map((a) => ({@@ -521,7 +521,7 @@ export const useEditor = create<EditorState>((set, get) => {};set({ subtitleStatus: "running", subtitleError: null });try {- const res = await apiFetch(`/api/projects/${projectId}/transcribe`, {+ const res = await apiFetch(`/api/cut/projects/${projectId}/transcribe`, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify(spec),@@ -531,7 +531,7 @@ export const useEditor = create<EditorState>((set, get) => {for (;;) {await new Promise((r) => setTimeout(r, 600));if (get().projectId !== projectId) return; // switched projects mid-run- const st = await apiFetch(`/api/projects/${projectId}/transcribe?job=${body.id}`);+ const st = await apiFetch(`/api/cut/projects/${projectId}/transcribe?job=${body.id}`);if (!st.ok) throw new Error("The transcription job was lost — try again.");const status = (await st.json()) as {status: string;diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.tsindex 580efe1c..da652b58 100644--- a/site/src/cut/lib/types.ts+++ b/site/src/cut/lib/types.ts@@ -28,7 +28,7 @@ export interface StoredAsset {/** Runtime asset: stored fields plus derived/browser-only data. */export interface MediaAsset extends StoredAsset {- url: string; // /api/projects/<id>/media/<fileName>+ url: string; // /api/cut/projects/<id>/media/<fileName>/** Filmstrip frames (video only), evenly spaced every `thumbStep` seconds. */thumbs?: string[];thumbStep?: number;@@ -180,4 +180,4 @@ export interface ProjectSummary {}export const mediaUrl = (projectId: string, fileName: string) =>- apiUrl(`/api/projects/${projectId}/media/${encodeURIComponent(fileName)}`);+ apiUrl(`/api/cut/projects/${projectId}/media/${encodeURIComponent(fileName)}`);diff --git a/site/src/proxy.ts b/site/src/proxy.tsindex c4f95e52..57980b0d 100644--- a/site/src/proxy.ts+++ b/site/src/proxy.ts@@ -1,5 +1,7 @@import { NextResponse, type NextRequest } from "next/server";+import { allowedOrigin, corsHeaders, preflightHeaders } from "@/cut/server/cors";+// Cut (the video editor, publicly "Donkey Cut") is served on the// cut.donkeyuse.com subdomain, but its routes live under /cut in this single// site app. For requests on the Cut host we rewrite page paths to /cut/* so@@ -21,37 +23,28 @@ const CUT_HOSTS = new Set(["cut.donkeyuse.com", "cut.localhost"]);// unauthenticated routes are unreachable.// - local: the page served from the hosted origin calls this engine// cross-origin, so grant exactly that origin CORS.-const CUT_API_PREFIXES = ["/api/ai", "/api/export", "/api/library", "/api/projects"];-const CUT_CLIENT_ORIGINS = new Set(["https://cut.donkeyuse.com"]);+const CUT_API_PREFIX = "/api/cut";const HOSTED = Boolean(process.env.VERCEL);const isCutApi = (pathname: string) =>- CUT_API_PREFIXES.some((p) => pathname === p || pathname.startsWith(`${p}/`));+ pathname === CUT_API_PREFIX || pathname.startsWith(`${CUT_API_PREFIX}/`);function cutApi(req: NextRequest): NextResponse {if (HOSTED) return new NextResponse(null, { status: 404 });- const origin = req.headers.get("origin") ?? "";- if (!CUT_CLIENT_ORIGINS.has(origin)) return NextResponse.next();+ // Same CORS policy as the packaged engine (src/cut/server/cors.ts): grant the+ // hosted Cut origin, pass everything else through as same-origin dev traffic.+ const cors = allowedOrigin(req.headers.get("origin") ?? "");+ if (!cors) return NextResponse.next();if (req.method === "OPTIONS") {return new NextResponse(null, {status: 204,- headers: {- "Access-Control-Allow-Origin": origin,- "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",- "Access-Control-Allow-Headers":- req.headers.get("access-control-request-headers") ?? "Content-Type",- // Chrome preflights public-site → local-network requests.- "Access-Control-Allow-Private-Network": "true",- "Access-Control-Max-Age": "86400",- Vary: "Origin",- },+ headers: preflightHeaders(cors, req.headers.get("access-control-request-headers")),});}const res = NextResponse.next();- res.headers.set("Access-Control-Allow-Origin", origin);- res.headers.set("Vary", "Origin");+ for (const [k, v] of Object.entries(corsHeaders(cors))) res.headers.set(k, v);return res;}@@ -76,9 +69,6 @@ export const config = {// hosted 404 and local CORS above cover all of them.matcher: ["/((?!_next/|.*\\..*).*)",- "/api/ai/:path*",- "/api/export/:path*",- "/api/library/:path*",- "/api/projects/:path*",+ "/api/cut/:path*",],};