Skip to content

Open source CapCut alternative.

TypeScript

feat(site): hold the Cut app behind a connect modal until the engine answers

David Le86023b3bd8fb
diff --git a/site/src/app/cut/app/layout.tsx b/site/src/app/cut/app/layout.tsx
index ebaf0402..db692b0b 100644
--- a/site/src/app/cut/app/layout.tsx
+++ b/site/src/app/cut/app/layout.tsx
@@ -10,9 +10,10 @@ import { RequireSession } from "@/cut/components/RequireSession";
// html white so the cream does not show through the overscroll area, and
// font-system matches the /app system font stack. RequireSession gates the
// whole subtree on a signed-in session, redirecting signed-out visitors to
-// sign-in with their target URL as the callback. ConnectGate holds the first
-// hosted visit on a connect screen so the browser's local-network permission
-// prompt fires from the user's own click instead of ambushing them at login.
+// sign-in with their target URL as the callback. ConnectGate keeps the app
+// blurred and inert behind a connect modal until the engine on this Mac
+// answers, so the browser's local-network permission prompt only ever fires
+// from the user's own Connect click.
export default function CutAppLayout({ children }: { children: ReactNode }) {
return (
<div className="min-h-screen bg-white font-system text-foreground antialiased">
diff --git a/site/src/cut/components/ConnectGate.tsx b/site/src/cut/components/ConnectGate.tsx
index 7f8c9d07..31245bf3 100644
--- a/site/src/cut/components/ConnectGate.tsx
+++ b/site/src/cut/components/ConnectGate.tsx
@@ -4,24 +4,49 @@ import Image from "next/image";
import { useCallback, useEffect, useState, type ReactNode } from "react";
import { Loader2, Plug, ShieldX } from "lucide-react";
+import { DONKEY_DOWNLOAD_URL } from "@/app/_components/landing/data";
import { Button } from "@/components/ui/button";
-import { engineConnect, servedFromEngine } from "@/cut/lib/api";
+import {
+ ENGINE_LOST_EVENT,
+ engineConnect,
+ engineGateOpen,
+ engineProbe,
+ servedFromEngine,
+} from "@/cut/lib/api";
// Chrome gates a public https page's first fetch to 127.0.0.1 behind its
// Local Network Access prompt — "donkeycut.com wants to access other apps and
-// services on this device". Left to fire from the projects list's mount-time
-// probe, it ambushes the user right after login, and a reflexive Block
-// silently strands every engine call. This gate holds the Cut app subtree
-// until the user starts the connection themselves: a connect screen says what
-// the browser is about to ask, the Connect click runs the first probe (which
-// waits out the prompt), and a denied permission gets its own recovery
-// screen. The screen shows once per browser — once connected (or
-// acknowledged), later visits pass straight through — and never when the page
-// is served by the engine itself, where loopback is same-origin.
+// services on this device". This gate renders the app blurred and inert
+// behind a modal until an engine probe actually succeeds, and asks with its
+// own UI first: while the browser permission is unresolved, the request that
+// raises Chrome's prompt only ever starts from the user's Connect click, so
+// the prompt can never ambush a login. The api.ts gate latch holds the
+// mounted app's own requests until the gate opens, making that true by
+// construction. The modal has two shapes:
+//
+// connect/install — no engine has answered: ask to connect (browser prompt
+// pending) or to install/open the Donkey app, with a direct DMG download.
+// blocked — the permission is denied; site-settings recovery.
+//
+// Once the permission is granted (or the page is served by the engine, where
+// loopback is same-origin) the gate probes quietly and keeps polling, so the
+// page springs to life the moment the app starts. Engine loss anywhere in
+// the app (api.ts's engineLost) puts the modal back up.
+// Set after a user-initiated connect. Only consulted when the permission
+// state can't be queried (non-Chrome, older Chrome): there it marks the
+// browser ask as already answered, making mount-time probing safe.
const ACK_KEY = "cut-engine-connect-acked";
-type Gate = "checking" | "connect" | "connecting" | "blocked" | "pass";
+type Gate = "checking" | "install" | "connecting" | "blocked" | "pass";
+
+/** Dev-only preview of a gate state, since localhost normally passes straight
+ * through: ?gate=ask (connect ask) | install (get-the-app variant) |
+ * connecting | blocked. Compiled out of production builds. */
+function forcedGate(): string | null {
+ if (process.env.NODE_ENV === "production") return null;
+ return new URLSearchParams(window.location.search).get("gate");
+}
/** The browser's local-network permission state, null where the permission
* (or the query) doesn't exist — non-Chrome browsers, older Chrome. */
@@ -38,84 +63,167 @@ async function permissionState(): Promise<PermissionState | null> {
export function ConnectGate({ children }: { children: ReactNode }) {
const [gate, setGate] = useState<Gate>("checking");
+ // Whether starting a probe would raise the browser's permission prompt.
+ // True blocks all automatic probing and turns the modal into the connect
+ // ask.
+ const [needsAsk, setNeedsAsk] = useState(false);
+
+ const pass = useCallback(() => {
+ engineGateOpen();
+ setGate("pass");
+ }, []);
const check = useCallback(async () => {
+ const forced = forcedGate();
+ if (forced) {
+ setNeedsAsk(forced === "ask" || forced === "connecting");
+ return setGate(forced === "ask" ? "install" : (forced as Gate));
+ }
const perm = await permissionState();
- if (servedFromEngine() || perm === "granted") return setGate("pass");
if (perm === "denied") return setGate("blocked");
- if (localStorage.getItem(ACK_KEY) === "1") return setGate("pass");
- setGate("connect");
- }, []);
+ const quiet =
+ servedFromEngine() ||
+ perm === "granted" ||
+ (perm === null && localStorage.getItem(ACK_KEY) === "1");
+ setNeedsAsk(!quiet);
+ if (!quiet) return setGate("install");
+ try {
+ await engineProbe();
+ pass();
+ } catch {
+ setGate("install");
+ }
+ }, [pass]);
useEffect(() => {
void check();
}, [check]);
+ // While waiting with a prompt-free path to loopback, keep probing so the
+ // page connects the moment the app starts.
+ useEffect(() => {
+ if (gate !== "install" || needsAsk || forcedGate()) return;
+ const t = setInterval(() => {
+ engineProbe().then(pass, () => {});
+ }, 3000);
+ return () => clearInterval(t);
+ }, [gate, needsAsk, pass]);
+
+ // The engine stopped answering mid-session: put the modal back up (its
+ // polling then restores the app when the engine does).
+ useEffect(() => {
+ const onLost = () => setGate((g) => (g === "pass" ? "install" : g));
+ window.addEventListener(ENGINE_LOST_EVENT, onLost);
+ return () => window.removeEventListener(ENGINE_LOST_EVENT, onLost);
+ }, []);
+
const connect = async () => {
setGate("connecting");
localStorage.setItem(ACK_KEY, "1");
- await engineConnect();
- // Any answer resolves the probe; only an explicit Block needs its own
- // screen. Everything else falls through to the app, which shows its own
- // get-Donkey state when no engine answered.
- setGate((await permissionState()) === "denied" ? "blocked" : "pass");
+ if (await engineConnect()) return pass();
+ // No engine answered, but the browser ask may still have been decided.
+ const perm = await permissionState();
+ if (perm === "denied") return setGate("blocked");
+ setNeedsAsk(perm === "prompt");
+ setGate("install");
};
- if (gate === "pass") return <>{children}</>;
-
- if (gate === "checking")
- return (
- <div className="grid min-h-screen place-items-center text-muted-foreground">
- <Loader2 className="size-5 animate-spin" />
- </div>
- );
-
- if (gate === "blocked")
- return (
- <div className="flex min-h-screen flex-col items-center px-6 pt-24 pb-12">
- <div className="flex w-full max-w-2xl flex-col items-center gap-4 text-center">
- <div className="grid size-14 place-items-center rounded-2xl bg-muted">
- <ShieldX className="size-7 text-muted-foreground" />
- </div>
- <h1 className="text-lg font-semibold tracking-tight">Connection blocked</h1>
- <p className="text-sm text-muted-foreground">
- Your browser is blocking this page from reaching the Donkey app on
- this Mac. Open the site settings from the icon next to the address
- bar, turn on{" "}
- <span className="font-medium text-foreground">Apps on device</span>,
- then try again.
- </p>
- <Image
- alt="Chrome's site settings open over the address bar, with the Apps on device toggle"
- className="w-full max-w-sm rounded-xl border shadow-sm"
- height={660}
- src="/cut/connect-site-settings.png"
- unoptimized
- width={970}
- />
- <Button onClick={() => void check()}>Try again</Button>
- </div>
- </div>
- );
-
+ const gated = gate !== "pass";
const connecting = gate === "connecting";
+
return (
- <div className="grid min-h-screen place-items-center">
- <div className="flex max-w-sm flex-col items-center gap-4 text-center">
- <div className="grid size-14 place-items-center rounded-2xl bg-muted">
- <Plug className="size-7 text-muted-foreground" />
+ <>
+ <div inert={gated || undefined}>{children}</div>
+ {gated && (
+ <div className="fixed inset-0 z-50 grid place-items-center overflow-y-auto bg-black/25 p-6 backdrop-blur-md">
+ {gate === "checking" ? (
+ <Loader2 className="size-5 animate-spin text-white/80" />
+ ) : gate === "blocked" ? (
+ <div className="flex w-full max-w-xl flex-col items-center gap-4 rounded-2xl border bg-background p-8 text-center shadow-2xl">
+ <div className="grid size-14 place-items-center rounded-2xl bg-muted">
+ <ShieldX className="size-7 text-muted-foreground" />
+ </div>
+ <h1 className="text-lg font-semibold tracking-tight">Connection blocked</h1>
+ <p className="self-start text-left text-sm text-muted-foreground">
+ Your browser is blocking this page from reaching the Donkey
+ app on this Mac. Open the site settings from the icon next to
+ the address bar, turn on{" "}
+ <span className="font-medium text-foreground">Apps on device</span>,
+ then try again.
+ </p>
+ <Image
+ alt="Chrome's site settings open over the address bar, with the Apps on device toggle"
+ className="w-full max-w-sm rounded-xl border shadow-sm"
+ height={660}
+ src="/cut/connect-site-settings.png"
+ unoptimized
+ width={970}
+ />
+ <Button onClick={() => void check()}>Try again</Button>
+ </div>
+ ) : (
+ <div className="flex w-full max-w-xl flex-col items-center gap-4 rounded-2xl border bg-background p-8 text-center shadow-2xl">
+ <div className="grid size-14 place-items-center rounded-2xl bg-muted">
+ <Plug className="size-7 text-muted-foreground" />
+ </div>
+ <h1 className="text-lg font-semibold tracking-tight">
+ {needsAsk ? "Connect to the Donkey app" : "Donkey Cut works with the Donkey Mac app"}
+ </h1>
+ <p className="self-start text-left text-sm text-muted-foreground">
+ {needsAsk ? (
+ <>
+ Donkey Cut runs locally in the Donkey app on this Mac.
+ Your browser will ask for permission to connect to apps on
+ this device — choose{" "}
+ <span className="font-medium text-foreground">Allow</span>.
+ </>
+ ) : (
+ <>
+ Everything runs locally on your Mac. Install Donkey, or
+ open it if it&rsquo;s already installed — this page
+ connects automatically.
+ </>
+ )}
+ </p>
+ {needsAsk ? (
+ <Button onClick={() => void connect()} disabled={connecting}>
+ {connecting && (
+ <Loader2 className="animate-spin" data-icon="inline-start" />
+ )}
+ {connecting ? "Connecting…" : "Connect"}
+ </Button>
+ ) : (
+ <div className="flex items-center gap-2">
+ <Button
+ onClick={() => {
+ window.location.href = DONKEY_DOWNLOAD_URL;
+ }}
+ >
+ Download for Mac
+ </Button>
+ <Button variant="ghost" onClick={() => void connect()} disabled={connecting}>
+ {connecting && (
+ <Loader2 className="animate-spin" data-icon="inline-start" />
+ )}
+ {connecting ? "Connecting…" : "Try again"}
+ </Button>
+ </div>
+ )}
+ {needsAsk && (
+ <p className="self-start text-left text-xs text-muted-foreground">
+ Don&rsquo;t have the Donkey app yet?{" "}
+ <a
+ className="font-medium text-foreground underline underline-offset-2"
+ href={DONKEY_DOWNLOAD_URL}
+ >
+ Install it for Mac
+ </a>
+ </p>
+ )}
+ </div>
+ )}
</div>
- <h1 className="text-lg font-semibold tracking-tight">Connect to the Donkey app</h1>
- <p className="text-sm text-muted-foreground">
- Donkey Cut runs locally — your projects live in the Donkey app on
- this Mac. Your browser will ask for permission to connect to apps on
- this device; choose <span className="font-medium text-foreground">Allow</span>.
- </p>
- <Button onClick={() => void connect()} disabled={connecting}>
- {connecting && <Loader2 className="animate-spin" data-icon="inline-start" />}
- {connecting ? "Choose Allow when your browser asks" : "Connect"}
- </Button>
- </div>
- </div>
+ )}
+ </>
);
}
diff --git a/site/src/cut/components/ProjectsHome.tsx b/site/src/cut/components/ProjectsHome.tsx
index 7d7de25d..6776888c 100644
--- a/site/src/cut/components/ProjectsHome.tsx
+++ b/site/src/cut/components/ProjectsHome.tsx
@@ -15,7 +15,6 @@ import {
Pencil,
Plus,
Trash2,
- Unplug,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { LiveElapsed } from "@/cut/components/Elapsed";
@@ -44,8 +43,7 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
-import { apiFetch, apiUrl } from "@/cut/lib/api";
-import { DONKEYCUT_CANONICAL } from "@/cut/lib/hosts";
+import { apiFetch, apiUrl, engineLost } from "@/cut/lib/api";
import { createProjectFromFile, isMediaFile } from "@/cut/lib/media";
import { homeHref, projectHref, useCutBase } from "@/cut/lib/nav";
import { formatTime } from "@/cut/lib/time";
@@ -89,7 +87,6 @@ export function ProjectsHome() {
const [deleting, setDeleting] = useState<ProjectSummary | null>(null);
const [name, setName] = useState("");
const [busy, setBusy] = useState(false);
- const [engineDown, setEngineDown] = useState(false);
// A count of desktop files still uploading into fresh projects, plus whether an
// OS-file drag is hovering the surface (a depth counter tames enter/leave noise
// as the cursor crosses child tiles).
@@ -116,11 +113,10 @@ export function ProjectsHome() {
if (!res.ok) throw new Error(String(res.status));
setProjects((await res.json()) as ProjectSummary[]);
setFolders(fres.ok ? ((await fres.json()) as ProjectFolder[]) : []);
- setEngineDown(false);
} catch {
- // The engine on this Mac isn't reachable — not running, or the page was
- // loaded from the hosted domain before starting it locally.
- setEngineDown(true);
+ // The engine on this Mac stopped answering; the ConnectGate takes the
+ // screen back over until it returns.
+ engineLost();
}
}, []);
@@ -184,14 +180,6 @@ 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 {
@@ -316,13 +304,13 @@ export function ProjectsHome() {
"rounded-3xl outline-2 outline-dashed outline-offset-[-10px] outline-[#0a84ff]/60"
)}
onDragEnter={(e) => {
- if (engineDown || !isFileDrag(e)) return;
+ if (!isFileDrag(e)) return;
e.preventDefault();
dragDepth.current += 1;
setFileOver(true);
}}
onDragOver={(e) => {
- if (engineDown || !isFileDrag(e)) return;
+ if (!isFileDrag(e)) return;
e.preventDefault();
e.dataTransfer.dropEffect = "copy";
}}
@@ -335,7 +323,7 @@ export function ProjectsHome() {
}
}}
onDrop={(e) => {
- if (engineDown || !isFileDrag(e)) return;
+ if (!isFileDrag(e)) return;
e.preventDefault();
dragDepth.current = 0;
setFileOver(false);
@@ -350,7 +338,7 @@ export function ProjectsHome() {
</span>
</div>
)}
- {!engineDown && projects && hasContent && (
+ {projects && hasContent && (
<div className="mb-5 flex items-center justify-between">
{openFolder === null ? (
<h1 className="text-lg font-semibold tracking-tight">Projects</h1>
@@ -400,7 +388,7 @@ export function ProjectsHome() {
</div>
)}
- {!engineDown && projects && openFolder === null && (folders.length > 0 || folderCreating) && (
+ {projects && openFolder === null && (folders.length > 0 || folderCreating) && (
<FolderShelf
folders={folders}
mime={PROJECT_MIME}
@@ -419,39 +407,7 @@ export function ProjectsHome() {
/>
)}
- {engineDown ? (
- <div className="grid min-h-[60vh] place-items-center">
- <div className="flex flex-col items-center gap-4 text-center">
- <div className="grid size-14 place-items-center rounded-2xl bg-muted">
- <Unplug className="size-7 text-muted-foreground" />
- </div>
- <h1 className="text-lg font-semibold tracking-tight">
- Donkey Cut works with the Donkey Mac app
- </h1>
- <p className="text-sm text-muted-foreground">
- Everything runs locally on your Mac.
- <br />
- Install Donkey, or open it if it&rsquo;s already installed, and
- this page connects automatically.
- </p>
- <div className="flex items-center gap-2">
- <Button onClick={() => window.open(`${DONKEYCUT_CANONICAL}/install`, "_blank")}>
- Get Donkey for Mac
- </Button>
- <Button
- variant="ghost"
- onClick={() => {
- setEngineDown(false);
- setProjects(null);
- void refresh();
- }}
- >
- Try again
- </Button>
- </div>
- </div>
- </div>
- ) : projects === null ? (
+ {projects === null ? (
<div className="grid place-items-center py-24 text-muted-foreground">
<Loader2 className="size-5 animate-spin" />
</div>
diff --git a/site/src/cut/lib/api.ts b/site/src/cut/lib/api.ts
index 20f0af0f..ed5049aa 100644
--- a/site/src/cut/lib/api.ts
+++ b/site/src/cut/lib/api.ts
@@ -29,6 +29,38 @@ export const servedFromEngine = () =>
let resolvedOrigin: string | null = null; // "" = same origin
let resolving: Promise<string> | null = null;
+// The ConnectGate renders the app blurred behind its connect modal, so app
+// code mounts — and starts requesting — before the user has agreed to the
+// connection. This latch makes an early loopback touch impossible by
+// construction: engineReady (and with it every apiFetch) waits here until the
+// gate opens, and only the gate's own probes (engineProbe, engineConnect)
+// bypass it.
+let openGate: () => void = () => {};
+let gateOpened = new Promise<void>((resolve) => {
+ openGate = resolve;
+});
+
+/** Called by the ConnectGate once the engine answered; releases every waiting
+ * engineReady/apiFetch. */
+export function engineGateOpen() {
+ openGate();
+}
+
+/** Fired on window when the engine stops answering mid-session; the
+ * ConnectGate listens and puts its connect modal back up. */
+export const ENGINE_LOST_EVENT = "cut-engine-lost";
+
+/** Drop the resolved engine, close the gate latch, and notify the gate. Data
+ * layers call this when engine requests start failing after a successful
+ * connect. */
+export function engineLost() {
+ resolvedOrigin = null;
+ gateOpened = new Promise<void>((resolve) => {
+ openGate = resolve;
+ });
+ window.dispatchEvent(new Event(ENGINE_LOST_EVENT));
+}
+
function candidates(): string[] {
// Manual override for unusual setups, e.g. an engine on a custom port.
const saved = localStorage.getItem("cut-engine-origin");
@@ -49,7 +81,7 @@ async function probe(origin: string, timeoutMs = PROBE_TIMEOUT_MS): Promise<bool
/** The hosted page's first connection to this Mac, run from the connect
* screen's button so the browser's permission prompt lands in context. Probes
* like engineReady but gives the user time to answer the prompt. Resolves
- * false when no engine answered; the app then shows its get-Donkey state. */
+ * false when no engine answered; the gate stays on its install screen. */
export async function engineConnect(): Promise<boolean> {
if (resolvedOrigin !== null) return true;
if (servedFromEngine()) {
@@ -65,10 +97,10 @@ export async function engineConnect(): Promise<boolean> {
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> {
+/** Resolve (and memoize) the engine origin without waiting on the gate latch
+ * — the ConnectGate's own quiet probe. Throws when no engine answers; a
+ * failed attempt is not memoized, so the next call probes again. */
+export function engineProbe(): Promise<string> {
if (resolvedOrigin !== null) return Promise.resolve(resolvedOrigin);
resolving ??= (async () => {
if (typeof window === "undefined" || isLocalHost(window.location.hostname)) {
@@ -88,6 +120,13 @@ export function engineReady(): Promise<string> {
return resolving;
}
+/** Resolve the engine for app code: waits for the ConnectGate to open first,
+ * so nothing outside the gate can be the first to touch loopback. */
+export async function engineReady(): Promise<string> {
+ await gateOpened;
+ return engineProbe();
+}
+
/** 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 {