Open source CapCut alternative.
TypeScript
feat(site): point Cut's client at the engine on the user's Mac
David Lee6663d070f07
diff --git a/site/src/app/cut/p/[id]/page.tsx b/site/src/app/cut/p/[id]/page.tsxindex a1633b87..f9472942 100644--- a/site/src/app/cut/p/[id]/page.tsx+++ b/site/src/app/cut/p/[id]/page.tsx@@ -1,10 +1,11 @@+"use client";++import { useParams } from "next/navigation";import { Editor } from "@/cut/components/Editor";-export default async function ProjectPage({- params,-}: {- params: Promise<{ id: string }>;-}) {- const { id } = await params;+// Client-only: the id comes from the URL in the browser, so the hosted shell+// carries no server-rendered data.+export default function ProjectPage() {+ const { id } = useParams<{ id: string }>();return <Editor projectId={id} />;}diff --git a/site/src/cut/components/AiPanel.tsx b/site/src/cut/components/AiPanel.tsxindex 6bb95117..b0ee43e1 100644--- a/site/src/cut/components/AiPanel.tsx+++ b/site/src/cut/components/AiPanel.tsx@@ -32,6 +32,7 @@ import {DropdownMenuSeparator,DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";+import { apiFetch, apiUrl } from "@/cut/lib/api";import { buildAiContext } from "@/cut/lib/aiContext";import { runAiTool } from "@/cut/lib/aiTools";import { draggedAssetId, hasAssetDrag, setAssetDragData } from "@/cut/lib/assetDrag";@@ -128,7 +129,7 @@ export function AiPanel({ onClose }: { onClose: () => void }) {useEffect(() => {let alive = true;- void fetch("/api/ai/models")+ void apiFetch("/api/ai/models").then((r) => r.json()).then((d: ModelsInfo) => alive && setInfo(d)).catch(() => {});@@ -356,7 +357,7 @@ function ChatSession({const transport = useMemo(() =>new DefaultChatTransport({- api: "/api/ai/chat",+ api: apiUrl("/api/ai/chat"),prepareSendMessagesRequest: ({ messages }) => ({body: {messages,@@ -385,7 +386,7 @@ function ChatSession({// server-side bridge (which is holding the provider's tool call open).void (async () => {const post = (payload: Record<string, unknown>) =>- fetch("/api/ai/tool-result", {+ apiFetch("/api/ai/tool-result", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsxindex d7caac03..453fed57 100644--- a/site/src/cut/components/Editor.tsx+++ b/site/src/cut/components/Editor.tsx@@ -4,6 +4,7 @@ import { useCallback, useEffect, useRef, useState } from "react";import Link from "next/link";import { Clapperboard, Loader2 } from "lucide-react";import { Button } from "@/components/ui/button";+import { apiFetch } from "@/cut/lib/api";import { enrichAsset, importFileToProject } from "@/cut/lib/media";import { serializeDoc, totalDuration, useEditor } from "@/cut/lib/store";import { AiPanel } from "./AiPanel";@@ -44,7 +45,7 @@ export function Editor({ projectId }: { projectId: string }) {if (!s.loaded || s.projectId !== projectId) return;s.setSaveState("saving");try {- const res = await fetch(`/api/projects/${projectId}`, {+ const res = await apiFetch(`/api/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 d3f6ed79..fd82c66b 100644--- a/site/src/cut/components/PlatformPreview.tsx+++ b/site/src/cut/components/PlatformPreview.tsx@@ -1,6 +1,7 @@"use client";import { useEffect, useRef, useState } from "react";+import { apiUrl } from "@/cut/lib/api";import {Bookmark,Camera,@@ -66,7 +67,7 @@ export function PlatformPreviewDialog({return () => window.removeEventListener("keydown", onKey);}, [onClose]);- const url = `/api/projects/${projectId}/exports/${encodeURIComponent(item.file)}`;+ const url = apiUrl(`/api/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/SidePanel.tsx b/site/src/cut/components/SidePanel.tsxindex 371efe81..e8a49328 100644--- a/site/src/cut/components/SidePanel.tsx+++ b/site/src/cut/components/SidePanel.tsx@@ -9,6 +9,7 @@ import {DropdownMenuItem,DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";+import { apiFetch, apiUrl } from "@/cut/lib/api";import { setAssetDragData } from "@/cut/lib/assetDrag";import {addLibraryAssetToProject,@@ -155,7 +156,7 @@ function MediaPanel({useEffect(() => {if (exportOpen) return;let alive = true;- void fetch(`/api/projects/${projectId}/exports`)+ void apiFetch(`/api/projects/${projectId}/exports`).then((r) => (r.ok ? (r.json() as Promise<ExportItem[]>) : [])).then((list) => alive && setExports(list)).catch(() => {});@@ -224,7 +225,7 @@ function MediaPanel({mutedplaysInlinepreload="metadata"- src={`/api/projects/${projectId}/exports/${encodeURIComponent(it.file)}#t=0.1`}+ src={`${apiUrl(`/api/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 8a5c7669..cd06fab2 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -1,5 +1,6 @@"use client";+import { apiFetch } from "./api";import { enrichAsset, ensurePeaks } from "./media";import { getClipSpans, TIMELINE_H_MAX, TIMELINE_H_MIN, totalDuration, useEditor } from "./store";import { buildAiContext } from "./aiContext";@@ -180,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 fetch(`/api/projects/${projectId}/freeze`, {+ const res = await apiFetch(`/api/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.tsnew file mode 100644index 00000000..0d9d6dc9--- /dev/null+++ b/site/src/cut/lib/api.ts@@ -0,0 +1,26 @@+// Cut's client reaches its engine two ways. Served locally (cut.localhost,+// 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";++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. */+export function engineOrigin(): string {+ if (typeof window === "undefined") return "";+ if (isLocalHost(window.location.hostname)) return "";+ return localStorage.getItem("cut-engine-origin") ?? DEFAULT_ENGINE;+}++/** 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);diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.tsindex 5f799c12..bc2416d9 100644--- a/site/src/cut/lib/exportClient.ts+++ b/site/src/cut/lib/exportClient.ts@@ -1,5 +1,6 @@"use client";+import { apiFetch, apiUrl } from "./api";import { getClipSpans, totalDuration } from "./store";import { cueOverlay } from "./subtitles";import { renderOverlayPng } from "./textRender";@@ -127,7 +128,7 @@ export function startExport();onProgress("Starting encoder", 0);- const res = await fetch("/api/export", { method: "POST", body: form });+ const res = await apiFetch("/api/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;@@ -136,7 +137,7 @@ export function startExport(for (;;) {if (canceled) throw new Error("Export canceled.");await new Promise((r) => setTimeout(r, 400));- const st = await fetch(`/api/export/${jobId}`);+ const st = await apiFetch(`/api/export/${jobId}`);const status = (await st.json()) as {status: string;progress: number;@@ -153,7 +154,7 @@ export function startExport(onProgress("Done", 1);const a = document.createElement("a");- a.href = `/api/export/${jobId}/file`;+ a.href = apiUrl(`/api/export/${jobId}/file`);a.download = outName;document.body.appendChild(a);a.click();@@ -165,7 +166,7 @@ export function startExport(done,cancel: () => {canceled = true;- if (jobId) void fetch(`/api/export/${jobId}`, { method: "DELETE" });+ if (jobId) void apiFetch(`/api/export/${jobId}`, { method: "DELETE" });},};}diff --git a/site/src/cut/lib/library.ts b/site/src/cut/lib/library.tsindex 13877754..8dee33cb 100644--- a/site/src/cut/lib/library.ts+++ b/site/src/cut/lib/library.ts@@ -1,5 +1,6 @@"use client";+import { apiFetch, apiUrl } from "./api";import { useEditor } from "./store";import type { MediaAsset } from "./types";import { mediaUrl } from "./types";@@ -16,10 +17,10 @@ export interface LibraryAsset {}export const libraryMediaUrl = (fileName: string) =>- `/api/library/media/${encodeURIComponent(fileName)}`;+ apiUrl(`/api/library/media/${encodeURIComponent(fileName)}`);export async function fetchLibrary(): Promise<LibraryAsset[]> {- const res = await fetch("/api/library");+ const res = await apiFetch("/api/library");if (!res.ok) throw new Error("Could not load the library.");return (await res.json()) as LibraryAsset[];}@@ -27,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 fetch("/api/library", { method: "POST", body: form });+ const res = await apiFetch("/api/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 fetch(`/api/library/${id}`, { method: "DELETE" });+ const res = await apiFetch(`/api/library/${id}`, { method: "DELETE" });if (!res.ok) throw new Error("Could not delete.");}@@ -43,7 +44,7 @@ export async function addLibraryAssetToProject(projectId: string,lib: LibraryAsset): Promise<MediaAsset> {- const res = await fetch("/api/library/use", {+ const res = await apiFetch("/api/library/use", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ assetId: lib.id, projectId }),@@ -70,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 fetch("/api/library/save", {+ const res = await apiFetch("/api/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 9c4cef92..9e9e214c 100644--- a/site/src/cut/lib/media.ts+++ b/site/src/cut/lib/media.ts@@ -1,5 +1,6 @@"use client";+import { apiFetch } from "./api";import { useEditor } from "./store";import type { MediaAsset } from "./types";import { mediaUrl } from "./types";@@ -34,7 +35,7 @@ export async function importFileToProject(const form = new FormData();form.append("file", file, file.name);- const res = await fetch(`/api/projects/${projectId}/media`, {+ const res = await apiFetch(`/api/projects/${projectId}/media`, {method: "POST",body: form,});@@ -118,6 +119,9 @@ function loadVideoMeta(url: string): Promise<HTMLVideoElement> {const v = document.createElement("video");v.preload = "metadata";v.muted = true;+ // Media may come from the engine on another origin; anonymous CORS keeps+ // canvas frame grabs (filmstrips, AI captures) from tainting.+ v.crossOrigin = "anonymous";v.src = url;v.onloadedmetadata = () => void ensureFiniteDuration(v).then(() => resolve(v));v.onerror = () => reject(new Error("Could not read this video file."));diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.tsindex 88f4b359..70de0890 100644--- a/site/src/cut/lib/store.ts+++ b/site/src/cut/lib/store.ts@@ -14,6 +14,7 @@ import type {TextOverlay,VideoClip,} from "./types";+import { apiFetch } from "./api";import { emptySubtitles, mediaUrl } from "./types";import { loadUiState, saveUiState } from "./uiState";@@ -224,7 +225,7 @@ export const useEditor = create<EditorState>((set, get) => {exportOpen: false,});try {- const [res, ui] = await Promise.all([fetch(`/api/projects/${id}`), loadUiState(id)]);+ const [res, ui] = await Promise.all([apiFetch(`/api/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) => ({@@ -520,7 +521,7 @@ export const useEditor = create<EditorState>((set, get) => {};set({ subtitleStatus: "running", subtitleError: null });try {- const res = await fetch(`/api/projects/${projectId}/transcribe`, {+ const res = await apiFetch(`/api/projects/${projectId}/transcribe`, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify(spec),@@ -530,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 fetch(`/api/projects/${projectId}/transcribe?job=${body.id}`);+ const st = await apiFetch(`/api/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 32e14353..580efe1c 100644--- a/site/src/cut/lib/types.ts+++ b/site/src/cut/lib/types.ts@@ -1,3 +1,5 @@+import { apiUrl } from "./api";+export type AssetType = "video" | "audio";/** Project output frame. Vertical (TikTok/Reels) or widescreen (YouTube). */@@ -178,4 +180,4 @@ export interface ProjectSummary {}export const mediaUrl = (projectId: string, fileName: string) =>- `/api/projects/${projectId}/media/${encodeURIComponent(fileName)}`;+ apiUrl(`/api/projects/${projectId}/media/${encodeURIComponent(fileName)}`);