Skip to content

Open source CapCut alternative.

TypeScript

feat(site): browser residency joins the shelf as Local

David Le5a70c9163648
diff --git a/site/src/cut/components/LibraryView.tsx b/site/src/cut/components/LibraryView.tsx
index 286a48d4..121e7ff7 100644
--- a/site/src/cut/components/LibraryView.tsx
+++ b/site/src/cut/components/LibraryView.tsx
@@ -68,7 +68,12 @@ import {
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 {
+ availableResidencies,
+ libraryResidencies,
+ RESIDENCY_LABEL,
+ type Residency,
+} from "@/cut/lib/residency";
import { TemplateCard } from "./TemplateCard";
import { homeHref, useCutBase } from "@/cut/lib/nav";
import { useRevealFlash } from "@/cut/lib/refReveal";
@@ -98,7 +103,7 @@ export function ShelfBadge({
const Icon = residency === "cloud" ? Cloud : Laptop;
return (
<span
- title={offline ? "On this Mac — open the Donkey app to use it" : RESIDENCY_LABEL[residency]}
+ title={offline ? "Local — open the Donkey app to use it" : RESIDENCY_LABEL[residency]}
className={className}
>
<Icon className="size-3" />
@@ -592,7 +597,7 @@ export function LibraryCard({
const videoRef = useRef<HTMLVideoElement>(null);
const { flash, attachReveal } = useRevealFlash("library", a.id);
// With one shelf listed, every card is on it — the badge would say nothing.
- const bothShelves = availableResidencies().length > 1 || offline;
+ const bothShelves = libraryResidencies(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.
diff --git a/site/src/cut/components/NewProjectButton.tsx b/site/src/cut/components/NewProjectButton.tsx
index 3f841c0a..5383c346 100644
--- a/site/src/cut/components/NewProjectButton.tsx
+++ b/site/src/cut/components/NewProjectButton.tsx
@@ -19,7 +19,11 @@ import { useNewProjectTarget } from "@/cut/lib/newProject";
import { RESIDENCY_LABEL, type Residency } from "@/cut/lib/residency";
import { cn } from "@/lib/utils";
-const RESIDENCY_ICON: Record<Residency, typeof Cloud> = { local: Laptop, cloud: Cloud };
+const RESIDENCY_ICON: Record<Residency, typeof Cloud> = {
+ local: Laptop,
+ cloud: Cloud,
+ browser: Laptop,
+};
// The picker is one switch for the whole app, and its tooltip is where that
// scope is stated: everything that lands on the shelf, then the shelf itself in
@@ -28,8 +32,9 @@ const RESIDENCY_ICON: Record<Residency, typeof Cloud> = { local: Laptop, cloud:
// names.
const RESIDENCY_LEAD = "All projects and media created going";
const RESIDENCY_SCOPE: Record<Residency, { tail: string; place: string }> = {
- local: { tail: "forward will be stored on", place: "this Mac" },
+ local: { tail: "forward will be stored on", place: "this device" },
cloud: { tail: "forward will be stored on the", place: "Cloud" },
+ browser: { tail: "forward will be stored on", place: "this device" },
};
/**
diff --git a/site/src/cut/components/ProjectsHome.tsx b/site/src/cut/components/ProjectsHome.tsx
index 6f892435..9c1925e6 100644
--- a/site/src/cut/components/ProjectsHome.tsx
+++ b/site/src/cut/components/ProjectsHome.tsx
@@ -77,6 +77,7 @@ import { clearProjectThreads } from "@/cut/lib/chatThreads";
import { useGenerate } from "@/cut/lib/generate";
import { useGenScene } from "@/cut/lib/genScene";
import { createProjectFromFile, isMediaFile } from "@/cut/lib/media";
+import { dropLocalProjectCopy, localMediaUrl } from "@/cut/lib/mediaSync";
import { copyProjectAcross } from "@/cut/lib/projectCopy";
import { homeHref, projectHref, useCutBase } from "@/cut/lib/nav";
import { daysUntil, formatTime } from "@/cut/lib/time";
@@ -130,6 +131,7 @@ function formatDate(ts: number) {
const RESIDENCY_HINT: Record<Residency, string> = {
local: "This is a local project",
cloud: "This is a cloud project",
+ browser: "This is a local project",
};
const OFFLINE_HINT = "This is a local project — open the Donkey app to edit it";
@@ -204,8 +206,9 @@ export function ProjectsHome() {
const router = useRouter();
const base = useCutBase();
const mode = useCutMode();
- // The home never runs in shared mode; anything non-cloud lists as local.
- const homeMode: Residency = mode === "cloud" ? "cloud" : "local";
+ // The home never runs in shared mode; anything else lists as local.
+ const homeMode: Residency =
+ mode === "cloud" ? "cloud" : mode === "browser" ? "browser" : "local";
// 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.
@@ -216,7 +219,20 @@ export function ProjectsHome() {
// 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 live = useCallback((r: Residency) => r !== "local" || engineUp, [engineUp]);
+ // A project moves between the two places the user thinks in: Local and
+ // Cloud. The two local kinds are the same place, so a local-kind project
+ // only offers the Cloud, and a cloud project offers one local kind — the
+ // Mac engine when it is up, this browser's storage otherwise.
+ const moveDests = useCallback(
+ (from: Residency): Residency[] => {
+ if (from !== "cloud") return residencies.includes("cloud") ? ["cloud"] : [];
+ const local = residencies.filter((d) => d !== "cloud" && live(d));
+ if (local.includes("local")) return ["local"];
+ return local;
+ },
+ [residencies, live]
+ );
const client = useQueryClient();
// Hooks can't run in a loop, so both sections are always wired and the
@@ -229,6 +245,10 @@ export function ProjectsHome() {
list: residencies.includes("cloud"),
live: true,
});
+ const browserSection = useProjectsSection("browser", {
+ list: residencies.includes("browser"),
+ live: residencies.includes("browser"),
+ });
const asSection = (q: typeof localSection): SectionData => ({
projects: q.data?.projects ?? null,
folders: q.data?.folders ?? [],
@@ -239,6 +259,7 @@ export function ProjectsHome() {
const data: Record<Residency, SectionData> = {
local: asSection(localSection),
cloud: asSection(cloudSection),
+ browser: asSection(browserSection),
};
// Optimistic edits to a section's cached listing; the next revalidation
@@ -477,11 +498,10 @@ export function ProjectsHome() {
}
};
- // Move a project to the other residency: copy it across (projectCopy.ts does
+ // Move a project to another residency: copy it across (projectCopy.ts does
// the doc + media transfer and cleans up a half-made copy itself), then drop
// 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";
+ const moveAcross = async (source: Residency, dest: Residency, p: ProjectSummary) => {
if (!live(source) || !live(dest)) return;
setDupError(null);
setBusy(true);
@@ -491,8 +511,9 @@ export function ProjectsHome() {
.fetch(`/api/cut/projects/${p.id}`, { method: "DELETE" })
.catch(() => {});
// The chat history moved with the project; the old project's copy goes
- // with the project itself.
+ // with the project itself, as does a cloud project's browser-store copy.
clearProjectThreads(p.id);
+ if (source === "cloud") void dropLocalProjectCopy(p.id);
await Promise.all([refresh(source), refresh(dest)]);
} catch (e) {
setDupError(e instanceof Error && e.message ? e.message : "Could not move the project.");
@@ -518,6 +539,7 @@ export function ProjectsHome() {
useGenerate.getState().cancelForOwner({ projectId: id });
clearProjectThreads(id);
dropCachedDoc(id, residency);
+ if (residency === "cloud") void dropLocalProjectCopy(id);
patch(residency, (s) => ({ ...s, projects: s.projects.filter((p) => p.id !== id) }));
setDeleting(null);
} finally {
@@ -659,14 +681,8 @@ export function ProjectsHome() {
setRenaming({ project: p, residency: r });
}}
onDuplicate={() => void duplicate(r, p)}
- moveTo={
- dual && engineUp
- ? {
- target: r === "cloud" ? "local" : "cloud",
- run: () => void moveAcross(r, p),
- }
- : undefined
- }
+ moveTo={moveDests(r)
+ .map((d) => ({ target: d, run: () => void moveAcross(r, d, p) }))}
onDelete={() => setDeleting({ project: p, residency: r })}
/>
)}
@@ -734,14 +750,8 @@ export function ProjectsHome() {
setRenaming({ project: p, residency: r });
}}
onDuplicate={() => void duplicate(r, p)}
- moveTo={
- dual && engineUp
- ? {
- target: r === "cloud" ? "local" : "cloud",
- run: () => void moveAcross(r, p),
- }
- : undefined
- }
+ moveTo={moveDests(r)
+ .map((d) => ({ target: d, run: () => void moveAcross(r, d, p) }))}
onDelete={() => setDeleting({ project: p, residency: r })}
/>
) : (
@@ -1019,8 +1029,25 @@ function CardPreview({
// out of IndexedDB a moment after that.
const [decoded, setDecoded] = useState(false);
const backend = backendFor(residency);
+ // A browser-resident card's media lives in the OPFS store, and blob URLs
+ // are session-scoped: a fresh tab holds none until this mints one. Until it
+ // resolves the card shows its cached poster, like an offline shelf.
+ const [storeUrl, setStoreUrl] = useState<string | null>(null);
+ const previewFile = p.previewFile;
+ useEffect(() => {
+ if (residency !== "browser" || !previewFile) return;
+ let alive = true;
+ void localMediaUrl(p.id, previewFile).then((u) => {
+ if (alive && u) setStoreUrl(u);
+ });
+ return () => {
+ alive = false;
+ };
+ }, [residency, p.id, previewFile]);
const fileUrl = (file: string) =>
- backend.url(`/api/cut/projects/${p.id}/media/${encodeURIComponent(file)}`);
+ residency === "browser"
+ ? (storeUrl ?? "")
+ : backend.url(`/api/cut/projects/${p.id}/media/${encodeURIComponent(file)}`);
if (offline) {
return poster ? (
@@ -1042,6 +1069,20 @@ function CardPreview({
);
}
+ if (residency === "browser" && !storeUrl) {
+ 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" />
+ );
+ }
+
// The proxy starts at the edit's first frame; the source starts at the clip's
// trim-in, so both posters show what actually plays first.
const posterT = p.hasPreview ? 0 : p.previewStart ?? 0.1;
@@ -1129,6 +1170,12 @@ function useCardPoster(
return poster;
}
+const MOVE_DEST: Record<Residency, { Icon: typeof Cloud; label: string }> = {
+ local: { Icon: Laptop, label: "Move to Local" },
+ cloud: { Icon: Cloud, label: "Move to Cloud" },
+ browser: { Icon: Laptop, label: "Move to Local" },
+};
+
function ProjectMenu({
className,
onRename,
@@ -1139,8 +1186,8 @@ function ProjectMenu({
className?: string;
onRename: () => void;
onDuplicate: () => void;
- /** Move to the other residency, when both are live. */
- moveTo?: { target: Residency; run: () => void };
+ /** The other live residencies this project can move to. */
+ moveTo?: { target: Residency; run: () => void }[];
onDelete: () => void;
}) {
return (
@@ -1165,12 +1212,14 @@ function ProjectMenu({
<DropdownMenuItem onClick={onDuplicate}>
<Copy /> Duplicate
</DropdownMenuItem>
- {moveTo && (
- <DropdownMenuItem onClick={moveTo.run}>
- {moveTo.target === "cloud" ? <Cloud /> : <Laptop />}{" "}
- {moveTo.target === "cloud" ? "Move to Cloud" : "Move to this Mac"}
- </DropdownMenuItem>
- )}
+ {moveTo?.map(({ target, run }) => {
+ const { Icon, label } = MOVE_DEST[target];
+ return (
+ <DropdownMenuItem key={target} onClick={run}>
+ <Icon /> {label}
+ </DropdownMenuItem>
+ );
+ })}
<DropdownMenuSeparator />
<DropdownMenuItem variant="destructive" onClick={onDelete}>
<Trash2 /> Delete
diff --git a/site/src/cut/components/SidePanel.tsx b/site/src/cut/components/SidePanel.tsx
index f66438cb..25e404e7 100644
--- a/site/src/cut/components/SidePanel.tsx
+++ b/site/src/cut/components/SidePanel.tsx
@@ -25,7 +25,7 @@ import {
} from "@/components/ui/dropdown-menu";
import { MEDIA_CORS } from "@/cut/lib/mediaCors";
import { apiFetch, apiUrl } from "@/cut/lib/backend";
-import { useCutCaps } from "@/cut/lib/backend/hooks";
+import { useCutCaps, useCutMode } from "@/cut/lib/backend/hooks";
import {
clearAssetDrag,
draggingLibrary,
@@ -65,7 +65,12 @@ import {
type LibraryFolder,
type LibraryTemplateItem,
} from "@/cut/lib/library";
-import { activeResidency, availableResidencies, type Residency } from "@/cut/lib/residency";
+import {
+ activeResidency,
+ availableResidencies,
+ libraryResidencies,
+ type Residency,
+} from "@/cut/lib/residency";
import { isStylePresetTemplate } from "@/cut/lib/stylePresets";
import { retryUpload } from "@/cut/lib/importQueue";
import { downloadMedia, isMediaFile, revealMedia } from "@/cut/lib/media";
@@ -623,6 +628,10 @@ function ProjectFilesPanel({
importing: boolean;
}) {
const caps = useCutCaps();
+ // The library passes over browser storage (`libraryResidencies`), and its
+ // server-side copy can't reach bytes that live in this browser's store, so
+ // a browser-resident project's templates stay on the project shelf.
+ const cutMode = useCutMode();
// Only user-imported media lives here; anything Cut created (recordings, AI
// generations, voiceovers, freeze frames, stock adds) is tagged with an
// `origin` and stays where it was made.
@@ -754,9 +763,11 @@ function ProjectFilesPanel({
if (r.scope === "project") useEditor.getState().addAssetToTemplate(t.id, r.id);
}}
extraMenu={
- <DropdownMenuItem onClick={() => void saveTemplate(projectId, t)}>
- <FolderPlus /> Add to Library
- </DropdownMenuItem>
+ cutMode === "browser" ? undefined : (
+ <DropdownMenuItem onClick={() => void saveTemplate(projectId, t)}>
+ <FolderPlus /> Add to Library
+ </DropdownMenuItem>
+ )
}
/>
))}
@@ -1283,7 +1294,7 @@ function LibraryPanel({ projectId }: { projectId: string }) {
};
const all = assets ?? [];
- const bothShelves = availableResidencies().length > 1;
+ const bothShelves = libraryResidencies(availableResidencies()).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;
diff --git a/site/src/cut/components/StoragePill.tsx b/site/src/cut/components/StoragePill.tsx
index bad69cff..6b87e826 100644
--- a/site/src/cut/components/StoragePill.tsx
+++ b/site/src/cut/components/StoragePill.tsx
@@ -3,8 +3,10 @@
// The top bar's subscription surface for cloud projects, one slot with two
// mutually exclusive faces: free accounts see their storage usage (click →
// upgrade dialog); a Pro set to cancel sees the days it has left (click →
-// Stripe portal, where Resume lives).
-import type { ReactNode } from "react";
+// Stripe portal, where Resume lives). A browser project's face is the
+// device's own storage estimate — there is no quota to sell past, so it only
+// informs.
+import { useEffect, useState, type ReactNode } from "react";
import { Loader2 } from "lucide-react";
import {
Tooltip,
@@ -35,11 +37,44 @@ export function usageLabel(bytes: number, quotaBytes: number): string {
}
export function StoragePill() {
- const cloud = useCutMode() === "cloud";
- if (!cloud) return null;
+ const mode = useCutMode();
+ if (mode === "browser") return <BrowserStoragePill />;
+ if (mode !== "cloud") return null;
return <CloudStoragePill />;
}
+function BrowserStoragePill() {
+ const [est, setEst] = useState<{ usage: number; quota: number } | null>(null);
+ useEffect(() => {
+ let alive = true;
+ const read = () =>
+ void navigator.storage
+ ?.estimate?.()
+ .then((e) => {
+ if (alive && typeof e.usage === "number" && typeof e.quota === "number") {
+ setEst({ usage: e.usage, quota: e.quota });
+ }
+ })
+ .catch(() => {});
+ read();
+ const timer = setInterval(read, 30_000);
+ return () => {
+ alive = false;
+ clearInterval(timer);
+ };
+ }, []);
+ if (!est) return null;
+ return (
+ <PillTooltip
+ message={`This is a local project. ${formatBytes(est.usage)} of the ${formatBytes(est.quota)} the browser allows is in use.`}
+ >
+ <TooltipTrigger className={cn(PILL, "cursor-default text-muted-foreground")}>
+ {usageLabel(est.usage, est.quota)}
+ </TooltipTrigger>
+ </PillTooltip>
+ );
+}
+
function CloudStoragePill() {
const pro = useProSubscription();
// The meter has to move as media lands, so this reader is the polling one.
diff --git a/site/src/cut/components/TopBar.tsx b/site/src/cut/components/TopBar.tsx
index c6fe21ed..ddb92376 100644
--- a/site/src/cut/components/TopBar.tsx
+++ b/site/src/cut/components/TopBar.tsx
@@ -26,6 +26,7 @@ import {
} from "@/components/ui/tooltip";
import { cloudBackend } from "@/cut/lib/backend/cloud";
import { cloudUsageQueryKey, useCutMode } from "@/cut/lib/backend/hooks";
+import { browserBackend } from "@/cut/lib/backend/browser";
import { localBackend } from "@/cut/lib/backend/local";
import { clearProjectThreads } from "@/cut/lib/chatThreads";
import { retryUpload } from "@/cut/lib/importQueue";
@@ -236,11 +237,11 @@ export function TopBar({
endEditing();
};
- // "Move to Cloud": copies this local project — doc and every media file — to
- // the cloud, deletes the local original, and reopens the editor on the cloud
- // copy.
+ // "Move to Cloud": copies this local or browser project — doc and every
+ // media file — to the cloud, deletes the original, and reopens the editor on
+ // the cloud copy.
const cutMode = useCutMode();
- const canMoveToCloud = cutMode === "local";
+ const canMoveToCloud = cutMode === "local" || cutMode === "browser";
// Cloud imports are real uploads worth reporting; local imports are instant
// disk copies, so they report nothing.
const cloudUploading = uploading > 0 && cutMode === "cloud";
@@ -278,10 +279,11 @@ export function TopBar({
for (let i = 0; i < 40 && useEditor.getState().saveState !== "saved"; i++) {
await new Promise((r) => setTimeout(r, 250));
}
- const newId = await copyProjectAcross(localBackend, cloudBackend, projectId, {
+ const src = cutMode === "browser" ? browserBackend : localBackend;
+ const newId = await copyProjectAcross(src, cloudBackend, projectId, {
onProgress: (done, total) => setMoveProgress(`Moving media ${done}/${total}…`),
});
- await localBackend
+ await src
.fetch(`/api/cut/projects/${projectId}`, { method: "DELETE" })
.catch(() => {});
// The chat history moved with the project; the old project's copy goes
@@ -307,13 +309,15 @@ export function TopBar({
// bar tightens. Chat keeps its label in both — it is the primary control.
const actionButtons = (compact: boolean) => (
<>
- {cutMode === "cloud" && (
+ {(cutMode === "cloud" || cutMode === "browser") && (
+ // Shares are served from the cloud, so for a browser project the
+ // Share button leads to the move that makes sharing possible.
<Button
variant="ghost"
size={compact ? "icon-sm" : "sm"}
aria-label="Share"
- title="Share"
- onClick={() => setShareOpen(true)}
+ title={cutMode === "browser" ? "Move to Cloud to share" : "Share"}
+ onClick={() => (cutMode === "browser" ? setMoveOpen(true) : setShareOpen(true))}
>
<Share2 data-icon={compact ? undefined : "inline-start"} />
{!compact && "Share"}
@@ -689,7 +693,8 @@ export function TopBar({
</DialogHeader>
<p className="text-sm text-muted-foreground">
Copies this project and its media to the cloud, then removes it
- from this Mac. Exports rendered here stay behind.
+ from {cutMode === "browser" ? "this browser" : "this Mac"}.
+ Exports rendered here stay behind.
</p>
{moveError && <p className="text-sm text-red-600">{moveError}</p>}
<DialogFooter className="mt-2">
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.ts
index 8671a921..4c7cd1ab 100644
--- a/site/src/cut/lib/aiTools.ts
+++ b/site/src/cut/lib/aiTools.ts
@@ -1265,7 +1265,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
(t - span.start) *
(span.clip.speed && span.clip.speed > 0 ? span.clip.speed : 1);
let body: MediaAsset;
- if (getBackend().kind === "cloud") {
+ if (getBackend().kind !== "local") {
// No engine to bake a still video — grab the frame in the browser and
// store it as a project image; image clips carry their own length,
// sized below to the requested duration, mirroring the engine's
@@ -2525,7 +2525,7 @@ async function fetchSilences(
// Same defaults and clamps as the engine's silence handler.
const thresholdDb = clamp(opts.thresholdDb ?? -30, -90, 0);
const minSilence = clamp(opts.minSilence ?? 0.35, 0.05, 10);
- if (getBackend().kind === "cloud") {
+ if (getBackend().kind !== "local") {
return detectSilenceClientSide(asset.url, {
from: opts.from,
...(opts.to !== undefined ? { to: opts.to } : {}),
@@ -2563,7 +2563,7 @@ async function listenToSource(
from: number,
to: number | undefined,
): Promise<InlineImage | null> {
- if (getBackend().kind === "cloud") {
+ if (getBackend().kind !== "local") {
const wav = await renderAudioSpanWav(asset.url, from, to).catch((e) => {
throw new ToolError(e instanceof Error ? e.message : "Could not read the audio.");
});
diff --git a/site/src/cut/lib/chatCloud.ts b/site/src/cut/lib/chatCloud.ts
index 66ddb8ab..0d713418 100644
--- a/site/src/cut/lib/chatCloud.ts
+++ b/site/src/cut/lib/chatCloud.ts
@@ -1,5 +1,5 @@
-// Cloud mirror of a project's chat threads. Local projects keep chat purely in
-// localStorage; a cloud project's threads also sync to the hosted
+// Cloud mirror of a project's chat threads. Local and browser projects keep
+// chat purely in localStorage; a cloud project's threads also sync to the hosted
// /projects/:id/chats routes so the history follows the account across
// devices. Threads stay opaque here — the module reads only id and updatedAt
// to merge, and ships the same slimmed payload the panel writes to storage.
@@ -24,7 +24,7 @@ export async function fetchCloudThreads(
): Promise<StoredThread[]> {
// The shared backend rewrites this path onto the viewer surface, which
// serves the owner's threads when the share includes chat.
- if (backend.kind === "local") return [];
+ if (backend.kind === "local" || backend.kind === "browser") return [];
// Throws on a failed read rather than reading as "no threads": the seed memo
// and a project copy both have to tell an empty history from a lost one.
const res = await backend.fetch(`/api/cut/projects/${projectId}/chats`);
@@ -60,7 +60,7 @@ export async function putCloudThread(
export function ensureCloudThreads(projectId: string): Promise<void> {
// Shared viewers sync too, read-only: syncThreads pushes nothing back, and
// the saves and deletes below are cloud-only.
- if (cutMode() === "local") return Promise.resolve();
+ if (cutMode() === "local" || cutMode() === "browser") return Promise.resolve();
let p = seeded.get(projectId);
if (!p) {
p = syncThreads(projectId).catch(() => {
diff --git a/site/src/cut/lib/generate.ts b/site/src/cut/lib/generate.ts
index ed296127..b6f3ed4f 100644
--- a/site/src/cut/lib/generate.ts
+++ b/site/src/cut/lib/generate.ts
@@ -3,6 +3,7 @@
import { useEffect } from "react";
import { create } from "zustand";
import { getBackend, type CutBackend, type CutMode } from "./backend";
+import { browserBackend } from "./backend/browser";
import { cloudBackend } from "./backend/cloud";
import { localBackend } from "./backend/local";
import { normalizeRef, type AssetRef } from "./assetRef";
@@ -201,7 +202,13 @@ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
/** The backend a job's results land on: its pinned residency; jobs persisted
* before residency existed fall back to the active backend. */
const jobBackend = (job: { residency?: CutMode }): CutBackend =>
- job.residency === "cloud" ? cloudBackend : job.residency === "local" ? localBackend : getBackend();
+ job.residency === "cloud"
+ ? cloudBackend
+ : job.residency === "local"
+ ? localBackend
+ : job.residency === "browser"
+ ? browserBackend
+ : getBackend();
/** Display name for the asset: the prompt, tidied and capped. */
const promptName = (prompt: string) => {
diff --git a/site/src/cut/lib/library.ts b/site/src/cut/lib/library.ts
index 11a9db9d..73bb1631 100644
--- a/site/src/cut/lib/library.ts
+++ b/site/src/cut/lib/library.ts
@@ -14,6 +14,7 @@ import {
activeResidency,
availableResidencies,
backendFor,
+ libraryResidencies,
libraryShelfKey,
listedResidencies,
type Residency,
@@ -106,8 +107,8 @@ async function rememberedLibraryFrom(r: Residency): Promise<LibraryData | null>
* item it can't copy into the project has no business in a picker.
*/
export async function fetchLibrary(opts?: { remembered?: boolean }): Promise<LibraryData> {
- const live = availableResidencies();
- const rs = opts?.remembered ? listedResidencies() : live;
+ const live = libraryResidencies(availableResidencies());
+ const rs = libraryResidencies(opts?.remembered ? listedResidencies() : live);
const parts = await Promise.all(
rs.map((r) =>
live.includes(r) ? fetchLibraryFrom(r).catch(() => null) : rememberedLibraryFrom(r)
diff --git a/site/src/cut/lib/newProject.ts b/site/src/cut/lib/newProject.ts
index 0d840d15..426599e3 100644
--- a/site/src/cut/lib/newProject.ts
+++ b/site/src/cut/lib/newProject.ts
@@ -13,6 +13,7 @@
import { useSyncExternalStore } from "react";
import { authClient } from "@/lib/auth-client";
+import { supportsBrowserStore } from "./backend/browser/opfs";
import { useLocalCompute } from "./backend/hooks";
import type { Residency } from "./residency";
@@ -25,7 +26,7 @@ function current(): Residency {
if (choice) return choice;
try {
const raw = localStorage.getItem(KEY);
- choice = raw === "cloud" || raw === "local" ? raw : "local";
+ choice = raw === "cloud" || raw === "local" || raw === "browser" ? raw : "local";
} catch {
choice = "local";
}
@@ -65,7 +66,18 @@ export function useNewProjectTarget(): NewProjectTarget {
// already has, and redraws when it lands.
const engineUp = useLocalCompute();
const stored = useSyncExternalStore(subscribe, current, () => "local" as const);
- const choices: Residency[] = !session ? ["local"] : engineUp ? ["local", "cloud"] : ["cloud"];
+ // "Local" is one place to the user, so one local entry ever lists: the Mac
+ // engine when it is up, else the browser's own store. First entry is the
+ // fallback default, so a signed-in user with no engine lands in the browser
+ // store: instant imports, no upload, no quota.
+ const store = supportsBrowserStore();
+ const choices: Residency[] = !session
+ ? ["local"]
+ : engineUp
+ ? ["local", "cloud"]
+ : store
+ ? ["browser", "cloud"]
+ : ["cloud"];
return {
target: choices.includes(stored) ? stored : choices[0],
choices,
diff --git a/site/src/cut/lib/queries.ts b/site/src/cut/lib/queries.ts
index bce2f35a..4eca5424 100644
--- a/site/src/cut/lib/queries.ts
+++ b/site/src/cut/lib/queries.ts
@@ -27,6 +27,7 @@ import { fetchLibrary, type LibraryData } from "./library";
import {
availableResidencies,
backendFor,
+ libraryResidencies,
listedResidencies,
projectsSnapshotKey,
type Residency,
@@ -46,7 +47,7 @@ export const projectsKey = (r: Residency) => ["cut", "projects", r] as const;
* the memory. */
export const libraryScope = () => {
const live = availableResidencies();
- return listedResidencies()
+ return libraryResidencies(listedResidencies())
.map((r) => (live.includes(r) ? r : `${r}!`))
.join("+");
};
diff --git a/site/src/cut/lib/residency.ts b/site/src/cut/lib/residency.ts
index c728f086..ebedcf61 100644
--- a/site/src/cut/lib/residency.ts
+++ b/site/src/cut/lib/residency.ts
@@ -14,6 +14,8 @@
// still pull one out of the cloud.
import { engineOrigin, servedFromEngine } from "./api";
import { cutMode } from "./backend";
+import { browserBackend } from "./backend/browser";
+import { supportsBrowserStore } from "./backend/browser/opfs";
import { cloudBackend } from "./backend/cloud";
import { localBackend } from "./backend/local";
import type { CutBackend, CutMode } from "./backend/types";
@@ -22,32 +24,45 @@ 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.) */
-export type Residency = "local" | "cloud";
+export type Residency = "local" | "cloud" | "browser";
export const backendFor = (r: Residency): CutBackend =>
- r === "cloud" ? cloudBackend : localBackend;
+ r === "cloud" ? cloudBackend : r === "browser" ? browserBackend : localBackend;
+// A project lives in one of two places the user thinks in: Local (this
+// device — the Mac engine or the browser's own storage, whichever this
+// session has) or Cloud. The two local kinds present identically; which one
+// backs "Local" is the app's business, so only one is ever offered at a time.
export const RESIDENCY_LABEL: Record<Residency, string> = {
- local: "On this Mac",
+ local: "Local",
cloud: "Cloud",
+ browser: "Local",
};
/**
* The residencies this browser can talk to right now.
*
* The cloud is always one of them — a signed-in account always has a hosted
- * shelf. The engine counts only once it has actually answered — the
- * ConnectGate resolved its origin, or the page is served by it. Probing here
- * could raise the browser's local-network prompt, and calling the engine
+ * shelf. The browser store counts when this browser can hold one (OPFS with
+ * committed writes). The engine counts only once it has actually answered —
+ * the ConnectGate resolved its origin, or the page is served by it. Probing
+ * here could raise the browser's local-network prompt, and calling the engine
* before the gate opens would hang on its latch.
*/
export function availableResidencies(): Residency[] {
const out: Residency[] = [];
if (servedFromEngine() || engineOrigin() !== "") out.push("local");
+ if (supportsBrowserStore()) out.push("browser");
out.push("cloud");
return out;
}
+/** The shelves the library spans. Library items keep a Mac and a cloud home;
+ * browser-resident storage holds projects only, so library reads and writes
+ * pass over it. */
+export const libraryResidencies = (rs: Residency[]): Residency[] =>
+ rs.filter((r) => r !== "browser");
+
/** 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. */
@@ -98,10 +113,12 @@ async function lastLocalProjects(): Promise<Set<string>> {
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. */
+/** The library residency the app is bound to: where a new library upload
+ * lands. Browser mode uploads to the cloud shelf — the library passes over
+ * browser storage. A shared view reads the local shelf. */
export function activeResidency(): Residency {
- return cutMode() === "cloud" ? "cloud" : "local";
+ const mode = cutMode();
+ return mode === "cloud" || mode === "browser" ? "cloud" : "local";
}
const owners = new Map<string, Promise<CutBackend>>();
@@ -118,8 +135,8 @@ export function projectBackend(projectId: string): Promise<CutBackend> {
let p = owners.get(projectId);
if (!p) {
p = resolveProjectMode(projectId).then((mode) => {
- if (mode !== "local") owners.delete(projectId);
- return backendFor(mode === "local" ? "local" : "cloud");
+ if (mode !== "local" && mode !== "browser") owners.delete(projectId);
+ return backendFor(mode === "local" || mode === "browser" ? mode : "cloud");
});
owners.set(projectId, p);
}
@@ -138,8 +155,27 @@ export type ProjectPlacement = { mode: CutMode; reachable: boolean };
* nothing and stays out of this set. */
const knownCloud = new Set<string>();
+/** Ids the browser store answered for. Same definitiveness as an engine hit:
+ * the store is this page's own storage, and a project never changes residency
+ * in place. */
+const knownBrowser = new Set<string>();
+
+/** Whether the browser store holds this id — the cheapest and most definitive
+ * ask, so it goes first. The store import stays lazy so pages that never see
+ * a browser project don't load it. */
+async function browserHasProject(projectId: string): Promise<boolean> {
+ if (!supportsBrowserStore()) return false;
+ const { readDoc } = await import("./backend/browser/opfs");
+ return (await readDoc(projectId)) !== null;
+}
+
export async function resolveProjectPlacement(projectId: string): Promise<ProjectPlacement> {
+ if (knownBrowser.has(projectId)) return { mode: "browser", reachable: true };
if (knownCloud.has(projectId)) return { mode: "cloud", reachable: true };
+ if (await browserHasProject(projectId)) {
+ knownBrowser.add(projectId);
+ return { mode: "browser", reachable: true };
+ }
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
diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.ts
index 225ba40b..02ed7f10 100644
--- a/site/src/cut/lib/types.ts
+++ b/site/src/cut/lib/types.ts
@@ -177,14 +177,20 @@ export interface StoredAsset {
}
/** An import whose bytes are still on their way to storage. While this is set
- * the asset plays from a local object URL, and it is held out of the saved
- * document along with the clips that use it — a reload cannot resume bytes
- * this tab was holding, so a doc pointing at them would open broken. */
+ * the asset plays from a local object URL. Whether it may join the saved
+ * document depends on where the bytes live: an upload holding only tab-scoped
+ * bytes is held out along with the clips that use it — a reload cannot resume
+ * them, so a doc pointing at them would open broken. One whose bytes sit in
+ * the browser store survives a reload and saves like any other asset; the
+ * store's ledger re-marks it pending on the next open. */
export interface AssetUpload {
/** Share of the bytes sent, 0..1. */
progress: number;
/** Set when the upload failed; the asset is retryable until it is removed. */
error?: string;
+ /** The bytes are held durably in the browser store, so the asset is safe to
+ * save and the upload safe to resume after a reload. */
+ stored?: boolean;
}
/** Runtime asset: stored fields plus derived/browser-only data. */
diff --git a/site/src/cut/lib/watch/sweep.ts b/site/src/cut/lib/watch/sweep.ts
index 7be014c7..a5f6d1a7 100644
--- a/site/src/cut/lib/watch/sweep.ts
+++ b/site/src/cut/lib/watch/sweep.ts
@@ -56,7 +56,7 @@ const decodersBusy = () => syncWatches > 0 || useEditor.getState().playing;
/** A free transcriber exists: the local engine, a Mac's engine behind a cloud
* project, or the hosted route's monthly included allowance while it lasts. */
const sttFree = () =>
- getBackend().kind !== "cloud" || hasLocalCompute() || hostedFreeExhaustedMonth !== utcMonth();
+ getBackend().kind === "local" || hasLocalCompute() || hostedFreeExhaustedMonth !== utcMonth();
/** Run a foreground watch with the sweep paused for its duration, so the
* call the assistant is waiting on gets the decoders to itself. */
@@ -91,7 +91,7 @@ async function transcribeFree(
projectId: string,
spec: CloudTranscribeSpec
): Promise<{ start: number; end: number; text: string }[] | null> {
- if (getBackend().kind !== "cloud") return runTranscription(projectId, spec);
+ if (getBackend().kind === "local") return runTranscription(projectId, spec);
const stale = () => useEditor.getState().projectId !== projectId;
const mix = await renderMix(projectId, spec);
if (stale()) return null;