Skip to content

Open source CapCut alternative.

TypeScript

fix(site): serialize doc saves and resume unsaved edits from disk [rebuild]

David Le1d1e8acfb5be
diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsx
index 27cbd80f..bd562523 100644
--- a/site/src/cut/components/Editor.tsx
+++ b/site/src/cut/components/Editor.tsx
@@ -11,8 +11,9 @@ import {
releaseCutMode,
subscribeCutMode,
} from "@/cut/lib/backend";
+import { knownDocVersion } from "@/cut/lib/backend/cloud";
import { loadedDocVersion } from "@/cut/lib/backend/shared";
-import { writeCachedDoc } from "@/cut/lib/docCache";
+import { flushCachedDocWrites, writeCachedDoc, writeCachedDocDirty } from "@/cut/lib/docCache";
import {
refreshShareCard,
refreshShareLadder,
@@ -408,11 +409,39 @@ export function Editor({
if (timer) clearTimeout(timer);
timer = setTimeout(() => void save(), 2000 * 2 ** (failures - 1));
};
+ // One save on the wire at a time: an edit landing mid-save queues one
+ // trailing save that captures the state as it stands then, instead of
+ // racing a second PUT alongside the first — the engine would apply the
+ // two in whichever order they arrive, and the cloud would answer the
+ // second with a conflict against this same session's write.
+ let inFlight = false;
+ let queued = false;
+ // Bumped on every edit. A save that succeeds only rewrites the disk
+ // snapshot clean when no edit landed while it was on the wire — a newer
+ // dirty record must not be overwritten by the older doc the save carried.
+ let editSeq = 0;
const save = async () => {
+ if (inFlight) {
+ queued = true;
+ return;
+ }
+ inFlight = true;
+ try {
+ await putDoc();
+ } finally {
+ inFlight = false;
+ if (queued) {
+ queued = false;
+ void save();
+ }
+ }
+ };
+ const putDoc = async () => {
const s = useEditor.getState();
if (!s.loaded || s.projectId !== projectId) return;
s.setSaveState("saving");
const doc = serializeDoc(s);
+ const seqAtSend = editSeq;
try {
const res = await apiFetch(`/api/cut/projects/${projectId}`, {
method: "PUT",
@@ -424,7 +453,7 @@ export function Editor({
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);
+ if (editSeq === seqAtSend) writeCachedDoc(projectId, doc);
return;
}
useEditor.getState().setSaveState("error");
@@ -463,6 +492,15 @@ export function Editor({
assetsChanged(s.assets);
return;
}
+ // The open resumed unsaved edits from the dirty disk snapshot: the
+ // document on screen is already ahead of the server, so push it up
+ // without waiting for a fresh edit.
+ if (s.resumePush) {
+ useEditor.setState({ resumePush: false });
+ if (timer) clearTimeout(timer);
+ timer = setTimeout(() => void save(), 800);
+ return;
+ }
// Evaluated every tick (not short-circuited) so the asset baseline
// advances even when another slice triggered this save.
const assetsDirty = assetsChanged(s.assets);
@@ -493,13 +531,24 @@ export function Editor({
if (!changed) return;
last = serializeDoc(s);
lastName = s.projectName;
+ editSeq++;
+ // Every edit lands on disk marked dirty before it lands on the server,
+ // with the version it was edited on top of: a crash or a closed tab
+ // inside the debounce window resumes on the next open instead of
+ // losing the edit.
+ writeCachedDocDirty(projectId, last, knownDocVersion(projectId));
if (s.saveState !== "saving") s.setSaveState("dirty");
if (timer) clearTimeout(timer);
timer = setTimeout(() => void save(), 800);
});
+ // Coalesced dirty writes land now or not at all when the page goes away.
+ const onPageHide = () => flushCachedDocWrites();
+ window.addEventListener("pagehide", onPageHide);
return () => {
unsub();
if (timer) clearTimeout(timer);
+ window.removeEventListener("pagehide", onPageHide);
+ flushCachedDocWrites();
};
}, [projectId, viewer]);
diff --git a/site/src/cut/lib/backend/cloud.ts b/site/src/cut/lib/backend/cloud.ts
index 11d1802f..9e08dd3a 100644
--- a/site/src/cut/lib/backend/cloud.ts
+++ b/site/src/cut/lib/backend/cloud.ts
@@ -14,6 +14,44 @@ const cloudPath = (path: string) => path.replace(/^\/api\/cut\//, "/api/cut-clou
// keep the engine's unversioned shapes.
const docVersions = new Map<string, string>();
+// Versions only grow, so the map keeps the newest it has seen. A GET response
+// that lands after a save carries the version from before it — writing that
+// back would make the next PUT report a conflict against this same session.
+function noteVersion(projectId: string, v: string | number | undefined | null) {
+ if (v === undefined || v === null) return;
+ const next = Number(v);
+ const known = Number(docVersions.get(projectId));
+ if (!Number.isFinite(next)) return;
+ if (!Number.isFinite(known) || next > known) docVersions.set(projectId, String(next));
+}
+
+/** The doc version the transport last saw acknowledged for a project — what a
+ * dirty snapshot records as the base its edits were made on top of. */
+export function knownDocVersion(projectId: string): string | null {
+ return docVersions.get(projectId) ?? null;
+}
+
+// A dirty snapshot resumed from disk was edited on top of a specific version.
+// Its push must carry that base — not whatever version the open's own GET
+// just reported — so a server copy that moved on answers 409 instead of being
+// silently overwritten. The pin holds until a PUT settles (ok or conflict);
+// transient failures keep it, so the retry still carries the base.
+const basePins = new Map<string, string>();
+
+export function pinDocBase(projectId: string, version: string | null) {
+ if (version === null) basePins.delete(projectId);
+ else basePins.set(projectId, version);
+}
+
+// One doc PUT on the wire per project: each waits for the one before it and
+// reads the version at dispatch. Two saves in flight would carry the same ?v=
+// and the later one would 409 against its own session's write.
+const putChains = new Map<string, Promise<unknown>>();
+
+// Doc GETs in flight, so a PUT racing the open never goes out unversioned —
+// an unversioned PUT is first-save semantics and would apply unconditionally.
+const docGets = new Map<string, Promise<void>>();
+
// /projects/:id only — /projects/folders is the folder collection, not a doc.
const PROJECT_DOC = /^\/api\/cut\/projects\/(?!folders$)([^/?]+)$/;
@@ -24,21 +62,40 @@ async function cloudFetch(path: string, init?: RequestInit): Promise<Response> {
const projectId = decodeURIComponent(doc[1]);
if (method === "GET") {
- const res = await fetch(cloudPath(path), init);
- const version = res.headers.get("x-cut-doc-version");
- if (res.ok && version) docVersions.set(projectId, version);
- return res;
+ const req = fetch(cloudPath(path), init);
+ const tracked = req.then(
+ (res) => {
+ if (res.ok) noteVersion(projectId, res.headers.get("x-cut-doc-version"));
+ },
+ () => {}
+ );
+ docGets.set(projectId, tracked);
+ void tracked.then(() => {
+ if (docGets.get(projectId) === tracked) docGets.delete(projectId);
+ });
+ return req;
}
- // A PUT with no known version is the first save; it succeeds unconditionally.
- const v = docVersions.get(projectId);
+ const prev = putChains.get(projectId) ?? Promise.resolve();
+ const run = prev.then(() => putDoc(projectId, path, init));
+ // The chain survives a failed link; the failure is the caller's to handle.
+ putChains.set(projectId, run.catch(() => undefined));
+ return run;
+}
+
+async function putDoc(projectId: string, path: string, init?: RequestInit): Promise<Response> {
+ await docGets.get(projectId);
+ // A pinned base outranks the map; with neither, an unversioned PUT is the
+ // first save and succeeds unconditionally.
+ const v = basePins.get(projectId) ?? docVersions.get(projectId);
const res = await fetch(cloudPath(path) + (v ? `?v=${encodeURIComponent(v)}` : ""), init);
+ if (res.ok || res.status === 409) basePins.delete(projectId);
if (res.status === 409) {
const body = (await res
.clone()
.json()
.catch(() => null)) as { doc?: unknown; version?: number | string } | null;
- if (body?.version !== undefined) docVersions.set(projectId, String(body.version));
+ noteVersion(projectId, body?.version);
window.dispatchEvent(
new CustomEvent("cut-cloud-doc-conflict", {
detail: { projectId, doc: body?.doc, version: body?.version },
@@ -49,7 +106,7 @@ async function cloudFetch(path: string, init?: RequestInit): Promise<Response> {
.clone()
.json()
.catch(() => null)) as { version?: number | string } | null;
- if (body?.version !== undefined) docVersions.set(projectId, String(body.version));
+ noteVersion(projectId, body?.version);
}
return res;
}
diff --git a/site/src/cut/lib/docCache.ts b/site/src/cut/lib/docCache.ts
index fc21feda..90a922c8 100644
--- a/site/src/cut/lib/docCache.ts
+++ b/site/src/cut/lib/docCache.ts
@@ -8,12 +8,14 @@
* 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.
+ * The document snapshot is also the editor's crash ledger: every edit rewrites
+ * it marked dirty, alongside the version it was edited on top of, and a
+ * successful save rewrites it clean. A snapshot that is clean is a head start
+ * and never the truth — the live document lands and replaces it. A snapshot
+ * that is dirty is unsaved work: the open resumes it and pushes it up, unless
+ * the server has moved past its base version, in which case the server wins
+ * like any conflict.
*/
import { getBackend } from "./backend";
@@ -30,15 +32,80 @@ const linksKey = (projectId: string, kind: CutMode) => snapshotKey(kind, "media-
export type CachedDoc = Partial<ProjectDoc>;
-export function readCachedDoc(projectId: string, kind = getBackend().kind) {
- return readSnapshot<CachedDoc>(docKey(projectId, kind));
+/** On-disk shape. Older records stored the bare doc; both read back. */
+type StoredDoc = { doc: CachedDoc; dirty?: boolean; baseVersion?: string | null };
+
+export type CachedDocHit = {
+ doc: CachedDoc;
+ at: number;
+ /** Edits the server never acknowledged. */
+ dirty: boolean;
+ /** The doc version the dirty edits were made on top of; null for a local
+ * project (the engine has no versions) or edits made before one was known. */
+ baseVersion: string | null;
+};
+
+export async function readCachedDoc(
+ projectId: string,
+ kind = getBackend().kind
+): Promise<CachedDocHit | null> {
+ const hit = await readSnapshot<StoredDoc | CachedDoc>(docKey(projectId, kind));
+ if (!hit) return null;
+ const v = hit.value as StoredDoc;
+ if (v && typeof v === "object" && "doc" in v && v.doc && typeof v.doc === "object") {
+ return { doc: v.doc, at: hit.at, dirty: v.dirty === true, baseVersion: v.baseVersion ?? null };
+ }
+ return { doc: hit.value as CachedDoc, at: hit.at, dirty: false, baseVersion: null };
+}
+
+// A drag can commit dozens of states a second; dirty writes trail-coalesce so
+// the disk sees the latest state a beat later instead of every intermediate
+// one. Clean writes land immediately and cancel whatever is pending — a save
+// that succeeded must not be re-marked dirty by a write it already covers.
+const DIRTY_WRITE_DELAY_MS = 150;
+const dirtyPending = new Map<string, StoredDoc>();
+const dirtyTimers = new Map<string, ReturnType<typeof setTimeout>>();
+
+function cancelDirtyWrite(key: string) {
+ const timer = dirtyTimers.get(key);
+ if (timer) clearTimeout(timer);
+ dirtyTimers.delete(key);
+ dirtyPending.delete(key);
+}
+
+function flushDirtyWrite(key: string) {
+ const value = dirtyPending.get(key);
+ cancelDirtyWrite(key);
+ if (value) writeSnapshot(key, value);
}
export function writeCachedDoc(projectId: string, doc: CachedDoc, kind = getBackend().kind) {
- writeSnapshot(docKey(projectId, kind), doc);
+ const key = docKey(projectId, kind);
+ cancelDirtyWrite(key);
+ writeSnapshot(key, { doc } satisfies StoredDoc);
+}
+
+export function writeCachedDocDirty(
+ projectId: string,
+ doc: CachedDoc,
+ baseVersion: string | null,
+ kind = getBackend().kind
+) {
+ const key = docKey(projectId, kind);
+ dirtyPending.set(key, { doc, dirty: true, baseVersion } satisfies StoredDoc);
+ if (!dirtyTimers.has(key)) {
+ dirtyTimers.set(key, setTimeout(() => flushDirtyWrite(key), DIRTY_WRITE_DELAY_MS));
+ }
+}
+
+/** Land every pending dirty write now — the page is going away, or the editor
+ * is closing and its coalescing timers are about to be torn down. */
+export function flushCachedDocWrites() {
+ for (const key of [...dirtyTimers.keys()]) flushDirtyWrite(key);
}
export function dropCachedDoc(projectId: string, kind = getBackend().kind) {
+ cancelDirtyWrite(docKey(projectId, kind));
dropSnapshot(docKey(projectId, kind));
dropSnapshot(linksKey(projectId, kind));
}
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index 054f2e5c..de726e2f 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -28,7 +28,7 @@ import type {
import type { VideoProject } from "./genvideo/types";
import { fillSlot } from "./genvideo/fillSlot";
import { apiFetch, apiJson, getBackend, hasLocalCompute } from "./backend";
-import { fetchSignedMediaUrls } from "./backend/cloud";
+import { fetchSignedMediaUrls, pinDocBase } from "./backend/cloud";
import { markSignedBatch } from "./mediaLinks";
import {
dropCachedDoc,
@@ -117,6 +117,9 @@ export interface EditorState {
loadEpoch: number;
loadError: string | null;
saveState: SaveState;
+ /** Raised when an open resumed unsaved edits from the dirty disk snapshot:
+ * autosave sees it, clears it, and pushes the resumed document up. */
+ resumePush: boolean;
/** Read-only shared view: the set wrapper strips doc-mutating writes, so
* every edit path is inert by construction. View state stays live. */
readOnly: boolean;
@@ -836,6 +839,7 @@ export const useEditor = create<EditorState>((baseSet, get) => {
loadEpoch: 0,
loadError: null,
saveState: "saved",
+ resumePush: false,
readOnly: false,
sharedFeatures: null,
@@ -890,6 +894,7 @@ export const useEditor = create<EditorState>((baseSet, get) => {
loaded: false,
loadError: null,
saveState: "saved",
+ resumePush: false,
assets: [],
clips: [],
audioClips: [],
@@ -1013,11 +1018,15 @@ export const useEditor = create<EditorState>((baseSet, get) => {
// 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;
+ // The painted snapshot held unsaved edits: they resume as the document,
+ // and autosave pushes them back up.
+ let paintedDirty = false;
+ let dirtyBase: string | null = null;
try {
const [cached, ui] = inPlace
? [null, null]
: await Promise.all([readCachedDoc(id), uiReq]);
- const stored = cached?.value;
+ const stored = cached?.doc;
const openable = () => !landed && get().projectId === id && !get().loaded;
if (stored && ui && openable()) {
const stale = stored.assets ?? [];
@@ -1038,6 +1047,15 @@ export const useEditor = create<EditorState>((baseSet, get) => {
// arrives: these links do expire.
markSignedBatch(id, links?.expiresAt ?? null);
paintedFromCache = true;
+ if (cached?.dirty && !get().readOnly) {
+ paintedDirty = true;
+ dirtyBase = cached.baseVersion;
+ // The push must carry the version these edits were made on top
+ // of, so a server copy that moved on answers 409 instead of
+ // being overwritten. Pinned now, before any save can dispatch.
+ if (getBackend().kind === "cloud") pinDocBase(id, dirtyBase);
+ set({ saveState: "dirty", resumePush: true });
+ }
}
}
} catch {
@@ -1052,14 +1070,14 @@ export const useEditor = create<EditorState>((baseSet, get) => {
// 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)) {
+ pinDocBase(id, null);
dropCachedDoc(id);
- set({ loaded: false, loadError: "This project no longer exists." });
+ set({ loaded: false, loadError: "This project no longer exists.", resumePush: false });
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),
@@ -1075,17 +1093,35 @@ export const useEditor = create<EditorState>((baseSet, get) => {
} 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")) {
+ // A dirty snapshot resumes only onto the version its edits were made
+ // on top of. The server having moved past that base is a conflict,
+ // and the server wins it the way it wins any conflict — even over
+ // edits made in the seconds since the resume painted, which were
+ // built on the losing base.
+ const serverVersion = res.headers.get("x-cut-doc-version");
+ const staleDirty =
+ paintedDirty && getBackend().kind === "cloud" && dirtyBase !== serverVersion;
+ if (staleDirty) {
+ pinDocBase(id, null);
+ set({ saveState: "saved", resumePush: false });
+ }
+ // The snapshot is on screen and is the newer document — resumed
+ // unsaved work, an undoable edit made since it painted, 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 &&
+ !staleDirty &&
+ (paintedDirty || history.length > 0 || get().saveState !== "saved")
+ ) {
get().applyMediaUrls(new Map(assets.map((a) => [a.fileName, a.url])));
return;
}
+ writeCachedDoc(id, doc);
hydrate(doc, assets, ui);
} catch (err) {
// Couldn't reach the server. A snapshot already on screen is the