Skip to content

Open source CapCut alternative.

TypeScript

perf(site): open Cut from what the client already has

David Le69b0a0e544ac
diff --git a/site/src/cut/components/AppSidebar.tsx b/site/src/cut/components/AppSidebar.tsx
index fa969536..6b224822 100644
--- a/site/src/cut/components/AppSidebar.tsx
+++ b/site/src/cut/components/AppSidebar.tsx
@@ -1,6 +1,7 @@
"use client";
import { useState } from "react";
+import { useQueryClient } from "@tanstack/react-query";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { Clapperboard, FolderOpen, Loader2, Plus } from "lucide-react";
@@ -13,7 +14,9 @@ import {
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
-import { apiFetch } from "@/cut/lib/backend";
+import { apiFetch, getBackend } from "@/cut/lib/backend";
+import { seedNewProjectDoc } from "@/cut/lib/docCache";
+import { patchProjects } from "@/cut/lib/queries";
import { track } from "@/lib/analytics";
import { NavUser } from "@/cut/components/NavUser";
import { homeHref, projectHref, tabForPath, useCutBase, type CutTab } from "@/cut/lib/nav";
@@ -29,6 +32,7 @@ export function AppSidebar() {
const pathname = usePathname();
const router = useRouter();
const base = useCutBase();
+ const client = useQueryClient();
const [createOpen, setCreateOpen] = useState(false);
const [name, setName] = useState("");
const [busy, setBusy] = useState(false);
@@ -42,6 +46,14 @@ export function AppSidebar() {
body: JSON.stringify({ name: name.trim() || "Untitled" }),
});
const project = (await res.json()) as ProjectSummary;
+ const kind = getBackend().kind;
+ patchProjects(client, kind === "cloud" ? "cloud" : "local", (s) => ({
+ ...s,
+ projects: [project, ...s.projects],
+ }));
+ // A brand-new project's document is empty, so the editor about to open
+ // needs no round trip to draw it.
+ seedNewProjectDoc(project.id, project.name, kind);
track("project_created", { source: "sidebar" });
// The sidebar creates on the globally bound backend, so the link carries
// that residency.
diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsx
index 673cd8a8..93a3bfe0 100644
--- a/site/src/cut/components/Editor.tsx
+++ b/site/src/cut/components/Editor.tsx
@@ -6,6 +6,7 @@ import { Clapperboard, Loader2, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { apiFetch, bindCutMode, releaseCutMode } from "@/cut/lib/backend";
import { loadedDocVersion } from "@/cut/lib/backend/shared";
+import { writeCachedDoc } from "@/cut/lib/docCache";
import { refreshShareCard, renderPreviewProxy } from "@/cut/lib/exportClient";
import { fileZoneAt, hasRefDrag } from "@/cut/lib/assetRef";
import { enrichAsset, importFileToProject } from "@/cut/lib/media";
@@ -267,15 +268,19 @@ export function Editor({
const s = useEditor.getState();
if (!s.loaded || s.projectId !== projectId) return;
s.setSaveState("saving");
+ const doc = serializeDoc(s);
try {
const res = await apiFetch(`/api/cut/projects/${projectId}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify(serializeDoc(s)),
+ body: JSON.stringify(doc),
});
if (res.ok) {
failures = 0;
useEditor.getState().setSaveState("saved");
+ // The snapshot the next open paints from is whatever this browser
+ // last put on the server, so it tracks every save.
+ writeCachedDoc(projectId, doc);
return;
}
useEditor.getState().setSaveState("error");
@@ -286,7 +291,10 @@ export function Editor({
}
};
- let primed = false;
+ // Re-baselined every time a document is hydrated — the snapshot an open
+ // paints, the live document that replaces it, a conflict reload — so a
+ // document that came from the server is never saved straight back to it.
+ let primedEpoch = -1;
// Assets change identity on runtime enrichment (thumbs, peaks) too, so a
// new reference compares by its stored projection: field edits like an
// origin change ("Add to Media", chat tagging) must save, enrichment not.
@@ -302,10 +310,10 @@ export function Editor({
};
const unsub = useEditor.subscribe((s) => {
if (!s.loaded || s.projectId !== projectId) return;
- if (!primed) {
- // First tick after load: snapshot the freshly loaded doc so opening
- // a project never counts as an edit.
- primed = true;
+ if (s.loadEpoch !== primedEpoch) {
+ // First tick after a hydration: snapshot the freshly loaded doc so
+ // arriving at one never counts as an edit.
+ primedEpoch = s.loadEpoch;
last = serializeDoc(s);
lastName = s.projectName;
assetsChanged(s.assets);
diff --git a/site/src/cut/components/LibraryView.tsx b/site/src/cut/components/LibraryView.tsx
index 6bb50d98..65eccb84 100644
--- a/site/src/cut/components/LibraryView.tsx
+++ b/site/src/cut/components/LibraryView.tsx
@@ -1,6 +1,7 @@
"use client";
-import { useEffect, useRef, useState } from "react";
+import { useCallback, useRef, useState } from "react";
+import { useQueryClient } from "@tanstack/react-query";
import { useRouter, useSearchParams } from "next/navigation";
import {
FolderOpen,
@@ -32,12 +33,12 @@ import {
import { Input } from "@/components/ui/input";
import { clearAssetDrag, setCardDragImage, setLibraryDragData } from "@/cut/lib/assetDrag";
import { isMediaFile } from "@/cut/lib/media";
+import { patchLibrary, refetchLibrary, useLibrary } from "@/cut/lib/queries";
import {
createLibraryFolder,
deleteFromLibrary,
deleteLibraryFolder,
deleteTemplate,
- fetchLibrary,
importUrlToLibrary,
libraryMediaUrl,
moveLibraryItem,
@@ -45,9 +46,8 @@ import {
renameTemplate,
uploadToLibrary,
type LibraryAsset,
- type LibraryFolder,
+ type LibraryData,
} from "@/cut/lib/library";
-import type { LibraryTemplate } from "@/cut/lib/types";
import { TemplateCard } from "./TemplateCard";
import { homeHref, useCutBase } from "@/cut/lib/nav";
import { useRevealFlash } from "@/cut/lib/refReveal";
@@ -64,9 +64,18 @@ const LIBRARY_MOVE_MIME = "application/x-cut-library-move";
export function LibraryView() {
const router = useRouter();
const base = useCutBase();
- const [assets, setAssets] = useState<LibraryAsset[] | null>(null);
- const [folders, setFolders] = useState<LibraryFolder[]>([]);
- const [templates, setTemplates] = useState<LibraryTemplate[]>([]);
+ 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.
+ const library = useLibrary();
+ const all = library.data?.assets ?? [];
+ const folders = library.data?.folders ?? [];
+ const templates = library.data?.templates ?? [];
+ const patch = useCallback(
+ (fn: (prev: LibraryData) => LibraryData) => patchLibrary(client, fn),
+ [client]
+ );
+ const reload = useCallback(() => refetchLibrary(client), [client]);
// The open folder lives in the URL (?folder=…) so the browser's back button
// steps folder → root and the location survives reloads.
const openFolder = useSearchParams().get("folder");
@@ -84,29 +93,16 @@ export function LibraryView() {
const [fileOver, setFileOver] = useState(false);
const dragDepth = useRef(0);
- const reload = () =>
- fetchLibrary()
- .then((d) => {
- setAssets(d.assets);
- setFolders(d.folders);
- setTemplates(d.templates);
- })
- .catch(() => setAssets([]));
-
const renameTpl = async (id: string, name: string) => {
- setTemplates((prev) => prev.map((t) => (t.id === id ? { ...t, name } : t)));
+ patch((d) => ({ ...d, templates: d.templates.map((t) => (t.id === id ? { ...t, name } : t)) }));
await renameTemplate(id, name).catch(() => void reload());
};
const removeTpl = async (id: string) => {
- setTemplates((prev) => prev.filter((t) => t.id !== id));
+ patch((d) => ({ ...d, templates: d.templates.filter((t) => t.id !== id) }));
await deleteTemplate(id).catch(() => void reload());
};
- useEffect(() => {
- 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) => {
@@ -119,7 +115,7 @@ export function LibraryView() {
await moveLibraryItem(asset.id, folderId).catch(() => {});
asset.folderId = folderId;
}
- setAssets((prev) => [asset, ...(prev ?? [])]);
+ patch((d) => ({ ...d, assets: [asset, ...d.assets] }));
} catch {
// Skip unreadable files; the rest of the batch still uploads.
} finally {
@@ -141,7 +137,7 @@ export function LibraryView() {
asset.folderId = openFolder;
}
}
- setAssets((prev) => [...imported, ...(prev ?? [])]);
+ patch((d) => ({ ...d, assets: [...imported, ...d.assets] }));
setUrl("");
setAddOpen(false);
} catch (e) {
@@ -155,7 +151,7 @@ export function LibraryView() {
if (!deleting) return;
const id = deleting.id;
setDeleting(null);
- setAssets((prev) => (prev ?? []).filter((a) => a.id !== id));
+ patch((d) => ({ ...d, assets: d.assets.filter((a) => a.id !== id) }));
try {
await deleteFromLibrary(id);
} catch {
@@ -173,8 +169,11 @@ export function LibraryView() {
const moveItems = async (ids: string[], folderId: string | null) => {
if (ids.length === 0) return;
const idset = new Set(ids);
- setAssets((prev) => (prev ?? []).map((a) => (idset.has(a.id) ? { ...a, folderId } : a)));
- setTemplates((prev) => prev.map((t) => (idset.has(t.id) ? { ...t, folderId } : t)));
+ patch((d) => ({
+ ...d,
+ assets: d.assets.map((a) => (idset.has(a.id) ? { ...a, folderId } : a)),
+ templates: d.templates.map((t) => (idset.has(t.id) ? { ...t, folderId } : t)),
+ }));
setSelected(new Set());
await Promise.all(ids.map((id) => moveLibraryItem(id, folderId))).catch(() => void reload());
};
@@ -197,7 +196,6 @@ export function LibraryView() {
}
};
- const all = assets ?? [];
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;
@@ -295,20 +293,23 @@ export function LibraryView() {
onOpen={gotoFolder}
onCreate={async (name) => {
const f = await createLibraryFolder(name);
- setFolders((prev) => [...prev, f]);
+ patch((d) => ({ ...d, folders: [...d.folders, f] }));
}}
onRename={async (id, name) => {
- setFolders((prev) => prev.map((f) => (f.id === id ? { ...f, name } : f)));
+ patch((d) => ({
+ ...d,
+ folders: d.folders.map((f) => (f.id === id ? { ...f, name } : f)),
+ }));
await renameLibraryFolder(id, name).catch(() => void reload());
}}
onDelete={async (id) => {
- setFolders((prev) => prev.filter((f) => f.id !== id));
- setAssets((prev) =>
- (prev ?? []).map((a) => (a.folderId === id ? { ...a, folderId: null } : a))
- );
- setTemplates((prev) =>
- prev.map((t) => (t.folderId === id ? { ...t, folderId: null } : t))
- );
+ patch((d) => ({
+ folders: d.folders.filter((f) => f.id !== id),
+ assets: d.assets.map((a) => (a.folderId === id ? { ...a, folderId: null } : a)),
+ templates: d.templates.map((t) =>
+ t.folderId === id ? { ...t, folderId: null } : t
+ ),
+ }));
if (openFolder === id) router.replace(homeHref(base, "library"));
await deleteLibraryFolder(id).catch(() => void reload());
}}
@@ -336,7 +337,7 @@ export function LibraryView() {
</div>
)}
- {assets === null ? (
+ {!library.data && library.isPending ? (
<div className="grid place-items-center py-24 text-muted-foreground">
<Loader2 className="size-5 animate-spin" />
</div>
diff --git a/site/src/cut/components/ProjectsHome.tsx b/site/src/cut/components/ProjectsHome.tsx
index b9104826..ea81d63f 100644
--- a/site/src/cut/components/ProjectsHome.tsx
+++ b/site/src/cut/components/ProjectsHome.tsx
@@ -1,6 +1,7 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
+import { useQueryClient } from "@tanstack/react-query";
import { useRouter, useSearchParams } from "next/navigation";
import {
Check,
@@ -45,12 +46,19 @@ import {
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
-import { engineLost, engineOrigin, servedFromEngine } from "@/cut/lib/api";
-import { cloudBackend, quotaErrorMessage } from "@/cut/lib/backend/cloud";
+import { engineOrigin, servedFromEngine } from "@/cut/lib/api";
+import { quotaErrorMessage } from "@/cut/lib/backend/cloud";
import { useCloudUsage, useCutMode } from "@/cut/lib/backend/hooks";
-import { localBackend } from "@/cut/lib/backend/local";
-import type { CutBackend } from "@/cut/lib/backend/types";
-import { useWebMode, webModeEnabled } from "@/cut/lib/flags";
+import { dropCachedDoc, seedNewProjectDoc } from "@/cut/lib/docCache";
+import {
+ backendFor,
+ patchProjects,
+ refetchProjects,
+ useProjectsSection,
+ type ProjectsSection,
+ type Residency,
+} from "@/cut/lib/queries";
+import { useWebMode } from "@/cut/lib/flags";
import { track } from "@/lib/analytics";
import { authClient } from "@/lib/auth-client";
import { useStartCheckout } from "@/queries/billing";
@@ -67,15 +75,10 @@ import { buildDragGhost, FolderCrumb, FolderShelf, formatBytes, Marquee } from "
type View = "gallery" | "list";
-// Where a project lives: the engine on this Mac or the hosted cloud backend.
-// The home lists each residency it can reach as its own section, talking to
-// the backend objects directly — the global mode is only bound when a project
-// opens into the editor. (The "shared" mode is a view of someone else's
-// project, never a residency of yours.)
-type Residency = "local" | "cloud";
-
-const backendFor = (r: Residency): CutBackend => (r === "cloud" ? cloudBackend : localBackend);
-
+// The home lists each residency it can reach, 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.
const RESIDENCY_LABEL: Record<Residency, string> = { local: "On this Mac", cloud: "Cloud" };
type SectionData = {
@@ -84,8 +87,6 @@ type SectionData = {
error: boolean;
};
-const EMPTY_SECTION: SectionData = { projects: null, folders: [], error: false };
-
// A dragged selection is carried as a JSON array of project ids, so one drag can
// move a whole marquee-selected collection into a folder.
const PROJECT_MIME = "application/x-cut-project";
@@ -176,10 +177,31 @@ export function ProjectsHome() {
const dual = residencies.length > 1;
const r0 = residencies[0];
- const [data, setData] = useState<Record<Residency, SectionData>>({
- local: EMPTY_SECTION,
- cloud: EMPTY_SECTION,
+ 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 asSection = (q: typeof localSection): SectionData => ({
+ projects: q.data?.projects ?? null,
+ folders: q.data?.folders ?? [],
+ // A cached listing on screen outranks a failed revalidation: the cards
+ // stay, and only a section with nothing to show says it couldn't load.
+ error: q.isError && q.data === undefined,
});
+ const data: Record<Residency, SectionData> = {
+ local: asSection(localSection),
+ cloud: asSection(cloudSection),
+ };
+
+ // Optimistic edits to a section's cached listing; the next revalidation
+ // reconciles whatever the server actually did.
+ const patch = useCallback(
+ (r: Residency, fn: (s: ProjectsSection) => ProjectsSection) => patchProjects(client, r, fn),
+ [client]
+ );
+ const refresh = useCallback((r: Residency) => refetchProjects(client, r), [client]);
+
// The open folder lives in the URL (?folder=…) so project URLs can point
// back into it and the browser's back button steps folder → root.
const openFolder = useSearchParams().get("folder");
@@ -214,46 +236,6 @@ export function ProjectsHome() {
localStorage.setItem("cut-projects-view", v);
};
- const refresh = useCallback(async (r: Residency) => {
- const backend = backendFor(r);
- try {
- const [res, fres] = await Promise.all([
- backend.fetch("/api/cut/projects"),
- backend.fetch("/api/cut/projects/folders"),
- ]);
- if (!res.ok) throw new Error(String(res.status));
- const projects = (await res.json()) as ProjectSummary[];
- const folders = fres.ok ? ((await fres.json()) as ProjectFolder[]) : [];
- setData((prev) => ({ ...prev, [r]: { projects, folders, error: false } }));
- } catch {
- if (r === "local" && !webModeEnabled()) {
- // The engine on this Mac stopped answering; the ConnectGate takes the
- // screen back over until it returns.
- engineLost();
- return;
- }
- // One backend failing never takes down the other's section.
- setData((prev) => ({ ...prev, [r]: { ...prev[r], error: true } }));
- }
- }, []);
-
- const residencyKey = residencies.join(",");
- useEffect(() => {
- for (const r of residencyKey.split(",") as Residency[]) void refresh(r);
- }, [residencyKey, refresh]);
-
- // A section stuck on "Couldn't load these projects" heals itself: while any
- // section is errored, retry its refresh every few seconds. A successful
- // refresh clears the error, which changes the key and drops the interval.
- const erroredKey = residencies.filter((r) => data[r].error).join(",");
- useEffect(() => {
- if (!erroredKey) return;
- const id = setInterval(() => {
- for (const r of erroredKey.split(",") as Residency[]) void refresh(r);
- }, 3000);
- return () => clearInterval(id);
- }, [erroredKey, refresh]);
-
const createFolder = async (r: Residency, fname: string) => {
const res = await backendFor(r).fetch("/api/cut/projects/folders", {
method: "POST",
@@ -262,18 +244,15 @@ export function ProjectsHome() {
});
if (res.ok) {
const f = (await res.json()) as ProjectFolder;
- setData((prev) => ({ ...prev, [r]: { ...prev[r], folders: [...prev[r].folders, f] } }));
+ patch(r, (s) => ({ ...s, folders: [...s.folders, f] }));
track("folder_created");
}
};
const renameFolder = async (r: Residency, id: string, fname: string) => {
- setData((prev) => ({
- ...prev,
- [r]: {
- ...prev[r],
- folders: prev[r].folders.map((f) => (f.id === id ? { ...f, name: fname } : f)),
- },
+ patch(r, (s) => ({
+ ...s,
+ folders: s.folders.map((f) => (f.id === id ? { ...f, name: fname } : f)),
}));
await backendFor(r)
.fetch(`/api/cut/projects/folders/${id}`, {
@@ -292,15 +271,9 @@ export function ProjectsHome() {
};
const deleteFolder = async (r: Residency, id: string) => {
- setData((prev) => ({
- ...prev,
- [r]: {
- ...prev[r],
- folders: prev[r].folders.filter((f) => f.id !== id),
- projects: (prev[r].projects ?? []).map((p) =>
- p.folderId === id ? { ...p, folderId: null } : p
- ),
- },
+ patch(r, (s) => ({
+ folders: s.folders.filter((f) => f.id !== id),
+ projects: s.projects.map((p) => (p.folderId === id ? { ...p, folderId: null } : p)),
}));
if (openFolder === id) router.replace(homeHref(base, "projects"));
await backendFor(r)
@@ -316,14 +289,9 @@ export function ProjectsHome() {
const move = ids.filter((id) => own.has(id));
if (move.length === 0) return;
const idset = new Set(move);
- setData((prev) => ({
- ...prev,
- [r]: {
- ...prev[r],
- projects: (prev[r].projects ?? []).map((p) =>
- idset.has(p.id) ? { ...p, folderId } : p
- ),
- },
+ patch(r, (s) => ({
+ ...s,
+ projects: s.projects.map((p) => (idset.has(p.id) ? { ...p, folderId } : p)),
}));
setSelected(new Set());
await Promise.all(
@@ -337,17 +305,28 @@ export function ProjectsHome() {
).catch(() => void refresh(r));
};
+ // Creating a project is the one moment where the whole answer is already
+ // known: the server hands back the summary, and the document it just wrote
+ // is empty. Seed both — the card is in the grid before the navigation, and
+ // 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) => {
+ const res = await backendFor(r).fetch("/api/cut/projects", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ name: pname, folderId }),
+ });
+ const project = (await res.json()) as ProjectSummary;
+ patch(r, (s) => ({ ...s, projects: [project, ...s.projects] }));
+ seedNewProjectDoc(project.id, project.name, r);
+ track("project_created", { source: "projects_home" });
+ router.push(projectHref(base, project.id, "projects", folderId));
+ };
+
const create = async () => {
setBusy(true);
try {
- const res = await backendFor(r0).fetch("/api/cut/projects", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ name: name.trim() || "Untitled", folderId: openFolder }),
- });
- const project = (await res.json()) as ProjectSummary;
- track("project_created", { source: "projects_home" });
- router.push(projectHref(base, project.id, "projects", openFolder));
+ await openNewProject(r0, name.trim() || "Untitled", openFolder);
} finally {
setBusy(false);
}
@@ -355,16 +334,8 @@ export function ProjectsHome() {
// Make a new project in the folder that's open (root when none), then jump
// straight into it — no naming step.
- const newProjectHere = async (r: Residency, folderId: string | null = openFolder) => {
- const res = await backendFor(r).fetch("/api/cut/projects", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ name: "Untitled", folderId }),
- });
- const project = (await res.json()) as ProjectSummary;
- track("project_created", { source: "projects_home" });
- router.push(projectHref(base, project.id, "projects", folderId));
- };
+ const newProjectHere = (r: Residency, folderId: string | null = openFolder) =>
+ openNewProject(r, "Untitled", folderId);
// Turn a batch of desktop files into projects filed under `folderId`. Each
// becomes its own project and pops into the grid the moment it's ready.
@@ -392,18 +363,20 @@ export function ProjectsHome() {
const rename = async () => {
if (!renaming) return;
- setBusy(true);
- try {
- await backendFor(renaming.residency).fetch(`/api/cut/projects/${renaming.project.id}`, {
+ const { project, residency } = renaming;
+ const next = name.trim() || project.name;
+ patch(residency, (s) => ({
+ ...s,
+ projects: s.projects.map((p) => (p.id === project.id ? { ...p, name: next } : p)),
+ }));
+ setRenaming(null);
+ await backendFor(residency)
+ .fetch(`/api/cut/projects/${project.id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ name: name.trim() || renaming.project.name }),
- });
- setRenaming(null);
- await refresh(renaming.residency);
- } finally {
- setBusy(false);
- }
+ body: JSON.stringify({ name: next }),
+ })
+ .catch(() => void refresh(residency));
};
const duplicate = async (r: Residency, p: ProjectSummary) => {
@@ -474,13 +447,15 @@ export function ProjectsHome() {
await backendFor(residency).fetch(`/api/cut/projects/${id}`, { method: "DELETE" });
// The doc, media, and exports go with the folder on the server. Purge the
// client-side residue keyed to this project so nothing survives it: a live
- // scene run, its in-flight renders, and its chat history (whose ids the
- // render-resume guard reads to keep a deleted thread's render from landing).
+ // scene run, its in-flight renders, its chat history (whose ids the
+ // render-resume guard reads to keep a deleted thread's render from
+ // landing), and the cached copy of its document.
useGenScene.getState().killProject(id);
useGenerate.getState().cancelForOwner({ projectId: id });
clearProjectThreads(id);
+ dropCachedDoc(id, residency);
+ patch(residency, (s) => ({ ...s, projects: s.projects.filter((p) => p.id !== id) }));
setDeleting(null);
- await refresh(residency);
} finally {
setBusy(false);
}
diff --git a/site/src/cut/lib/api.ts b/site/src/cut/lib/api.ts
index c80a4ab7..56a73763 100644
--- a/site/src/cut/lib/api.ts
+++ b/site/src/cut/lib/api.ts
@@ -141,6 +141,13 @@ export function setEngineUser(id: string) {
engineUser = id;
}
+/** The bound account, or null before the session resolves. Client-side caches
+ * scope their keys to it so two accounts sharing a browser can't read each
+ * other's snapshots. */
+export function currentEngineUser(): string | null {
+ return engineUser;
+}
+
const scopedPath = (path: string) =>
engineUser
? `${path}${path.includes("?") ? "&" : "?"}u=${encodeURIComponent(engineUser)}`
diff --git a/site/src/cut/lib/cache.ts b/site/src/cut/lib/cache.ts
new file mode 100644
index 00000000..9957c215
--- /dev/null
+++ b/site/src/cut/lib/cache.ts
@@ -0,0 +1,122 @@
+"use client";
+
+/**
+ * Last-known-good snapshots of what the app re-reads on every visit: the
+ * projects and library listings, a project's document, its signed media
+ * links. They live in IndexedDB, so a reload paints what you saw last time
+ * within a millisecond or two while the real request is still in flight.
+ *
+ * Everything here is a cache and never a source of truth. A miss, a quota
+ * failure, or a private-mode browser costs a spinner and nothing else, so
+ * every entry point swallows its errors. Keys are scoped to the signed-in
+ * account and to the backend that served the data, because a second account
+ * on the same Mac and a project's cloud twin must never read each other's
+ * snapshots.
+ */
+
+import { currentEngineUser } from "./api";
+
+const DB_NAME = "cut";
+// v1 held only the per-project view state; v2 adds this store beside it.
+const DB_VERSION = 2;
+const UI_STORE = "project-ui";
+const SNAPSHOT_STORE = "snapshots";
+
+/** A snapshot older than this is dropped on read — too old to be a useful
+ * head start, and old enough that painting it would be a lie. */
+const MAX_AGE_MS = 14 * 24 * 60 * 60 * 1000;
+
+type Entry = { at: number; value: unknown };
+
+let db: Promise<IDBDatabase> | null = null;
+
+/** The app's one IndexedDB handle. Shared with uiState.ts: two modules
+ * opening the same database at different versions would deadlock each other. */
+export function openCutDb(): Promise<IDBDatabase> {
+ db ??= new Promise<IDBDatabase>((resolve, reject) => {
+ const req = indexedDB.open(DB_NAME, DB_VERSION);
+ req.onupgradeneeded = () => {
+ const names = req.result.objectStoreNames;
+ if (!names.contains(UI_STORE)) req.result.createObjectStore(UI_STORE);
+ if (!names.contains(SNAPSHOT_STORE)) req.result.createObjectStore(SNAPSHOT_STORE);
+ };
+ req.onsuccess = () => resolve(req.result);
+ req.onerror = () => reject(req.error);
+ })
+ .then((conn) => {
+ prune(conn);
+ return conn;
+ })
+ .catch((err) => {
+ db = null; // a failed open isn't memoized; the next reader tries again
+ throw err;
+ });
+ return db;
+}
+
+/** Sweep entries past their age, once per session on the first open, so a
+ * browser that has visited a few hundred projects doesn't keep them all. */
+function prune(conn: IDBDatabase) {
+ try {
+ const store = conn.transaction(SNAPSHOT_STORE, "readwrite").objectStore(SNAPSHOT_STORE);
+ const cutoff = Date.now() - MAX_AGE_MS;
+ const req = store.openCursor();
+ req.onsuccess = () => {
+ const cursor = req.result;
+ if (!cursor) return;
+ if ((cursor.value as Entry)?.at < cutoff) cursor.delete();
+ cursor.continue();
+ };
+ } catch {
+ // Entries past their age are ignored on read anyway.
+ }
+}
+
+/** Scope a key to the signed-in account and the backend that owns the data.
+ * Anything read before the session binds gets the `-` scope, which no real
+ * account shares, so it simply misses. */
+export const snapshotKey = (backend: string, ...parts: string[]) =>
+ [currentEngineUser() ?? "-", backend, ...parts].join("/");
+
+export async function readSnapshot<T>(key: string): Promise<{ value: T; at: number } | null> {
+ try {
+ const conn = await openCutDb();
+ const entry = await new Promise<Entry | undefined>((resolve) => {
+ const req = conn.transaction(SNAPSHOT_STORE).objectStore(SNAPSHOT_STORE).get(key);
+ req.onsuccess = () => resolve(req.result as Entry | undefined);
+ req.onerror = () => resolve(undefined);
+ });
+ if (!entry || Date.now() - entry.at > MAX_AGE_MS) return null;
+ return { value: entry.value as T, at: entry.at };
+ } catch {
+ return null;
+ }
+}
+
+/** Record a snapshot. Fire-and-forget: callers are on the happy path of a
+ * request that already succeeded and have nothing to do if the write fails. */
+export function writeSnapshot(key: string, value: unknown): void {
+ void (async () => {
+ try {
+ const conn = await openCutDb();
+ conn
+ .transaction(SNAPSHOT_STORE, "readwrite")
+ .objectStore(SNAPSHOT_STORE)
+ .put({ at: Date.now(), value } satisfies Entry, key);
+ } catch {
+ // Best-effort; the next visit just waits on the network like before.
+ }
+ })();
+}
+
+export function dropSnapshot(key: string): void {
+ void (async () => {
+ try {
+ const conn = await openCutDb();
+ conn.transaction(SNAPSHOT_STORE, "readwrite").objectStore(SNAPSHOT_STORE).delete(key);
+ } catch {
+ // A snapshot that outlives its subject expires on its own age.
+ }
+ })();
+}
+
diff --git a/site/src/cut/lib/docCache.ts b/site/src/cut/lib/docCache.ts
new file mode 100644
index 00000000..fc21feda
--- /dev/null
+++ b/site/src/cut/lib/docCache.ts
@@ -0,0 +1,97 @@
+"use client";
+
+/**
+ * A project's own snapshots: the document the editor opens with, and the
+ * signed links that make its media playable.
+ *
+ * Opening a cloud project is two round trips before a frame can be drawn —
+ * fetch the doc, then mint a batch of R2 URLs for its files. Both answers are
+ * things this browser already had the last time it held the project, so both
+ * are kept on disk and painted immediately while the real ones are fetched.
+ * The document snapshot is rewritten on every successful save, which makes it
+ * a copy of what this browser itself last pushed to the server.
+ *
+ * The snapshot is a head start, never the truth: the live document always
+ * lands and replaces it, and a project edited from another device simply
+ * corrects itself a moment after it opens.
+ */
+
+import { getBackend } from "./backend";
+import type { CutMode } from "./backend/types";
+import { dropSnapshot, readSnapshot, snapshotKey, writeSnapshot } from "./cache";
+import type { ProjectDoc } from "./types";
+
+/** Reuse a stored batch only with this much life left, so a project opened on
+ * a snapshot is never handed links that expire while it is being edited. */
+const LINK_REUSE_FLOOR_MS = 10 * 60 * 1000;
+
+const docKey = (projectId: string, kind: CutMode) => snapshotKey(kind, "doc", projectId);
+const linksKey = (projectId: string, kind: CutMode) => snapshotKey(kind, "media-links", projectId);
+
+export type CachedDoc = Partial<ProjectDoc>;
+
+export function readCachedDoc(projectId: string, kind = getBackend().kind) {
+ return readSnapshot<CachedDoc>(docKey(projectId, kind));
+}
+
+export function writeCachedDoc(projectId: string, doc: CachedDoc, kind = getBackend().kind) {
+ writeSnapshot(docKey(projectId, kind), doc);
+}
+
+export function dropCachedDoc(projectId: string, kind = getBackend().kind) {
+ dropSnapshot(docKey(projectId, kind));
+ dropSnapshot(linksKey(projectId, kind));
+}
+
+type StoredLinks = { urls: [string, string][]; expiresAt: number };
+
+/** The stored signed batch, when it still covers every file the project holds
+ * and has comfortable life left. Anything less returns null and the caller
+ * mints a fresh batch, which is what it did before this cache existed. */
+export async function readCachedMediaLinks(
+ projectId: string,
+ fileNames: string[]
+): Promise<{ urls: Map<string, string>; expiresAt: number } | null> {
+ const hit = await readSnapshot<StoredLinks>(linksKey(projectId, getBackend().kind));
+ if (!hit) return null;
+ const { urls, expiresAt } = hit.value;
+ if (expiresAt - Date.now() < LINK_REUSE_FLOOR_MS) return null;
+ const map = new Map(urls);
+ if (fileNames.some((f) => !map.has(f))) return null;
+ return { urls: map, expiresAt };
+}
+
+export function writeCachedMediaLinks(
+ projectId: string,
+ urls: Map<string, string>,
+ expiresAt: number | null
+) {
+ if (expiresAt === null || urls.size === 0) {
+ dropSnapshot(linksKey(projectId, getBackend().kind));
+ return;
+ }
+ writeSnapshot(linksKey(projectId, getBackend().kind), {
+ urls: [...urls],
+ expiresAt,
+ } satisfies StoredLinks);
+}
+
+/** The document a project has the instant it is created: a name and nothing
+ * else. Seeding it lets the editor the user is about to land in open on the
+ * first frame instead of waiting out a round trip for a document we can
+ * already describe in full. */
+export function seedNewProjectDoc(projectId: string, name: string, kind: CutMode) {
+ writeCachedDoc(
+ projectId,
+ {
+ name,
+ assets: [],
+ clips: [],
+ audioClips: [],
+ overlays: [],
+ templates: [],
+ renders: [],
+ },
+ kind
+ );
+}
diff --git a/site/src/cut/lib/queries.ts b/site/src/cut/lib/queries.ts
new file mode 100644
index 00000000..5c838570
--- /dev/null
+++ b/site/src/cut/lib/queries.ts
@@ -0,0 +1,169 @@
+"use client";
+
+/**
+ * The home surfaces' data layer: the projects listing per residency and the
+ * library listing for the active backend.
+ *
+ * Both are read on every visit and change rarely, so they are cached twice
+ * over. TanStack Query holds them for the life of the tab, which is what makes
+ * project → back → project instant; a snapshot in IndexedDB carries the last
+ * answer across reloads, so even a cold load paints the shelf it painted last
+ * time. Neither is ever waited on: the live request goes out regardless and
+ * replaces whatever was showing.
+ *
+ * Mutations edit the cached lists in place through the patch helpers rather
+ * than refetching, so a rename or a move lands on screen in the same frame the
+ * user asked for it.
+ */
+
+import { useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query";
+import { useEffect } from "react";
+
+import { engineLost } from "./api";
+import { getBackend } from "./backend";
+import { cloudBackend } from "./backend/cloud";
+import { localBackend } from "./backend/local";
+import { useCutMode } from "./backend/hooks";
+import type { CutBackend, CutMode } from "./backend/types";
+import { readSnapshot, snapshotKey, writeSnapshot } from "./cache";
+import { webModeEnabled } from "./flags";
+import { fetchLibrary, type LibraryData } from "./library";
+import type { ProjectFolder, ProjectSummary } from "./types";
+
+/** Where a project lives: the engine on this Mac, or the hosted cloud
+ * backend. ("shared" is a view of someone else's project, never a residency
+ * of yours, so it never lists here.) */
+export type Residency = "local" | "cloud";
+
+export const backendFor = (r: Residency): CutBackend =>
+ r === "cloud" ? cloudBackend : localBackend;
+
+export type ProjectsSection = { projects: ProjectSummary[]; folders: ProjectFolder[] };
+
+export const projectsKey = (r: Residency) => ["cut", "projects", r] as const;
+export const libraryKey = (mode: CutMode) => ["cut", "library", mode] as const;
+
+/**
+ * Paint the last answer we stored while the live one is in flight. The
+ * snapshot is backdated to when it was taken, so the query still counts as
+ * stale and the request already on its way is the one that wins; a live
+ * answer that beat the disk read is never overwritten.
+ */
+function seedFromSnapshot<T>(client: QueryClient, queryKey: readonly unknown[], cacheKey: string) {
+ let alive = true;
+ void readSnapshot<T>(cacheKey).then((hit) => {
+ if (!alive || !hit || client.getQueryData(queryKey) !== undefined) return;
+ client.setQueryData(queryKey, hit.value, { updatedAt: hit.at });
+ });
+ return () => {
+ alive = false;
+ };
+}
+
+async function fetchProjectsSection(r: Residency): Promise<ProjectsSection> {
+ const backend = backendFor(r);
+ const [res, fres] = await Promise.all([
+ backend.fetch("/api/cut/projects"),
+ backend.fetch("/api/cut/projects/folders"),
+ ]);
+ if (!res.ok) throw new Error(String(res.status));
+ return {
+ projects: (await res.json()) as ProjectSummary[],
+ folders: fres.ok ? ((await fres.json()) as ProjectFolder[]) : [],
+ };
+}
+
+/** 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) {
+ const client = useQueryClient();
+
+ useEffect(() => {
+ if (!enabled) return;
+ return seedFromSnapshot<ProjectsSection>(client, projectsKey(r), snapshotKey(r, "projects"));
+ }, [client, r, enabled]);
+
+ return useQuery<ProjectsSection>({
+ enabled,
+ queryKey: projectsKey(r),
+ queryFn: async () => {
+ try {
+ const data = await fetchProjectsSection(r);
+ 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.
+ engineLost();
+ }
+ throw err;
+ }
+ },
+ // The listing is cheap to re-read and its cards carry edit times and
+ // sizes, so every visit revalidates — behind the cached paint, never a
+ // spinner.
+ staleTime: 0,
+ refetchOnMount: "always",
+ retry: false,
+ // A section stuck on "Couldn't load these projects" heals itself.
+ refetchInterval: (q) => (q.state.status === "error" ? 3000 : false),
+ });
+}
+
+/** The library of the backend the app is currently bound to. */
+export function useLibrary() {
+ const mode = useCutMode();
+ const client = useQueryClient();
+
+ useEffect(
+ () => seedFromSnapshot<LibraryData>(client, libraryKey(mode), snapshotKey(mode, "library")),
+ [client, mode]
+ );
+
+ return useQuery<LibraryData>({
+ queryKey: libraryKey(mode),
+ queryFn: async () => {
+ const data = await fetchLibrary();
+ writeSnapshot(snapshotKey(mode, "library"), data);
+ return data;
+ },
+ staleTime: 0,
+ refetchOnMount: "always",
+ retry: false,
+ });
+}
+
+/** Edit a residency's cached listing in place — the optimistic half of every
+ * projects mutation. The snapshot moves with it, so a reload right after a
+ * rename shows the new name rather than flashing the old one back. */
+export function patchProjects(
+ client: QueryClient,
+ r: Residency,
+ fn: (prev: ProjectsSection) => ProjectsSection
+) {
+ const next = client.setQueryData<ProjectsSection>(projectsKey(r), (prev) =>
+ prev ? fn(prev) : prev
+ );
+ if (next) writeSnapshot(snapshotKey(r, "projects"), next);
+}
+
+/** The library's equivalent. Keyed on the active backend, which is the only
+ * one the library view ever shows. */
+export function patchLibrary(client: QueryClient, fn: (prev: LibraryData) => LibraryData) {
+ const mode = getBackend().kind;
+ const next = client.setQueryData<LibraryData>(libraryKey(mode), (prev) =>
+ prev ? fn(prev) : prev
+ );
+ if (next) writeSnapshot(snapshotKey(mode, "library"), next);
+}
+
+/** Pull a residency's listing again — for the changes only the server can
+ * describe, like the size and duration a duplicate came out at. */
+export function refetchProjects(client: QueryClient, r: Residency) {
+ return client.invalidateQueries({ queryKey: projectsKey(r) });
+}
+
+export function refetchLibrary(client: QueryClient) {
+ return client.invalidateQueries({ queryKey: libraryKey(getBackend().kind) });
+}
diff --git a/site/src/cut/lib/residency.ts b/site/src/cut/lib/residency.ts
index f5baea58..ebeb6322 100644
--- a/site/src/cut/lib/residency.ts
+++ b/site/src/cut/lib/residency.ts
@@ -13,7 +13,9 @@ export async function resolveProjectMode(projectId: string): Promise<CutMode> {
if (!webModeEnabled()) return "local";
if (!servedFromEngine() && !engineOrigin()) return "cloud";
try {
- const res = await localBackend.fetch(`/api/cut/projects/${projectId}`);
+ // 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";
} catch {
// The engine dropped since the gate probed it; the cloud copy (if any)
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index 5bca542c..6c48c6c4 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -30,11 +30,18 @@ import { fillSlot } from "./genvideo/fillSlot";
import { apiFetch, apiJson, getBackend } from "./backend";
import { fetchSignedMediaUrls } from "./backend/cloud";
import { markSignedBatch } from "./mediaLinks";
+import {
+ dropCachedDoc,
+ readCachedDoc,
+ readCachedMediaLinks,
+ writeCachedDoc,
+ writeCachedMediaLinks,
+} from "./docCache";
import { cloudTranscribeSpec, type CloudTranscribeSpec } from "./cloudTranscribe";
import { trackLocale } from "./subtitles";
import { ANIM_STYLE_IDS, emptySubtitles, IMAGE_CLIP_SECONDS, LOOK_IDS, MAX_SUBTITLE_LANES, mediaUrl, migrateLegacyTransitions, normalizeAspect, SPEED_FLOOR, SPEED_MIN, TRANSITION_MAX } from "./types";
import { readTextStyle } from "./textStyle";
-import { loadUiState, saveUiState } from "./uiState";
+import { loadUiState, saveUiState, type ProjectUiState } from "./uiState";
import { captureTimelineFrames } from "./visualFrames";
const uid = () => crypto.randomUUID().slice(0, 8);
@@ -100,6 +107,11 @@ export interface EditorState {
projectId: string | null;
projectName: string;
loaded: boolean;
+ /** Bumped every time a document is hydrated into the store — the cached
+ * copy an open paints first, the live one that replaces it, a conflict
+ * reload. Autosave watches it to re-baseline, so a document that arrived
+ * from the server is never saved straight back to it. */
+ loadEpoch: number;
loadError: string | null;
saveState: SaveState;
/** Read-only shared view: the set wrapper strips doc-mutating writes, so
@@ -783,6 +795,7 @@ export const useEditor = create<EditorState>((baseSet, get) => {
projectId: null,
projectName: "",
loaded: false,
+ loadEpoch: 0,
loadError: null,
saveState: "saved",
readOnly: false,
@@ -819,6 +832,10 @@ export const useEditor = create<EditorState>((baseSet, get) => {
renders: [],
loadProject: async (id) => {
+ // Re-reading a project already on screen — a viewer's change poll, a
+ // conflict reload. The whole point of those is that the stored copy has
+ // moved on, so the snapshot below is exactly the wrong thing to paint.
+ const reloading = get().projectId === id && get().loaded;
history.length = 0;
future.length = 0;
pending = null;
@@ -863,28 +880,16 @@ export const useEditor = create<EditorState>((baseSet, get) => {
// the drain and the fetch below. Lazy import: docWriter reads store
// helpers, so a static import would be a cycle.
await import("./genvideo/docWriter").then((m) => m.docWriterIdle(id)).catch(() => {});
- try {
- const [res, ui] = await Promise.all([apiFetch(`/api/cut/projects/${id}`), loadUiState(id)]);
- if (!res.ok) throw new Error("This project no longer exists.");
- const doc = (await res.json()) as ProjectDoc;
- const assets: MediaAsset[] = doc.assets.map((a) => ({
- ...a,
- url: mediaUrl(id, a.fileName),
- }));
- // Cloud and shared media ride signed R2 URLs, batch-minted once per
- // load; the /media route's 302 stays the fallback for anything the
- // mint misses. mediaLinks re-mints the batch as it nears expiry.
- if (getBackend().kind !== "local") {
- const signed = await fetchSignedMediaUrls(id, assets.map((a) => a.fileName));
- for (const a of assets) a.url = signed.urls.get(a.fileName) ?? a.url;
- markSignedBatch(id, signed.expiresAt);
- } else {
- markSignedBatch(id, null);
- }
+
+ // One shape of hydration, used by both the snapshot painted below and
+ // the live document that replaces it, so the legacy migrations happen
+ // once per document rather than once per code path.
+ const hydrate = (doc: Partial<ProjectDoc>, assets: MediaAsset[], ui: ProjectUiState) => {
+ const docClips = doc.clips ?? [];
// Older docs stored video track 0 packed (array order implied the
// position); bake explicit starts in once so every clip is free-placed.
- const legacy = (doc.clips as LegacyClip[]).some((c) => typeof c.start !== "number");
- const folded = (legacy ? packStarts(doc.clips as LegacyClip[]) : doc.clips).map((c) => ({
+ const legacy = (docClips as LegacyClip[]).some((c) => typeof c.start !== "number");
+ const folded = (legacy ? packStarts(docClips as LegacyClip[]) : docClips).map((c) => ({
...c,
track: c.track ?? 0,
}));
@@ -911,11 +916,11 @@ export const useEditor = create<EditorState>((baseSet, get) => {
const merged = migrateLegacyTransitions(lifted);
hydrating = true;
set({
- projectName: doc.name,
+ projectName: doc.name ?? "",
assets,
clips: merged,
- audioClips: doc.audioClips,
- overlays: doc.overlays,
+ audioClips: doc.audioClips ?? [],
+ overlays: doc.overlays ?? [],
templates: doc.templates ?? [],
aspect: normalizeAspect(doc.aspect) ?? "9:16",
aspectTouched: doc.aspect !== undefined,
@@ -944,9 +949,109 @@ export const useEditor = create<EditorState>((baseSet, get) => {
genvideo: doc.genvideo ?? undefined,
renders: Array.isArray(doc.renders) ? doc.renders : [],
loaded: true,
+ loadEpoch: get().loadEpoch + 1,
});
+ hydrating = false;
+ };
+
+ // The live document goes out first, so everything below is a head start
+ // on it and never a substitute for it.
+ const docReq = apiFetch(`/api/cut/projects/${id}`);
+ const uiReq = loadUiState(id);
+ let landed = false;
+ const settle = () => {
+ landed = true;
+ };
+ void docReq.then(settle, settle);
+
+ // Paint the copy this browser last held. It is written on load and on
+ // every successful save, so for the ordinary case — reopening your own
+ // project — it is the document, and the editor draws on the next frame
+ // instead of a round trip later. Whether it is still on screen when the
+ // live document arrives decides how that one is applied.
+ let paintedFromCache = false;
+ try {
+ const [cached, ui] = reloading
+ ? [null, null]
+ : await Promise.all([readCachedDoc(id), uiReq]);
+ const stored = cached?.value;
+ const openable = () => !landed && get().projectId === id && !get().loaded;
+ if (stored && ui && openable()) {
+ const stale = stored.assets ?? [];
+ // Signed R2 links are cached alongside the doc, so a snapshot open
+ // hands its clips the very URLs the live load is about to hand
+ // them: identical strings, so nothing reloads when it lands.
+ const links =
+ getBackend().kind === "local"
+ ? null
+ : await readCachedMediaLinks(id, stale.map((a) => a.fileName));
+ if (openable()) {
+ hydrate(
+ stored,
+ stale.map((a) => ({ ...a, url: links?.urls.get(a.fileName) ?? mediaUrl(id, a.fileName) })),
+ ui
+ );
+ // Keep the re-mint schedule honest even if the live load never
+ // arrives: these links do expire.
+ markSignedBatch(id, links?.expiresAt ?? null);
+ paintedFromCache = true;
+ }
+ }
+ } catch {
+ // A snapshot miss costs a spinner and nothing else.
+ }
+
+ try {
+ const [res, ui] = await Promise.all([docReq, uiReq]);
+ if (!res.ok) {
+ // Gone, or no longer ours to read: the server is the authority on
+ // that, so retire the snapshot and show the error even when it is
+ // already on screen. Any other status is a server having a bad
+ // moment, which is the same case as not reaching it at all.
+ if ([401, 403, 404].includes(res.status)) {
+ dropCachedDoc(id);
+ set({ loaded: false, loadError: "This project no longer exists." });
+ return;
+ }
+ throw new Error("This project could not be loaded.");
+ }
+ const doc = (await res.json()) as ProjectDoc;
+ writeCachedDoc(id, doc);
+ const assets: MediaAsset[] = doc.assets.map((a) => ({
+ ...a,
+ url: mediaUrl(id, a.fileName),
+ }));
+ // Cloud and shared media ride signed R2 URLs, batch-minted once per
+ // load; the /media route's 302 stays the fallback for anything the
+ // mint misses. mediaLinks re-mints the batch as it nears expiry.
+ if (getBackend().kind !== "local") {
+ const signed = await fetchSignedMediaUrls(id, assets.map((a) => a.fileName));
+ for (const a of assets) a.url = signed.urls.get(a.fileName) ?? a.url;
+ markSignedBatch(id, signed.expiresAt);
+ writeCachedMediaLinks(id, signed.urls, signed.expiresAt);
+ } else {
+ markSignedBatch(id, null);
+ }
+ // The snapshot is on screen and has already been edited on top of —
+ // an undoable edit, or a project-level one like a rename that autosave
+ // has already marked dirty. Replacing it would throw that work away,
+ // so only the media links go in; the edits don't touch them and they
+ // do expire. The edits save as usual, and a stored copy that really
+ // has moved on answers that save with a conflict, which reloads
+ // through this same path.
+ if (paintedFromCache && (history.length > 0 || get().saveState !== "saved")) {
+ get().applyMediaUrls(new Map(assets.map((a) => [a.fileName, a.url])));
+ return;
+ }
+ hydrate(doc, assets, ui);
} catch (err) {
- set({ loadError: err instanceof Error ? err.message : String(err) });
+ // Couldn't reach the server. A snapshot already on screen is the
+ // better answer than an error page: the project is open and editable,
+ // a version behind at worst, and autosave retries until the link is
+ // back.
+ if (!paintedFromCache) {
+ set({ loadError: err instanceof Error ? err.message : String(err) });
+ }
} finally {
hydrating = false;
}
diff --git a/site/src/cut/lib/uiState.ts b/site/src/cut/lib/uiState.ts
index 622f1786..dc19264f 100644
--- a/site/src/cut/lib/uiState.ts
+++ b/site/src/cut/lib/uiState.ts
@@ -2,6 +2,8 @@
import { useCallback, useState } from "react";
+import { openCutDb } from "./cache";
+
/**
* Per-project view state (zoom level, timeline panel height) — how this
* browser looks at a project, not part of the cut. Stored in IndexedDB
@@ -15,23 +17,11 @@ export interface ProjectUiState {
timelineH?: number;
}
-const DB_NAME = "cut";
const STORE = "project-ui";
-function openDb(): Promise<IDBDatabase> {
- return new Promise((resolve, reject) => {
- const req = indexedDB.open(DB_NAME, 1);
- req.onupgradeneeded = () => {
- if (!req.result.objectStoreNames.contains(STORE)) req.result.createObjectStore(STORE);
- };
- req.onsuccess = () => resolve(req.result);
- req.onerror = () => reject(req.error);
- });
-}
-
export async function loadUiState(projectId: string): Promise<ProjectUiState> {
try {
- const db = await openDb();
+ const db = await openCutDb();
return await new Promise((resolve) => {
const req = db.transaction(STORE).objectStore(STORE).get(projectId);
req.onsuccess = () => resolve((req.result as ProjectUiState) ?? {});
@@ -51,7 +41,7 @@ async function flush() {
pending = null;
if (!job) return;
try {
- const db = await openDb();
+ const db = await openCutDb();
const tx = db.transaction(STORE, "readwrite");
const store = tx.objectStore(STORE);
const req = store.get(job.projectId);