Skip to content

Open source CapCut alternative.

TypeScript

feat(site): keep what's on this Mac listed with the Donkey app closed

David Le220a5eaa15bd
diff --git a/docs/guides/cut/README.md b/docs/guides/cut/README.md
index 31358ea5..24ffe0fc 100644
--- a/docs/guides/cut/README.md
+++ b/docs/guides/cut/README.md
@@ -24,15 +24,15 @@ browser ── API calls ──▶ Cut engine on 127.0.0.1 (spawned by the Donke
**What loads is cached locally.** Every visit re-reads the same three things: the projects listing, the library, and a project's document. The browser keeps the last answer to each in IndexedDB, scoped to the account and the backend that served it, and paints it on arrival while the real request runs behind it. So returning to a project draws on the next frame instead of after a round trip, and a project you just created opens on a document the client already knows is empty. A snapshot is a head start and the live answer always replaces it; where the two disagree the server wins. The one exception is an edit made on top of a snapshot — that is kept rather than overwritten, saves like any other edit, and a cloud project whose stored copy really has moved on answers that save with the version conflict it already had.
-The client probes the engine's health endpoint (dedicated port first, dev server second) and remembers the winner. Browsers permission-gate a hosted page's calls to the local machine, so the page probes only when that raises no prompt — it is served by the engine, or the permission is already granted — and starts in the cloud otherwise. The engine grants the hosted origin cross-origin access, and only that origin. Nothing walls the app, because cloud editing always works. What the page will not do is fail quietly: a browser that has reached this Mac's engine before and cannot now — the app is closed, or the browser is blocking the connection — gets a banner it cannot dismiss, since its local projects are the ones that will not open, and the banner opens the recovery steps in a dialog with the button that fires the browser's permission prompt. Probing continues behind it, so starting the app clears the banner. Engine updates ride the Donkey app's own auto-updater, so the client never prompts to update.
+The client probes the engine's health endpoint (dedicated port first, dev server second) and remembers the winner. Browsers permission-gate a hosted page's calls to the local machine, so the page probes only when that raises no prompt — it is served by the engine, or the permission is already granted — and starts in the cloud otherwise. The engine grants the hosted origin cross-origin access, and only that origin. Nothing walls the app, because cloud editing always works. Closing the Donkey app does not hide the work made in it either: a browser that has reached this Mac's engine before keeps listing that shelf from the listing it stored, so those projects stay on the home beside the cloud ones, each badged with where it lives. They are read-only while the app is away — no renames, moves, or deletes — and opening one says that it lives on this Mac rather than guessing at a cloud copy that was never there. That is where the warning belongs, so that is the only place it appears: a banner over the thing that will not open, which the user cannot dismiss and which opens the recovery steps in a dialog with the button that fires the browser's permission prompt. Probing continues behind it, so starting the app clears the banner and loads the project. Engine updates ride the Donkey app's own auto-updater, so the client never prompts to update.
## Cloud projects
Cloud projects make Cut usable in any browser on any OS with nothing installed, and they run alongside local ones: every account has both halves, and which one a project uses is decided per project.
-Every client call goes through a backend seam (`site/src/cut/lib/backend/`): the local driver is the engine transport unchanged, and the cloud driver rewrites the same paths to `/api/cut-cloud/*` with the session cookie. Residency is per project and fixed when the project is created, so creating one is where the user chooses. One picker makes that choice, standing beside New project in the sidebar: it names a shelf — this Mac or the cloud — and everything the browser creates lands there, new projects and anything added to the library alike. The choice sticks on that browser until they change it, and every other New project button follows it rather than asking again. With no Donkey app running there is nothing to choose and every new project is a cloud project; inside a folder the folder decides, since a project files only into a folder beside it. The home lists both shelves as one listing, each project badged with where it lives, and opening one binds the editor to that project's backend. Capability flags on the driver hide what a backend can't do, so components never feature-detect.
+Every client call goes through a backend seam (`site/src/cut/lib/backend/`): the local driver is the engine transport unchanged, and the cloud driver rewrites the same paths to `/api/cut-cloud/*` with the session cookie. Residency is per project and fixed when the project is created, so creating one is where the user chooses. One picker makes that choice, standing beside New project in the sidebar: it names a shelf — this Mac or the cloud — and everything the browser creates lands there, new projects and anything added to the library alike. The choice sticks on that browser until they change it, and every other New project button follows it rather than asking again. With no Donkey app running there is nothing to choose and every new project is a cloud project; inside a folder the folder decides, since a project files only into a folder beside it. The home lists both shelves as one listing — the Mac's from its stored listing when the app is closed — each project badged with where it lives, and opening one binds the editor to that project's backend. Capability flags on the driver hide what a backend can't do, so components never feature-detect.
-The library is the exception, because it is a shelf rather than a place: it lists every residency the browser can reach at once — the Mac's when an engine has answered, the cloud's always — as one listing, newest first, with a badge saying which shelf each item is on. So a cloud project can pull a clip off this Mac, and a local project can pull one out of the cloud. Each item's own shelf answers for it: previews, renames, and deletes go to the backend it came from, and folders belong to one shelf, so items file only into folders beside them. Adding to a project is the one crossing: on the project's own shelf the server copies the file without the bytes leaving it, and off it the browser carries them down and back up.
+The library is the exception, because it is a shelf rather than a place: it lists every residency at once — the Mac's and the cloud's — as one listing, newest first, with a badge saying which shelf each item is on. So a cloud project can pull a clip off this Mac, and a local project can pull one out of the cloud. Each half is remembered on its own, so the Library tab keeps listing the Mac's items with the app closed, read-only, and clicking one raises the same banner an unreachable local project does. The editor's library picker asks only for what it can reach, since an item it cannot copy into the project has no business in a picker. Each item's own shelf answers for it: previews, renames, and deletes go to the backend it came from, and folders belong to one shelf, so items file only into folders beside them. Adding to a project is the one crossing: on the project's own shelf the server copies the file without the bytes leaving it, and off it the browser carries them down and back up.
Cloud projects store their doc in Postgres (versioned; a stale autosave 409s and the editor reloads the newer copy) and media in R2: uploads go direct from the browser on presigned URLs (the hosted functions never see the bytes), playback streams on signed range URLs, and a flat per-user quota is enforced at presign time. That quota is visible rather than implicit: a free account editing a cloud project sees what it has used in the editor's top bar, and a presign rejected for space opens an upgrade offer wherever it happened instead of a bare error. The same slot carries the countdown when a subscription is set to cancel, and clicking it opens the billing portal.
diff --git a/site/src/cut/components/ConnectGate.tsx b/site/src/cut/components/ConnectGate.tsx
index e825fa7f..48e8b2bd 100644
--- a/site/src/cut/components/ConnectGate.tsx
+++ b/site/src/cut/components/ConnectGate.tsx
@@ -23,6 +23,9 @@ import {
servedFromEngine,
} from "@/cut/lib/api";
import { announceLocalCompute, setCutMode } from "@/cut/lib/backend";
+import { useCutMode } from "@/cut/lib/backend/hooks";
+import { setNeedsApp, useNeedsApp } from "@/cut/lib/needsApp";
+import { engineSeen, markEngineSeen } from "@/cut/lib/residency";
// Which backend the app starts on, decided once per load. Chrome gates a
// public https page's first fetch to 127.0.0.1 behind its Local Network Access
@@ -33,21 +36,20 @@ import { announceLocalCompute, setCutMode } from "@/cut/lib/backend";
// loopback until a probe succeeds, so the prompt can never ambush a login.
//
// Nothing here blocks the app. Cloud editing always works, so a Mac with no
-// engine reachable is a working editor, not a wall. What it is not is silent:
-// a browser that has reached this Mac's engine before and can't now gets a
-// banner it can't dismiss — its local projects are the ones that won't open —
-// and the banner opens the recovery instructions in a dialog. The gate keeps
-// probing behind the banner, so starting the Donkey app clears it. Engine
-// loss mid-session (api.ts's engineLost) lands in the same state.
+// engine reachable is a working editor, not a wall. The banner is not a
+// warning about the app being closed, then — it belongs to the projects that
+// need it. The projects home keeps listing the Mac's shelf from what it last
+// saw there, and the banner rises when one of those projects is open: that is
+// the moment something is actually blocked, and the banner opens the recovery
+// steps in a dialog. The gate keeps probing behind it, so starting the Donkey
+// app clears the banner and the project loads. Engine loss mid-session
+// (api.ts's engineLost) lands in the same state.
const ACK_KEY = "cut-engine-connect-acked";
-// Set the first time an engine answers in this browser. It separates a Mac
-// user whose app is missing from a browser that never had one, which is the
-// difference between a banner worth showing and noise.
-const SEEN_KEY = "cut-engine-seen";
/** Dev-only preview of the banner and its dialog, since localhost always
- * reaches its engine: ?gate=ask (connect ask) | install (get-the-app variant)
- * | blocked. Compiled out of production builds. */
+ * reaches its engine — open a local project with it, since that is where the
+ * banner shows: ?gate=ask (connect ask) | install (get-the-app variant) |
+ * 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");
@@ -70,6 +72,11 @@ export function ConnectGate({ children }: { children: ReactNode }) {
// Settings pages (billing, usage, feature flags) never touch the engine, so
// they skip the probe and the banner.
const onSettings = (usePathname() ?? "").split("/").includes("settings");
+ // What the user reached for: an editor pins the open project's residency,
+ // and any other surface raises the flag when it hands back something that
+ // needs the app. Either one is what the banner is about.
+ const mode = useCutMode();
+ const needsApp = useNeedsApp();
// Whether the engine on this Mac is reachable right now.
const [reached, setReached] = useState<boolean | null>(null);
// This browser has used the engine before, so an unreachable one is news.
@@ -84,9 +91,11 @@ export function ConnectGate({ children }: { children: ReactNode }) {
const [howOpen, setHowOpen] = useState(false);
const bindEngine = useCallback(() => {
- localStorage.setItem(SEEN_KEY, "1");
+ markEngineSeen();
setSeen(true);
setBlocked(false);
+ // Whatever was reached for is reachable again.
+ setNeedsApp(false);
setCutMode("local");
engineGateOpen();
announceLocalCompute();
@@ -108,7 +117,7 @@ export function ConnectGate({ children }: { children: ReactNode }) {
return bindCloud();
}
const perm = await permissionState();
- setSeen(localStorage.getItem(SEEN_KEY) === "1");
+ setSeen(engineSeen());
setBlocked(perm === "denied");
const quiet =
servedFromEngine() ||
@@ -169,9 +178,13 @@ export function ConnectGate({ children }: { children: ReactNode }) {
setNeedsAsk(perm === "prompt");
};
- // The banner reports a fact about this browser, so it stays up until the
- // engine answers; the instructions behind it are a dialog the user closes.
- const banner = reached === false && seen && !onSettings;
+ // The banner belongs to what the user reached for, not to the browser: it
+ // rises when that thing lives on this Mac and the app isn't answering, and
+ // stays up until it is. An open project says so by pinning its residency; a
+ // click on a recalled library item raises the flag. Both listings stay on
+ // screen either way, so nothing is hidden by keeping the banner off them.
+ // The instructions behind it are a dialog the user closes.
+ const banner = reached === false && seen && (mode === "local" || needsApp) && !onSettings;
// The banner takes its 32px out of the viewport rather than pushing the app
// past it: the surfaces below fill this column's remaining height (h-full),
@@ -181,10 +194,10 @@ export function ConnectGate({ children }: { children: ReactNode }) {
{banner && (
<div className="flex h-8 shrink-0 items-center justify-center gap-3 bg-red-600 px-4 text-xs font-medium text-white">
<span className="min-w-0 truncate">
+ This project is stored on this Mac, and{" "}
{blocked
- ? "Your browser is blocking this page from reaching the Donkey app on this Mac."
- : "Donkey Cut can’t reach the Donkey app on this Mac."}{" "}
- Projects stored on this Mac won’t open.
+ ? "your browser is blocking this page from reaching the Donkey app."
+ : "Donkey Cut can’t reach the Donkey app."}
</span>
<button
className="shrink-0 underline underline-offset-2"
@@ -204,29 +217,31 @@ export function ConnectGate({ children }: { children: ReactNode }) {
? "Connection blocked"
: needsAsk
? "Connect to the Donkey app"
- : "Donkey Cut works with the Donkey Mac app"}
+ : "This project is stored on this Mac"}
</DialogTitle>
</DialogHeader>
<p className="text-sm text-muted-foreground">
{blocked ? (
<>
- 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{" "}
+ This is a local project — its video and its edits live on this
+ Mac, and your browser is blocking this page from reaching the
+ Donkey app that opens them. 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.
</>
) : 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{" "}
+ This is a local project — it lives 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
+ This is a local project: its video and its edits live on this
+ Mac, and the Donkey app is what opens them. Install Donkey, or
+ open it if it&rsquo;s already installed — this page connects
automatically.
</>
)}
@@ -241,18 +256,6 @@ export function ConnectGate({ children }: { children: ReactNode }) {
width={970}
/>
)}
- {!blocked && !needsAsk && (
- <p className="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}
- onClick={() => track("app_install_clicked", { source: "connect_gate_link" })}
- >
- Install it for Mac
- </a>
- </p>
- )}
<DialogFooter className="mt-2">
{!blocked && !needsAsk && (
<Button
diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsx
index aab9edcd..2650440b 100644
--- a/site/src/cut/components/Editor.tsx
+++ b/site/src/cut/components/Editor.tsx
@@ -2,9 +2,15 @@
import { useCallback, useEffect, useRef, useState } from "react";
import Link from "next/link";
-import { Clapperboard, Loader2, X } from "lucide-react";
+import { Clapperboard, Laptop, Loader2, X } from "lucide-react";
import { Button } from "@/components/ui/button";
-import { apiFetch, bindCutMode, releaseCutMode } from "@/cut/lib/backend";
+import {
+ apiFetch,
+ bindCutMode,
+ hasLocalCompute,
+ releaseCutMode,
+ subscribeCutMode,
+} from "@/cut/lib/backend";
import { loadedDocVersion } from "@/cut/lib/backend/shared";
import { writeCachedDoc } from "@/cut/lib/docCache";
import {
@@ -21,7 +27,7 @@ import { enrichAsset, importFileToProject, prepareImport } from "@/cut/lib/media
import "@/cut/lib/genScene";
import { installDevHooks } from "@/cut/lib/devHooks";
import { backTarget, useCutBase } from "@/cut/lib/nav";
-import { resolveProjectMode } from "@/cut/lib/residency";
+import { resolveProjectPlacement } from "@/cut/lib/residency";
import {
docAudioClips,
docClips,
@@ -90,6 +96,9 @@ export function Editor({
const sending = useEditor((s) => s.assets.reduce((n, a) => (a.upload ? 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. Nothing
+ // to load, and nothing to guess at either: say where it is and wait.
+ const [needsApp, setNeedsApp] = useState(false);
const dragDepth = useRef(0);
// Load the project document, then enrich assets (thumbs/waveforms) lazily.
@@ -97,29 +106,55 @@ export function Editor({
// lives (residency.ts) and pin the backend before anything else fetches.
// Pinning, rather than setting the ambient mode, is what makes this stick —
// the ConnectGate's engine probe finishes on its own schedule and would
- // otherwise flip an open cloud project onto the engine.
+ // otherwise flip an open cloud project onto the engine. It is also what
+ // raises the gate's banner over a local project the app isn't answering for:
+ // the banner follows the open project's residency.
// A share view skips that — its page pinned the shared backend already.
useEffect(() => {
let alive = true;
- const bind = viewer
- ? Promise.resolve()
- : resolveProjectMode(projectId).then((mode) => {
- if (alive) bindCutMode(mode);
- });
- void bind.then(() => {
- if (!alive) return;
- void useEditor
- .getState()
- .loadProject(projectId)
- .then(() => {
- for (const asset of useEditor.getState().assets) void enrichAsset(asset);
+ let waiting: (() => void) | undefined;
+
+ const open = () => {
+ const bind = viewer
+ ? Promise.resolve({ mode: "shared" as const, reachable: true })
+ : resolveProjectPlacement(projectId).then((placement) => {
+ if (alive) bindCutMode(placement.mode);
+ return placement;
+ });
+ void bind.then((placement) => {
+ if (!alive) return;
+ setNeedsApp(!placement.reachable);
+ if (placement.reachable) {
+ void useEditor
+ .getState()
+ .loadProject(projectId)
+ .then(() => {
+ for (const asset of useEditor.getState().assets) void enrichAsset(asset);
+ });
+ return;
+ }
+ // The project is on this Mac with no app answering. The gate keeps
+ // probing behind its banner, so wait for that rather than retrying:
+ // the moment the app is back, this opens the project as if the user
+ // had just clicked it. Waiting on the engine here — rather than
+ // re-running on it — is what keeps an open cloud project from being
+ // re-resolved out from under its own pinned backend.
+ waiting = subscribeCutMode(() => {
+ if (!alive || !hasLocalCompute()) return;
+ waiting?.();
+ waiting = undefined;
+ open();
});
- });
+ });
+ };
+ open();
+
// An export still rendering after a reload rejoins on its own: the app-wide
// exports dock polls the engine's job feed, so it reappears with no per-
// project reconnect here.
return () => {
alive = false;
+ waiting?.();
releaseCutMode();
};
}, [projectId, viewer]);
@@ -633,6 +668,28 @@ export function Editor({
return () => window.removeEventListener("keydown", onKey);
}, []);
+ // The project is here, on this Mac — it just can't be opened without the app
+ // that holds it. The gate's banner sits above this with the recovery steps,
+ // and the moment the app answers this screen loads the project itself.
+ if (needsApp) {
+ return (
+ <div className="grid h-full place-items-center">
+ <div className="flex max-w-sm flex-col items-center gap-3 text-center">
+ <Laptop className="size-7 text-muted-foreground" />
+ <p className="text-sm text-muted-foreground">
+ This is a local project — it lives on this Mac. Open the Donkey app and it opens
+ here.
+ </p>
+ <Button
+ variant="outline"
+ nativeButton={false}
+ render={<Link href={back.href}>Back to {back.tab}</Link>}
+ />
+ </div>
+ </div>
+ );
+ }
+
if (loadError && !stale) {
return (
<div className="grid h-full place-items-center">
diff --git a/site/src/cut/components/LibraryView.tsx b/site/src/cut/components/LibraryView.tsx
index 24bfd6e3..2c4b9375 100644
--- a/site/src/cut/components/LibraryView.tsx
+++ b/site/src/cut/components/LibraryView.tsx
@@ -1,15 +1,18 @@
"use client";
-import { useCallback, useRef, useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { useRouter, useSearchParams } from "next/navigation";
import {
Cloud,
+ Film,
FolderOpen,
FolderPlus,
+ Image as ImageIcon,
Laptop,
Link as LinkIcon,
Loader2,
+ Music,
Plus,
Trash2,
Upload,
@@ -53,6 +56,8 @@ import {
type LibraryData,
} from "@/cut/lib/library";
import { useNewProjectTarget } from "@/cut/lib/newProject";
+import { useListedResidencies, useLocalCompute } from "@/cut/lib/backend/hooks";
+import { setNeedsApp } from "@/cut/lib/needsApp";
import { availableResidencies, RESIDENCY_LABEL, type Residency } from "@/cut/lib/residency";
import { TemplateCard } from "./TemplateCard";
import { homeHref, useCutBase } from "@/cut/lib/nav";
@@ -68,17 +73,23 @@ import { buildDragGhost, FolderCrumb, FolderShelf, Marquee } from "./desktopFold
const LIBRARY_MOVE_MIME = "application/x-cut-library-move";
/** Which shelf an item sits on, on its card. The library merges both, so the
- * badge is how you tell a clip on this Mac from one in the cloud. */
+ * badge is how you tell a clip on this Mac from one in the cloud — and, when
+ * the app isn't answering, why that clip is showing but not usable. */
export function ShelfBadge({
residency,
+ offline = false,
className,
}: {
residency: Residency;
+ offline?: boolean;
className?: string;
}) {
const Icon = residency === "cloud" ? Cloud : Laptop;
return (
- <span title={RESIDENCY_LABEL[residency]} className={className}>
+ <span
+ title={offline ? "On this Mac — open the Donkey app to use it" : RESIDENCY_LABEL[residency]}
+ className={className}
+ >
<Icon className="size-3" />
</span>
);
@@ -89,8 +100,18 @@ export function LibraryView() {
const base = useCutBase();
const client = useQueryClient();
// The listing is cached (lib/queries.ts): coming back to the library paints
- // the shelf it painted last time and revalidates behind it.
+ // the shelf it painted last time and revalidates behind it. With the Donkey
+ // app closed that cache is the Mac's half outright — those files are still
+ // on that disk, so they still list, badged and read-only until the app is
+ // back. Clicking one raises the gate's banner, which is where the way out
+ // of that state lives.
const library = useLibrary();
+ const listed = useListedResidencies();
+ const engineUp = useLocalCompute();
+ const live = useCallback((r: Residency) => r === "cloud" || engineUp, [engineUp]);
+ // Drop the flag when this view goes away: the banner belongs to the surface
+ // that raised it.
+ useEffect(() => () => setNeedsApp(false), []);
// New projects and new library items answer the same question — which shelf
// is this browser putting things on — so they read the one choice the user
// already made, rather than the backend the app happens to be bound to.
@@ -121,29 +142,39 @@ export function LibraryView() {
const dragDepth = useRef(0);
// Every mutation goes to the shelf its item sits on; only new items need a
- // destination, and that is the folder they land in, or the bound backend.
+ // destination, and that is the folder they land in, or the bound backend. A
+ // shelf that isn't answering takes none of them, so each one checks first.
const shelfOf = (id: string): Residency | null =>
all.find((a) => a.id === id)?.residency ??
templates.find((t) => t.id === id)?.residency ??
null;
- const shelfForNew = (folderId: string | null) =>
- (folderId ? folders.find((f) => f.id === folderId)?.residency : null) ?? target;
+ // Where a new item lands, and the folder it can land in: a folder on a shelf
+ // that isn't answering can't take one, so the item goes to the root of the
+ // shelf new items go to.
+ const landing = (folderId: string | null) => {
+ const owner = folderId ? folders.find((f) => f.id === folderId)?.residency : null;
+ const residency = owner && live(owner) ? owner : target;
+ return { residency, folderId: owner === residency ? folderId : null };
+ };
const renameTpl = async (r: Residency, id: string, name: string) => {
+ if (!live(r)) return;
patch((d) => ({ ...d, templates: d.templates.map((t) => (t.id === id ? { ...t, name } : t)) }));
await renameTemplate(r, id, name).catch(() => void reload());
};
const removeTpl = async (r: Residency, id: string) => {
+ if (!live(r)) return;
patch((d) => ({ ...d, templates: d.templates.filter((t) => t.id !== id) }));
await deleteTemplate(r, id).catch(() => void reload());
};
// Upload a batch into `folderId` (the open folder by default — folder tiles
// pass their own id when files are dropped straight onto them).
- const upload = async (files: FileList | File[], folderId: string | null = openFolder) => {
+ const upload = async (files: FileList | File[], into: string | null = openFolder) => {
const list = Array.from(files).filter(isMediaFile);
- const residency = shelfForNew(folderId);
+ const { residency, folderId } = landing(into);
+ if (!live(residency)) return;
setUploading((n) => n + list.length);
for (const file of list) {
try {
@@ -164,15 +195,16 @@ export function LibraryView() {
const importUrl = async () => {
const value = url.trim();
if (!value || importing) return;
+ const { residency, folderId } = landing(openFolder);
+ if (!live(residency)) return;
setImporting(true);
setUrlError(null);
- const residency = shelfForNew(openFolder);
try {
const imported = await importUrlToLibrary(value, residency);
- if (openFolder) {
+ if (folderId) {
for (const asset of imported) {
- await moveLibraryItem(residency, asset.id, openFolder).catch(() => {});
- asset.folderId = openFolder;
+ await moveLibraryItem(residency, asset.id, folderId).catch(() => {});
+ asset.folderId = folderId;
}
}
patch((d) => ({ ...d, assets: [...imported, ...d.assets] }));
@@ -189,6 +221,7 @@ export function LibraryView() {
if (!deleting) return;
const { id, residency } = deleting;
setDeleting(null);
+ if (!live(residency)) return;
patch((d) => ({ ...d, assets: d.assets.filter((a) => a.id !== id) }));
try {
await deleteFromLibrary(residency, id);
@@ -211,6 +244,7 @@ export function LibraryView() {
const moving = ids
.map((id) => ({ id, residency: shelfOf(id) }))
.filter((x): x is { id: string; residency: Residency } => !!x.residency)
+ .filter((x) => live(x.residency))
.filter((x) => !target || x.residency === target);
if (moving.length === 0) return;
const idset = new Set(moving.map((x) => x.id));
@@ -243,7 +277,7 @@ export function LibraryView() {
}
};
- const bothShelves = availableResidencies().length > 1;
+ const bothShelves = listed.length > 1;
const shown = all.filter((a) => (a.folderId ?? null) === openFolder);
const shownTemplates = templates.filter((t) => (t.folderId ?? null) === openFolder);
const openFolderName = folders.find((f) => f.id === openFolder)?.name;
@@ -340,16 +374,17 @@ export function LibraryView() {
})}
badgeOf={(id) => {
const r = folders.find((f) => f.id === id)?.residency;
- return bothShelves && r ? <ShelfBadge residency={r} /> : null;
+ return bothShelves && r ? <ShelfBadge residency={r} offline={!live(r)} /> : null;
}}
onOpen={gotoFolder}
onCreate={async (name) => {
+ if (!live(target)) return;
const f = await createLibraryFolder(name, target);
patch((d) => ({ ...d, folders: [...d.folders, f] }));
}}
onRename={async (id, name) => {
const r = folders.find((f) => f.id === id)?.residency;
- if (!r) return;
+ if (!r || !live(r)) return;
patch((d) => ({
...d,
folders: d.folders.map((f) => (f.id === id ? { ...f, name } : f)),
@@ -358,7 +393,7 @@ export function LibraryView() {
}}
onDelete={async (id) => {
const r = folders.find((f) => f.id === id)?.residency;
- if (!r) return;
+ if (!r || !live(r)) return;
patch((d) => ({
folders: d.folders.filter((f) => f.id !== id),
assets: d.assets.map((a) => (a.folderId === id ? { ...a, folderId: null } : a)),
@@ -381,13 +416,17 @@ export function LibraryView() {
key={t.id}
template={t}
mediaSrc={(f) => libraryMediaUrl(f, t.residency)}
- drag={{ scope: "library", template: t }}
+ drag={live(t.residency) ? { scope: "library", template: t } : undefined}
onDragStartExtra={(e) => {
e.dataTransfer.setData(LIBRARY_MOVE_MIME, JSON.stringify([t.id]));
e.dataTransfer.effectAllowed = "copyMove";
}}
- onRename={(name) => void renameTpl(t.residency, t.id, name)}
- onDelete={() => void removeTpl(t.residency, t.id)}
+ onRename={
+ live(t.residency) ? (name) => void renameTpl(t.residency, t.id, name) : undefined
+ }
+ onDelete={
+ live(t.residency) ? () => void removeTpl(t.residency, t.id) : undefined
+ }
/>
))}
</div>
@@ -426,7 +465,12 @@ export function LibraryView() {
key={a.id}
asset={a}
selected={selected.has(a.id)}
- onDelete={() => setDeleting(a)}
+ offline={!live(a.residency)}
+ // Clicking an item this browser can only remember is the moment
+ // something is actually blocked, so that is when the gate's
+ // banner — and the way out of it — comes up.
+ onClick={live(a.residency) ? undefined : () => setNeedsApp(true)}
+ onDelete={live(a.residency) ? () => setDeleting(a) : undefined}
onDragStartExtra={(e) => onCardDragExtra(e, a)}
/>
))}
@@ -518,21 +562,26 @@ export function LibraryView() {
export function LibraryCard({
asset: a,
selected,
+ offline = false,
+ onClick,
onDelete,
onUse,
onDragStartExtra,
}: {
asset: LibraryAsset;
selected?: boolean;
+ /** The shelf this item is on isn't answering: it lists from memory, so the
+ * card shows what it knows and reaches for no media it can't load. */
+ offline?: boolean;
+ onClick?: () => void;
onDelete?: () => void;
onUse?: () => void;
onDragStartExtra?: (e: React.DragEvent) => void;
}) {
const videoRef = useRef<HTMLVideoElement>(null);
const { flash, attachReveal } = useRevealFlash("library", a.id);
- // With one shelf reachable, every card is on it — the badge would say
- // nothing.
- const bothShelves = availableResidencies().length > 1;
+ // With one shelf listed, every card is on it — the badge would say nothing.
+ const bothShelves = availableResidencies().length > 1 || offline;
// Each card is a real media element, so the source waits until the tile has
// been scrolled near: a large library would otherwise pull every file's
// metadata across the network the moment the page opened.
@@ -547,7 +596,8 @@ export function LibraryCard({
ref={attachReveal}
data-sel-id={a.id}
className="group flex flex-col"
- draggable
+ draggable={!offline}
+ onClick={onClick}
onDragStart={(e) => {
setLibraryDragData(e, a);
onDragStartExtra?.(e);
@@ -569,7 +619,19 @@ export function LibraryCard({
selected || flash ? "border-[#0a84ff] ring-2 ring-[#0a84ff]" : "border-border"
)}
>
- {a.type === "video" ? (
+ {offline ? (
+ // Nothing to load from a shelf that isn't answering, so the card
+ // shows what it knows: the kind of file, its name, its length.
+ <span className="grid size-full place-items-center">
+ {a.type === "audio" ? (
+ <Music className="size-6 text-muted-foreground/50" />
+ ) : a.type === "image" ? (
+ <ImageIcon className="size-6 text-muted-foreground/50" />
+ ) : (
+ <Film className="size-6 text-muted-foreground/50" />
+ )}
+ </span>
+ ) : a.type === "video" ? (
seen && (
<video
crossOrigin={MEDIA_CORS}
@@ -618,8 +680,10 @@ export function LibraryCard({
{bothShelves && (
<ShelfBadge
residency={a.residency}
+ offline={offline}
className={cn(
- "absolute top-2 right-2 text-white/85 transition-opacity",
+ "absolute top-2 right-2 transition-opacity",
+ offline ? "text-muted-foreground" : "text-white/85",
// The delete button takes this corner on hover.
onDelete && "group-hover:opacity-0"
)}
diff --git a/site/src/cut/components/ProjectsHome.tsx b/site/src/cut/components/ProjectsHome.tsx
index a96c42ba..132856cc 100644
--- a/site/src/cut/components/ProjectsHome.tsx
+++ b/site/src/cut/components/ProjectsHome.tsx
@@ -55,7 +55,12 @@ import {
import { MEDIA_CORS } from "@/cut/lib/mediaCors";
import { capturePosterWhenReady, readPoster } from "@/cut/lib/posterCache";
import { quotaErrorMessage } from "@/cut/lib/backend/cloud";
-import { useCloudUsage, useCutMode } from "@/cut/lib/backend/hooks";
+import {
+ useCloudUsage,
+ useCutMode,
+ useListedResidencies,
+ useLocalCompute,
+} from "@/cut/lib/backend/hooks";
import { dropCachedDoc, seedNewProjectDoc } from "@/cut/lib/docCache";
import {
backendFor,
@@ -83,10 +88,18 @@ import { buildDragGhost, FolderCrumb, FolderShelf, formatBytes, Marquee } from "
type View = "gallery" | "list";
-// The home lists each residency it can reach, talking to the backend objects
+// The home lists every residency the user has, talking to the backend objects
// directly — the global mode is only bound when a project opens into the
// editor. Each section's listing is cached (lib/queries.ts), so returning here
// paints the shelf immediately and revalidates behind it.
+//
+// That cache is also what keeps the Mac's shelf on screen with the Donkey app
+// closed: local projects still exist, so they still list, and the card says
+// where each one lives. What they don't do is change — a shelf whose engine
+// isn't answering takes no renames, moves, or deletes, so the cards carry no
+// menu and every mutation checks first. Opening one is allowed, and lands on
+// the editor's "this project is on this Mac" screen with the gate's banner
+// above it.
type SectionData = {
projects: ProjectSummary[] | null;
@@ -113,13 +126,24 @@ function formatDate(ts: number) {
}
// The badge marks where one project lives, so it says that outright rather
-// than repeating the shelf heading it sits under.
+// than repeating the shelf heading it sits under. A local project the Donkey
+// app isn't answering for says that instead: it is the reason its card can't
+// be renamed or moved.
const RESIDENCY_HINT: Record<Residency, string> = {
local: "This is a local project",
cloud: "This is a cloud project",
};
+const OFFLINE_HINT = "This is a local project — open the Donkey app to edit it";
-function ResidencyBadge({ residency, className }: { residency: Residency; className?: string }) {
+function ResidencyBadge({
+ residency,
+ offline = false,
+ className,
+}: {
+ residency: Residency;
+ offline?: boolean;
+ className?: string;
+}) {
const Icon = residency === "cloud" ? Cloud : Laptop;
return (
<TooltipProvider>
@@ -127,7 +151,7 @@ function ResidencyBadge({ residency, className }: { residency: Residency; classN
<TooltipTrigger render={<span />} className={className}>
<Icon className="size-3" />
</TooltipTrigger>
- <TooltipContent>{RESIDENCY_HINT[residency]}</TooltipContent>
+ <TooltipContent>{offline ? OFFLINE_HINT : RESIDENCY_HINT[residency]}</TooltipContent>
</Tooltip>
</TooltipProvider>
);
@@ -184,18 +208,29 @@ 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";
- // Which backends this home lists, and where its New project button aims.
- // They are the same question: a shelf this browser and account can reach is
- // a shelf a project can be made on.
- const { target, choices: residencies } = useNewProjectTarget();
+ // What this home shows and what a new project can be made on are two
+ // questions now. The Mac's shelf lists whenever this browser has used it,
+ // reachable or not; creating on it needs the Donkey app answering.
+ const residencies = useListedResidencies();
+ const { target } = useNewProjectTarget();
const dual = residencies.length > 1;
const r0 = residencies[0];
+ // Whether a shelf takes writes right now. The cloud always does; the Mac's
+ // does while its engine answers.
+ const engineUp = useLocalCompute();
+ const live = useCallback((r: Residency) => r === "cloud" || engineUp, [engineUp]);
const client = useQueryClient();
// Hooks can't run in a loop, so both sections are always wired and the
// inactive one simply stays disabled.
- const localSection = useProjectsSection("local", residencies.includes("local"));
- const cloudSection = useProjectsSection("cloud", residencies.includes("cloud"));
+ const localSection = useProjectsSection("local", {
+ list: residencies.includes("local"),
+ live: engineUp,
+ });
+ const cloudSection = useProjectsSection("cloud", {
+ list: residencies.includes("cloud"),
+ live: true,
+ });
const asSection = (q: typeof localSection): SectionData => ({
projects: q.data?.projects ?? null,
folders: q.data?.folders ?? [],
@@ -252,7 +287,11 @@ export function ProjectsHome() {
localStorage.setItem("cut-projects-view", v);
};
+ // Each mutation below opens with the same guard: a shelf that isn't
+ // answering takes no changes, and an optimistic patch would paint a rename
+ // that never happened and then take it back on reconnect.
const createFolder = async (r: Residency, fname: string) => {
+ if (!live(r)) return;
const res = await backendFor(r).fetch("/api/cut/projects/folders", {
method: "POST",
headers: { "Content-Type": "application/json" },
@@ -266,6 +305,7 @@ export function ProjectsHome() {
};
const renameFolder = async (r: Residency, id: string, fname: string) => {
+ if (!live(r)) return;
patch(r, (s) => ({
...s,
folders: s.folders.map((f) => (f.id === id ? { ...f, name: fname } : f)),
@@ -287,6 +327,7 @@ export function ProjectsHome() {
};
const deleteFolder = async (r: Residency, id: string) => {
+ if (!live(r)) return;
patch(r, (s) => ({
folders: s.folders.filter((f) => f.id !== id),
projects: s.projects.map((p) => (p.folderId === id ? { ...p, folderId: null } : p)),
@@ -301,6 +342,7 @@ export function ProjectsHome() {
// null). Optimistic; reconciles from disk on any failure. A dragged
// selection can span sections, so a backend only ever moves its own.
const moveProjects = async (r: Residency, ids: string[], folderId: string | null) => {
+ if (!live(r)) return;
const own = new Set((data[r].projects ?? []).map((p) => p.id));
const move = ids.filter((id) => own.has(id));
if (move.length === 0) return;
@@ -327,6 +369,7 @@ export function ProjectsHome() {
// the editor opens on its first frame instead of waiting out a round trip
// for a document we can describe in full.
const openNewProject = async (r: Residency, pname: string, folderId: string | null) => {
+ if (!live(r)) return;
const res = await backendFor(r).fetch("/api/cut/projects", {
method: "POST",
headers: { "Content-Type": "application/json" },
@@ -380,6 +423,7 @@ export function ProjectsHome() {
const rename = async () => {
if (!renaming) return;
const { project, residency } = renaming;
+ if (!live(residency)) return setRenaming(null);
const next = name.trim() || project.name;
patch(residency, (s) => ({
...s,
@@ -396,6 +440,7 @@ export function ProjectsHome() {
};
const duplicate = async (r: Residency, p: ProjectSummary) => {
+ if (!live(r)) return;
setBusy(true);
setDupError(null);
try {
@@ -439,6 +484,7 @@ export function ProjectsHome() {
// the original. The copy landing first is what makes deleting it safe.
const moveAcross = async (source: Residency, p: ProjectSummary) => {
const dest: Residency = source === "cloud" ? "local" : "cloud";
+ if (!live(source) || !live(dest)) return;
setDupError(null);
setBusy(true);
try {
@@ -459,8 +505,9 @@ export function ProjectsHome() {
const remove = async () => {
if (!deleting) return;
- setBusy(true);
const { project, residency } = deleting;
+ if (!live(residency)) return setDeleting(null);
+ setBusy(true);
const id = project.id;
try {
await backendFor(residency).fetch(`/api/cut/projects/${id}`, { method: "DELETE" });
@@ -487,6 +534,11 @@ export function ProjectsHome() {
const openFolderName = folderOwner
? data[folderOwner].folders.find((f) => f.id === openFolder)?.name
: undefined;
+ // A folder pins where a new project lands, but only a shelf that answers can
+ // take one: inside a folder on an unreachable shelf, New project goes where
+ // the picker points instead.
+ const pinnedTarget = folderOwner && live(folderOwner) ? folderOwner : null;
+ const newTarget = pinnedTarget ?? target;
const anySettled = residencies.some((r) => data[r].projects !== null || data[r].error);
const anyProjects = residencies.some((r) => (data[r].projects?.length ?? 0) > 0);
@@ -569,7 +621,7 @@ export function ProjectsHome() {
key={p.id}
data-sel-id={p.id}
className="group cursor-pointer"
- draggable
+ draggable={live(r)}
onDragStart={(e) => onProjectDragStart(e, p)}
onClick={(e) => {
if (e.shiftKey || e.metaKey) {
@@ -587,39 +639,42 @@ export function ProjectsHome() {
selected.has(p.id) ? "border-[#0a84ff] ring-2 ring-[#0a84ff]" : "border-border"
)}
>
- <CardPreview project={p} residency={r} />
+ <CardPreview project={p} residency={r} offline={!live(r)} />
<span className="absolute top-2 left-2 max-w-[70%] truncate rounded-lg bg-black/55 px-2 py-1 text-[11px] font-medium text-white backdrop-blur-sm">
{p.name}
</span>
{dual && (
<ResidencyBadge
residency={r}
+ offline={!live(r)}
className="absolute bottom-2 left-2 z-10 grid size-5 place-items-center rounded-md bg-black/65 text-white"
/>
)}
<span className="absolute right-2 bottom-2 rounded-md bg-black/65 px-1.5 py-0.5 font-mono text-[10px] text-white tabular-nums">
{formatTime(p.duration)}
</span>
- <ProjectMenu
- project={p}
- className="absolute top-1.5 right-1.5 opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100"
- folders={data[r].folders}
- onRename={() => {
- setName(p.name);
- setRenaming({ project: p, residency: r });
- }}
- onDuplicate={() => void duplicate(r, p)}
- moveTo={
- dual
- ? {
- target: r === "cloud" ? "local" : "cloud",
- run: () => void moveAcross(r, p),
- }
- : undefined
- }
- onMove={(folderId) => void moveProjects(r, [p.id], folderId)}
- onDelete={() => setDeleting({ project: p, residency: r })}
- />
+ {live(r) && (
+ <ProjectMenu
+ project={p}
+ className="absolute top-1.5 right-1.5 opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100"
+ folders={data[r].folders}
+ onRename={() => {
+ setName(p.name);
+ setRenaming({ project: p, residency: r });
+ }}
+ onDuplicate={() => void duplicate(r, p)}
+ moveTo={
+ dual && engineUp
+ ? {
+ target: r === "cloud" ? "local" : "cloud",
+ run: () => void moveAcross(r, p),
+ }
+ : undefined
+ }
+ onMove={(folderId) => void moveProjects(r, [p.id], folderId)}
+ onDelete={() => setDeleting({ project: p, residency: r })}
+ />
+ )}
</div>
<div className="mt-2 px-0.5 text-xs text-muted-foreground">
{formatBytes(p.sizeBytes ?? 0)} · edited {formatDate(p.updatedAt)}
@@ -646,7 +701,7 @@ export function ProjectsHome() {
"group grid cursor-pointer grid-cols-[1fr_90px_70px_110px_40px] items-center gap-3 border-b border-border px-4 py-2.5 text-sm last:border-b-0 hover:bg-muted/50",
selected.has(p.id) && "bg-[#0a84ff]/10 hover:bg-[#0a84ff]/15"
)}
- draggable
+ draggable={live(r)}
onDragStart={(e) => onProjectDragStart(e, p)}
onClick={(e) => {
if (e.shiftKey || e.metaKey) {
@@ -661,7 +716,11 @@ export function ProjectsHome() {
<Film className="size-4 shrink-0 text-muted-foreground" />
<span className="truncate font-medium">{p.name}</span>
{dual && (
- <ResidencyBadge residency={r} className="shrink-0 text-muted-foreground" />
+ <ResidencyBadge
+ residency={r}
+ offline={!live(r)}
+ className="shrink-0 text-muted-foreground"
+ />
)}
</span>
<span className="font-mono text-xs text-muted-foreground tabular-nums">
@@ -673,31 +732,35 @@ export function ProjectsHome() {
<span className="text-xs text-muted-foreground">
{formatDate(p.updatedAt)}
</span>
- <ProjectMenu
- project={p}
- folders={data[r].folders}
- onRename={() => {
- setName(p.name);
- setRenaming({ project: p, residency: r });
- }}
- onDuplicate={() => void duplicate(r, p)}
- moveTo={
- dual
- ? {
- target: r === "cloud" ? "local" : "cloud",
- run: () => void moveAcross(r, p),
- }
- : undefined
- }
- onMove={(folderId) => void moveProjects(r, [p.id], folderId)}
- onDelete={() => setDeleting({ project: p, residency: r })}
- />
+ {live(r) ? (
+ <ProjectMenu
+ project={p}
+ folders={data[r].folders}
+ onRename={() => {
+ setName(p.name);
+ setRenaming({ project: p, residency: r });
+ }}
+ onDuplicate={() => void duplicate(r, p)}
+ moveTo={
+ dual && engineUp
+ ? {
+ target: r === "cloud" ? "local" : "cloud",
+ run: () => void moveAcross(r, p),
+ }
+ : undefined
+ }
+ onMove={(folderId) => void moveProjects(r, [p.id], folderId)}
+ onDelete={() => setDeleting({ project: p, residency: r })}
+ />
+ ) : (
+ <span />
+ )}
</div>
))}
<button
type="button"
data-no-marquee
- onClick={() => void newProjectHere(folderOwner ?? target)}
+ onClick={() => void newProjectHere(newTarget)}
className="flex w-full items-center gap-2.5 px-4 py-2.5 text-sm font-medium text-muted-foreground transition-colors hover:bg-muted/50 hover:text-foreground"
>
<Plus className="size-4" /> New project
@@ -780,7 +843,7 @@ export function ProjectsHome() {
</Button>
)}
<NewProjectButton
- pinned={folderOwner}
+ pinned={pinnedTarget}
onCreate={(r) => void newProjectHere(r)}
/>
{anyProjects && (
@@ -833,7 +896,7 @@ export function ProjectsHome() {
Create a new project to get started
</h1>
<NewProjectButton
- pinned={folderOwner}
+ pinned={pinnedTarget}
onCreate={(r) => {
setName("");
setCreateIn(r);
@@ -942,8 +1005,17 @@ export function ProjectsHome() {
* The source is withheld until the tile has been scrolled near, because each
* card is a real media element: a grid of cloud projects would otherwise open
* a connection per card on arrival and pull every file's metadata across the
- * network before the first row settled. */
-function CardPreview({ project: p, residency }: { project: ProjectSummary; residency: Residency }) {
+ * network before the first row settled. A shelf that isn't answering has no
+ * media to reach at all, so those cards stop at the frame they cached. */
+function CardPreview({
+ project: p,
+ residency,
+ offline = false,
+}: {
+ project: ProjectSummary;
+ residency: Residency;
+ offline?: boolean;
+}) {
const videoRef = useRef<HTMLVideoElement>(null);
const [tileRef, seen] = useInView<HTMLDivElement>();
// The frame this card drew last time, so coming back from a project shows the
@@ -958,6 +1030,20 @@ function CardPreview({ project: p, residency }: { project: ProjectSummary; resid
const fileUrl = (file: string) =>
backend.url(`/api/cut/projects/${p.id}/media/${encodeURIComponent(file)}`);
+ if (offline) {
+ return poster ? (
+ // eslint-disable-next-line @next/next/no-img-element -- a cached data URL, not a Next asset
+ <img
+ src={poster}
+ alt=""
+ draggable={false}
+ className="absolute inset-0 size-full object-cover"
+ />
+ ) : (
+ <Film className="size-7 text-muted-foreground/50" />
+ );
+ }
+
if (!p.previewFile && !p.hasPreview) {
return (
<Film className="size-7 text-muted-foreground/50 transition-transform group-hover:scale-110" />
diff --git a/site/src/cut/components/TemplateCard.tsx b/site/src/cut/components/TemplateCard.tsx
index 4f62074c..97a01250 100644
--- a/site/src/cut/components/TemplateCard.tsx
+++ b/site/src/cut/components/TemplateCard.tsx
@@ -63,8 +63,10 @@ export function TemplateCard({
/** The "+" action; omit to drop the button (e.g. no open project). */
onAdd?: () => void;
addTitle?: string;
- onRename: (name: string) => void;
- onDelete: () => void;
+ /** Rename and delete; omit both on a shelf that can't be written to right
+ * now — the card keeps its preview and drops the menu. */
+ onRename?: (name: string) => void;
+ onDelete?: () => void;
/** When set, the card accepts media drops (cards and timeline clips) —
* filter by `ref.scope` and append the item to the template. */
onRefDrop?: (ref: AssetRef) => void;
@@ -160,7 +162,7 @@ export function TemplateCard({
onBlur={() => setRenaming(false)}
onKeyDown={(e) => {
if (e.key === "Enter" && draft.trim()) {
- onRename(draft.trim());
+ onRename?.(draft.trim());
setRenaming(false);
} else if (e.key === "Escape") setRenaming(false);
}}
@@ -188,36 +190,44 @@ export function TemplateCard({
<Plus className="size-3.5" />
</button>
)}
- <DropdownMenu>
- <DropdownMenuTrigger
- render={
- <button
- title="Template options"
- className={cn(
- cardIconButton,
- "opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100",
- )}
- />
- }
- >
- <MoreHorizontal className="size-3.5" />
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="min-w-40">
- <DropdownMenuItem
- onClick={() => {
- setDraft(t.name);
- setRenaming(true);
- }}
+ {(onRename || onDelete) && (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <button
+ title="Template options"
+ className={cn(
+ cardIconButton,
+ "opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100",
+ )}
+ />
+ }
>
- <Pencil /> Rename
- </DropdownMenuItem>
- {extraMenu}
- <DropdownMenuSeparator />
- <DropdownMenuItem variant="destructive" onClick={onDelete}>
- <Trash2 /> Delete
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
+ <MoreHorizontal className="size-3.5" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="min-w-40">
+ {onRename && (
+ <DropdownMenuItem
+ onClick={() => {
+ setDraft(t.name);
+ setRenaming(true);
+ }}
+ >
+ <Pencil /> Rename
+ </DropdownMenuItem>
+ )}
+ {extraMenu}
+ {onDelete && (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem variant="destructive" onClick={onDelete}>
+ <Trash2 /> Delete
+ </DropdownMenuItem>
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
</div>
</div>
{expanded && parts.length > 0 && (
diff --git a/site/src/cut/lib/backend/hooks.ts b/site/src/cut/lib/backend/hooks.ts
index 4440258b..61fca98c 100644
--- a/site/src/cut/lib/backend/hooks.ts
+++ b/site/src/cut/lib/backend/hooks.ts
@@ -3,6 +3,7 @@
import { useQuery } from "@tanstack/react-query";
import { useSyncExternalStore } from "react";
+import { listedResidencies, type Residency } from "../residency";
import { cutMode, getBackend, hasLocalCompute, subscribeCutMode } from "./index";
import type { CutCaps, CutMode } from "./types";
@@ -17,6 +18,23 @@ export function useLocalCompute(): boolean {
return useSyncExternalStore(subscribeCutMode, hasLocalCompute, () => false);
}
+// The shelves the home lists, as a subscription. The array is held between
+// reads and replaced only when the set actually changes: useSyncExternalStore
+// re-renders forever on a fresh object every call.
+const CLOUD_ONLY: Residency[] = ["cloud"];
+let listed: Residency[] = CLOUD_ONLY;
+
+function listedSnapshot(): Residency[] {
+ const next = listedResidencies();
+ if (next.length !== listed.length || next.some((r, i) => r !== listed[i])) listed = next;
+ return listed;
+}
+
+/** Which residencies the projects home shows — see `listedResidencies`. */
+export function useListedResidencies(): Residency[] {
+ return useSyncExternalStore(subscribeCutMode, listedSnapshot, () => CLOUD_ONLY);
+}
+
export function useCutCaps(): CutCaps {
useCutMode();
return getBackend().caps;
diff --git a/site/src/cut/lib/library.ts b/site/src/cut/lib/library.ts
index 62edf71c..fa782f1b 100644
--- a/site/src/cut/lib/library.ts
+++ b/site/src/cut/lib/library.ts
@@ -1,11 +1,14 @@
"use client";
import { apiJson, getBackend } from "./backend";
+import { readSnapshot, writeSnapshot } from "./cache";
import { enrichAsset, presignedUpload, probeFileMeta, uploadProjectMediaTo } from "./media";
import {
activeResidency,
availableResidencies,
backendFor,
+ libraryShelfKey,
+ listedResidencies,
type Residency,
} from "./residency";
import { useEditor } from "./store";
@@ -59,21 +62,43 @@ async function fetchLibraryFrom(r: Residency): Promise<LibraryData> {
const res = await backendFor(r).fetch("/api/cut/library");
if (!res.ok) throw new Error("Could not load the library.");
const data = (await res.json()) as LibraryData;
- return {
+ const shelf: LibraryData = {
assets: (data.assets ?? []).map((a) => ({ ...a, residency: r })),
folders: (data.folders ?? []).map((f) => ({ ...f, residency: r })),
templates: (data.templates ?? []).map((t) => ({ ...t, residency: r })),
};
+ // Each half is stored on its own, so one can be recalled while the other is
+ // re-read: that is what keeps the Mac's shelf listed with the app closed.
+ writeSnapshot(libraryShelfKey(r), shelf);
+ return shelf;
+}
+
+/** One shelf as this browser last saw it, for a residency it can't ask right
+ * now. Those files are still on that Mac; only the way to reach them is gone. */
+async function rememberedLibraryFrom(r: Residency): Promise<LibraryData | null> {
+ const hit = await readSnapshot<LibraryData>(libraryShelfKey(r));
+ return hit?.value ?? null;
}
/**
- * The whole shelf: every reachable residency's library in one listing, newest
- * first. A residency that fails is left out rather than failing the read — one
+ * The whole shelf: every residency's library in one listing, newest first. A
+ * residency that fails is left out rather than failing the read — one
* unreachable half never hides the other; only both failing is an error.
+ *
+ * `remembered` widens that from what this browser can reach to what the user
+ * has: a shelf whose backend isn't answering is recalled from its last
+ * listing. The Library tab asks for it, because those items exist and the user
+ * is entitled to see them; the editor's library picker doesn't, because an
+ * item it can't copy into the project has no business in a picker.
*/
-export async function fetchLibrary(): Promise<LibraryData> {
- const rs = availableResidencies();
- const parts = await Promise.all(rs.map((r) => fetchLibraryFrom(r).catch(() => null)));
+export async function fetchLibrary(opts?: { remembered?: boolean }): Promise<LibraryData> {
+ const live = availableResidencies();
+ const rs = opts?.remembered ? listedResidencies() : live;
+ const parts = await Promise.all(
+ rs.map((r) =>
+ live.includes(r) ? fetchLibraryFrom(r).catch(() => null) : rememberedLibraryFrom(r)
+ )
+ );
const got = parts.filter((p): p is LibraryData => p !== null);
if (got.length === 0) throw new Error("Could not load the library.");
const byNewest = <T extends { addedAt: number }>(items: T[]) =>
diff --git a/site/src/cut/lib/needsApp.ts b/site/src/cut/lib/needsApp.ts
new file mode 100644
index 00000000..314361f4
--- /dev/null
+++ b/site/src/cut/lib/needsApp.ts
@@ -0,0 +1,36 @@
+"use client";
+
+// The user reached for something that lives on this Mac while the Donkey app
+// isn't answering. The ConnectGate turns this into its banner; the surfaces
+// that know what was reached for are the ones that raise it — the library when
+// a recalled item is clicked, and the editor by pinning a local project's
+// residency, which the gate reads directly.
+//
+// It is raised by a gesture and dropped when the surface that raised it goes
+// away, so the banner tracks what the user is looking at rather than standing
+// over the whole app.
+import { useSyncExternalStore } from "react";
+
+let needed = false;
+const listeners = new Set<() => void>();
+
+export function setNeedsApp(next: boolean) {
+ if (needed === next) return;
+ needed = next;
+ listeners.forEach((l) => l());
+}
+
+function subscribe(onChange: () => void) {
+ listeners.add(onChange);
+ return () => {
+ listeners.delete(onChange);
+ };
+}
+
+export function useNeedsApp(): boolean {
+ return useSyncExternalStore(
+ subscribe,
+ () => needed,
+ () => false
+ );
+}
diff --git a/site/src/cut/lib/queries.ts b/site/src/cut/lib/queries.ts
index 159b640c..bce2f35a 100644
--- a/site/src/cut/lib/queries.ts
+++ b/site/src/cut/lib/queries.ts
@@ -24,7 +24,13 @@ import { cutMode } from "./backend";
import { useCutMode } from "./backend/hooks";
import { readSnapshot, snapshotKey, writeSnapshot } from "./cache";
import { fetchLibrary, type LibraryData } from "./library";
-import { availableResidencies, backendFor, type Residency } from "./residency";
+import {
+ availableResidencies,
+ backendFor,
+ listedResidencies,
+ projectsSnapshotKey,
+ type Residency,
+} from "./residency";
import type { ProjectFolder, ProjectSummary } from "./types";
export { backendFor };
@@ -33,10 +39,17 @@ export type { Residency };
export type ProjectsSection = { projects: ProjectSummary[]; folders: ProjectFolder[] };
export const projectsKey = (r: Residency) => ["cut", "projects", r] as const;
-/** The library listing spans every reachable residency, so the set itself is
+/** The library listing spans every shelf the user has, so the set itself is
* the cache key — connecting the engine mid-session widens the shelf rather
- * than repainting a stale half of it. */
-export const libraryScope = () => availableResidencies().join("+");
+ * than repainting a stale half of it. A recalled shelf keys apart from a live
+ * one (`local!`), so the app answering re-reads it instead of holding on to
+ * the memory. */
+export const libraryScope = () => {
+ const live = availableResidencies();
+ return listedResidencies()
+ .map((r) => (live.includes(r) ? r : `${r}!`))
+ .join("+");
+};
export const libraryKey = (scope: string) => ["cut", "library", scope] as const;
/**
@@ -69,23 +82,30 @@ async function fetchProjectsSection(r: Residency): Promise<ProjectsSection> {
};
}
-/** One residency's projects and folders. Errors surface as `isError` rather
- * than an empty list, so one backend failing never blanks the other's cards. */
-export function useProjectsSection(r: Residency, enabled: boolean) {
+/**
+ * One residency's projects and folders. Errors surface as `isError` rather
+ * than an empty list, so one backend failing never blanks the other's cards.
+ *
+ * Listing a shelf and reading it are separate: the Mac's shelf lists with the
+ * Donkey app closed, off the snapshot alone, because those projects still
+ * exist and the user is entitled to see them. `live` is what asks the backend
+ * for a fresh answer, and it turns on by itself the moment the app connects.
+ */
+export function useProjectsSection(r: Residency, { list, live }: { list: boolean; live: boolean }) {
const client = useQueryClient();
useEffect(() => {
- if (!enabled) return;
- return seedFromSnapshot<ProjectsSection>(client, projectsKey(r), snapshotKey(r, "projects"));
- }, [client, r, enabled]);
+ if (!list) return;
+ return seedFromSnapshot<ProjectsSection>(client, projectsKey(r), projectsSnapshotKey(r));
+ }, [client, r, list]);
return useQuery<ProjectsSection>({
- enabled,
+ enabled: list && live,
queryKey: projectsKey(r),
queryFn: async () => {
try {
const data = await fetchProjectsSection(r);
- writeSnapshot(snapshotKey(r, "projects"), data);
+ writeSnapshot(projectsSnapshotKey(r), data);
return data;
} catch (err) {
if (r === "local" && cutMode() === "local") {
@@ -109,7 +129,8 @@ export function useProjectsSection(r: Residency, enabled: boolean) {
});
}
-/** The user's whole shelf: every reachable residency's library, merged. */
+/** The user's whole shelf: every residency's library, merged — including the
+ * one this browser can only remember. */
export function useLibrary() {
// Not read for the query itself — the backend binding decides which
// residencies are reachable, so a mode change re-keys and re-reads.
@@ -126,7 +147,7 @@ export function useLibrary() {
return useQuery<LibraryData>({
queryKey: libraryKey(scope),
queryFn: async () => {
- const data = await fetchLibrary();
+ const data = await fetchLibrary({ remembered: true });
writeSnapshot(snap, data);
return data;
},
@@ -147,7 +168,7 @@ export function patchProjects(
const next = client.setQueryData<ProjectsSection>(projectsKey(r), (prev) =>
prev ? fn(prev) : prev
);
- if (next) writeSnapshot(snapshotKey(r, "projects"), next);
+ if (next) writeSnapshot(projectsSnapshotKey(r), next);
}
/** The library's equivalent. Its items carry their own residency, so one
diff --git a/site/src/cut/lib/residency.ts b/site/src/cut/lib/residency.ts
index fa228854..f146c4ad 100644
--- a/site/src/cut/lib/residency.ts
+++ b/site/src/cut/lib/residency.ts
@@ -2,7 +2,10 @@
// 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.
+// and a miss means the project is cloud-resident. With no engine connected
+// there is nothing to ask, so the listing this browser last stored answers
+// instead: a project it saw on this Mac stays a local project, one the Donkey
+// app has to come back for.
//
// 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
@@ -14,6 +17,8 @@ import { cutMode } from "./backend";
import { cloudBackend } from "./backend/cloud";
import { localBackend } from "./backend/local";
import type { CutBackend, CutMode } from "./backend/types";
+import { readSnapshot, snapshotKey } from "./cache";
+import type { ProjectSummary } from "./types";
/** 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.) */
@@ -43,6 +48,56 @@ export function availableResidencies(): Residency[] {
return out;
}
+/** Set the first time an engine answers in this browser (by the ConnectGate).
+ * It separates a browser that never had the Donkey app from one whose app
+ * isn't running — the second has projects on this Mac and the first doesn't. */
+const SEEN_KEY = "cut-engine-seen";
+
+export function engineSeen(): boolean {
+ try {
+ return localStorage.getItem(SEEN_KEY) === "1";
+ } catch {
+ return false;
+ }
+}
+
+export function markEngineSeen(): void {
+ try {
+ localStorage.setItem(SEEN_KEY, "1");
+ } catch {
+ // Private mode: this browser re-learns the answer on every visit.
+ }
+}
+
+/** Where a residency's last listing is stored, so the shelf survives the
+ * backend that served it going away. The library keys per shelf as well as by
+ * the merged set, because the halves have to be remembered separately: the
+ * cloud's is re-read while the Mac's is recalled. */
+export const projectsSnapshotKey = (r: Residency) => snapshotKey(r, "projects");
+export const libraryShelfKey = (r: Residency) => snapshotKey(r, "library", "shelf");
+
+/**
+ * The residencies the projects home lists.
+ *
+ * Closing the Donkey app doesn't delete the projects on this Mac, so the shelf
+ * doesn't vanish with it: a browser that has reached an engine here lists that
+ * shelf from the listing it stored, whether or not the app is answering now.
+ * The cards are read-only until it is, and opening one says where the project
+ * lives instead of guessing at the cloud.
+ */
+export function listedResidencies(): Residency[] {
+ const live = availableResidencies();
+ if (live.includes("local") || !engineSeen()) return live;
+ return ["local", ...live];
+}
+
+/** The projects this browser last saw on this Mac. Read when the engine can't
+ * be asked: the listing it can't fetch is the one it already stored. */
+async function lastLocalProjects(): Promise<Set<string>> {
+ const hit = await readSnapshot<{ projects: ProjectSummary[] }>(projectsSnapshotKey("local"));
+ return new Set((hit?.value.projects ?? []).map((p) => p.id));
+}
+
/** The residency the app is bound to: where a new library upload lands, and
* where the open project lives. A shared view reads the local shelf. */
export function activeResidency(): Residency {
@@ -71,16 +126,33 @@ export function projectBackend(projectId: string): Promise<CutBackend> {
return p;
}
-export async function resolveProjectMode(projectId: string): Promise<CutMode> {
- if (!servedFromEngine() && !engineOrigin()) return "cloud";
+/** Where a project lives, and whether that place is answering. A project on
+ * this Mac with the app closed is `{ mode: "local", reachable: false }`: it
+ * exists, it is the user's, and nothing can open it until the app is back. */
+export type ProjectPlacement = { mode: CutMode; reachable: boolean };
+
+export async function resolveProjectPlacement(projectId: string): Promise<ProjectPlacement> {
+ if (!servedFromEngine() && !engineOrigin()) {
+ // No engine to ask. A project this browser last saw on this Mac is still
+ // that project — saying "cloud" would send the editor to fetch a document
+ // that was never there and call it deleted.
+ if (engineSeen() && (await lastLocalProjects()).has(projectId)) {
+ return { mode: "local", reachable: false };
+ }
+ return { mode: "cloud", reachable: true };
+ }
try {
// HEAD: the question is whether the engine owns the id, and the answer is
// the status. The doc itself is fetched a moment later by the load.
const res = await localBackend.fetch(`/api/cut/projects/${projectId}`, { method: "HEAD" });
- if (res.ok) return "local";
+ if (res.ok) return { mode: "local", reachable: true };
} catch {
// The engine dropped since the gate probed it; the cloud copy (if any)
// is the only reachable one.
}
- return "cloud";
+ return { mode: "cloud", reachable: true };
+}
+
+export async function resolveProjectMode(projectId: string): Promise<CutMode> {
+ return (await resolveProjectPlacement(projectId)).mode;
}