Open source CapCut alternative.
TypeScript
feat(site): phone surfaces — Camera Roll, Notes, and the iOS link [rebuild]
David Lec1d75f34af6c
diff --git a/docs/guides/cut/README.md b/docs/guides/cut/README.mdindex 84364e9f..a130e079 100644--- a/docs/guides/cut/README.md+++ b/docs/guides/cut/README.md@@ -70,6 +70,8 @@ Every client call goes through a backend seam (`site/src/cut/lib/backend/`): theThe library is the exception, because it is the user's one shelf across places: every residency keeps a library, and the Library lists them at once as one listing, newest first, with a badge saying which shelf each item is on. So a cloud project can pull a clip off this Mac, and a browser project can pull one out of the cloud. A shelf that lives in the page holds its media in the same origin-private storage its projects use, and a link imported onto it rides the cloud worker — a page can't fetch a video off a YouTube link — with the bytes coming back down and the staged cloud copy dropped after. The Mac's shelf takes that same route as a second try: sites refuse fetches on the strength of the tool making them, so a link the engine's own tools can't bring back is fetched by the worker and lands here anyway. Each shelf is remembered on its own, so the Library tab keeps listing the Mac's items with the app closed, read-only, and clicking one raises the same banner an unreachable local project does. The editor's library picker asks only for what it can reach, since an item it cannot copy into the project has no business in a picker. Each item's own shelf answers for it: previews, renames, and deletes go to the backend it came from, and folders belong to one shelf, so items file only into folders beside them. Adding to a project is the one crossing: on the project's own shelf the server copies the file without the bytes leaving it, and off it the browser carries them down and back up. Filing an item into a folder on another shelf crosses the same way — the bytes come down and go back up, a file with its cover and a template with its own media, and the copy left behind comes off.+The phone feeds the cloud shelf. Clips recorded in the iOS app upload themselves to it, marked as camera footage; that marker gives the desktop its Camera Roll — a tab of phone clips kept out of the main Library grid, and a locked Camera Roll folder in the editor's library panel so the footage drops into any project. Inspiration saved on the phone lands in an Inspiration folder on the same shelf, links riding the same worker import every shelf uses. Notes are the one thing that flows both ways: the phone and the desktop's Notes tab edit the same set, the newer edit winning, deletes carrying across. Every request from the app carries a client marker, the server remembers accounts it has seen it from, and only those accounts get the phone tabs — a desktop-only account's sidebar never changes. The app's own guide covers the phone side: [The iOS App](../ios-app.md).+Some of what the Library holds is lent. Most items are copied when they are used — a clip's bytes become the project's own — but a font is pointed at: every title set in it names it, and the file stays on the shelf where every project can reach it. Lent items follow three rules. They are identified by their bytes, so the same file on two shelves is one entry in the menu and one id in a document. A new one lands on the shelf every surface can read, whenever it is small and the account has room. And a project moving to the cloud takes what it points at with it, so a title keeps its typeface when it starts rendering there — since the id is the bytes, not a word of the document changes. Fonts are the first of these; a .ttf, .otf, .woff or .woff2 dropped on the Library is filed in folders, deleted, and counted against storage like anything else, and every project offers it for titles and captions. A font download arrives as a zip, so the zip is droppable: the faces come out of it and the licence text stays behind, and a family of eighteen weights becomes a single entry. The file is checked by installing it through the renderer's font seam before any bytes move, so what lands is what a preview and an export can draw with, and the family name comes off the font's own metadata. That same moment draws the specimen the shelf keeps as the file's cover, so a font card shows the alphabet in its own face whether or not the page looking at it has that face installed. A new account starts with an empty Fonts folder to say the shelf takes them; it is an ordinary folder and can be deleted. A render job reaches the cloud shelf alone, which is what those rules are for. A font filed into a folder belongs to that folder's shelf like anything else, and a full account keeps its font on the shelf it was working from: it draws in the tab, is marked in the font menu as living on this device, and falls back to the base face in a render job. A title set in a font that is later deleted falls back too, so nothing in a document has to be rewritten.Cloud projects store their doc in Postgres (versioned; a stale autosave 409s and the editor reloads the newer copy) and media in R2: uploads go direct from the browser on presigned URLs (the hosted functions never see the bytes), playback streams on signed range URLs, and a flat per-user quota is enforced at presign time. That quota is visible rather than implicit: a free account editing a cloud project sees what it has used in the editor's top bar, and a presign rejected for space opens an upgrade offer wherever it happened instead of a bare error. The same slot carries the countdown when a subscription is set to cancel, and clicking it opens the billing portal.diff --git a/site/prisma/Cut.prisma b/site/prisma/Cut.prismaindex d0f706b6..7768b396 100644--- a/site/prisma/Cut.prisma+++ b/site/prisma/Cut.prisma@@ -133,6 +133,30 @@ model CutStorageUsage {updatedAt DateTime @updatedAt}+// One synced note, shared by the iOS app and the desktop Notes tab. The id is+// client-generated (the phone's UUID). `updatedAt` is the last-writer-wins+// clock and comes from the writing client; a delete keeps the row as a+// tombstone so the other side drops its copy on the next merge.+model CutNote {+ id String @id+ userId String+ title String @default("")+ body String @default("")+ colorIndex Int @default(0)+ updatedAt DateTime+ deletedAt DateTime?+ createdAt DateTime @default(now())++ @@index([userId, updatedAt])+}++// Set once an account has been seen from the iOS app. The desktop shows its+// mobile surfaces (Camera Roll, Notes) only for accounts with this row.+model CutPhoneLink {+ userId String @id+ lastSeenAt DateTime @updatedAt+}+// Work the render worker executes: exports, hover preview proxies, URL// imports. The client polls through the hosted API; only the worker claims// rows.diff --git a/site/src/app/cut/app/(home)/camera-roll/page.tsx b/site/src/app/cut/app/(home)/camera-roll/page.tsxnew file mode 100644index 00000000..83fa17c0--- /dev/null+++ b/site/src/app/cut/app/(home)/camera-roll/page.tsx@@ -0,0 +1,15 @@+import { Suspense } from "react";+import { CameraRollView } from "@/cut/components/CameraRollView";+import { SessionGate } from "@/cut/components/SessionGate";++export const unstable_instant = { prefetch: "static" };++export default function CameraRollPage() {+ return (+ <Suspense>+ <SessionGate>+ <CameraRollView />+ </SessionGate>+ </Suspense>+ );+}diff --git a/site/src/app/cut/app/(home)/notes/page.tsx b/site/src/app/cut/app/(home)/notes/page.tsxnew file mode 100644index 00000000..f2592879--- /dev/null+++ b/site/src/app/cut/app/(home)/notes/page.tsx@@ -0,0 +1,15 @@+import { Suspense } from "react";+import { NotesView } from "@/cut/components/NotesView";+import { SessionGate } from "@/cut/components/SessionGate";++export const unstable_instant = { prefetch: "static" };++export default function NotesPage() {+ return (+ <Suspense>+ <SessionGate>+ <NotesView />+ </SessionGate>+ </Suspense>+ );+}diff --git a/site/src/cut/components/AppSidebar.tsx b/site/src/cut/components/AppSidebar.tsxindex f1a1c084..99985b49 100644--- a/site/src/cut/components/AppSidebar.tsx+++ b/site/src/cut/components/AppSidebar.tsx@@ -4,7 +4,7 @@ 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 } from "lucide-react";+import { Camera, Clapperboard, FolderOpen, Loader2, StickyNote } from "lucide-react";import { Button } from "@/components/ui/button";import {Dialog,@@ -15,7 +15,7 @@ import {} from "@/components/ui/dialog";import { Input } from "@/components/ui/input";import { seedNewProjectDoc } from "@/cut/lib/docCache";-import { patchProjects } from "@/cut/lib/queries";+import { patchProjects, usePhoneLink } from "@/cut/lib/queries";import { backendFor, type Residency } from "@/cut/lib/residency";import { track } from "@/lib/analytics";import { NavStorage } from "@/cut/components/NavStorage";@@ -30,11 +30,18 @@ const NAV: { tab: CutTab; label: string; icon: typeof Clapperboard }[] = [{ tab: "library", label: "Library", icon: FolderOpen },];+// Surfaces fed by the iOS app, listed only for accounts that use it.+const PHONE_NAV: { tab: CutTab; label: string; icon: typeof Clapperboard }[] = [+ { tab: "camera-roll", label: "Camera Roll", icon: Camera },+ { tab: "notes", label: "Notes", icon: StickyNote },+];+export function AppSidebar() {const pathname = usePathname();const router = useRouter();const base = useCutBase();const client = useQueryClient();+ const phoneLinked = usePhoneLink();// The residency the pending creation was launched for; null when the naming// dialog is closed.const [createIn, setCreateIn] = useState<Residency | null>(null);@@ -93,7 +100,7 @@ export function AppSidebar() {/><nav className="flex flex-col gap-0.5">- {NAV.map(({ tab, label, icon: Icon }) => {+ {[...NAV, ...(phoneLinked ? PHONE_NAV : [])].map(({ tab, label, icon: Icon }) => {const href = homeHref(base, tab);const active = pathname === href;return (diff --git a/site/src/cut/components/CameraRollView.tsx b/site/src/cut/components/CameraRollView.tsxnew file mode 100644index 00000000..2a7442c2--- /dev/null+++ b/site/src/cut/components/CameraRollView.tsx@@ -0,0 +1,138 @@+"use client";++import { useCallback, useState } from "react";+import { useQueryClient } from "@tanstack/react-query";+import { Camera, Loader2 } from "lucide-react";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@/components/ui/alert-dialog";+import {+ deleteFromLibrary,+ libraryMediaUrl,+ libraryPosterUrl,+ type LibraryAsset,+} from "@/cut/lib/library";+import { useLightbox } from "@/cut/lib/lightbox";+import { patchLibrary, refetchLibrary, useLibrary } from "@/cut/lib/queries";+import { shapeBand } from "@/cut/lib/types";+import { Lightbox } from "./Lightbox";+import { LibraryCard } from "./LibraryView";++/** The phone's recordings, synced up from the iOS app: every cloud library+ * asset tagged origin "camera", newest first. Clips here are ordinary library+ * assets — the editor's Library panel offers them to any project — this page+ * is where they are watched and pruned. */+export function CameraRollView() {+ const client = useQueryClient();+ const library = useLibrary();+ const [deleting, setDeleting] = useState<LibraryAsset | null>(null);+ const clips = (library.data?.assets ?? []).filter((a) => a.origin === "camera");+ const patch = useCallback(+ (fn: Parameters<typeof patchLibrary>[1]) => patchLibrary(client, fn),+ [client]+ );++ const remove = async () => {+ if (!deleting) return;+ const { id, residency } = deleting;+ setDeleting(null);+ patch((d) => ({ ...d, assets: d.assets.filter((a) => a.id !== id) }));+ await deleteFromLibrary(residency, id).catch(() => void refetchLibrary(client));+ };++ // Same banding as the Library grid: tiles of one shape share a row, every+ // tile carries the same area.+ const bands = new Map<number, LibraryAsset[]>();+ for (const a of clips) {+ const key = a.width && a.height ? shapeBand(a.width, a.height) : 0;+ const band = bands.get(key) ?? [];+ if (band.length === 0) bands.set(key, band);+ band.push(a);+ }+ const TILE_AREA = 180 * 320;++ return (+ <div className="mx-auto w-full max-w-6xl px-10 py-9">+ <div className="mb-5 flex items-center justify-between gap-4">+ <h1 className="text-lg font-semibold tracking-tight">Camera Roll</h1>+ </div>++ {!library.data && library.isPending ? (+ <div className="grid place-items-center py-24 text-muted-foreground">+ <Loader2 className="size-5 animate-spin" />+ </div>+ ) : clips.length === 0 ? (+ <div className="grid w-full place-items-center rounded-2xl py-24">+ <div className="flex flex-col items-center gap-3 text-center">+ <Camera className="size-8 text-muted-foreground" />+ <div className="text-base font-medium">Nothing from your phone yet.</div>+ <p className="text-sm text-muted-foreground">+ Clips you record in the Donkey Cut iOS app sync here automatically.+ </p>+ </div>+ </div>+ ) : (+ <div className="flex flex-col gap-8">+ {[...bands.values()].map((band, i) => (+ <div key={i} className="flex flex-wrap items-start gap-4">+ {band.map((a) => (+ <LibraryCard+ key={a.id}+ asset={a}+ area={TILE_AREA}+ onClick={() =>+ useLightbox.getState().open({+ kind: a.type,+ src: libraryMediaUrl(a.fileName, a.residency),+ name: a.name,+ prompt: "",+ assetId: null,+ libraryId: a.id,+ bare: true,+ ...(a.width && a.height ? { ratio: a.width / a.height } : {}),+ ...(libraryPosterUrl(a) ? { poster: libraryPosterUrl(a) } : {}),+ })+ }+ onDelete={() => setDeleting(a)}+ />+ ))}+ </div>+ ))}+ </div>+ )}++ <AlertDialog open={!!deleting} onOpenChange={(o) => !o && setDeleting(null)}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Delete “{deleting?.name}”?</AlertDialogTitle>+ <AlertDialogDescription>+ The clip leaves your cloud Camera Roll. Projects that already use it keep their own+ copy, and a copy still on your phone stays there.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction+ className="bg-destructive/10 text-destructive hover:bg-destructive/20"+ onClick={(e) => {+ e.preventDefault();+ void remove();+ }}+ >+ Delete+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>++ <Lightbox />+ </div>+ );+}diff --git a/site/src/cut/components/LibraryView.tools.ts b/site/src/cut/components/LibraryView.tools.tsindex cab21249..38d377da 100644--- a/site/src/cut/components/LibraryView.tools.ts+++ b/site/src/cut/components/LibraryView.tools.ts@@ -12,7 +12,13 @@ export const LIBRARY_TOOLS = [{name: "library_list",description:- "List the shared Library — reusable media saved across projects: folders, assets (video/audio/image, and the account's own font files), and templates (saved arrangements of clips, overlays, titles, and captions). Library items live outside the project: library_add imports an asset, template_add re-materializes a template.",+ "List the shared Library — reusable media saved across projects: folders, assets (video/audio/image, and the account's own font files), and templates (saved arrangements of clips, overlays, titles, and captions). An asset's `origin` says it came from the user's iOS app: \"camera\" is a clip they recorded on their phone (their Camera Roll), \"inspiration\" a reference they saved to the Inspiration folder. Library items live outside the project: library_add imports an asset, template_add re-materializes a template.",+ inputSchema: obj({}),+ },+ {+ name: "notes_list",+ description:+ "List the user's synced notes — short scripts and ideas written in the Donkey Cut iOS app or the desktop Notes tab. Read them when the user points at \"my note(s)\" for a script, caption, or voiceover text; quote a note's body verbatim when they ask for its words.",inputSchema: obj({}),},{diff --git a/site/src/cut/components/LibraryView.tsx b/site/src/cut/components/LibraryView.tsxindex 85f26698..c0e898b5 100644--- a/site/src/cut/components/LibraryView.tsx+++ b/site/src/cut/components/LibraryView.tsx@@ -363,7 +363,9 @@ export function LibraryView() {// is this browser putting things on — so they read the one choice the user// already made, rather than the backend the app happens to be bound to.const { target } = useNewProjectTarget();- const all = library.data?.assets ?? [];+ // Phone camera recordings have their own home tab (Camera Roll); the+ // Library grid lists everything else.+ const all = (library.data?.assets ?? []).filter((a) => a.origin !== "camera");const folders = library.data?.folders ?? [];const templates = library.data?.templates ?? [];const patch = useCallback(diff --git a/site/src/cut/components/NotesView.tsx b/site/src/cut/components/NotesView.tsxnew file mode 100644index 00000000..4c2852ea--- /dev/null+++ b/site/src/cut/components/NotesView.tsx@@ -0,0 +1,204 @@+"use client";++import { useState } from "react";+import { useQueryClient } from "@tanstack/react-query";+import { Loader2, Plus, StickyNote, Trash2 } from "lucide-react";+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import {+ deleteNote,+ NOTE_COLORS,+ noteColor,+ saveNote,+ type CutNote,+} from "@/cut/lib/notes";+import { notesKey, patchNotes, useNotes } from "@/cut/lib/queries";+import { cn } from "@/lib/utils";++// The note paper's ink, matching the iOS app.+const NOTE_INK = "#201a0d";++interface Draft {+ id: string;+ title: string;+ body: string;+ colorIndex: number;+ isNew: boolean;+}++/** Synced notes: written on the phone or here, merged by last writer wins.+ * The phone reads these into its teleprompter, so a script drafted at the+ * desk is on the camera by the time the phone is in hand. */+export function NotesView() {+ const client = useQueryClient();+ const notes = useNotes();+ const [draft, setDraft] = useState<Draft | null>(null);++ const openNew = () =>+ setDraft({ id: crypto.randomUUID(), title: "", body: "", colorIndex: 0, isNew: true });+ const openNote = (n: CutNote) =>+ setDraft({ id: n.id, title: n.title, body: n.body, colorIndex: n.colorIndex, isNew: false });++ const commit = async () => {+ if (!draft) return;+ const { id, title, body, colorIndex } = draft;+ setDraft(null);+ if (!title.trim() && !body.trim()) return;+ const now = Date.now();+ const optimistic: CutNote = {+ id,+ title: title.trim() || "Untitled",+ body: body.trim(),+ colorIndex,+ updatedAt: now,+ deletedAt: null,+ createdAt: now,+ };+ patchNotes(client, (prev) => {+ const rest = prev.filter((n) => n.id !== id);+ const existing = prev.find((n) => n.id === id);+ return [{ ...optimistic, createdAt: existing?.createdAt ?? now }, ...rest];+ });+ const saved = await saveNote({+ id,+ title: optimistic.title,+ body: optimistic.body,+ colorIndex,+ }).catch(() => null);+ // The server answers with the winning version — this write, or a newer+ // one from the phone.+ if (saved) patchNotes(client, (prev) => prev.map((n) => (n.id === id ? saved : n)));+ else void client.invalidateQueries({ queryKey: notesKey });+ };++ const remove = async () => {+ if (!draft) return;+ const { id, isNew } = draft;+ setDraft(null);+ if (isNew) return;+ patchNotes(client, (prev) => prev.filter((n) => n.id !== id));+ await deleteNote(id).catch(() => void client.invalidateQueries({ queryKey: notesKey }));+ };++ const list = notes.data ?? [];++ return (+ <div className="mx-auto w-full max-w-6xl px-10 py-9">+ <div className="mb-5 flex items-center justify-between gap-4">+ <h1 className="text-lg font-semibold tracking-tight">Notes</h1>+ <Button onClick={openNew}>+ <Plus data-icon="inline-start" /> New note+ </Button>+ </div>++ {!notes.data && notes.isPending ? (+ <div className="grid place-items-center py-24 text-muted-foreground">+ <Loader2 className="size-5 animate-spin" />+ </div>+ ) : list.length === 0 ? (+ <button+ className="grid w-full cursor-pointer place-items-center rounded-2xl py-24"+ onClick={openNew}+ >+ <div className="flex flex-col items-center gap-3 text-center">+ <StickyNote className="size-8 text-muted-foreground" />+ <div className="text-base font-medium">No notes yet.</div>+ <p className="text-sm text-muted-foreground">+ Notes sync with the Donkey Cut iOS app — a script written here is ready on the+ phone's teleprompter.+ </p>+ </div>+ </button>+ ) : (+ <div className="grid grid-cols-[repeat(auto-fill,minmax(220px,1fr))] gap-3">+ {list.map((n) => (+ <button+ key={n.id}+ className="flex min-h-40 cursor-pointer flex-col gap-1.5 rounded-2xl p-4 text-left shadow-sm transition-transform hover:-translate-y-0.5"+ style={{ backgroundColor: noteColor(n.colorIndex).background, color: NOTE_INK }}+ onClick={() => openNote(n)}+ >+ {n.title && <div className="font-semibold">{n.title}</div>}+ <div className="line-clamp-6 text-sm whitespace-pre-wrap opacity-80">{n.body}</div>+ </button>+ ))}+ </div>+ )}++ <Dialog open={!!draft} onOpenChange={(o) => (o ? undefined : void commit())}>+ <DialogContent+ className="sm:max-w-lg"+ style={+ draft+ ? { backgroundColor: noteColor(draft.colorIndex).background, color: NOTE_INK }+ : undefined+ }+ >+ <DialogHeader>+ <DialogTitle className="sr-only">{draft?.isNew ? "New note" : "Edit note"}</DialogTitle>+ </DialogHeader>+ {draft && (+ <div className="flex flex-col gap-3">+ <Input+ autoFocus+ value={draft.title}+ placeholder="Title"+ className="border-none bg-transparent px-0 text-base font-semibold shadow-none focus-visible:ring-0 dark:bg-transparent"+ style={{ color: NOTE_INK }}+ onChange={(e) => setDraft({ ...draft, title: e.target.value })}+ />+ <textarea+ value={draft.body}+ placeholder="Write your note…"+ rows={10}+ className="resize-none bg-transparent text-sm outline-none placeholder:opacity-50"+ style={{ color: NOTE_INK }}+ onChange={(e) => setDraft({ ...draft, body: e.target.value })}+ />+ <DialogFooter className="flex-row items-center sm:justify-between">+ <div className="flex items-center gap-1.5">+ {NOTE_COLORS.map((c, i) => (+ <button+ key={c.background}+ aria-label={`Note color ${i + 1}`}+ className={cn(+ "size-5 cursor-pointer rounded-full border",+ draft.colorIndex === i ? "border-black/50" : "border-black/15"+ )}+ style={{ backgroundColor: c.accent }}+ onClick={() => setDraft({ ...draft, colorIndex: i })}+ />+ ))}+ </div>+ <div className="flex items-center gap-2">+ {!draft.isNew && (+ <Button+ variant="ghost"+ className="text-destructive hover:bg-black/5 hover:text-destructive"+ onClick={() => void remove()}+ >+ <Trash2 data-icon="inline-start" /> Delete+ </Button>+ )}+ <Button+ className="bg-black/80 text-white hover:bg-black"+ onClick={() => void commit()}+ >+ Done+ </Button>+ </div>+ </DialogFooter>+ </div>+ )}+ </DialogContent>+ </Dialog>+ </div>+ );+}diff --git a/site/src/cut/components/SidePanel.tsx b/site/src/cut/components/SidePanel.tsxindex 859affa5..284d1c13 100644--- a/site/src/cut/components/SidePanel.tsx+++ b/site/src/cut/components/SidePanel.tsx@@ -1174,6 +1174,11 @@ function AssetCard({ asset, projectId }: { asset: MediaAsset; projectId: string);}+// The derived folder holding phone recordings in the editor's Library panel.+// Not a server folder: assets tagged origin "camera" file here by themselves,+// so phone footage is one click from any project.+const CAMERA_ROLL_FOLDER = "camera-roll";+function LibraryPanel({ projectId }: { projectId: string }) {const [assets, setAssets] = useState<LibraryAsset[] | null>(null);const [folders, setFolders] = useState<LibraryFolder[]>([]);@@ -1197,18 +1202,26 @@ function LibraryPanel({ projectId }: { projectId: string }) {}).catch(() => setAssets([]));+ // Where an asset shows: phone recordings gather in the derived Camera Roll+ // folder whatever their server folderId says.+ const folderOf = (a: LibraryAsset) =>+ a.origin === "camera" ? CAMERA_ROLL_FOLDER : (a.folderId ?? null);+ const cameraCount = (assets ?? []).filter((a) => a.origin === "camera").length;+// A remembered folder can vanish between sessions; drop back to the root.useEffect(() => {- if (assets !== null && openFolder !== null && !folders.some((f) => f.id === openFolder))- setOpenFolder(null);- }, [assets, folders, openFolder, setOpenFolder]);+ const known =+ folders.some((f) => f.id === openFolder) ||+ (openFolder === CAMERA_ROLL_FOLDER && cameraCount > 0);+ if (assets !== null && openFolder !== null && !known) setOpenFolder(null);+ }, [assets, folders, openFolder, cameraCount, setOpenFolder]);// A revealed library asset may sit inside a folder — open it so the card is// on screen to scroll to and flash.useRevealEffect((ref) => {if (ref.scope !== "library") return;const a = (assets ?? []).find((x) => x.id === ref.id);- if (a) setOpenFolder(a.folderId ?? null);+ if (a) setOpenFolder(folderOf(a));});const removeTemplate = async (r: Residency, id: string) => {@@ -1247,6 +1260,7 @@ function LibraryPanel({ projectId }: { projectId: string }) {null;const move = async (id: string, folderId: string | null) => {+ if (folderId === CAMERA_ROLL_FOLDER) return; // derived; only the phone files hereconst residency = shelfOf(id);if (!residency) return;if (folderId && folders.find((f) => f.id === folderId)?.residency !== residency) return;@@ -1260,7 +1274,10 @@ function LibraryPanel({ projectId }: { projectId: string }) {const shelfForNew = (folderId: string | null) =>(folderId ? folders.find((f) => f.id === folderId)?.residency : null) ?? activeResidency();- const upload = async (files: FileList | File[], folderId: string | null = openFolder) => {+ const upload = async (files: FileList | File[], into: string | null = openFolder) => {+ // The Camera Roll takes nothing by hand; an upload made while it is open+ // lands at the root like any other.+ const folderId = into === CAMERA_ROLL_FOLDER ? null : into;const list = (await expandLinkedFiles(Array.from(files))).filter((f) => isMediaFile(f) || isLinkedFile(f));@@ -1315,9 +1332,26 @@ function LibraryPanel({ projectId }: { projectId: string }) {const all = assets ?? [];const bothShelves = availableResidencies().length > 1;- const shown = all.filter((a) => (a.folderId ?? null) === openFolder);+ const shown = all.filter((a) => folderOf(a) === openFolder);const shownTemplates = templates.filter((t) => (t.folderId ?? null) === openFolder);- const openFolderName = folders.find((f) => f.id === openFolder)?.name;+ // The Camera Roll tile leads the shelf while the phone has synced anything.+ const shelfFolders: (LibraryFolder & { locked?: boolean })[] =+ cameraCount > 0+ ? [+ {+ id: CAMERA_ROLL_FOLDER,+ name: "Camera Roll",+ createdAt: 0,+ residency: "cloud",+ locked: true,+ },+ ...folders,+ ]+ : folders;+ const openFolderName =+ openFolder === CAMERA_ROLL_FOLDER+ ? "Camera Roll"+ : folders.find((f) => f.id === openFolder)?.name;return (<div@@ -1341,15 +1375,15 @@ function LibraryPanel({ projectId }: { projectId: string }) {/></div>)}- {openFolder === null && folders.length > 0 ? (+ {openFolder === null && shelfFolders.length > 0 ? (<div className="shrink-0 px-3.5"><FolderShelfrows- folders={folders}+ folders={shelfFolders}mime={LIBRARY_MOVE_MIME}statOf={(id) => ({count:- all.filter((a) => (a.folderId ?? null) === id).length ++ all.filter((a) => folderOf(a) === id).length +templates.filter((t) => (t.folderId ?? null) === id).length,})}badgeOf={(id) => {diff --git a/site/src/cut/components/desktopFolders.tsx b/site/src/cut/components/desktopFolders.tsxindex 95210bce..f201096b 100644--- a/site/src/cut/components/desktopFolders.tsx+++ b/site/src/cut/components/desktopFolders.tsx@@ -23,6 +23,10 @@ import { cn } from "@/lib/utils";export interface DeskFolder {id: string;name: string;+ /** A folder the host derives from the items themselves (the editor's Camera+ * Roll): it opens like any other but can't be renamed, deleted, or dropped+ * into. */+ locked?: boolean;}export function formatBytes(n: number): string {@@ -297,32 +301,36 @@ export function FolderShelf<F extends DeskFolder>({);const interact = {onClick: () => onOpen(f.id),- onDoubleClick: () => {- setDraft(f.name);- setEditingId(f.id);- },- onDragOver: (e: React.DragEvent) => {- if (!accepts(e)) return;- e.preventDefault();- e.dataTransfer.dropEffect = dragTypes(e).includes(mime) ? "move" : "copy";- setOver(f.id);- },- onDragLeave: () => setOver((o) => (o === f.id ? null : o)),- onDrop: (e: React.DragEvent) => {- if (!accepts(e)) return;- e.preventDefault();- setOver(null);- // Files land in this folder; stop the drop bubbling to the page's- // catch-all so it isn't also imported at the current level.- if (onDropFiles && dragTypes(e).includes("Files") && e.dataTransfer.files.length) {- e.stopPropagation();- onDropFiles(e.dataTransfer.files, f.id);- return;- }- onDropIds(readDragIds(e, mime), f.id);- },+ ...(f.locked+ ? {}+ : {+ onDoubleClick: () => {+ setDraft(f.name);+ setEditingId(f.id);+ },+ onDragOver: (e: React.DragEvent) => {+ if (!accepts(e)) return;+ e.preventDefault();+ e.dataTransfer.dropEffect = dragTypes(e).includes(mime) ? "move" : "copy";+ setOver(f.id);+ },+ onDragLeave: () => setOver((o: string | null) => (o === f.id ? null : o)),+ onDrop: (e: React.DragEvent) => {+ if (!accepts(e)) return;+ e.preventDefault();+ setOver(null);+ // Files land in this folder; stop the drop bubbling to the page's+ // catch-all so it isn't also imported at the current level.+ if (onDropFiles && dragTypes(e).includes("Files") && e.dataTransfer.files.length) {+ e.stopPropagation();+ onDropFiles(e.dataTransfer.files, f.id);+ return;+ }+ onDropIds(readDragIds(e, mime), f.id);+ },+ }),};- const menu = (+ const menu = f.locked ? null : (<DropdownMenu><DropdownMenuTriggerrender={diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex 459ef0c9..62de1602 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -62,6 +62,7 @@ import {renameLibraryFolder,saveAssetToLibrary,} from "./library";+import { fetchNotes } from "./notes";import {captureFreezeFrame,detectSilenceClientSide,@@ -2420,6 +2421,9 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {kind: a.type,duration: round2(a.duration),...(a.folderId ? { folderId: a.folderId } : {}),+ // "camera" = recorded on the user's phone (their Camera Roll);+ // "inspiration" = saved from the phone's Ideas tab.+ ...(a.origin ? { origin: a.origin } : {}),})),templates: lib.templates.map((t) => ({id: t.id,@@ -2430,6 +2434,18 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {};},+ notes_list: async () => {+ const notes = await fetchNotes();+ return {+ notes: notes.map((n) => ({+ id: n.id,+ title: n.title,+ body: n.body,+ updatedAt: new Date(n.updatedAt).toISOString(),+ })),+ };+ },+library_add: async (s, input) => {const projectId = s.projectId;if (!projectId) throw new ToolError("No project open.");diff --git a/site/src/cut/lib/library.ts b/site/src/cut/lib/library.tsindex b3367b4b..60d87222 100644--- a/site/src/cut/lib/library.ts+++ b/site/src/cut/lib/library.ts@@ -58,6 +58,10 @@ export interface LibraryAsset {* An import from a site that publishes one carries it; it is what a card and* the viewer show while the video itself loads. */posterFile?: string;+ /** How the asset entered the account from the iOS app: a phone camera+ * recording (shown in Camera Roll, kept out of the Library grid) or an+ * inspiration item. Cloud shelf only. */+ origin?: "camera" | "inspiration";/** Which shelf this came off. Stamped on arrival — the servers each answer* for themselves and don't know the other exists. */residency: Residency;diff --git a/site/src/cut/lib/nav.tsx b/site/src/cut/lib/nav.tsxindex e85ee357..a0e64e20 100644--- a/site/src/cut/lib/nav.tsx+++ b/site/src/cut/lib/nav.tsx@@ -14,17 +14,20 @@ export function useCutBase(): string {// project was opened from — Projects, Library, or a folder within one. The// home pages read ?folder=… as the open folder, which also lets the browser's// own back button step folder → root.-export type CutTab = "projects" | "library";+export type CutTab = "projects" | "library" | "camera-roll" | "notes";/** Which home tab a pathname is on (base-agnostic). */export function tabForPath(pathname: string): CutTab {- return pathname.endsWith("/library") ? "library" : "projects";+ if (pathname.endsWith("/library")) return "library";+ if (pathname.endsWith("/camera-roll")) return "camera-roll";+ if (pathname.endsWith("/notes")) return "notes";+ return "projects";}/** Home tab URL under the given base, optionally inside a folder. Projects is* the base root. */export function homeHref(base: string, tab: CutTab, folder?: string | null): string {- const root = tab === "library" ? `${base}/library` : base || "/";+ const root = tab === "projects" ? base || "/" : `${base}/${tab}`;return folder ? `${root}?folder=${encodeURIComponent(folder)}` : root;}diff --git a/site/src/cut/lib/notes.ts b/site/src/cut/lib/notes.tsnew file mode 100644index 00000000..a10b4b95--- /dev/null+++ b/site/src/cut/lib/notes.ts@@ -0,0 +1,70 @@+"use client";++/**+ * Synced notes, the desktop half. Notes live in the cloud (/api/cut-cloud/notes)+ * and are written from two places — the iOS app and the Notes tab — so every+ * write carries its own `updatedAt` stamp and the server keeps whichever+ * version is newer (last writer wins). Deletes leave tombstones; the list is+ * filtered here so the UI only ever sees live notes.+ */++import { backendFor } from "./residency";++export interface CutNote {+ id: string;+ title: string;+ body: string;+ colorIndex: number;+ updatedAt: number;+ deletedAt: number | null;+ createdAt: number;+}++/** The note paper palette, shared with the iOS app (NoteColor). Index into it+ * with `colorIndex`. */+export const NOTE_COLORS = [+ { background: "#faefb6", accent: "#f2c94c" }, // butter+ { background: "#fbd8d4", accent: "#ef8b80" }, // blush+ { background: "#d5e8fb", accent: "#7fb2ef" }, // sky+ { background: "#d9f3d6", accent: "#82cf7a" }, // mint+ { background: "#e6dcf7", accent: "#a988e0" }, // lilac+] as const;++export const noteColor = (index: number) =>+ NOTE_COLORS[((index % NOTE_COLORS.length) + NOTE_COLORS.length) % NOTE_COLORS.length];++const notesFetch = (path: string, init?: RequestInit) =>+ backendFor("cloud").fetch(path, init);++/** Every live note, newest first. Tombstones are the phone's concern; the+ * desktop just drops them. */+export async function fetchNotes(): Promise<CutNote[]> {+ const res = await notesFetch("/api/cut/notes");+ if (!res.ok) throw new Error("Could not load notes.");+ const body = (await res.json()) as { notes?: CutNote[] };+ return (body.notes ?? []).filter((n) => n.deletedAt === null);+}++/** Write one note. The server answers with the winning version — this write,+ * or a newer one from the phone. */+export async function saveNote(note: {+ id: string;+ title: string;+ body: string;+ colorIndex: number;+}): Promise<CutNote> {+ const res = await notesFetch(`/api/cut/notes/${encodeURIComponent(note.id)}`, {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ ...note, updatedAt: Date.now() }),+ });+ if (!res.ok) throw new Error("Could not save the note.");+ return (await res.json()) as CutNote;+}++export async function deleteNote(id: string): Promise<void> {+ const res = await notesFetch(`/api/cut/notes/${encodeURIComponent(id)}`, {+ method: "DELETE",+ });+ if (!res.ok) throw new Error("Could not delete the note.");+}diff --git a/site/src/cut/lib/queries.ts b/site/src/cut/lib/queries.tsindex bce2f35a..c40b20a1 100644--- a/site/src/cut/lib/queries.ts+++ b/site/src/cut/lib/queries.ts@@ -24,6 +24,7 @@ import { cutMode } from "./backend";import { useCutMode } from "./backend/hooks";import { readSnapshot, snapshotKey, writeSnapshot } from "./cache";import { fetchLibrary, type LibraryData } from "./library";+import { fetchNotes, type CutNote } from "./notes";import {availableResidencies,backendFor,@@ -190,3 +191,51 @@ export function refetchProjects(client: QueryClient, r: Residency) {export function refetchLibrary(client: QueryClient) {return client.invalidateQueries({ queryKey: libraryKey(libraryScope()) });}++// --- Phone surfaces: the iOS link flag and synced notes ---++const PHONE_KEY = ["cut", "phone"] as const;++/** Whether this account has been seen from the iOS app. Gates the mobile+ * surfaces (Camera Roll, Notes) in the home sidebar; an account that never+ * signed in on a phone keeps the desktop exactly as it was. */+export function usePhoneLink() {+ const query = useQuery<boolean>({+ queryKey: PHONE_KEY,+ queryFn: async () => {+ const res = await backendFor("cloud").fetch("/api/cut/phone");+ if (!res.ok) throw new Error(String(res.status));+ return ((await res.json()) as { linked?: boolean }).linked === true;+ },+ // The flag only ever turns on, and once on it never needs re-asking.+ staleTime: Infinity,+ retry: false,+ });+ return query.data === true;+}++export const notesKey = ["cut", "notes"] as const;+const NOTES_SNAPSHOT = "cut-notes";++/** The account's synced notes, phone and desktop edits merged server-side. */+export function useNotes() {+ const client = useQueryClient();+ useEffect(() => seedFromSnapshot<CutNote[]>(client, notesKey, NOTES_SNAPSHOT), [client]);+ return useQuery<CutNote[]>({+ queryKey: notesKey,+ queryFn: async () => {+ const notes = await fetchNotes();+ writeSnapshot(NOTES_SNAPSHOT, notes);+ return notes;+ },+ staleTime: 0,+ refetchOnMount: "always",+ retry: false,+ });+}++/** Optimistic edit of the cached notes list, snapshot moving with it. */+export function patchNotes(client: QueryClient, fn: (prev: CutNote[]) => CutNote[]) {+ const next = client.setQueryData<CutNote[]>(notesKey, (prev) => (prev ? fn(prev) : prev));+ if (next) writeSnapshot(NOTES_SNAPSHOT, next);+}diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex eca51bb8..d4aa3879 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -347,6 +347,8 @@ Project media (\`media\` in editor_state) is every file in the open project. The- convert_media rewrites project media as MP4 (H.264/AAC) in place, one call for a whole list of asset ids. Reach for it when footage plays black or shows a format warning — phone HEVC, ProRes, raw PCM sound — and whenever someone asks for mp4 files. That ask is usually files dropped straight on this chat: convert them and each one is on its own card in the thread, converted, ready to download or drag onto the timeline — close by saying they're on their cards. An asset that came from the Media panel stays there. Streams that already fit are copied, so most .mov files convert in seconds, and a file that is already H.264/AAC MP4 comes back untouched (say so instead of claiming a conversion); max_height shrinks an oversized source at the same time. Clips already cut from the asset keep playing. It runs on whichever machine already holds the bytes — this Mac, the render worker, or the tab — and works with no editor tab attached; when nothing available can decode the source the error names the fix (the Mac app, another browser, or moving the project to the cloud), so report it and move on.The Library is shared across every project: folders, reusable assets, and templates — a template is a saved arrangement (clips, overlays, titles, captions, by reference) that comes back editable.- library_list browses it; library_add copies an asset into the project (the import step "library"-scope attachments need); template_add re-materializes a template; save_template saves timeline items as one.+- Assets from the user's iOS app carry an origin: "camera" is a clip they recorded on their phone (their Camera Roll — "the video I shot on my phone" lives here), "inspiration" a reference saved into the Library's Inspiration folder. library_add imports either like any other asset.+- notes_list reads the user's synced notes (written on their phone or the Notes tab) — the place to look when they point at "my note" for a script, caption, or voiceover text.- library_organize handles folders (create/rename/delete), filing (move_asset), and deletes (permanent — explicit ask only).- import_url reads any URL (TikTok, YouTube, Instagram, an X post or Article, a web page, direct links): a page comes back as its article text and its pictures, a post as its video or photos, and a source that is only words as sourceText alone. Media lands as a card in the chat with that text quoted beside it; the user drags a card to the timeline, Media, or the Library. Place it with add_clip only when they asked for it in the cut.Attachments: media files dropped on the chat import into project media by themselves; library attachments wait for library_add.`,diff --git a/site/src/cut/server/ai/headlessTools.ts b/site/src/cut/server/ai/headlessTools.tsindex 246541b1..2f074d00 100644--- a/site/src/cut/server/ai/headlessTools.ts+++ b/site/src/cut/server/ai/headlessTools.ts@@ -51,6 +51,7 @@ const PAGE_SESSION_TOOLS: ReadonlySet<string> = new Set(["library_list","library_add","library_organize",+ "notes_list","template_add","file_asset","import_url",diff --git a/site/src/cut/server/cloud/jobs.ts b/site/src/cut/server/cloud/jobs.tsindex 6ae6fc45..2c7e9e3f 100644--- a/site/src/cut/server/cloud/jobs.ts+++ b/site/src/cut/server/cloud/jobs.ts@@ -460,7 +460,7 @@ export const jobsCloud = {* the assets, and the client polls this job for them. */async importUrlToLibrary(userId: string, req: Request) {try {- const { url } = (await req.json()) as { url?: string };+ const { url, origin } = (await req.json()) as { url?: string; origin?: string };if (!url) return err("No URL provided.", 400);const capped = await renderJobCheck(userId);if (capped) return capped;@@ -468,7 +468,13 @@ export const jobsCloud = {data: {userId,kind: "import_url",- spec: { url, target: "library" } as unknown as Prisma.InputJsonValue,+ spec: {+ url,+ target: "library",+ // An inspiration link's downloads land in the Inspiration folder,+ // carrying the origin the Camera Roll and Library filters read.+ ...(origin === "inspiration" ? { origin } : {}),+ } as unknown as Prisma.InputJsonValue,},});wakeRenderWorker();diff --git a/site/src/cut/server/cloud/library.ts b/site/src/cut/server/cloud/library.tsindex eff72958..a9ace089 100644--- a/site/src/cut/server/cloud/library.ts+++ b/site/src/cut/server/cloud/library.ts@@ -23,6 +23,7 @@ import {decodeFileParam,dedupeName,err,+ inspirationFolderId,redirect,safeFileName,typeOf,@@ -41,6 +42,9 @@ interface AssetMeta {/** File name of the source's cover image, an object of its own under this* account's library prefix. */posterFile?: string;+ /** How the asset entered the account from the iOS app: a phone camera+ * recording (the desktop's Camera Roll) or an inspiration item. */+ origin?: "camera" | "inspiration";}interface TemplateDoc {@@ -86,6 +90,7 @@ function assetView(folderId: row.folderId ?? null,...(meta.source ? { source: meta.source } : {}),...(meta.posterFile ? { posterFile: meta.posterFile } : {}),+ ...(meta.origin ? { origin: meta.origin } : {}),};}@@ -291,11 +296,30 @@ export const libraryCloud = {fileName?: string;mime?: string;bytes?: number;+ resume?: boolean;};if (!body.fileName || typeof body.bytes !== "number" || body.bytes <= 0) {return err("fileName and bytes are required.", 400);}if (!typeOf(body.fileName)) return err("Unsupported file type.", 400);+ // A resumed upload already holds its claim: the client kept the bytes+ // (the iOS app's journal) and asks for a fresh URL under the same name.+ // A claim that completed in the meantime reports done and uploads+ // nothing; a same-named row of a different size is a different file and+ // falls through to a fresh claim under a deduped name.+ if (body.resume) {+ const row = await prisma.cutMediaObject.findFirst({+ where: { userId, kind: "library", fileName: safeFileName(body.fileName) },+ orderBy: { createdAt: "desc" },+ });+ if (row && Number(row.bytes) === Math.round(body.bytes)) {+ if (row.uploadState === "complete") {+ return Response.json({ fileName: row.fileName, key: row.r2Key, done: true });+ }+ const url = await presignPut(row.r2Key, body.mime ?? "application/octet-stream");+ return Response.json({ fileName: row.fileName, key: row.r2Key, url });+ }+ }const over = await quotaCheck(userId, body.bytes);if (over) return over;const fileName = dedupeName(@@ -324,19 +348,38 @@ export const libraryCloud = {}},- /** Finish a library upload: verify, mark complete, register the asset. */+ /** Finish a library upload: verify, mark complete, register the asset. An+ * inspiration upload files itself into the ensured Inspiration folder; any+ * other folderId must name one of this user's library folders. */async complete(userId: string, req: Request) {try {- const { key, posterKey, meta } = (await req.json()) as {+ const { key, posterKey, meta, folderId } = (await req.json()) as {key?: string;posterKey?: string;meta?: AssetMeta;+ folderId?: string;};if (!key) return err("key is required.", 400);+ let destFolder: string | null = null;+ if (meta?.origin === "inspiration") {+ destFolder = await ensureInspirationFolder(userId);+ } else if (folderId) {+ const folder = await prisma.cutFolder.findFirst({+ where: { id: folderId, userId, scope: "library" },+ });+ if (!folder) return err("Folder not found.", 404);+ destFolder = folderId;+ }const obj = await prisma.cutMediaObject.findFirst({where: { userId, r2Key: key },});if (!obj) return err("Unknown upload.", 404);+ // A retried complete (the iOS app reconciling after an interrupted+ // sync) lands on the asset it already made instead of minting a twin.+ const already = await prisma.cutLibraryAsset.findFirst({+ where: { userId, mediaObjectId: obj.id },+ });+ if (already) return Response.json(assetView(already, obj));const info = obj.uploadState === "complete" ? null : await head(key);if (obj.uploadState !== "complete" && !info)return err("The upload never arrived.", 400);@@ -382,6 +425,7 @@ export const libraryCloud = {data: {userId,mediaObjectId: obj.id,+ folderId: destFolder,meta: {name: meta?.name ?? obj.fileName,type: meta?.type ?? typeOf(obj.fileName) ?? "video",@@ -393,6 +437,9 @@ export const libraryCloud = {...((posterFile ?? meta?.posterFile)? { posterFile: posterFile ?? meta?.posterFile }: {}),+ ...(meta?.origin === "camera" || meta?.origin === "inspiration"+ ? { origin: meta.origin }+ : {}),} as unknown as Prisma.InputJsonValue,},});@@ -511,8 +558,9 @@ export const libraryCloud = {async remove(userId: string, id: string) {try {- const freed = await deleteLibraryAssetCascade(userId, id);- if (freed === null) throw new Error("Library asset not found.");+ // Idempotent: a delete replayed from the iOS app's journal after the+ // asset already left reports done, so the tombstone clears.+ await deleteLibraryAssetCascade(userId, id);return Response.json({ ok: true });} catch (e) {return caught(e, "Could not delete.");@@ -838,6 +886,19 @@ export const libraryCloud = {* rename, empty, or delete. */export const fontsFolderId = (userId: string) => `fonts-${userId}`;+/** The Inspiration folder, created the first time an inspiration item lands.+ * Its id is derived (util.inspirationFolderId), so every writer converges on+ * one row; an ordinary folder otherwise, free to rename or delete. */+export async function ensureInspirationFolder(userId: string): Promise<string> {+ const id = inspirationFolderId(userId);+ await prisma.cutFolder.upsert({+ where: { id },+ create: { id, userId, name: "Inspiration", scope: "library" },+ update: {},+ });+ return id;+}+export async function seedFontsFolder(userId: string): Promise<void> {const id = fontsFolderId(userId);if (await prisma.cutFolder.findUnique({ where: { id } })) return;diff --git a/site/src/cut/server/cloud/notes.ts b/site/src/cut/server/cloud/notes.tsnew file mode 100644index 00000000..aa75cf06--- /dev/null+++ b/site/src/cut/server/cloud/notes.ts@@ -0,0 +1,103 @@+// Synced notes: one CutNote row per note, written by the iOS app and the+// desktop Notes tab. Both sides merge by last-writer-wins on the client's+// `updatedAt` stamp, and deletes keep tombstone rows so a removal made+// offline on one device still lands on the other.+import { prisma } from "@/lib/prisma";+import { caught, err } from "./util";++export interface NoteView {+ id: string;+ title: string;+ body: string;+ colorIndex: number;+ updatedAt: number;+ deletedAt: number | null;+ createdAt: number;+}++const view = (row: {+ id: string;+ title: string;+ body: string;+ colorIndex: number;+ updatedAt: Date;+ deletedAt: Date | null;+ createdAt: Date;+}): NoteView => ({+ id: row.id,+ title: row.title,+ body: row.body,+ colorIndex: row.colorIndex,+ updatedAt: row.updatedAt.getTime(),+ deletedAt: row.deletedAt?.getTime() ?? null,+ createdAt: row.createdAt.getTime(),+});++const NOTE_ID = /^[\w-]{1,64}$/;+const TEXT_MAX = 20_000;++export const notesCloud = {+ /** Every note including tombstones, newest first. Notes are small and the+ * set is one person's, so the merge reads the whole list. */+ async list(userId: string) {+ const rows = await prisma.cutNote.findMany({+ where: { userId },+ orderBy: { updatedAt: "desc" },+ });+ return Response.json({ notes: rows.map(view) });+ },++ /** Upsert one note. The write applies only when its stamp is not older than+ * the stored row's — last writer wins — and a live write revives a+ * tombstone. The response is whichever version won. */+ async put(userId: string, id: string, req: Request) {+ try {+ if (!NOTE_ID.test(id)) return err("Invalid note id.", 400);+ const body = (await req.json()) as {+ title?: string;+ body?: string;+ colorIndex?: number;+ updatedAt?: number;+ };+ if (typeof body.updatedAt !== "number" || !Number.isFinite(body.updatedAt)) {+ return err("updatedAt is required.", 400);+ }+ const stamp = new Date(body.updatedAt);+ const data = {+ title: String(body.title ?? "").slice(0, 200),+ body: String(body.body ?? "").slice(0, TEXT_MAX),+ colorIndex: Number.isInteger(body.colorIndex) ? (body.colorIndex as number) : 0,+ updatedAt: stamp,+ deletedAt: null,+ };+ const existing = await prisma.cutNote.findFirst({ where: { id, userId } });+ if (!existing) {+ const row = await prisma.cutNote.create({ data: { id, userId, ...data } });+ return Response.json(view(row));+ }+ if (existing.updatedAt.getTime() > stamp.getTime()) {+ return Response.json(view(existing));+ }+ const row = await prisma.cutNote.update({ where: { id }, data });+ return Response.json(view(row));+ } catch (e) {+ return caught(e, "Could not save the note.");+ }+ },++ /** Delete one note: the row stays as a tombstone carrying the delete's own+ * stamp, so both clients drop their copies on the next merge. */+ async remove(userId: string, id: string) {+ try {+ const existing = await prisma.cutNote.findFirst({ where: { id, userId } });+ if (!existing) return Response.json({ ok: true });+ await prisma.cutNote.update({+ where: { id },+ data: { updatedAt: new Date(), deletedAt: new Date() },+ });+ return Response.json({ ok: true });+ } catch (e) {+ return caught(e, "Could not delete the note.");+ }+ },+};diff --git a/site/src/cut/server/cloud/phone.ts b/site/src/cut/server/cloud/phone.tsnew file mode 100644index 00000000..5b1484d3--- /dev/null+++ b/site/src/cut/server/cloud/phone.ts@@ -0,0 +1,42 @@+// The account's link to the iOS app. Every request the app makes carries+// `x-donkey-cut-client: ios`; the first sighting writes a CutPhoneLink row and+// the desktop keys its mobile surfaces (Camera Roll, Notes) off that row.+import { prisma } from "@/lib/prisma";++export const PHONE_CLIENT_HEADER = "x-donkey-cut-client";++// Accounts whose link this process already refreshed recently, so the row is+// written about once an hour per server instead of once per request.+const seenAt = new Map<string, number>();+const SEEN_TTL_MS = 60 * 60 * 1000;++/** Record that this request came from the iOS app, when it did. Fire-and-forget:+ * the link is a convenience flag and never gates the request itself. */+export function notePhoneClient(req: Request, userId: string): void {+ if (req.headers.get(PHONE_CLIENT_HEADER) !== "ios") return;+ const last = seenAt.get(userId);+ const now = Date.now();+ if (last && now - last < SEEN_TTL_MS) return;+ // Sweep expired entries so the map stays bounded by accounts active within+ // the TTL. At most one sweep per account per hour.+ for (const [id, at] of seenAt) {+ if (now - at >= SEEN_TTL_MS) seenAt.delete(id);+ }+ seenAt.set(userId, now);+ void prisma.cutPhoneLink+ .upsert({+ where: { userId },+ create: { userId },+ update: {},+ })+ .catch(() => {+ seenAt.delete(userId);+ });+}++export const phoneApi = {+ async get(userId: string) {+ const row = await prisma.cutPhoneLink.findUnique({ where: { userId } });+ return Response.json({ linked: row != null });+ },+};diff --git a/site/src/cut/server/cloud/routes.ts b/site/src/cut/server/cloud/routes.tsindex f0a6df38..528ac10e 100644--- a/site/src/cut/server/cloud/routes.ts+++ b/site/src/cut/server/cloud/routes.ts@@ -13,6 +13,8 @@ import { runGc } from "./gc";import { jobsCloud } from "./jobs";import { libraryCloud } from "./library";import { mediaCloud } from "./media";+import { notesCloud } from "./notes";+import { notePhoneClient, phoneApi } from "./phone";import { projectsCloud } from "./projects";import { turnsCloud } from "./turns";import { shareCloud } from "./share";@@ -96,6 +98,11 @@ const CUT_CLOUD_ROUTES: CloudRoute[] = [{ method: "POST", path: "/api/cut-cloud/projects/:id/turns", handler: (r, u, p) => turnsCloud.queue(u, p.id, r) },{ method: "POST", path: "/api/cut-cloud/turns/:jobId/cancel", handler: (_r, u, p) => turnsCloud.cancel(u, p.jobId) },+ { method: "GET", path: "/api/cut-cloud/notes", handler: (_r, u) => notesCloud.list(u) },+ { method: "PUT", path: "/api/cut-cloud/notes/:id", handler: (r, u, p) => notesCloud.put(u, p.id, r) },+ { method: "DELETE", path: "/api/cut-cloud/notes/:id", handler: (_r, u, p) => notesCloud.remove(u, p.id) },+ { method: "GET", path: "/api/cut-cloud/phone", handler: (_r, u) => phoneApi.get(u) },+{ method: "POST", path: "/api/cut-cloud/transcribe", handler: (r, u) => transcribeCloud.transcribe(u, r) },{ method: "POST", path: "/api/cut-cloud/ai/captions", handler: (r, u) => captionsCloud.captions(u, r) },{ method: "POST", path: "/api/cut-cloud/ai/visual-subtitles", handler: (r, u) => captionsCloud.visualSubtitles(u, r) },@@ -135,6 +142,7 @@ export async function cutCloudCatchAll(req: DonkeyAuthenticatedRequest): Promiseheaders: { Allow: match.methodNotAllowed.join(", ") },});}+ notePhoneClient(req, req.donkey.userId);const res = await match.route.handler(req, req.donkey.userId, match.params);// A HEAD reply carries the GET headers but no body.if (match.head && res.body) {diff --git a/site/src/cut/server/cloud/util.ts b/site/src/cut/server/cloud/util.tsindex ada57def..79e36b0d 100644--- a/site/src/cut/server/cloud/util.ts+++ b/site/src/cut/server/cloud/util.ts@@ -58,6 +58,11 @@ export function dedupeName(base: string, taken: ReadonlySet<string>): string {return name;}+/** The library folder inspiration items land in, derived from the user id so+ * every writer — the complete route, the URL-import worker — upserts the same+ * row instead of racing to create one. An ordinary folder otherwise. */+export const inspirationFolderId = (userId: string) => `inspiration-${userId}`;+const VIDEO_RE = /\.(mp4|mov|m4v|webm|mkv)$/i;const AUDIO_RE = /\.(mp3|m4a|aac|wav|ogg|flac)$/i;const IMAGE_RE = /\.(png|jpe?g|webp|gif|avif|bmp)$/i;diff --git a/site/src/cut/server/library.ts b/site/src/cut/server/library.tsindex 133a97bc..4ecf6ef4 100644--- a/site/src/cut/server/library.ts+++ b/site/src/cut/server/library.ts@@ -35,6 +35,10 @@ export interface LibraryAsset {* same media route — what a card and the viewer show while the video loads.* Only an import from a site that publishes one has it. */posterFile?: string;+ /** How the asset entered the account from the iOS app: a phone camera+ * recording (the desktop's Camera Roll) or an inspiration item. Cloud shelf+ * only. */+ origin?: "camera" | "inspiration";}export interface LibraryFolder {diff --git a/site/src/cut/worker/importUrlJob.ts b/site/src/cut/worker/importUrlJob.tsindex e5767c0e..7a903eaa 100644--- a/site/src/cut/worker/importUrlJob.ts+++ b/site/src/cut/worker/importUrlJob.ts@@ -2,7 +2,7 @@ import { mkdtemp, rm } from "node:fs/promises";import os from "node:os";import path from "node:path";import type { Prisma } from "@/generated/prisma/client";-import { dedupeName, safeFileName, typeOf } from "../server/cloud/util";+import { dedupeName, inspirationFolderId, safeFileName, typeOf } from "../server/cloud/util";import type { LibraryAsset } from "../server/library";import { probeDuration } from "../server/frames";import { download } from "../server/urlDownload";@@ -35,11 +35,27 @@ export async function runImportUrlJob(job: ClaimedJob,isCanceled: () => boolean): Promise<ImportUrlResult | LibraryImportResult> {- const { url, target } = (job.spec ?? {}) as { url?: string; target?: string };+ const { url, target, origin } = (job.spec ?? {}) as {+ url?: string;+ target?: string;+ origin?: string;+ };if (!url || !/^https?:\/\//i.test(url.trim())) throw new Error("Enter a valid http(s) URL.");const toLibrary = target === "library";const projectId = job.projectId;if (!toLibrary && !projectId) throw new Error("Import job has no project.");+ // An inspiration link's downloads are filed into the ensured Inspiration+ // folder and tagged with the origin the desktop filters read.+ const inspiration = toLibrary && origin === "inspiration";+ let folderId: string | null = null;+ if (inspiration) {+ folderId = inspirationFolderId(job.userId);+ await prisma.cutFolder.upsert({+ where: { id: folderId },+ create: { id: folderId, userId: job.userId, name: "Inspiration", scope: "library" },+ update: {},+ });+ }const tmp = await mkdtemp(path.join(os.tmpdir(), "cut-dl-"));try {@@ -111,7 +127,8 @@ export async function runImportUrlJob(f.file,f.title,dl.source,- posterFile+ posterFile,+ inspiration ? { folderId: folderId!, origin: "inspiration" } : undefined);libraryRows.push(asset.id);assets.push(asset);@@ -141,7 +158,8 @@ async function addLibraryRow(localFile: string,title: string,source: LibraryAsset["source"],- posterFile?: string+ posterFile?: string,+ filing?: { folderId: string; origin: "inspiration" }): Promise<LibraryAsset> {const type = typeOf(fileName);if (!type) throw new Error("Unsupported file type.");@@ -154,11 +172,13 @@ async function addLibraryRow(...(dims ? { width: dims.width, height: dims.height } : {}),...(source ? { source } : {}),...(posterFile ? { posterFile } : {}),+ ...(filing ? { origin: filing.origin } : {}),};const row = await prisma.cutLibraryAsset.create({data: {userId,mediaObjectId,+ folderId: filing?.folderId ?? null,meta: meta as unknown as Prisma.InputJsonValue,},});@@ -170,8 +190,9 @@ async function addLibraryRow(duration,...(dims ? { width: dims.width, height: dims.height } : {}),addedAt: row.createdAt.getTime(),- folderId: null,+ folderId: filing?.folderId ?? null,...(source ? { source } : {}),...(posterFile ? { posterFile } : {}),+ ...(filing ? { origin: filing.origin } : {}),};}