Skip to content

Open source CapCut alternative.

TypeScript

refactor(cut): capture transports and separate operation failures [rebuild]

David Le8a59514b2061
diff --git a/site/src/cut/components/StorageUpgradeDialog.tsx b/site/src/cut/components/StorageUpgradeDialog.tsx
index 9cb0945b..f895f370 100644
--- a/site/src/cut/components/StorageUpgradeDialog.tsx
+++ b/site/src/cut/components/StorageUpgradeDialog.tsx
@@ -16,12 +16,14 @@ import {
import { useUpgradeToPro } from "@/cut/lib/proUpgrade";
import {
clearStorageQuotaWall,
+ emitStorageQuota,
onStorageQuota,
type StorageQuotaDetail,
} from "@/cut/lib/storageQuota";
import { daysUntil } from "@/cut/lib/time";
import { track } from "@/lib/analytics";
import { useProSubscription } from "@/queries/billing";
+import { onOperationFailure } from "@/cut/lib/operationFailure";
import { formatBytes } from "@/lib/bytes";
export function StorageUpgradeDialog() {
@@ -36,6 +38,11 @@ export function StorageUpgradeDialog() {
[]
);
+ useEffect(() => onOperationFailure((failure) => {
+ if (failure.code === "storage_quota_exceeded")
+ emitStorageQuota({ ...failure, source: "quota-413" });
+ }), []);
+
const close = () => {
setDetail(null);
clearStorageQuotaWall();
diff --git a/site/src/cut/lib/backend/browser.ts b/site/src/cut/lib/backend/browser.ts
index 65693acb..e6d370db 100644
--- a/site/src/cut/lib/backend/browser.ts
+++ b/site/src/cut/lib/backend/browser.ts
@@ -4,6 +4,7 @@
// compiled into the engine binary with the rest of backend/, so the router and
// store load through a function-scoped dynamic import and nothing here touches
// the DOM at module scope.
+import { observeOperationResponse } from "../operationFailure";
import { registeredUrl } from "./browser/registry";
import type { CutBackend } from "./types";
@@ -12,7 +13,7 @@ const cloudPath = (path: string) => path.replace(/^\/api\/cut\//, "/api/cut-clou
async function browserFetch(path: string, init?: RequestInit): Promise<Response> {
const { dispatchBrowserRoute } = await import("./browser/router");
const owned = await dispatchBrowserRoute(path, init);
- return owned ?? fetch(cloudPath(path), init);
+ return observeOperationResponse(owned ?? await fetch(cloudPath(path), init));
}
export const browserBackend: CutBackend = {
diff --git a/site/src/cut/lib/backend/cloud.ts b/site/src/cut/lib/backend/cloud.ts
index 7a44a2b4..280fb2e4 100644
--- a/site/src/cut/lib/backend/cloud.ts
+++ b/site/src/cut/lib/backend/cloud.ts
@@ -3,7 +3,7 @@
// the session). Routes mirror the engine's JSON shapes under /api/cut-cloud.
// Media bytes ride presigned R2 URLs minted by those routes, not this
// transport.
-import { emitStorageQuota } from "../storageQuota";
+import { observeOperationResponse, operationFailure } from "../operationFailure";
import type { CutBackend, CutRequestInit } from "./types";
const cloudPath = (path: string) => path.replace(/^\/api\/cut\//, "/api/cut-cloud/");
@@ -18,12 +18,26 @@ export function bindCloudSession(base: string, headers: Record<string, string>)
/** A request on the hosted site as this process's user: same-origin in the
* page, the bound session's origin and headers in a headless process. */
+type CloudSession = { base: string; headers: Record<string, string> } | null;
+
+function requestWithSession(bound: CloudSession, path: string, init?: RequestInit): Promise<Response> {
+ const headers = new Headers(bound?.headers);
+ new Headers(init?.headers).forEach((value, key) => headers.set(key, value));
+ return fetch((bound?.base ?? "") + path, { ...init, headers }).then(observeOperationResponse);
+}
+
export function cloudRequest(path: string, init?: RequestInit): Promise<Response> {
- if (!session) return fetch(path, init);
- return fetch(session.base + path, {
- ...init,
- headers: { ...session.headers, ...(init?.headers as Record<string, string> | undefined) },
- });
+ return requestWithSession(session, path, init);
+}
+
+/** Capture transport credentials for work that outlives the active project. */
+export function captureCloudBackend(): CutBackend {
+ const bound = session ? { base: session.base, headers: { ...session.headers } } : null;
+ return {
+ ...cloudBackend,
+ fetch: (path, init) => cloudFetch(path, init, (url, options) => requestWithSession(bound, url, options)),
+ url: (path) => (bound?.base ?? "") + cloudPath(path),
+ };
}
// Cloud project docs are versioned for lost-write detection: GET hands the
@@ -73,15 +87,15 @@ const docGets = new Map<string, Promise<void>>();
// /projects/:id only — /projects/folders is the folder collection, not a doc.
const PROJECT_DOC = /^\/api\/cut\/projects\/(?!folders$)([^/?]+)$/;
-async function cloudFetch(path: string, options?: CutRequestInit): Promise<Response> {
+async function cloudFetch(path: string, options?: CutRequestInit, request = cloudRequest): Promise<Response> {
const { observe, ...init } = options ?? {};
const doc = PROJECT_DOC.exec(path);
const method = (init?.method ?? "GET").toUpperCase();
- if (observe || !doc || (method !== "GET" && method !== "PUT")) return cloudRequest(cloudPath(path), init);
+ if (observe || !doc || (method !== "GET" && method !== "PUT")) return request(cloudPath(path), init);
const projectId = decodeURIComponent(doc[1]);
if (method === "GET") {
- const req = cloudRequest(cloudPath(path), init);
+ const req = request(cloudPath(path), init);
const tracked = req.then(
(res) => {
if (res.ok) noteVersion(projectId, res.headers.get("x-cut-doc-version"));
@@ -96,18 +110,18 @@ async function cloudFetch(path: string, options?: CutRequestInit): Promise<Respo
}
const prev = putChains.get(projectId) ?? Promise.resolve();
- const run = prev.then(() => putDoc(projectId, path, init));
+ const run = prev.then(() => putDoc(projectId, path, init, request));
// The chain survives a failed link; the failure is the caller's to handle.
putChains.set(projectId, run.catch(() => undefined));
return run;
}
-async function putDoc(projectId: string, path: string, init?: RequestInit): Promise<Response> {
+async function putDoc(projectId: string, path: string, init?: RequestInit, request = cloudRequest): Promise<Response> {
await docGets.get(projectId);
// A pinned base outranks the map; with neither, an unversioned PUT is the
// first save and succeeds unconditionally.
const v = basePins.get(projectId) ?? docVersions.get(projectId);
- const res = await cloudRequest(cloudPath(path) + (v ? `?v=${encodeURIComponent(v)}` : ""), init);
+ const res = await request(cloudPath(path) + (v ? `?v=${encodeURIComponent(v)}` : ""), init);
if (res.ok || res.status === 409) basePins.delete(projectId);
if (res.status === 409) {
const body = (await res
@@ -178,16 +192,13 @@ export async function fetchSignedMediaUrls(
return out;
}
-/** Friendly message for a presign 413 quota rejection, else null. Also raises
- * the storage-quota wall so the upgrade dialog opens wherever the rejection
- * happened — this inline string stays as the terse fallback next to it. */
+/** Pure message formatting; the host decides how a quota failure is presented. */
export function quotaErrorMessage(
status: number,
body: { error?: string; bytes?: number; quotaBytes?: number } | null | undefined
): string | null {
- if (status !== 413 || body?.error !== "storage_quota_exceeded") return null;
- emitStorageQuota({ bytes: body?.bytes, quotaBytes: body?.quotaBytes, source: "quota-413" });
- return "Cloud storage is full.";
+ const failure = operationFailure(status, body);
+ return failure?.code === "storage_quota_exceeded" ? failure.message : null;
}
export const cloudBackend: CutBackend = {
diff --git a/site/src/cut/lib/backend/cloudCapture.test.ts b/site/src/cut/lib/backend/cloudCapture.test.ts
new file mode 100644
index 00000000..81cef5bf
--- /dev/null
+++ b/site/src/cut/lib/backend/cloudCapture.test.ts
@@ -0,0 +1,19 @@
+import { afterEach, expect, spyOn, test } from "bun:test";
+import { bindCloudSession, captureCloudBackend } from "./cloud";
+
+afterEach(() => { bindCloudSession("", {}); });
+
+test("background requests retain captured credentials after the process is rebound", async () => {
+ const fetcher = spyOn(globalThis, "fetch").mockResolvedValue(new Response("{}"));
+ try {
+ bindCloudSession("https://first.invalid", { Authorization: "first" });
+ const first = captureCloudBackend();
+ bindCloudSession("https://second.invalid", { Authorization: "second" });
+ await first.fetch("/api/cut/export/example", { headers: new Headers({ "X-Example": "value" }) });
+ const [url, options] = fetcher.mock.calls[0];
+ expect(url).toBe("https://first.invalid/api/cut-cloud/export/example");
+ expect(new Headers(options?.headers).get("Authorization")).toBe("first");
+ expect(new Headers(options?.headers).get("X-Example")).toBe("value");
+ expect(first.url("/api/cut/export/example/file")).toBe("https://first.invalid/api/cut-cloud/export/example/file");
+ } finally { fetcher.mockRestore(); }
+});
diff --git a/site/src/cut/lib/backend/local.ts b/site/src/cut/lib/backend/local.ts
index d9924205..163fedd2 100644
--- a/site/src/cut/lib/backend/local.ts
+++ b/site/src/cut/lib/backend/local.ts
@@ -1,7 +1,7 @@
// The local backend: the engine on this Mac. A pass-through to the existing
// engine transport in ../api, so request shapes are exactly what they were
// before the backend seam existed.
-import { apiFetch, apiUrl } from "../api";
+import { apiFetch, apiUrl, engineReady, engineOrigin, currentEngineUser } from "../api";
import type { CutBackend } from "./types";
export const localBackend: CutBackend = {
@@ -17,3 +17,15 @@ export const localBackend: CutBackend = {
fetch: (path, init) => apiFetch(path, init),
url: (path) => apiUrl(path),
};
+
+export function captureLocalBackend(): CutBackend {
+ const userId = currentEngineUser();
+ const origin = engineOrigin();
+ const scoped = (path: string) => userId
+ ? `${path}${path.includes("?") ? "&" : "?"}u=${encodeURIComponent(userId)}` : path;
+ return {
+ ...localBackend,
+ fetch: async (path, init) => fetch(`${origin || await engineReady()}${scoped(path)}`, init),
+ url: (path) => `${origin}${scoped(path)}`,
+ };
+}
diff --git a/site/src/cut/lib/hosted.ts b/site/src/cut/lib/hosted.ts
index a9b7f920..fa62bc5d 100644
--- a/site/src/cut/lib/hosted.ts
+++ b/site/src/cut/lib/hosted.ts
@@ -4,6 +4,7 @@ import { useEffect } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { create } from "zustand";
+import { observeOperationResponse } from "./operationFailure";
import { offloadHostedMedia } from "./hostedBlobs";
// Donkey's hosted inference routes, called from the page with the user's
@@ -180,6 +181,7 @@ export const hostedPost = async (path: string, body: unknown, signal?: AbortSign
body: payload,
signal,
});
+ await observeOperationResponse(res);
await noteBalance(res);
return res;
};
diff --git a/site/src/cut/lib/operationFailure.test.ts b/site/src/cut/lib/operationFailure.test.ts
new file mode 100644
index 00000000..2b232e1c
--- /dev/null
+++ b/site/src/cut/lib/operationFailure.test.ts
@@ -0,0 +1,21 @@
+import { expect, test } from "bun:test";
+import { observeOperationResponse, onOperationFailure, operationFailure } from "./operationFailure";
+
+test("a storage failure is data and leaves the response readable", async () => {
+ const body = { error: "storage_quota_exceeded", bytes: 20, quotaBytes: 10 };
+ const failures: unknown[] = [];
+ const stop = onOperationFailure((failure) => failures.push(failure));
+ try {
+ const response = new Response(JSON.stringify(body), { status: 413 });
+ expect(await observeOperationResponse(response)).toBe(response);
+ expect(await response.json()).toEqual(body);
+ expect(failures).toEqual([{ code: body.error, message: "Cloud storage is full.", bytes: 20, quotaBytes: 10 }]);
+ } finally { stop(); }
+});
+
+test("size limits are distinct from account storage and generation credits from an empty balance", () => {
+ expect(operationFailure(413, { error: "File too large." })).toBeNull();
+ expect(operationFailure(402, { error: "insufficient_credits_for_generation" })?.code).toBe("insufficient_credits_for_generation");
+ expect(operationFailure(402, {})?.code).toBe("insufficient_credits");
+ expect(operationFailure(401, null)?.code).toBe("authentication_required");
+});
diff --git a/site/src/cut/lib/operationFailure.ts b/site/src/cut/lib/operationFailure.ts
new file mode 100644
index 00000000..313c2591
--- /dev/null
+++ b/site/src/cut/lib/operationFailure.ts
@@ -0,0 +1,46 @@
+/** JSON-safe failures shared by transports, headless commands, and host UIs. */
+export type OperationFailure = {
+ code: "storage_quota_exceeded" | "insufficient_credits" | "insufficient_credits_for_generation" | "authentication_required";
+ message: string;
+ bytes?: number;
+ quotaBytes?: number;
+};
+
+export function operationFailure(status: number, body: unknown): OperationFailure | null {
+ const data = body && typeof body === "object" ? body as Record<string, unknown> : {};
+ if (status === 401) return { code: "authentication_required", message: "Sign in to continue." };
+ if (status === 413 && data.error === "storage_quota_exceeded") {
+ return {
+ code: "storage_quota_exceeded", message: "Cloud storage is full.",
+ ...(typeof data.bytes === "number" ? { bytes: data.bytes } : {}),
+ ...(typeof data.quotaBytes === "number" ? { quotaBytes: data.quotaBytes } : {}),
+ };
+ }
+ if (status === 402) return {
+ code: data.error === "insufficient_credits_for_generation"
+ ? "insufficient_credits_for_generation" : "insufficient_credits",
+ message: "There are not enough AI credits for this operation.",
+ };
+ return null;
+}
+
+export class OperationError extends Error {
+ constructor(readonly failure: OperationFailure) {
+ super(failure.message);
+ this.name = "OperationError";
+ }
+}
+
+const listeners = new Set<(failure: OperationFailure) => void>();
+export function onOperationFailure(listener: (failure: OperationFailure) => void): () => void {
+ listeners.add(listener);
+ return () => { listeners.delete(listener); };
+}
+
+/** Hosts opt into presentation. Reading a response never consumes its body. */
+export async function observeOperationResponse(response: Response): Promise<Response> {
+ if (![401, 402, 413].includes(response.status)) return response;
+ const failure = operationFailure(response.status, await response.clone().json().catch(() => null));
+ if (failure) for (const listener of listeners) listener(failure);
+ return response;
+}
diff --git a/site/src/cut/lib/projectOperation.ts b/site/src/cut/lib/projectOperation.ts
new file mode 100644
index 00000000..47e52ac6
--- /dev/null
+++ b/site/src/cut/lib/projectOperation.ts
@@ -0,0 +1,24 @@
+import { getBackend, type CutBackend, type CutCaps, type CutMode } from "@/cut/lib/backend";
+import { captureCloudBackend, cloudBackend, knownDocVersion } from "@/cut/lib/backend/cloud";
+import { captureLocalBackend, localBackend } from "@/cut/lib/backend/local";
+import { projectRevision } from "@/cut/lib/projectRevision";
+
+/** Execution context captured before asynchronous work starts. Server routes
+ * remain responsible for authenticating and authorizing every request. */
+export type ProjectOperation = {
+ projectId: string;
+ residency: CutMode;
+ version: string | null;
+ backend: CutBackend;
+ capabilities: Readonly<CutCaps>;
+};
+
+export function projectOperation(projectId: string, backend = getBackend()): ProjectOperation {
+ if (backend.kind === "shared") throw new Error("A shared project is read-only.");
+ const captured = backend === cloudBackend ? captureCloudBackend() : backend === localBackend ? captureLocalBackend() : backend;
+ return {
+ projectId, backend: captured, residency: captured.kind,
+ version: projectRevision(projectId) ?? (captured.kind === "cloud" ? knownDocVersion(projectId) : null),
+ capabilities: { ...captured.caps },
+ };
+}
diff --git a/site/src/cut/lib/storageQuota.ts b/site/src/cut/lib/storageQuota.ts
index a5c8006e..c8656afd 100644
--- a/site/src/cut/lib/storageQuota.ts
+++ b/site/src/cut/lib/storageQuota.ts
@@ -1,7 +1,3 @@
-// The storage-quota wall: one contract shared by the code that hits the limit
-// (the cloud transport's 413 handler) and the dialog that offers the upgrade.
-// It lives in lib so the React-free transport can raise it.
-
export type StorageQuotaDetail = {
bytes?: number;
quotaBytes?: number;
@@ -9,7 +5,7 @@ export type StorageQuotaDetail = {
grace?: { deadline: string; overBytes: number };
};
-const EVENT = "cut-storage-quota";
+const listeners = new Set<(detail: StorageQuotaDetail) => void>();
// A rejected upload rejects once per file, and every file in the batch is over
// the same limit. The first one raises the wall; the rest are the same event,
@@ -17,9 +13,9 @@ const EVENT = "cut-storage-quota";
let walled = false;
export function emitStorageQuota(detail: StorageQuotaDetail): void {
- if (typeof window === "undefined" || walled) return;
+ if (walled || listeners.size === 0) return;
walled = true;
- window.dispatchEvent(new CustomEvent(EVENT, { detail }));
+ for (const listener of listeners) listener(detail);
}
/** Open the dialog from a deliberate click, past any standing wall. */
@@ -34,7 +30,9 @@ export function clearStorageQuotaWall(): void {
}
export function onStorageQuota(handler: (detail: StorageQuotaDetail) => void): () => void {
- const listener = (e: Event) => handler((e as CustomEvent<StorageQuotaDetail>).detail);
- window.addEventListener(EVENT, listener);
- return () => window.removeEventListener(EVENT, listener);
+ listeners.add(handler);
+ return () => {
+ listeners.delete(handler);
+ if (listeners.size === 0) walled = false;
+ };
}