Open source CapCut alternative.
TypeScript
feat(site): phone recordings name themselves [rebuild]
David Le9982c1ce476b
diff --git a/site/src/cut/components/CameraRollView.tsx b/site/src/cut/components/CameraRollView.tsxindex 722f14a0..5c492493 100644--- a/site/src/cut/components/CameraRollView.tsx+++ b/site/src/cut/components/CameraRollView.tsx@@ -13,9 +13,11 @@ import {AlertDialogHeader,AlertDialogTitle,} from "@/components/ui/alert-dialog";+import { useClipTitles } from "@/cut/lib/clipTitle";import { deleteFromLibrary, type LibraryAsset } from "@/cut/lib/library";import { lightboxItemFromLibrary, useLightbox } from "@/cut/lib/lightbox";import { patchLibrary, refetchLibrary, useLibrary } from "@/cut/lib/queries";+import { formatDate } from "@/cut/lib/time";import { shapeBand } from "@/cut/lib/types";import { Lightbox } from "./Lightbox";import { LibraryCard } from "./LibraryView";@@ -24,7 +26,8 @@ import { LibraryCard } from "./LibraryView";* 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. The listing stays live while the tab- * is open, so a recording made on the phone arrives on its own. */+ * is open, so a recording made on the phone arrives on its own, and names+ * itself off what is said in it. */export function CameraRollView() {const client = useQueryClient();// The phone fills this page, so it re-reads on a timer and whenever the@@ -38,6 +41,7 @@ export function CameraRollView() {(fn: Parameters<typeof patchLibrary>[1]) => patchLibrary(client, fn),[client]);+ useClipTitles(clips, patch);const remove = async () => {if (!deleting) return;@@ -87,6 +91,7 @@ export function CameraRollView() {key={a.id}asset={a}area={TILE_AREA}+ caption={formatDate(a.addedAt)}onClick={() =>useLightbox.getState().open(lightboxItemFromLibrary(a, true))}@@ -101,7 +106,7 @@ export function CameraRollView() {<AlertDialog open={!!deleting} onOpenChange={(o) => !o && setDeleting(null)}><AlertDialogContent><AlertDialogHeader>- <AlertDialogTitle>Delete “{deleting?.name}”?</AlertDialogTitle>+ <AlertDialogTitle>Delete “{deleting?.title || deleting?.name}”?</AlertDialogTitle><AlertDialogDescription>The clip leaves your cloud Camera Roll and the phone it was shot on. Projects thatalready use it keep their own copy.diff --git a/site/src/cut/components/LibraryView.tsx b/site/src/cut/components/LibraryView.tsxindex e0ed914a..f177394c 100644--- a/site/src/cut/components/LibraryView.tsx+++ b/site/src/cut/components/LibraryView.tsx@@ -1,6 +1,6 @@"use client";-import { useCallback, useEffect, useRef, useState } from "react";+import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";import { useQueryClient } from "@tanstack/react-query";import { useRouter, useSearchParams } from "next/navigation";import {@@ -1032,6 +1032,7 @@ export function LibraryCard({offline = false,area,mention = false,+ caption,dragGroup,onClick,onDelete,@@ -1051,6 +1052,8 @@ export function LibraryCard({/** The card sits beside a prompt (the editor's Library panel), so its name* doubles as a mention token to copy. */mention?: boolean;+ /** A line under the tile — where the Camera Roll puts a recording's date. */+ caption?: ReactNode;/** Everything picked on this shelf right now. Dragging a card that is one of* them carries the whole set, so a drop lands the lot. */dragGroup?: LibraryAsset[];@@ -1194,6 +1197,7 @@ export function LibraryCard({<div className="mx-3 flex items-center justify-between gap-2 border-t border-white/10 py-2 @[220px]:mx-5 @[220px]:py-3"><CopyNameLabelname={a.name}+ label={a.title}darkmention={false}className="min-w-0 text-[11px] font-medium @[220px]:text-[13px]"@@ -1411,6 +1415,7 @@ export function LibraryCard({{!font && (<CopyNameLabelname={a.name}+ label={a.title}dark={a.type === "audio"}mention={mention}className={cn(@@ -1421,6 +1426,11 @@ export function LibraryCard({/>)}</div>+ {caption && (+ <div data-drag-omit className="mt-2 px-0.5 text-xs text-muted-foreground">+ {caption}+ </div>+ )}</div>);}diff --git a/site/src/cut/components/SidePanel.tsx b/site/src/cut/components/SidePanel.tsxindex 72c76176..e6a15610 100644--- a/site/src/cut/components/SidePanel.tsx+++ b/site/src/cut/components/SidePanel.tsx@@ -78,6 +78,7 @@ import {type LibraryData,type LibraryFolder,} from "@/cut/lib/library";+import { useClipTitles } from "@/cut/lib/clipTitle";import { patchLibrary, refetchLibrary, useLibrary } from "@/cut/lib/queries";import {activeResidency,@@ -1257,6 +1258,9 @@ function AssetCard({// 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";+/** A stable empty list, so the titling hook sees no work rather than a new+ * array on every render. */+const EMPTY_CLIPS: LibraryAsset[] = [];function LibraryPanel({ projectId }: { projectId: string }) {const client = useQueryClient();@@ -1297,7 +1301,12 @@ function LibraryPanel({ projectId }: { projectId: string }) {// 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;+ const cameraClips = assets.filter((a) => a.origin === "camera");+ const cameraCount = cameraClips.length;+ // Phone recordings name themselves off what is said in them. Only while the+ // Camera Roll folder is open — a panel showing anything else has no reason+ // to read those files.+ useClipTitles(openFolder === CAMERA_ROLL_FOLDER ? cameraClips : EMPTY_CLIPS, patch);// A remembered folder can vanish between sessions; drop back to the root.const knownFolder =diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.tsindex 38e95a12..3b25616c 100644--- a/site/src/cut/lib/aiTools.ts+++ b/site/src/cut/lib/aiTools.ts@@ -2537,6 +2537,10 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {assets: lib.assets.map((a) => ({id: a.id,name: a.name,+ // Read off the clip itself — what is said in it and what is on+ // screen. A phone recording's own name is the clock it was shot on,+ // so this is what says which clip it is.+ ...(a.title ? { title: a.title } : {}),kind: a.type,duration: round2(a.duration),...(a.folderId ? { folderId: a.folderId } : {}),diff --git a/site/src/cut/lib/clipTitle.ts b/site/src/cut/lib/clipTitle.tsnew file mode 100644index 00000000..e9d53964--- /dev/null+++ b/site/src/cut/lib/clipTitle.ts@@ -0,0 +1,187 @@+"use client";++// A short name for one recording, read off the clip itself.+//+// A phone recording arrives named after the clock it was shot on, so a camera+// roll of them reads as one repeated string. This pulls the opening speech and+// one still out of the media the page is already showing, hands both to the+// hosted titler (server/cloud/clipTitle.ts), and gets back a few words naming+// what the clip is about. The shelf stores the answer, so a clip is read once+// and every device sees the same title afterwards.+//+// The reads go through the media seams — the audio span decoder and the frame+// sink — so this works wherever those do.++import { useEffect, useRef } from "react";+import { encodeWav } from "./cloudTranscribe";+import {+ libraryMediaUrl,+ libraryPosterUrl,+ type LibraryAsset,+ type LibraryData,+} from "./library";+import { decodeAudioSpan, frameAt } from "./mediaRead";+import { createRasterCanvas, decodeRasterImage, rasterCanvasToBlob } from "./raster";+import { backendFor } from "./residency";++/** How much of the opening the titler hears. Long enough for someone to say+ * what they are doing, short enough that reading it is a fraction of the file+ * rather than the whole clip. */+const LISTEN_SECONDS = 30;+/** The wire rate the hosted models read speech at, matching transcription. */+const RATE = 16000;+/** Wider than this teaches the model nothing more about one frame. */+const FRAME_WIDTH = 512;+/** Below this the span is silence and worth no round trip. */+const SILENCE_PEAK = 1e-3;+/** What the titler will look at. A cover comes off the shelf as it was stored;+ * anything else is encoded here. */+const FRAME_MIMES = new Set(["image/jpeg", "image/png", "image/webp"]);+/** What the titler accepts in one request; anything larger is redrawn small. */+const MAX_FRAME_BYTES = 2 * 1024 * 1024;++/** The clip's opening as 16 kHz mono, the format the hosted models read, or+ * null when the file has no audio or opens on silence. */+async function opening(url: string, duration: number): Promise<Blob | null> {+ const span = Math.min(LISTEN_SECONDS, duration > 0 ? duration : LISTEN_SECONDS);+ const buf = await decodeAudioSpan(url, 0, span).catch(() => null);+ if (!buf || buf.length === 0) return null;+ const ctx = new OfflineAudioContext(+ 1,+ Math.max(1, Math.round((buf.length / buf.sampleRate) * RATE)),+ RATE,+ );+ const source = ctx.createBufferSource();+ source.buffer = buf;+ source.connect(ctx.destination);+ source.start();+ const mono = (await ctx.startRendering()).getChannelData(0);+ for (let i = 0; i < mono.length; i++) {+ if (Math.abs(mono[i]) > SILENCE_PEAK) return encodeWav(mono);+ }+ return null;+}++/** One frame to look at: the cover the clip already carries, the picture+ * itself, or a frame read out of the video. */+async function still(a: LibraryAsset): Promise<Blob | null> {+ const url = libraryMediaUrl(a.fileName, a.residency);+ const poster = libraryPosterUrl(a);+ if (poster || a.type === "image") {+ const stored = await fetch(poster ?? url, { mode: "cors" })+ .then((r) => (r.ok ? r.blob() : null))+ .catch(() => null);+ if (stored && stored.size > 0) return sendable(stored);+ }+ if (a.type !== "video") return null;+ const wrapped = await frameAt(url, Math.min(1, (a.duration || 2) / 2), {+ width: FRAME_WIDTH,+ }).catch(() => null);+ return wrapped ? rasterCanvasToBlob(wrapped.canvas, "image/jpeg", 0.7) : null;+}++/** A stored picture as the titler will take it: small enough to ride the+ * request and in a format it reads, redrawn through the raster seam when the+ * bytes on the shelf are neither. */+async function sendable(blob: Blob): Promise<Blob | null> {+ if (blob.size <= MAX_FRAME_BYTES && FRAME_MIMES.has(blob.type)) return blob;+ const image = await decodeRasterImage(blob);+ if (!image?.width || !image.height) return null;+ const w = Math.min(FRAME_WIDTH, image.width);+ const h = Math.max(1, Math.round((image.height / image.width) * w));+ const canvas = createRasterCanvas(w, h);+ const ctx = canvas.getContext("2d") as CanvasRenderingContext2D | null;+ if (!ctx) return null;+ ctx.drawImage(image.source, 0, 0, w, h);+ return rasterCanvasToBlob(canvas, "image/jpeg", 0.7);+}++/** Read one clip and hand back the title the shelf now holds for it, or null+ * when there was nothing to read it from. Already-titled assets come back with+ * the title they have without a model call. */+export async function titleClip(a: LibraryAsset): Promise<string | null> {+ if (a.title) return a.title;+ const [audio, frame] = await Promise.all([+ opening(libraryMediaUrl(a.fileName, a.residency), a.duration).catch(() => null),+ still(a).catch(() => null),+ ]);+ if (!audio && !frame) return null;+ const form = new FormData();+ form.set("assetId", a.id);+ if (audio) form.set("audio", new File([audio], "opening.wav", { type: "audio/wav" }));+ if (frame) {+ const type = FRAME_MIMES.has(frame.type) ? frame.type : "image/jpeg";+ form.set("frame", new File([frame], "frame", { type }));+ }+ const res = await backendFor(a.residency).fetch("/api/cut/library/title", {+ method: "POST",+ body: form,+ });+ if (!res.ok) return null;+ const { title } = (await res.json()) as { title?: string };+ return title?.trim() || null;+}++/** How many clips are read for a title at once. Each one pulls the opening of+ * its own file across the network, so a shelf that just filled up titles+ * itself a couple at a time rather than all at once. */+const TITLING_AT_ONCE = 2;++/** Give every untitled clip on a surface a name read off itself.+ *+ * The work happens once per clip — the shelf stores the answer, and every+ * surface showing that clip reads it afterwards — and a clip that fails is+ * left alone until the surface is opened again, so nothing loops on a file+ * that cannot be read. Hand it an empty list where the clips are not on+ * screen: a picker nobody has opened has no reason to read files.+ */+export function useClipTitles(+ clips: LibraryAsset[],+ patch: (fn: (d: LibraryData) => LibraryData) => void,+) {+ const shelf = useRef(clips);+ const claimed = useRef(new Set<string>());+ const running = useRef(0);+ // The listing is re-read on a timer, so the array itself is new every render.+ // What says there is work to do is which clips still want a name.+ const untitled = clips+ .filter((c) => !c.title)+ .map((c) => c.id)+ .join(" ");++ useEffect(() => {+ shelf.current = clips;+ });++ useEffect(() => {+ let live = true;+ const pump = () => {+ while (live && running.current < TITLING_AT_ONCE) {+ const next = shelf.current.find((c) => !c.title && !claimed.current.has(c.id));+ if (!next) return;+ claimed.current.add(next.id);+ running.current += 1;+ void titleClip(next)+ .then((title) => {+ // A title that landed is kept even if the surface has since been+ // left: the server already wrote it, and the listing this cache+ // holds should say the same thing.+ if (!title) return;+ patch((d) => ({+ ...d,+ assets: d.assets.map((x) => (x.id === next.id ? { ...x, title } : x)),+ }));+ })+ .catch(() => {})+ .finally(() => {+ running.current -= 1;+ pump();+ });+ }+ };+ pump();+ return () => {+ live = false;+ };+ }, [untitled, patch]);+}diff --git a/site/src/cut/lib/library.ts b/site/src/cut/lib/library.tsindex 493a58c9..e9b416ee 100644--- a/site/src/cut/lib/library.ts+++ b/site/src/cut/lib/library.ts@@ -62,6 +62,12 @@ export interface LibraryAsset {* recording (shown in Camera Roll, kept out of the Library grid) or an* inspiration item. Cloud shelf only. */origin?: "camera" | "inspiration";+ /** A short name read off the clip itself — what is said in it and what is on+ * screen — standing in for `name` wherever the asset is shown. A phone+ * recording arrives named after the clock it was shot on, which tells nobody+ * which clip it is; this is what the card, the viewer and the assistant read+ * instead. Written once per clip by lib/clipTitle.ts. */+ title?: string;/** Which shelf this came off. Stamped on arrival — the servers each answer* for themselves and don't know the other exists. */residency: Residency;@@ -499,7 +505,9 @@ export async function carryAssetTo(new File([await res.blob()], asset.fileName),to,{- name: asset.name,+ // A clip carried to another shelf keeps the name the user reads, which+ // for a phone recording is the title read off the clip.+ name: asset.title || asset.name,...(asset.source ? { source: asset.source } : {}),...(cover ? { poster: cover } : {}),},@@ -696,7 +704,9 @@ export async function importLibraryAsset(projectId,{url: libraryMediaUrl(lib.fileName, lib.residency),- name: lib.name,+ // The project's media takes the name the shelf shows, so a phone+ // recording lands on the timeline under its title.+ name: lib.title || lib.name,fileName: lib.fileName,type: lib.type,duration: lib.duration,diff --git a/site/src/cut/lib/lightbox.ts b/site/src/cut/lib/lightbox.tsindex 1a37dcd7..e49ac237 100644--- a/site/src/cut/lib/lightbox.ts+++ b/site/src/cut/lib/lightbox.ts@@ -54,7 +54,9 @@ export const lightboxItemFromLibrary = (): LightboxItem => ({kind: a.type,src: libraryMediaUrl(a.fileName, a.residency),- name: a.name,+ // The title read off the clip is what it is called wherever it is shown, so+ // the viewer captions it that way and an import from here lands under it.+ name: a.title || a.name,prompt: "",assetId: null,libraryId: a.id,diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex e2f3b7a5..fdfd9ddc 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -358,7 +358,7 @@ 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.+- 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.- 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.diff --git a/site/src/cut/server/cloud/clipTitle.ts b/site/src/cut/server/cloud/clipTitle.tsnew file mode 100644index 00000000..8bd4029c--- /dev/null+++ b/site/src/cut/server/cloud/clipTitle.ts@@ -0,0 +1,223 @@+// Hosted clip titling: a short name for one recording, read off what is said+// in it and what is on screen.+//+// POST library/title {assetId, audio?, frame?} -> {title}+//+// The client sends the opening speech as a 16 kHz mono WAV and one still,+// both pulled from media it is already showing (lib/clipTitle.ts). The title+// is written onto the asset's meta, so the model runs once per clip and every+// device reads the same name afterwards. Titles are on the house — a phone+// recording arrives named after its clock, and the name that replaces it is+// not something anyone asked to buy.+import {+ creditErrorResponse,+ recordFailedInferenceUsage,+ recordInferenceUsage,+} from "@/lib/credits/inference";+import {+ defaultGeminiClientFactory,+ geminiApiError,+ geminiCandidateParts,+ geminiCandidates,+ geminiClientConfig,+ stringValue,+} from "@/lib/inference/adapters/gemini-client";+import { geminiModelRoles } from "@/lib/inference/gemini-models";+import { toJsonValue } from "@/lib/inference/json";+import type { JsonValue } from "@/lib/inference/providers";+import { prisma } from "@/lib/prisma";+import { err } from "./util";++const ROUTE = "/api/cut-cloud/library/title";+const PROVIDER = "gemini";+// A four-word name off half a minute of speech and one frame: the lightest+// model in the registry answers this well and costs a fraction of a cent.+const MODEL = geminiModelRoles.fastDecision;+const REQUEST_KIND = "clip_title";++const MAX_AUDIO_BYTES = 4 * 1024 * 1024;+const MAX_FRAME_BYTES = 2 * 1024 * 1024;+const FRAME_TYPES = new Set(["image/jpeg", "image/png", "image/webp"]);+/** Long enough that a hovering card can hand the whole line over, short enough+ * that the tile reads at a glance. */+const MAX_TITLE_CHARS = 60;++type GeminiPart = { text: string } | { inlineData: { mimeType: string; data: string } };++interface AssetMetaWithTitle {+ name?: string;+ title?: string;+ duration?: number;+}++const prompt = (heard: boolean, seen: boolean, duration: number) =>+ [+ "Name this video clip the way its owner would in a camera roll.",+ heard+ ? "The audio is the opening of the clip; take the subject from what is actually said."+ : "",+ seen ? "The image is a frame from the clip." : "",+ duration > 0 ? `The clip runs ${Math.round(duration)} seconds.` : "",+ "Write at most five words, in title case, naming what this clip is about.",+ "Two clips shot in the same room must still read apart, so name the subject rather than the setting.",+ 'Never use a date, a time, or the words "video", "clip", or "recording".',+ 'Return ONLY JSON: {"title": "<the title>"}',+ ]+ .filter(Boolean)+ .join(" ");++/** The model's object, parsed defensively: code fences stripped, the outermost+ * {...} recovered from surrounding prose. Null when no title can be read. */+function parseTitle(raw: string): string | null {+ const cleaned = raw+ .trim()+ .replace(/^```(?:json)?\s*/i, "")+ .replace(/```\s*$/, "")+ .trim();+ let parsed: unknown;+ try {+ parsed = JSON.parse(cleaned);+ } catch {+ const s = cleaned.indexOf("{");+ const e = cleaned.lastIndexOf("}");+ if (s < 0 || e <= s) return null;+ try {+ parsed = JSON.parse(cleaned.slice(s, e + 1));+ } catch {+ return null;+ }+ }+ if (!parsed || typeof parsed !== "object") return null;+ const title = (parsed as Record<string, unknown>).title;+ return typeof title === "string" ? clean(title) : null;+}++/** One line, no wrapping quotes, no trailing punctuation, cut at a word+ * boundary when the model runs long. */+function clean(raw: string): string | null {+ let s = raw.replace(/\s+/g, " ").trim();+ s = s.replace(/^["'“”‘’]+|["'“”‘’]+$/g, "").trim();+ s = s.replace(/[.,;:!?]+$/, "").trim();+ if (!s) return null;+ if (s.length > MAX_TITLE_CHARS) {+ const cut = s.slice(0, MAX_TITLE_CHARS);+ const space = cut.lastIndexOf(" ");+ s = (space > 20 ? cut.slice(0, space) : cut).trim();+ }+ return s || null;+}++export const clipTitleCloud = {+ async title(userId: string, req: Request): Promise<Response> {+ let assetId = "";+ let audio: File | null = null;+ let frame: File | null = null;+ try {+ const form = await req.formData();+ const id = form.get("assetId");+ assetId = typeof id === "string" ? id.trim() : "";+ const a = form.get("audio");+ audio = a instanceof File && a.size > 0 ? a : null;+ const f = form.get("frame");+ frame = f instanceof File && f.size > 0 ? f : null;+ } catch {+ return err("Send multipart form data.", 400);+ }+ if (!assetId) return err("assetId is required.", 400);+ if (audio && audio.size > MAX_AUDIO_BYTES) return err("Audio too large.", 413);+ if (frame && frame.size > MAX_FRAME_BYTES) return err("Frame too large.", 413);+ if (frame && !FRAME_TYPES.has(frame.type)) frame = null;+ if (!audio && !frame) return err("Send audio, a frame, or both.", 400);++ const row = await prisma.cutLibraryAsset.findFirst({+ where: { id: assetId, userId, deletedAt: null },+ });+ if (!row) return err("Asset not found.", 404);+ const meta = (row.meta ?? {}) as AssetMetaWithTitle;+ // A clip is titled once. A second caller — another tab reading the same+ // shelf, a listing that arrived before the write — gets the title back+ // without spending a model call on it.+ if (meta.title) return Response.json({ title: meta.title });++ const clientConfig = geminiClientConfig(process.env);+ if (!clientConfig.configured) return err("Titling is not configured on this deployment.", 500);++ const parts: GeminiPart[] = [];+ if (audio) {+ parts.push({+ inlineData: {+ mimeType: "audio/wav",+ data: Buffer.from(await audio.arrayBuffer()).toString("base64"),+ },+ });+ }+ if (frame) {+ parts.push({+ inlineData: {+ mimeType: frame.type,+ data: Buffer.from(await frame.arrayBuffer()).toString("base64"),+ },+ });+ }+ parts.push({ text: prompt(!!audio, !!frame, meta.duration ?? 0) });++ let raw: unknown;+ try {+ const client = defaultGeminiClientFactory(clientConfig.options);+ raw = await client.models.generateContent({+ model: MODEL,+ contents: [{ role: "user", parts }],+ // JSON mode without a schema — constrained decoding degrades output.+ config: { responseMimeType: "application/json", temperature: 0.4 },+ });+ } catch (error) {+ await recordFailedInferenceUsage({+ billingMode: "included",+ clientId: null,+ errorCode: "provider_error",+ model: MODEL,+ provider: PROVIDER,+ requestKind: REQUEST_KIND,+ route: ROUTE,+ userId,+ });+ const credit = creditErrorResponse(error);+ if (credit) return credit;+ const mapped = geminiApiError("The titling model is unavailable.", error);+ return err(mapped.message, mapped.statusCode ?? 502);+ }++ const usage = (raw as { usageMetadata?: unknown }).usageMetadata;+ try {+ await recordInferenceUsage({+ billingMode: "included",+ clientId: null,+ model: MODEL,+ provider: PROVIDER,+ requestKind: REQUEST_KIND,+ route: ROUTE,+ status: "succeeded",+ usage: toJsonValue(usage ?? null),+ userId,+ });+ } catch (error) {+ const credit = creditErrorResponse(error);+ if (credit) return credit;+ throw error;+ }++ const text = geminiCandidateParts(geminiCandidates(raw as JsonValue)[0])+ .map((p) => stringValue(p.text) ?? "")+ .join("");+ const title = parseTitle(text);+ if (!title) return err("The titling model returned an unreadable response.", 502);++ // Written under the row's own meta so the name outlives this tab and+ // reaches the phone's next listing.+ await prisma.cutLibraryAsset.update({+ where: { id: row.id },+ data: { meta: { ...(meta as Record<string, unknown>), title } },+ });+ return Response.json({ title });+ },+};diff --git a/site/src/cut/server/cloud/library.ts b/site/src/cut/server/cloud/library.tsindex 33b0f9c4..540ef899 100644--- a/site/src/cut/server/cloud/library.ts+++ b/site/src/cut/server/cloud/library.ts@@ -37,6 +37,10 @@ const PRESIGN_GET_BATCH_MAX = 500;* the source project doc. */interface AssetMeta {name?: string;+ /** The short name the titling model read off the clip itself, standing in+ * for the file's own name wherever the asset is shown. Written once, by+ * cloud/clipTitle.ts. */+ title?: string;type?: "video" | "audio" | "image" | "font";duration?: number;width?: number;@@ -93,6 +97,7 @@ function assetView(folderId: row.folderId ?? null,...(meta.source ? { source: meta.source } : {}),...(meta.posterFile ? { posterFile: meta.posterFile } : {}),+ ...(meta.title ? { title: meta.title } : {}),...(meta.origin ? { origin: meta.origin } : {}),};}diff --git a/site/src/cut/server/cloud/routes.ts b/site/src/cut/server/cloud/routes.tsindex 6a3b3ed6..1c4feb04 100644--- a/site/src/cut/server/cloud/routes.ts+++ b/site/src/cut/server/cloud/routes.ts@@ -11,6 +11,7 @@ import { chatsCloud } from "./chats";import { copyJobs } from "./copyQueue";import { runGc } from "./gc";import { jobsCloud } from "./jobs";+import { clipTitleCloud } from "./clipTitle";import { libraryCloud } from "./library";import { mediaCloud } from "./media";import { notesCloud } from "./notes";@@ -72,6 +73,7 @@ const CUT_CLOUD_ROUTES: CloudRoute[] = [{ method: "POST", path: "/api/cut-cloud/library/complete", handler: (r, u) => libraryCloud.complete(u, r) },{ method: "POST", path: "/api/cut-cloud/library/presign-get", handler: (r, u) => libraryCloud.presignGetBatch(u, r) },{ method: "POST", path: "/api/cut-cloud/library/use", handler: (r, u) => libraryCloud.use(u, r) },+ { method: "POST", path: "/api/cut-cloud/library/title", handler: (r, u) => clipTitleCloud.title(u, r) },{ method: "POST", path: "/api/cut-cloud/library/save", handler: (r, u) => libraryCloud.save(u, r) },{ method: "POST", path: "/api/cut-cloud/library/move", handler: (r, u) => libraryCloud.move(u, r) },{ method: "POST", path: "/api/cut-cloud/library/templates", handler: (r, u) => libraryCloud.saveTemplate(u, r) },