Open source CapCut alternative.
TypeScript
fix(site): surface failed imports and drop bytes that beat a cancel
David Le167434035af8
diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsxindex bd562523..276ad2f4 100644--- a/site/src/cut/components/Editor.tsx+++ b/site/src/cut/components/Editor.tsx@@ -104,7 +104,9 @@ export function Editor({const [importing, setImporting] = useState(0);// Files being probed and named, plus the ones already placed whose bytes are// still going out — both are work the save indicator reports.- const sending = useEditor((s) => s.assets.reduce((n, a) => (a.upload ? n + 1 : n), 0));+ const sending = useEditor((s) =>+ s.assets.reduce((n, a) => (a.upload && !a.upload.error ? n + 1 : n), 0)+ );const [conflictReloaded, setConflictReloaded] = useState(false);const [shareGone, setShareGone] = useState(false);// This project lives on this Mac and the Donkey app isn't answering. Nothingdiff --git a/site/src/cut/components/TopBar.tsx b/site/src/cut/components/TopBar.tsxindex 7d231e5b..c6fe21ed 100644--- a/site/src/cut/components/TopBar.tsx+++ b/site/src/cut/components/TopBar.tsx@@ -28,6 +28,7 @@ import { cloudBackend } from "@/cut/lib/backend/cloud";import { cloudUsageQueryKey, useCutMode } from "@/cut/lib/backend/hooks";import { localBackend } from "@/cut/lib/backend/local";import { clearProjectThreads } from "@/cut/lib/chatThreads";+import { retryUpload } from "@/cut/lib/importQueue";import { backTarget, projectHref, useCutBase } from "@/cut/lib/nav";import { copyProjectAcross } from "@/cut/lib/projectCopy";import { useEditor } from "@/cut/lib/store";@@ -243,6 +244,14 @@ export function TopBar({// Cloud imports are real uploads worth reporting; local imports are instant// disk copies, so they report nothing.const cloudUploading = uploading > 0 && cutMode === "cloud";+ // An import whose bytes never landed is absent from the saved document, so+ // its clip disappears on the next open. The Media panel shows this for a+ // dropped file, but a stock or library import lives on the timeline and has+ // no tile there — the save indicator is the one place every import reports.+ const failedImports = useEditor((s) => s.assets.filter((a) => a.upload?.error).length);+ const retryFailedImports = () => {+ for (const a of useEditor.getState().assets) if (a.upload?.error) retryUpload(a.id);+ };// Uploads settle in bursts; refresh the storage pill's number when a burst// ends. Only the settling edge counts — on mount nothing has landed yet.const queryClient = useQueryClient();@@ -338,10 +347,18 @@ export function TopBar({size={compact ? "icon-sm" : "sm"}aria-label="Export"// A render reads the saved document, which an import still uploading- // is deliberately absent from — exporting now would quietly leave it- // out of the video.- disabled={!hasClips || cloudUploading}- title={cloudUploading ? "Finishing uploads…" : compact ? "Export" : undefined}+ // (or one that failed) is deliberately absent from — exporting now+ // would quietly leave it out of the video.+ disabled={!hasClips || cloudUploading || failedImports > 0}+ title={+ failedImports > 0+ ? "Retry the failed imports first"+ : cloudUploading+ ? "Finishing uploads…"+ : compact+ ? "Export"+ : undefined+ }onClick={() => {const s = useEditor.getState();s.setPlaying(false);@@ -424,7 +441,20 @@ export function TopBar({saveState === "saved" && !cloudUploading && "opacity-60")}>- {cloudUploading ? (+ {failedImports > 0 ? (+ <>+ <span className="text-destructive">+ {failedImports === 1 ? "1 import failed" : `${failedImports} imports failed`}+ </span>+ <button+ type="button"+ className="font-medium underline underline-offset-2"+ onClick={retryFailedImports}+ >+ Retry+ </button>+ </>+ ) : cloudUploading ? (<><Loader2 className="size-3 animate-spin" />{" "}{uploading === 1 ? "Uploading" : `Uploading ${uploading} files`}diff --git a/site/src/cut/lib/importQueue.ts b/site/src/cut/lib/importQueue.tsindex 487bf54c..3d3d0b01 100644--- a/site/src/cut/lib/importQueue.ts+++ b/site/src/cut/lib/importQueue.ts@@ -9,10 +9,13 @@// Three things keep that honest:// - Nothing about a pending asset reaches the saved document (see storedAssets// / docClips), so a tab that dies mid-upload leaves no broken reference.-// - Deleting a pending asset aborts its upload; the claimed object is never-// completed and is collected server-side.+// - Deleting a pending asset aborts its upload. A dropped file's claimed+// object is never completed and is collected server-side; a remote copy+// completes inside a single call, so one that lands after the asset is gone+// is deleted here rather than left to count against the account.// - A failed upload leaves the asset in place with an error, so the user can// retry it rather than discover later that it was never saved.+import { getBackend, type CutBackend } from "./backend";import type { PendingImport } from "./media";import { useEditor } from "./store";import { mediaUrl } from "./types";@@ -38,14 +41,26 @@ function release() {else active--;}-type Job = { pending: PendingImport; projectId: string; controller: AbortController };+type Job = {+ pending: PendingImport;+ projectId: string;+ /** Pinned at start: the copy can outlast a move to a project of the other+ * residency, and its cleanup has to reach the backend it landed on. */+ backend: CutBackend;+ controller: AbortController;+};const jobs = new Map<string, Job>();/** Start the background upload for a prepared import. The asset must already* be in the store. */export function startUpload(projectId: string, pending: PendingImport) {- const job: Job = { pending, projectId, controller: new AbortController() };+ const job: Job = {+ pending,+ projectId,+ backend: getBackend(),+ controller: new AbortController(),+ };jobs.set(pending.asset.id, job);void run(job);}@@ -59,8 +74,19 @@ export function retryUpload(assetId: string) {void run(job);}-/** Stop an upload whose asset is gone. The claimed object is left incomplete- * on purpose — it was never counted against the account. */+/** Drop bytes that landed for an asset that is no longer here. A copy that+ * completes counts against the account's storage, so a cancel that arrives+ * once it has finished has to take the file back out. */+function dropLanded(job: Job, fileName: string) {+ void job.backend+ .fetch(`/api/cut/projects/${job.projectId}/media/${encodeURIComponent(fileName)}`, {+ method: "DELETE",+ })+ .catch(() => {});+}++/** Stop an upload whose asset is gone. A claim the copy never completed is+ * left incomplete on purpose — it was never counted against the account. */export function cancelUpload(assetId: string) {const job = jobs.get(assetId);if (!job) return;@@ -94,7 +120,12 @@ async function run(job: Job) {useEditor.getState().updateAsset(asset.id, { upload: { progress: fraction } });},});- if (!wanted(job)) return cancelUpload(asset.id);+ if (!wanted(job)) {+ // The bytes beat the cancel: they are stored and counted, and nothing+ // in the document points at them any more.+ cancelUpload(asset.id);+ return dropLanded(job, fileName);+ }jobs.delete(asset.id);// The stored file takes over from the source bytes, under the name the// copy resolved to (a dropped file reserved it up front; a remote importdiff --git a/site/src/cut/lib/media.ts b/site/src/cut/lib/media.tsindex b4663cf6..6c3e5e42 100644--- a/site/src/cut/lib/media.ts+++ b/site/src/cut/lib/media.ts@@ -467,7 +467,7 @@ function loadImageMeta(url: string): Promise<{ width: number; height: number }>type RemoteImportInit = {url: string;name: string;- /** Stored name to claim; defaults to the URL's basename. */+ /** Name to store the bytes under; defaults to the URL's basename. */fileName?: string;type: AssetType;duration: number;@@ -504,11 +504,17 @@ export function importRemote(init: RemoteImportInit,copy?: (opts?: { onProgress?: (fraction: number) => void; signal?: AbortSignal }) => Promise<string>): MediaAsset {- const fileName =- init.fileName || init.url.split("/").pop()?.split("?")[0] || `${init.type}-${uid()}`;+ const id = uid();+ // The name the bytes will be stored under is the copy's to decide — the+ // server dedupes it against what the project already holds — so until they+ // land the asset answers to a name of its own. A name borrowed from the+ // source would collide with a file already in the project and speak for it:+ // the delete guard and the filmstrip cache both key on this field.+ const storeAs =+ init.fileName || init.url.split("/").pop()?.split("?")[0] || `${init.type}-${id}`;const asset: MediaAsset = {- id: uid(),- fileName,+ id,+ fileName: `pending-${id}`,name: init.name,type: init.type,duration: init.duration,@@ -538,7 +544,7 @@ export function importRemote(const dl = await fetch(init.url, { signal: opts?.signal });if (!dl.ok) throw new Error("Could not read the media.");const blob = await dl.blob();- return uploadProjectMediaTo(getBackend(), projectId, blob, fileName, opts);+ return uploadProjectMediaTo(getBackend(), projectId, blob, storeAs, opts);};startUpload(projectId, {asset,@@ -560,6 +566,11 @@ export async function importImage(// The size frames the still (and the first-asset aspect guess); the source// is a same-origin file, so this is one cached header read, not a download.const dims = await loadImageMeta(image.url);+ // 0×0 is how the read reports a source it could not open (a stock id that+ // no longer resolves, a dead link). Registering that would place a broken+ // still and hand the first-asset aspect guess a meaningless size, so the+ // import fails here instead.+ if (dims.width === 0 || dims.height === 0) throw new Error("Could not read the image.");// A stock image lands on the timeline where the caller places it, not in the// Media panel — tag it so it stays out.return importRemote(projectId, {