Open source CapCut alternative.
TypeScript
feat(site): notes wear labels [rebuild]
David Le040dffebda86
diff --git a/site/prisma/Cut.prisma b/site/prisma/Cut.prismaindex 0213f09a..b2a0524b 100644--- a/site/prisma/Cut.prisma+++ b/site/prisma/Cut.prisma@@ -149,6 +149,9 @@ model CutNote {colorIndex Int @default(0)// The CutFolder (scope "note") this note is filed in; null is the top level.folderId String?+ // CutNoteLabel ids this note carries. Labels ride the note's own+ // last-writer-wins write; ids naming no label are dropped on read.+ labelIds String[] @default([])updatedAt DateTimedeletedAt DateTime?createdAt DateTime @default(now())@@ -156,6 +159,19 @@ model CutNote {@@index([userId, updatedAt])}+// One note label, shared by the iOS app and the desktop Notes tab. Like note+// folders: the id is client-generated, one PUT creates and renames, and the+// listing is the truth — a label missing from it was deleted.+model CutNoteLabel {+ id String @id+ userId String+ name String+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ @@index([userId])+}+// 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 {diff --git a/site/prisma/migrations/20260826070000/migration.sql b/site/prisma/migrations/20260826070000/migration.sqlnew file mode 100644index 00000000..fbf51950--- /dev/null+++ b/site/prisma/migrations/20260826070000/migration.sql@@ -0,0 +1,16 @@+-- AlterTable+ALTER TABLE "CutNote" ADD COLUMN "labelIds" TEXT[] DEFAULT ARRAY[]::TEXT[];++-- CreateTable+CREATE TABLE "CutNoteLabel" (+ "id" TEXT NOT NULL,+ "userId" TEXT NOT NULL,+ "name" TEXT NOT NULL,+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updatedAt" TIMESTAMP(3) NOT NULL,++ CONSTRAINT "CutNoteLabel_pkey" PRIMARY KEY ("id")+);++-- CreateIndex+CREATE INDEX "CutNoteLabel_userId_idx" ON "CutNoteLabel"("userId");diff --git a/site/src/cut/components/LibraryView.tools.ts b/site/src/cut/components/LibraryView.tools.tsindex 043982fe..11c17ab8 100644--- a/site/src/cut/components/LibraryView.tools.ts+++ b/site/src/cut/components/LibraryView.tools.ts@@ -18,7 +18,7 @@ export const LIBRARY_TOOLS = [{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 — with the folders they are filed in. Read them when the user points at \"my note(s)\" for a script, caption, or voiceover text, and when they name a folder (\"the scripts folder\") match it against `folders` and read the notes carrying that folder. Quote a note's body verbatim when they ask for its words.",+ "List the user's synced notes — short scripts and ideas written in the Donkey Cut iOS app or the desktop Notes tab — with the folders they are filed in and the labels they carry. Read them when the user points at \"my note(s)\" for a script, caption, or voiceover text; when they name a folder (\"the scripts folder\") match it against `folders` and read the notes carrying that folder; when they name a label (\"my hook ideas\") match it against `labels` and read the notes wearing it. Quote a note's body verbatim when they ask for its words.",inputSchema: obj({}),},{diff --git a/site/src/cut/components/NoteComposer.tsx b/site/src/cut/components/NoteComposer.tsxindex 30f50c62..cacaac42 100644--- a/site/src/cut/components/NoteComposer.tsx+++ b/site/src/cut/components/NoteComposer.tsx@@ -1,9 +1,9 @@"use client";-import { useEffect, useLayoutEffect, useRef } from "react";+import { useEffect, useLayoutEffect, useRef, useState } from "react";import type React from "react";import { createPortal } from "react-dom";-import { ArrowLeft, Check, ChevronDown, Trash2 } from "lucide-react";+import { ArrowLeft, Check, ChevronDown, Pencil, Plus, Tag, Trash2 } from "lucide-react";import { Button } from "@/components/ui/button";import {DropdownMenu,@@ -11,7 +11,10 @@ import {DropdownMenuItem,DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";-import { NOTE_COLORS, noteColor } from "@/cut/lib/notes";+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";+import { NOTE_COLORS, noteColor, type CutNoteLabel } from "@/cut/lib/notes";+import { NOTE_LABELS_MAX } from "@/cut/lib/types";+import { cn } from "@/lib/utils";// The note paper's ink, matching the iOS app.const NOTE_INK = "#201a0d";@@ -22,17 +25,26 @@ export interface NoteDraft {body: string;colorIndex: number;folderId: string | null;+ labelIds: string[];isNew: boolean;/** What the note held when it opened. A draft that still matches closes* without a write, so opening a note to read it leaves the list alone. */- saved: { title: string; body: string; colorIndex: number };+ saved: { title: string; body: string; colorIndex: number; labelIds: string[] };}+/** The labels a note wears, as a comparable key. A note wears a set — the+ * chips read in the account's own order, and the picker appends where it+ * toggles — so taking a label off and putting it back is no change, and must+ * not stamp the note as edited: that stamp wins last-writer-wins against a+ * real edit made on the phone. */+const labelKey = (ids: string[]) => [...new Set(ids)].sort().join("\n");+/** True when the draft holds something the stored note does not. */export const noteChanged = (d: NoteDraft) =>d.title.trim() !== d.saved.title ||d.body.trim() !== d.saved.body ||- d.colorIndex !== d.saved.colorIndex;+ d.colorIndex !== d.saved.colorIndex ||+ labelKey(d.labelIds) !== labelKey(d.saved.labelIds);/** The box that scrolls around `node`: the app shell gives each page a main* column with its own scrollbar, and the document itself scrolls only where@@ -74,9 +86,13 @@ export function NoteComposer({draft,back,from,+ labels,onChange,onClose,onDelete,+ onCreateLabel,+ onRenameLabel,+ onDeleteLabel,}: {draft: NoteDraft;/** Where closing goes back to: the folder the note is filed in, or all@@ -85,16 +101,26 @@ export function NoteComposer({/** The list this note was opened from. The sheet is portaled out of the* page, so this is how it finds the box to hold still while it is up. */from?: React.RefObject<HTMLElement | null>;+ /** Every label on the account, for the note's label row and its picker. */+ labels: CutNoteLabel[];onChange: (draft: NoteDraft) => void;onClose: () => void;onDelete: () => void;+ /** Make a label and answer with its id, so the picker can put it on the+ * note at once. */+ onCreateLabel: (name: string) => string;+ onRenameLabel: (id: string, name: string) => void;+ onDeleteLabel: (id: string) => void;}) {const paper = noteColor(draft.colorIndex);const titleRef = useAutoGrow(draft.title);const bodyRef = useAutoGrow(draft.body);+ // While the label picker is up, Escape is its to close.+ const [picking, setPicking] = useState(false);useEffect(() => {const onKey = (e: KeyboardEvent) => {+ if (e.key === "Escape" && picking) return;if (e.key === "Escape" || ((e.metaKey || e.ctrlKey) && e.key === "Enter")) {e.preventDefault();onClose();@@ -102,7 +128,21 @@ export function NoteComposer({};window.addEventListener("keydown", onKey);return () => window.removeEventListener("keydown", onKey);- }, [onClose]);+ }, [onClose, picking]);++ const toggleLabel = (id: string) => {+ const worn = draft.labelIds.includes(id);+ // A full note takes no more: the server refuses the write past the cap,+ // so the picker is where it stops.+ if (!worn && draft.labelIds.length >= NOTE_LABELS_MAX) return;+ onChange({+ ...draft,+ labelIds: worn ? draft.labelIds.filter((l) => l !== id) : [...draft.labelIds, id],+ });+ };+ // The note's labels, in the order the account lists them. An id naming+ // nothing — a label deleted on another device — drops out of view.+ const worn = labels.filter((l) => draft.labelIds.includes(l.id));// The page behind the sheet stays put, so a wheel over the note moves the// note and closing it comes back to the same place in the list. The app shell@@ -213,6 +253,44 @@ export function NoteComposer({}}}/>+ {/* The note's labels, worn under the title. The picker adds and+ removes them, and keeps the account's label list itself. */}+ <div className="flex flex-wrap items-center gap-1.5">+ {worn.map((l) => (+ <button+ key={l.id}+ className="group flex cursor-pointer items-center gap-1 rounded-full bg-black/10 px-2.5 py-1 text-xs font-medium hover:bg-black/15"+ aria-label={`Remove label ${l.name}`}+ onClick={() => toggleLabel(l.id)}+ >+ {l.name}+ <span className="opacity-40 group-hover:opacity-80">×</span>+ </button>+ ))}+ <Popover open={picking} onOpenChange={setPicking}>+ <PopoverTrigger+ render={+ <button+ className="flex cursor-pointer items-center gap-1 rounded-full px-2.5 py-1 text-xs font-medium opacity-50 hover:bg-black/10 hover:opacity-80"+ aria-label="Add label"+ />+ }+ >+ {worn.length === 0 ? <Tag className="size-3.5" /> : <Plus className="size-3.5" />}+ {worn.length === 0 ? "Add label" : "Label"}+ </PopoverTrigger>+ <PopoverContent align="start" className="w-64">+ <LabelPicker+ labels={labels}+ selected={draft.labelIds}+ onToggle={toggleLabel}+ onCreate={(name) => toggleLabel(onCreateLabel(name))}+ onRename={onRenameLabel}+ onDelete={onDeleteLabel}+ />+ </PopoverContent>+ </Popover>+ </div><textarearef={bodyRef}rows={1}@@ -228,3 +306,149 @@ export function NoteComposer({document.body);}++/** The label picker: every label on the account, the note's own checked.+ * Typing filters the list, and Enter — or the create row — makes what was+ * typed and puts it on the note. Each row renames in place and deletes; a+ * delete takes the label off every note. */+function LabelPicker({+ labels,+ selected,+ onToggle,+ onCreate,+ onRename,+ onDelete,+}: {+ labels: CutNoteLabel[];+ selected: string[];+ onToggle: (id: string) => void;+ onCreate: (name: string) => void;+ onRename: (id: string, name: string) => void;+ onDelete: (id: string) => void;+}) {+ const [query, setQuery] = useState("");+ const [renaming, setRenaming] = useState<{ id: string; name: string } | null>(null);+ const typed = query.trim();+ const full = selected.length >= NOTE_LABELS_MAX;+ const shown = labels.filter((l) => l.name.toLowerCase().includes(typed.toLowerCase()));+ const exact = labels.find((l) => l.name.toLowerCase() === typed.toLowerCase());++ /** Enter on the input: put the typed label on the note, making it first+ * when the account has no label by that name. */+ const commitTyped = () => {+ if (!typed || full) return;+ if (exact) {+ if (!selected.includes(exact.id)) onToggle(exact.id);+ } else {+ onCreate(typed);+ }+ setQuery("");+ };++ const commitRename = () => {+ if (!renaming) return;+ const name = renaming.name.trim();+ const held = labels.find((l) => l.id === renaming.id);+ if (name && held && name !== held.name) onRename(renaming.id, name);+ setRenaming(null);+ };++ return (+ <div className="flex max-h-80 w-full flex-col">+ <input+ autoFocus+ value={query}+ placeholder={labels.length === 0 ? "New label…" : "Find or create…"}+ className="border-b border-foreground/10 px-3 py-2.5 text-sm outline-none placeholder:text-muted-foreground"+ onChange={(e) => setQuery(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ e.preventDefault();+ commitTyped();+ }+ }}+ />+ <div className="min-h-0 flex-1 overflow-y-auto p-1">+ {shown.map((l) =>+ renaming?.id === l.id ? (+ <input+ key={l.id}+ autoFocus+ value={renaming.name}+ className="w-full rounded-md bg-foreground/5 px-2.5 py-1.5 text-sm outline-none"+ onChange={(e) => setRenaming({ id: l.id, name: e.target.value })}+ onBlur={commitRename}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ e.preventDefault();+ commitRename();+ } else if (e.key === "Escape") {+ e.preventDefault();+ e.stopPropagation();+ setRenaming(null);+ }+ }}+ />+ ) : (+ <div+ key={l.id}+ className="group flex items-center gap-1 rounded-md hover:bg-foreground/5"+ >+ <button+ className={cn(+ "flex min-w-0 flex-1 items-center gap-2 px-2.5 py-1.5 text-left text-sm",+ full && !selected.includes(l.id)+ ? "cursor-default opacity-40"+ : "cursor-pointer",+ )}+ disabled={full && !selected.includes(l.id)}+ onClick={() => onToggle(l.id)}+ >+ <span className="min-w-0 flex-1 truncate">{l.name}</span>+ <Check+ className={cn(+ "size-4 shrink-0 opacity-70",+ !selected.includes(l.id) && "invisible",+ )}+ />+ </button>+ <button+ className="hidden shrink-0 cursor-pointer rounded p-1 text-muted-foreground group-hover:block hover:text-foreground"+ aria-label={`Rename label ${l.name}`}+ onClick={() => setRenaming({ id: l.id, name: l.name })}+ >+ <Pencil className="size-3.5" />+ </button>+ <button+ className="hidden shrink-0 cursor-pointer rounded p-1 pr-2 text-muted-foreground group-hover:block hover:text-destructive"+ aria-label={`Delete label ${l.name}`}+ onClick={() => onDelete(l.id)}+ >+ <Trash2 className="size-3.5" />+ </button>+ </div>+ ),+ )}+ {typed && !exact && !full && (+ <button+ className="flex w-full cursor-pointer items-center gap-2 rounded-md px-2.5 py-1.5 text-left text-sm hover:bg-foreground/5"+ onClick={commitTyped}+ >+ <Plus className="size-4 shrink-0 opacity-70" />+ <span className="min-w-0 flex-1 truncate">Create “{typed}”</span>+ </button>+ )}+ {full && (+ <div className="px-2.5 py-2 text-sm text-muted-foreground">+ A note holds {NOTE_LABELS_MAX} labels. Take one off to add another.+ </div>+ )}+ {labels.length === 0 && !typed && (+ <div className="px-2.5 py-2 text-sm text-muted-foreground">+ Type a name to make your first label.+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/site/src/cut/components/NotesView.tsx b/site/src/cut/components/NotesView.tsxindex 60089d13..915fa3d4 100644--- a/site/src/cut/components/NotesView.tsx+++ b/site/src/cut/components/NotesView.tsx@@ -8,9 +8,11 @@ import { Button } from "@/components/ui/button";import {deleteNote,deleteNoteFolder,+ deleteNoteLabel,noteColor,saveNote,saveNoteFolder,+ saveNoteLabel,type CutNote,} from "@/cut/lib/notes";import { homeHref, useCutBase } from "@/cut/lib/nav";@@ -38,8 +40,9 @@ async function writeNote(client: QueryClient,d: NoteDraft,settleFolder: (folderId: string | null) => Promise<void>,+ settleLabels: (labelIds: string[]) => Promise<string[]>,): Promise<boolean> {- const { id, title, body, colorIndex, folderId } = d;+ const { id, title, body, colorIndex, folderId, labelIds } = d;if (!title.trim() && !body.trim()) return true;if (!noteChanged(d)) return true;const now = Date.now();@@ -49,6 +52,7 @@ async function writeNote(body: body.trim(),colorIndex,folderId,+ labelIds,updatedAt: now,deletedAt: null,createdAt: now,@@ -62,12 +66,17 @@ async function writeNote(};});await settleFolder(folderId);+ // Only the labels whose own writes landed: one the server never got would be+ // dropped from the note there, and the note would come back missing a label+ // the picker is still showing.+ const live = await settleLabels(labelIds);const saved = await saveNote({id,title: optimistic.title,body: optimistic.body,colorIndex,folderId,+ labelIds: live,}).catch(() => null);if (!saved) return false;patchNotes(client, (prev) => ({@@ -77,6 +86,14 @@ async function writeNote(return true;}+/** A fresh label under a client-minted id, stamped now. */+const mintLabel = (name: string) => ({+ id: crypto.randomUUID(),+ name,+ updatedAt: Date.now(),+ createdAt: Date.now(),+});+/** A stored note, opened for editing. */const draftOf = (n: CutNote): NoteDraft => ({id: n.id,@@ -84,8 +101,9 @@ const draftOf = (n: CutNote): NoteDraft => ({body: n.body,colorIndex: n.colorIndex,folderId: n.folderId ?? null,+ labelIds: n.labelIds,isNew: false,- saved: { title: n.title, body: n.body, colorIndex: n.colorIndex },+ saved: { title: n.title, body: n.body, colorIndex: n.colorIndex, labelIds: n.labelIds },});/** Synced notes: written on the phone or here, merged by last writer wins.@@ -110,6 +128,8 @@ export function NotesView() {const list = notes.data?.notes ?? [];const folders = notes.data?.folders ?? [];+ const labels = notes.data?.labels ?? [];+ const labelName = new Map(labels.map((l) => [l.id, l.name]));// The open folder and the open note both live in the URL (?folder=…¬e=…),// so the browser's back button — the mouse's too — steps out of the note and// then out of the folder, and the location survives a reload.@@ -159,8 +179,9 @@ export function NotesView() {colorIndex: 0,// A note written inside a folder is filed there.folderId: openFolder,+ labelIds: [],isNew: true,- saved: { title: "", body: "", colorIndex: 0 },+ saved: { title: "", body: "", colorIndex: 0, labelIds: [] },});openAt(id);};@@ -174,11 +195,77 @@ export function NotesView() {const settleFolder = async (folderId: string | null) => {if (folderId) await folderWrites.current.get(folderId);};+ // The same holds for labels: one made in the picker is on the note at once,+ // and its own write is awaited before a note carries the id to the server.+ // A write that failed answers false, and the id it minted never reaches a+ // note — the server would drop it from labelIds without a word.+ const labelWrites = useRef(new Map<string, Promise<boolean>>());+ const settleLabels = async (labelIds: string[]) => {+ const landed = await Promise.all(+ labelIds.map(async (id) => (await labelWrites.current.get(id)) ?? true),+ );+ return labelIds.filter((_, i) => landed[i]);+ };++ /** Take a label out of the picker, off every note, and off the open draft.+ * What a delete does here, and what a failed create undoes. */+ const forgetLabel = (id: string) => {+ patchNotes(client, (prev) => ({+ ...prev,+ labels: prev.labels.filter((l) => l.id !== id),+ notes: prev.notes.map((n) =>+ n.labelIds.includes(id)+ ? { ...n, labelIds: n.labelIds.filter((l) => l !== id) }+ : n,+ ),+ }));+ const held = buffer.current;+ if (held?.labelIds.includes(id)) {+ edit({+ ...held,+ labelIds: held.labelIds.filter((l) => l !== id),+ saved: { ...held.saved, labelIds: held.saved.labelIds.filter((l) => l !== id) },+ });+ }+ };++ /** Make a label under a fresh id and answer with it. */+ const createLabel = (name: string): string => {+ const label = mintLabel(name);+ patchNotes(client, (prev) => ({ ...prev, labels: [...prev.labels, label] }));+ const write = saveNoteLabel(label.id, name).then(+ () => true,+ () => {+ // The label was never made, so it comes off the picker and off the+ // note that was wearing it rather than lingering as a dead id.+ forgetLabel(label.id);+ return false;+ },+ );+ labelWrites.current.set(label.id, write);+ void write.finally(() => labelWrites.current.delete(label.id));+ return label.id;+ };++ const renameLabel = (id: string, name: string) => {+ patchNotes(client, (prev) => ({+ ...prev,+ labels: prev.labels.map((l) => (l.id === id ? { ...l, name } : l)),+ }));+ void saveNoteLabel(id, name).catch(() => reload());+ };++ /** Delete a label. Every note wearing it — the open draft too — lets it+ * go. */+ const removeLabel = (id: string) => {+ forgetLabel(id);+ void deleteNoteLabel(id).catch(() => reload());+ };/** Write a note out and let go of it. */const commit = (d: NoteDraft) => {setEditing(null);- void writeNote(client, d, settleFolder).then((ok) => {+ void writeNote(client, d, settleFolder, settleLabels).then((ok) => {if (!ok) reload();});};@@ -231,6 +318,7 @@ export function NotesView() {body: n.body,colorIndex: n.colorIndex,folderId,+ labelIds: n.labelIds,}).catch(() => null),),);@@ -317,9 +405,13 @@ export function NotesView() {draft={draft}back={draftFolderName ?? "All notes"}from={pageRef}+ labels={labels}onChange={edit}onClose={closeNote}onDelete={remove}+ onCreateLabel={createLabel}+ onRenameLabel={renameLabel}+ onDeleteLabel={removeLabel}/>)}<div className="mb-5 flex items-center justify-between gap-4">@@ -386,6 +478,7 @@ export function NotesView() {}}onDelete={async (id) => {patchNotes(client, (prev) => ({+ ...prev,folders: prev.folders.filter((f) => f.id !== id),notes: prev.notes.map((n) =>n.folderId === id ? { ...n, folderId: null } : n,@@ -423,23 +516,40 @@ export function NotesView() {selected={selected}setSelected={setSelected}>- {shown.map((n) => (- <button- key={n.id}- data-sel-id={n.id}- draggable- onDragStart={(e) => onCardDragStart(e, n.id)}- className={cn(- "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",- selected.has(n.id) && "ring-2 ring-[#0a84ff]",- )}- 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>- ))}+ {shown.map((n) => {+ const worn = n.labelIds+ .map((id) => labelName.get(id))+ .filter((name): name is string => !!name);+ return (+ <button+ key={n.id}+ data-sel-id={n.id}+ draggable+ onDragStart={(e) => onCardDragStart(e, n.id)}+ className={cn(+ "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",+ selected.has(n.id) && "ring-2 ring-[#0a84ff]",+ )}+ 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>+ {worn.length > 0 && (+ <div className="mt-auto flex flex-wrap gap-1 pt-1.5">+ {worn.map((name) => (+ <span+ key={name}+ className="rounded-full bg-black/10 px-2 py-0.5 text-[11px] font-medium"+ >+ {name}+ </span>+ ))}+ </div>+ )}+ </button>+ );+ })}</Marquee>)}</div>diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex 3b25616c..8a2db709 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -2558,17 +2558,25 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {},notes_list: async () => {- const { notes, folders } = await fetchNotes();+ const { notes, folders, labels } = await fetchNotes();const folderName = new Map(folders.map((f) => [f.id, f.name]));+ const labelName = new Map(labels.map((l) => [l.id, l.name]));return {folders: folders.map((f) => ({ id: f.id, name: f.name })),- notes: notes.map((n) => ({- id: n.id,- title: n.title,- body: n.body,- ...(n.folderId ? { folder: folderName.get(n.folderId) ?? n.folderId } : {}),- updatedAt: new Date(n.updatedAt).toISOString(),- })),+ labels: labels.map((l) => l.name),+ notes: notes.map((n) => {+ const worn = n.labelIds+ .map((id) => labelName.get(id))+ .filter((name): name is string => !!name);+ return {+ id: n.id,+ title: n.title,+ body: n.body,+ ...(n.folderId ? { folder: folderName.get(n.folderId) ?? n.folderId } : {}),+ ...(worn.length > 0 ? { labels: worn } : {}),+ updatedAt: new Date(n.updatedAt).toISOString(),+ };+ }),};},diff --git a/site/src/cut/lib/notes.ts b/site/src/cut/lib/notes.tsindex b73a2665..48354973 100644--- a/site/src/cut/lib/notes.ts+++ b/site/src/cut/lib/notes.ts@@ -20,6 +20,7 @@ export interface CutNote {body: string;colorIndex: number;folderId: string | null;+ labelIds: string[];updatedAt: number;deletedAt: number | null;createdAt: number;@@ -32,9 +33,19 @@ export interface CutNoteFolder {createdAt: number;}+/** A label notes carry. Like folders, ids are client-generated and one PUT+ * both creates and renames. */+export interface CutNoteLabel {+ id: string;+ name: string;+ updatedAt: number;+ createdAt: number;+}+export interface NotesData {notes: CutNote[];folders: CutNoteFolder[];+ labels: CutNoteLabel[];}/** The note paper palette, shared with the iOS app (NoteColor). Index into it@@ -68,6 +79,7 @@ export async function fetchNotes(): Promise<NotesData> {return {notes: (body.notes ?? []).filter((n) => n.deletedAt === null),folders: body.folders ?? [],+ labels: body.labels ?? [],};}@@ -79,6 +91,7 @@ export async function saveNote(note: {body: string;colorIndex: number;folderId: string | null;+ labelIds: string[];}): Promise<CutNote> {const res = await notesFetch(`/api/cut/notes/${encodeURIComponent(note.id)}`,@@ -113,3 +126,22 @@ export async function deleteNoteFolder(id: string): Promise<void> {});if (!res.ok) throw new Error("Could not delete the folder.");}++/** Create or rename a label under `id`. A create mints the id here so the+ * new label is on the note before the write returns. */+export async function saveNoteLabel(id: string, name: string): Promise<CutNoteLabel> {+ const res = await notesFetch(+ `/api/cut/notes/labels/${encodeURIComponent(id)}`,+ json({ name }),+ );+ if (!res.ok) throw new Error("Could not save the label.");+ return (await res.json()) as CutNoteLabel;+}++/** Delete a label. Every note carrying it lets it go. */+export async function deleteNoteLabel(id: string): Promise<void> {+ const res = await notesFetch(`/api/cut/notes/labels/${encodeURIComponent(id)}`, {+ method: "DELETE",+ });+ if (!res.ok) throw new Error("Could not delete the label.");+}diff --git a/site/src/cut/lib/queries.ts b/site/src/cut/lib/queries.tsindex cc6905cf..c463225d 100644--- a/site/src/cut/lib/queries.ts+++ b/site/src/cut/lib/queries.ts@@ -256,9 +256,9 @@ export function usePhoneLink() {}export const notesKey = ["cut", "notes"] as const;-// The snapshot carries the notes and their folders together; the key moved-// with that shape so a page holding the old array never paints from it.-const NOTES_SNAPSHOT = "cut-notes-v2";+// The snapshot carries the notes with their folders and labels; the key moves+// with that shape so a page holding an old shape never paints from it.+const NOTES_SNAPSHOT = "cut-notes-v3";/** The account's synced notes and their folders, phone and desktop edits* merged server-side. */diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.tsindex 5961473c..e26b5860 100644--- a/site/src/cut/lib/types.ts+++ b/site/src/cut/lib/types.ts@@ -192,6 +192,12 @@ export interface StoredAsset {chatId?: string;}+/** Most labels one note may wear. Both clients hold the line at this — the+ * picker stops offering more — and the write is refused past it, so a note+ * never comes back from the server quietly wearing fewer labels than the+ * person put on it. */+export const NOTE_LABELS_MAX = 20;+/** True for an asset that carries no sound. Only video and audio files hold an* audio track; a still (a freeze frame, an imported image) is not a media* container at all, and handing its URL to the audio reader fails the readdiff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex fdfd9ddc..0d177322 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -359,7 +359,7 @@ Project media (\`media\` in editor_state) is every file in the open project. TheThe 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. A camera clip's name is the clock it was shot on; its title, when it has one, was read off the clip itself and is what the user sees on the card — match a request like "the one about the launch" against the title.-- notes_list reads the user's synced notes (written on their phone or the Notes tab) and the folders they are filed in — the place to look when they point at "my note" or name a folder for a script, caption, or voiceover text.+- notes_list reads the user's synced notes (written on their phone or the Notes tab) with the folders they are filed in and the labels they carry — the place to look when they point at "my note", or name a folder or label, 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/cloud/notes.ts b/site/src/cut/server/cloud/notes.tsindex 04e2a0bf..5b5b32f5 100644--- a/site/src/cut/server/cloud/notes.ts+++ b/site/src/cut/server/cloud/notes.ts@@ -7,6 +7,7 @@// the library and the projects home keep their folders in. Folder ids are// client-generated like note ids, so a phone can make one offline and push it// under the id it already filed notes against.+import { NOTE_LABELS_MAX } from "@/cut/lib/types";import { prisma } from "@/lib/prisma";import { caught, err } from "./util";@@ -16,6 +17,7 @@ export interface NoteView {body: string;colorIndex: number;folderId: string | null;+ labelIds: string[];updatedAt: number;deletedAt: number | null;createdAt: number;@@ -28,12 +30,20 @@ export interface NoteFolderView {createdAt: number;}+export interface NoteLabelView {+ id: string;+ name: string;+ updatedAt: number;+ createdAt: number;+}+const view = (row: {id: string;title: string;body: string;colorIndex: number;folderId: string | null;+ labelIds: string[];updatedAt: Date;deletedAt: Date | null;createdAt: Date;@@ -43,6 +53,7 @@ const view = (row: {body: row.body,colorIndex: row.colorIndex,folderId: row.folderId,+ labelIds: row.labelIds,updatedAt: row.updatedAt.getTime(),deletedAt: row.deletedAt?.getTime() ?? null,createdAt: row.createdAt.getTime(),@@ -60,6 +71,18 @@ const folderView = (row: {createdAt: row.createdAt.getTime(),});+const labelView = (row: {+ id: string;+ name: string;+ updatedAt: Date;+ createdAt: Date;+}): NoteLabelView => ({+ id: row.id,+ name: row.name,+ updatedAt: row.updatedAt.getTime(),+ createdAt: row.createdAt.getTime(),+});+const NOTE_ID = /^[\w-]{1,64}$/;const TEXT_MAX = 20_000;@@ -76,19 +99,41 @@ async function resolveFolder(userId: string, folderId: unknown): Promise<stringreturn row?.id ?? null;}+/** The labels a note may carry: the ids among `labelIds` that name one of+ * this account's labels. An id naming nothing is dropped rather than failing+ * the write — the label may have been deleted on the other device while this+ * one was offline. `undefined` means the write said nothing about labels — an+ * older client — and the note keeps the labels it has. */+async function resolveLabels(userId: string, labelIds: unknown): Promise<string[] | undefined> {+ if (!Array.isArray(labelIds)) return undefined;+ const asked = [...new Set(labelIds.filter((id): id is string => typeof id === "string"))];+ if (asked.length === 0) return [];+ const rows = await prisma.cutNoteLabel.findMany({+ where: { id: { in: asked }, userId },+ select: { id: true },+ });+ const known = new Set(rows.map((r) => r.id));+ return asked.filter((id) => known.has(id));+}+export const notesCloud = {/** Every note including tombstones, newest first, and the folders they file* into. Notes are small and the set is one person's, so the merge reads the* whole list. */async list(userId: string) {- const [rows, folders] = await Promise.all([+ const [rows, folders, labels] = await Promise.all([prisma.cutNote.findMany({ where: { userId }, orderBy: { updatedAt: "desc" } }),prisma.cutFolder.findMany({where: { userId, scope: "note" },orderBy: { createdAt: "asc" },}),+ prisma.cutNoteLabel.findMany({ where: { userId }, orderBy: { createdAt: "asc" } }),]);- return Response.json({ notes: rows.map(view), folders: folders.map(folderView) });+ return Response.json({+ notes: rows.map(view),+ folders: folders.map(folderView),+ labels: labels.map(labelView),+ });},/** Upsert one note. The write applies only when its stamp is not older than@@ -102,12 +147,20 @@ export const notesCloud = {body?: string;colorIndex?: number;folderId?: string | null;+ labelIds?: string[];updatedAt?: number;};if (typeof body.updatedAt !== "number" || !Number.isFinite(body.updatedAt)) {return err("updatedAt is required.", 400);}const stamp = new Date(body.updatedAt);+ // Over the cap the write is refused outright: truncating here would+ // answer 200 with a note wearing fewer labels than the person gave it,+ // and the merge would carry that loss back to their other device.+ if (Array.isArray(body.labelIds) && new Set(body.labelIds).size > NOTE_LABELS_MAX) {+ return err(`A note can carry at most ${NOTE_LABELS_MAX} labels.`, 400);+ }+ const labelIds = await resolveLabels(userId, body.labelIds);const data = {title: String(body.title ?? "").slice(0, 200),body: String(body.body ?? "").slice(0, TEXT_MAX),@@ -118,13 +171,19 @@ export const notesCloud = {};const existing = await prisma.cutNote.findFirst({ where: { id, userId } });if (!existing) {- const row = await prisma.cutNote.create({ data: { id, userId, ...data } });+ const row = await prisma.cutNote.create({+ data: { id, userId, ...data, labelIds: labelIds ?? [] },+ });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 });+ const row = await prisma.cutNote.update({+ where: { id },+ // A write that said nothing about labels keeps the ones stored.+ data: labelIds === undefined ? data : { ...data, labelIds },+ });return Response.json(view(row));} catch (e) {return caught(e, "Could not save the note.");@@ -187,4 +246,55 @@ export const notesCloud = {return caught(e, "Could not delete the folder.");}},++ // --- Labels ---++ /** Create or rename one label under a client-chosen id, the way folders+ * work: one call serves both, so a phone that made the label offline pushes+ * it with the request a rename uses. */+ async putLabel(userId: string, id: string, req: Request) {+ try {+ if (!NOTE_ID.test(id)) return err("Invalid label id.", 400);+ const body = (await req.json()) as { name?: string };+ const name = String(body.name ?? "").trim().slice(0, 60);+ if (!name) return err("Label name required.", 400);+ const existing = await prisma.cutNoteLabel.findFirst({+ where: { id, userId },+ select: { id: true },+ });+ if (!existing) {+ const row = await prisma.cutNoteLabel.create({ data: { id, userId, name } });+ return Response.json(labelView(row));+ }+ const row = await prisma.cutNoteLabel.update({ where: { id }, data: { name } });+ return Response.json(labelView(row));+ } catch (e) {+ return caught(e, "Could not save the label.");+ }+ },++ /** Delete one label and take it off every note that carries it. The notes'+ * own stamps stay put — dropping a dead id is not an edit that should win a+ * merge — and clients drop unknown ids on their own. */+ async removeLabel(userId: string, id: string) {+ try {+ await prisma.$transaction(async (tx) => {+ const { count } = await tx.cutNoteLabel.deleteMany({ where: { id, userId } });+ if (!count) return;+ const notes = await tx.cutNote.findMany({+ where: { userId, labelIds: { has: id } },+ select: { id: true, labelIds: true },+ });+ for (const n of notes) {+ await tx.cutNote.update({+ where: { id: n.id },+ data: { labelIds: n.labelIds.filter((l) => l !== id) },+ });+ }+ });+ return Response.json({ ok: true });+ } catch (e) {+ return caught(e, "Could not delete the label.");+ }+ },};diff --git a/site/src/cut/server/cloud/routes.ts b/site/src/cut/server/cloud/routes.tsindex 1c4feb04..94af1d5e 100644--- a/site/src/cut/server/cloud/routes.ts+++ b/site/src/cut/server/cloud/routes.ts@@ -107,6 +107,8 @@ const CUT_CLOUD_ROUTES: CloudRoute[] = [{ method: "GET", path: "/api/cut-cloud/notes", handler: (_r, u) => notesCloud.list(u) },{ method: "PUT", path: "/api/cut-cloud/notes/folders/:id", handler: (r, u, p) => notesCloud.putFolder(u, p.id, r) },{ method: "DELETE", path: "/api/cut-cloud/notes/folders/:id", handler: (_r, u, p) => notesCloud.removeFolder(u, p.id) },+ { method: "PUT", path: "/api/cut-cloud/notes/labels/:id", handler: (r, u, p) => notesCloud.putLabel(u, p.id, r) },+ { method: "DELETE", path: "/api/cut-cloud/notes/labels/:id", handler: (_r, u, p) => notesCloud.removeLabel(u, p.id) },{ 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) },