Open source CapCut alternative.
TypeScript
feat(site): run cloud projects alongside local
David Le1d8433b27d6c
diff --git a/site/src/app/cut/app/(home)/settings/flags/page.tsx b/site/src/app/cut/app/(home)/settings/flags/page.tsxindex 5230c8b3..1e4653a1 100644--- a/site/src/app/cut/app/(home)/settings/flags/page.tsx+++ b/site/src/app/cut/app/(home)/settings/flags/page.tsx@@ -2,15 +2,13 @@import { useEffect, useState } from "react";-import { track } from "@/lib/analytics";import { Switch } from "@/components/ui/switch";-import { applyWebModeLocal } from "@/cut/lib/flags";type FlagRow = { id: string; title: string; description: string; enabled: boolean };-// Self-serve account feature flags. The account is the source of truth; the-// Cut client mirrors "cut-web-mode" locally so the editor reacts to a flip-// without a reload.+// Self-serve account feature flags. The account is the source of truth: the+// switch writes the row and the page holds the new state optimistically until+// the write answers.export default function CutFeatureFlagsPage() {const [flags, setFlags] = useState<FlagRow[] | null>(null);const [error, setError] = useState<string | null>(null);@@ -33,19 +31,14 @@ export default function CutFeatureFlagsPage() {const toggle = (id: string, enabled: boolean) => {setFlags((cur) => cur?.map((f) => (f.id === id ? { ...f, enabled } : f)) ?? cur);- if (id === "cut-web-mode") {- applyWebModeLocal(enabled);- if (enabled) track("cut_cloud_enable_clicked", { source: "settings_flags" });- }void fetch("/api/account/feature-flags", {method: "PUT",headers: { "Content-Type": "application/json" },body: JSON.stringify({ flag: id, enabled }),}).then((res) => {if (res.ok) return;- // The account write failed; put the switch (and the mirror) back.+ // The account write failed; put the switch back.setFlags((cur) => cur?.map((f) => (f.id === id ? { ...f, enabled: !enabled } : f)) ?? cur);- if (id === "cut-web-mode") applyWebModeLocal(!enabled);setError("Couldn't save that change — try again.");});};@@ -55,6 +48,11 @@ export default function CutFeatureFlagsPage() {<div className="rounded-xl border bg-card p-5">{error && <p className="mb-3 text-sm text-red-600">{error}</p>}{!flags && !error && <p className="text-sm text-muted-foreground">Loading…</p>}+ {flags?.length === 0 && (+ <p className="text-sm text-muted-foreground">+ There are no early features to turn on right now.+ </p>+ )}{flags?.map((f, i) => (<div key={f.id} className={i > 0 ? "mt-4 border-t pt-4" : undefined}><div className="flex items-start justify-between gap-6">diff --git a/site/src/cut/components/ProjectsHome.tsx b/site/src/cut/components/ProjectsHome.tsxindex a9850e51..a09ebaf8 100644--- a/site/src/cut/components/ProjectsHome.tsx+++ b/site/src/cut/components/ProjectsHome.tsx@@ -61,7 +61,6 @@ import {type Residency,} from "@/cut/lib/queries";import { useInView } from "@/cut/hooks/useInView";-import { useWebMode } from "@/cut/lib/flags";import { track } from "@/lib/analytics";import { authClient } from "@/lib/auth-client";import { useStartCheckout } from "@/queries/billing";@@ -168,15 +167,17 @@ export function ProjectsHome() {const mode = useCutMode();// The home never runs in shared mode; anything non-cloud lists as local.const homeMode: Residency = mode === "cloud" ? "cloud" : "local";- const webMode = useWebMode();const { data: session } = authClient.useSession();// Which backends this home lists. Engine presence is what the ConnectGate// already resolved for this tab (same-origin page, or a memoized loopback// origin) — never a fresh probe, which could raise the browser's// local-network prompt.const engineUp = servedFromEngine() || engineOrigin() !== "";- const residencies: Residency[] =- !webMode || !session ? ["local"] : engineUp ? ["local", "cloud"] : ["cloud"];+ const residencies: Residency[] = !session+ ? ["local"]+ : engineUp+ ? ["local", "cloud"]+ : ["cloud"];const dual = residencies.length > 1;const r0 = residencies[0];diff --git a/site/src/cut/components/RequireSession.tsx b/site/src/cut/components/RequireSession.tsxindex 65219de3..86b6c415 100644--- a/site/src/cut/components/RequireSession.tsx+++ b/site/src/cut/components/RequireSession.tsx@@ -4,7 +4,6 @@ import { useEffect, type ReactNode } from "react";import { authHrefFor } from "@/app/_components/landing/useAppEntryHref";import { setEngineUser } from "@/cut/lib/api";-import { syncAccountFlags } from "@/cut/lib/flags";import { useAppLoaded } from "@/lib/analytics";import { authClient } from "@/lib/auth-client";@@ -26,14 +25,6 @@ export function RequireSession({ children }: { children: ReactNode }) {useAppLoaded("cut", session?.user);- // The web-mode flag lives on the account; refresh the local mirror once the- // session is known so a grant (or revoke) from another device takes effect- // on the next load here.- const userId = session?.user.id;- useEffect(() => {- if (userId) void syncAccountFlags();- }, [userId]);-useEffect(() => {if (!signedOut) return;const here = window.location.pathname + window.location.search;diff --git a/site/src/cut/components/TopBar.tsx b/site/src/cut/components/TopBar.tsxindex f057698d..b831b0f4 100644--- a/site/src/cut/components/TopBar.tsx+++ b/site/src/cut/components/TopBar.tsx@@ -28,7 +28,6 @@ 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 { useWebMode } from "@/cut/lib/flags";import { backTarget, projectHref, useCutBase } from "@/cut/lib/nav";import { copyProjectAcross } from "@/cut/lib/projectCopy";import { useEditor } from "@/cut/lib/store";@@ -187,14 +186,13 @@ export function TopBar({endEditing();};- // "Move to Cloud" (cut-web-mode flag): copies this local project — doc and- // every media file — to the cloud, deletes the local original, and reopens- // the editor on the cloud copy.- const webMode = useWebMode();+ // "Move to Cloud": copies this local project — doc and every media file — to+ // the cloud, deletes the local original, and reopens the editor on the cloud+ // copy.const cutMode = useCutMode();- const canMoveToCloud = webMode && cutMode === "local";+ const canMoveToCloud = cutMode === "local";// Cloud imports are real uploads worth reporting; local imports are instant- // disk copies, so the flag-off surface stays exactly as it was.+ // disk copies, so they report nothing.const cloudUploading = uploading > 0 && cutMode === "cloud";// 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.diff --git a/site/src/cut/components/ViewerTopBar.tsx b/site/src/cut/components/ViewerTopBar.tsxindex 21bc0a06..6c76acb1 100644--- a/site/src/cut/components/ViewerTopBar.tsx+++ b/site/src/cut/components/ViewerTopBar.tsx@@ -6,7 +6,6 @@ import { authHrefFor } from "@/app/_components/landing/useAppEntryHref";import { Button } from "@/components/ui/button";import { apiFetch } from "@/cut/lib/backend";import { quotaErrorMessage } from "@/cut/lib/backend/cloud";-import { enableWebMode } from "@/cut/lib/flags";import { projectHref, useCutBase } from "@/cut/lib/nav";import { useEditor } from "@/cut/lib/store";import { authClient } from "@/lib/auth-client";@@ -54,9 +53,6 @@ export function ViewerTopBar() {error?: string;};if (job.state === "done" && job.newProjectId) {- // The copy is a cloud project, so cloud editing must be on for- // this account before the editor opens it.- await enableWebMode();window.location.href = projectHref(base, job.newProjectId, "projects");return;}diff --git a/site/src/cut/lib/backend/index.ts b/site/src/cut/lib/backend/index.tsindex 07e4b8d0..824d1b11 100644--- a/site/src/cut/lib/backend/index.ts+++ b/site/src/cut/lib/backend/index.ts@@ -1,8 +1,7 @@// The backend seam: every Cut API call dispatches through the active backend.-// The app runs local (the engine on this Mac) unless the ConnectGate put it in-// cloud mode — web mode with no engine present, behind the `cut-web-mode`-// flag. Call sites keep the exact apiFetch/apiUrl/apiJson shapes they always-// had; only the import moved from ../api to this module.+// The app runs local (the engine on this Mac) when the ConnectGate reached one,+// and in the cloud otherwise. Call sites keep the exact apiFetch/apiUrl/apiJson+// shapes they always had; only the import moved from ../api to this module.//// This module stays React-free: the engine binary compiles lib/types.ts, which// imports apiUrl from here. React hooks live in ./hooks.diff --git a/site/src/cut/lib/exportStore.ts b/site/src/cut/lib/exportStore.tsindex 90be2c44..e729dcb0 100644--- a/site/src/cut/lib/exportStore.ts+++ b/site/src/cut/lib/exportStore.ts@@ -6,7 +6,6 @@ import { engineOrigin, servedFromEngine } from "./api";import { getBackend, type CutBackend, type CutMode } from "./backend";import { cloudBackend } from "./backend/cloud";import { localBackend } from "./backend/local";-import { webModeEnabled } from "./flags";import {cancelExportJob,createExportJob,@@ -21,10 +20,10 @@ import { useGenNotify } from "./genNotify";// starting an export in one project while another still renders just adds a row.// The dock (ExportsDock) renders it; the engine does the queueing.//-// With web mode on, local and cloud jobs can be in flight at once, so the-// store reflects both backends' feeds; each row is tagged with the residency-// it came from and every per-row action goes to that row's own backend — the-// globally bound mode rebinds whenever a project of the other residency opens.+// Local and cloud jobs can be in flight at once, so the store reflects both+// backends' feeds; each row is tagged with the residency it came from and+// every per-row action goes to that row's own backend — the globally bound+// mode rebinds whenever a project of the other residency opens.export interface ExportJob {id: string;@@ -184,14 +183,12 @@ export const useExports = create<ExportsState>((set, get) => ({return null;}};- // Flag off: exactly the pre-seam behavior — the local feed only. Flag on,- // jobs of both residencies can run at once, so poll every plausible feed:- // local when an engine is actually reachable, cloud always.- const cloudOn = webModeEnabled();- const pollLocal = !cloudOn || engineOrigin() !== "" || servedFromEngine();+ // Jobs of both residencies can run at once, so poll every feed this+ // browser can reach: the cloud always, local once an engine has answered.+ const pollLocal = engineOrigin() !== "" || servedFromEngine();const [localRows, cloudRows] = await Promise.all([pollLocal ? fetchFeed(localBackend) : Promise.resolve(null),- cloudOn ? fetchFeed(cloudBackend) : Promise.resolve(null),+ fetchFeed(cloudBackend),]);set((s) => {// A failed or skipped feed keeps its previous rows; only a fresh answerdiff --git a/site/src/cut/lib/flags.ts b/site/src/cut/lib/flags.tsdeleted file mode 100644index d8fed8e0..00000000--- a/site/src/cut/lib/flags.ts+++ /dev/null@@ -1,72 +0,0 @@-// Cut's web-mode flag is an ACCOUNT feature flag ("cut-web-mode"), set per user-// in the account settings' Feature flags section. It ships on for everyone, so-// the switch is an opt-out. localStorage only mirrors the server value so reads-// stay synchronous; RequireSession refreshes the mirror from the account on-// every app load, and the settings page updates it when the user flips the-// switch. Reads go through useSyncExternalStore so every component — and every-// other tab, via the storage event — reacts to a change immediately.-import { featureFlagDefault } from "@/lib/feature-flags";-import { useSyncExternalStore } from "react";--const WEB_MODE_KEY = "cut-web-mode";-const FLAG_EVENT = "cut-flags-changed";--const WEB_MODE_DEFAULT = featureFlagDefault(WEB_MODE_KEY);--/** The mirror is three-valued: "1" on, "0" off, absent means the account has- * never been read here, which is the flag's registry default. */-export function webModeEnabled(): boolean {- if (typeof window === "undefined") return WEB_MODE_DEFAULT;- const mirror = localStorage.getItem(WEB_MODE_KEY);- if (mirror === null) return WEB_MODE_DEFAULT;- return mirror === "1";-}--/** Update the local mirror (this tab reacts immediately, other tabs via the- * storage event). The account value is written by the settings page's PUT;- * this never calls the server. */-export function applyWebModeLocal(on: boolean) {- localStorage.setItem(WEB_MODE_KEY, on ? "1" : "0");- window.dispatchEvent(new Event(FLAG_EVENT));-}--/** Turn the account flag on (same PUT the settings page issues) and mirror it- * locally on success. Returns whether the account write landed. */-export async function enableWebMode(): Promise<boolean> {- const res = await fetch("/api/account/feature-flags", {- method: "PUT",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ flag: WEB_MODE_KEY, enabled: true }),- }).catch(() => null);- if (!res?.ok) return false;- applyWebModeLocal(true);- return true;-}--/** Refresh the mirror from the signed-in account's flags. Errors keep the- * current mirror — a transient fetch failure must not flip the editor's- * backend out from under the user. */-export async function syncAccountFlags() {- try {- const res = await fetch("/api/account/feature-flags");- if (!res.ok) return;- const body = (await res.json()) as { flags?: { id: string; enabled: boolean }[] };- const webMode = body.flags?.find((f) => f.id === WEB_MODE_KEY);- if (webMode) applyWebModeLocal(webMode.enabled);- } catch {- // Offline or hosted API unreachable; the mirror stands.- }-}--function subscribe(onChange: () => void) {- window.addEventListener(FLAG_EVENT, onChange);- window.addEventListener("storage", onChange);- return () => {- window.removeEventListener(FLAG_EVENT, onChange);- window.removeEventListener("storage", onChange);- };-}--export function useWebMode(): boolean {- return useSyncExternalStore(subscribe, webModeEnabled, () => WEB_MODE_DEFAULT);-}diff --git a/site/src/cut/lib/queries.ts b/site/src/cut/lib/queries.tsindex 2483beb1..159b640c 100644--- a/site/src/cut/lib/queries.ts+++ b/site/src/cut/lib/queries.ts@@ -20,9 +20,9 @@ import { useQuery, useQueryClient, type QueryClient } from "@tanstack/react-querimport { useEffect } from "react";import { engineLost } from "./api";+import { cutMode } from "./backend";import { useCutMode } from "./backend/hooks";import { readSnapshot, snapshotKey, writeSnapshot } from "./cache";-import { webModeEnabled } from "./flags";import { fetchLibrary, type LibraryData } from "./library";import { availableResidencies, backendFor, type Residency } from "./residency";import type { ProjectFolder, ProjectSummary } from "./types";@@ -88,9 +88,11 @@ export function useProjectsSection(r: Residency, enabled: boolean) {writeSnapshot(snapshotKey(r, "projects"), data);return data;} catch (err) {- if (r === "local" && !webModeEnabled()) {- // The engine on this Mac stopped answering; the ConnectGate takes- // the screen back over until it returns.+ if (r === "local" && cutMode() === "local") {+ // The engine this app is running on stopped answering; the+ // ConnectGate falls back to the cloud and says so. A cloud-bound app+ // whose local shelf hiccups keeps running — that failure is one+ // section's error, not the ground moving.engineLost();}throw err;diff --git a/site/src/cut/lib/residency.ts b/site/src/cut/lib/residency.tsindex ed6a7c8b..b5c8a265 100644--- a/site/src/cut/lib/residency.ts+++ b/site/src/cut/lib/residency.ts@@ -1,9 +1,8 @@// Where a project lives is a fact about the project, not the link that opened-// it: the editor resolves residency by asking, so URLs stay clean. With the-// web-mode flag off everything is local (today's behavior). Otherwise the-// engine — when one is already connected; loopback is never probed here, so-// the browser's local-network ask can't fire — is asked whether it owns the-// id, and a miss means the project is cloud-resident.+// it: the editor resolves residency by asking, so URLs stay clean. The engine+// — when one is already connected; loopback is never probed here, so the+// browser's local-network ask can't fire — is asked whether it owns the id,+// and a miss means the project is cloud-resident.//// A project opens into one residency. The library is the other way around: it// is the user's shelf, and both halves of it are theirs, so every surface that@@ -15,7 +14,6 @@ import { cutMode } from "./backend";import { cloudBackend } from "./backend/cloud";import { localBackend } from "./backend/local";import type { CutBackend, CutMode } from "./backend/types";-import { webModeEnabled } from "./flags";/** Where a piece of the user's own data lives. ("shared" is a view of someone* else's cloud project, never a residency of yours, so it never lists here.) */@@ -32,19 +30,16 @@ export const RESIDENCY_LABEL: Record<Residency, string> = {/*** The residencies this browser can talk to right now.*- * The engine counts only once it has actually answered — the ConnectGate- * resolved its origin, or the page is served by it. Probing here could raise- * the browser's local-network prompt, and calling the engine before the gate- * opens would hang on its latch. The cloud counts whenever web mode is on;- * without the flag there is no hosted half to read.+ * The cloud is always one of them — a signed-in account always has a hosted+ * shelf. The engine counts only once it has actually answered — the+ * ConnectGate resolved its origin, or the page is served by it. Probing here+ * could raise the browser's local-network prompt, and calling the engine+ * before the gate opens would hang on its latch.*/export function availableResidencies(): Residency[] {const out: Residency[] = [];if (servedFromEngine() || engineOrigin() !== "") out.push("local");- if (webModeEnabled()) out.push("cloud");- // Neither resolved yet: fall back to whatever the app is bound to, so a- // caller always has one backend to ask.- if (out.length === 0) out.push(activeResidency());+ out.push("cloud");return out;}@@ -55,7 +50,6 @@ export function activeResidency(): Residency {}export async function resolveProjectMode(projectId: string): Promise<CutMode> {- if (!webModeEnabled()) return "local";if (!servedFromEngine() && !engineOrigin()) return "cloud";try {// HEAD: the question is whether the engine owns the id, and the answer isdiff --git a/site/src/lib/analytics.ts b/site/src/lib/analytics.tsindex 4e15e2a1..8409f4ab 100644--- a/site/src/lib/analytics.ts+++ b/site/src/lib/analytics.ts@@ -11,14 +11,6 @@ export type AnalyticsEvents = {home_download_clicked: { location: "hero" | "final_cta" };// Install prompts on the Cut app home's connect gate.app_install_clicked: { source: "connect_gate_button" | "connect_gate_link" };- // Cut cloud mode turned on (the cut-web-mode account flag).- cut_cloud_enable_clicked: {- source:- | "connect_gate_install"- | "connect_gate_ask"- | "connect_gate_blocked"- | "settings_flags";- };// Cut projects home.project_created: { source: "projects_home" | "sidebar" | "file_import" };folder_created: void;diff --git a/site/src/lib/feature-flags.ts b/site/src/lib/feature-flags.tsindex ba1ddc7f..ebf175ea 100644--- a/site/src/lib/feature-flags.ts+++ b/site/src/lib/feature-flags.ts@@ -10,18 +10,7 @@ export type AccountFeatureFlag = {defaultEnabled: boolean;};-export const ACCOUNT_FEATURE_FLAGS: AccountFeatureFlag[] = [- {- id: "cut-web-mode",- title: "Cloud mode (beta)",- description:- "Edit in any browser on any OS with no install: projects stored in the cloud, exports rendered by a cloud worker. The Mac app keeps running everything locally.",- defaultEnabled: true,- },-];--export const featureFlagDefault = (id: string) =>- ACCOUNT_FEATURE_FLAGS.find((f) => f.id === id)?.defaultEnabled ?? false;+export const ACCOUNT_FEATURE_FLAGS: AccountFeatureFlag[] = [];export const isKnownFeatureFlag = (id: string) =>ACCOUNT_FEATURE_FLAGS.some((f) => f.id === id);