Skip to content

Open source CapCut alternative.

TypeScript

feat(site): attach OS file drops and text files as composer references

David Leb1b4b620ce54
diff --git a/site/src/cut/components/AiPanel.tsx b/site/src/cut/components/AiPanel.tsx
index d76741de..68e92eb9 100644
--- a/site/src/cut/components/AiPanel.tsx
+++ b/site/src/cut/components/AiPanel.tsx
@@ -52,9 +52,11 @@ import { signInUrl, useSignedIn } from "@/cut/lib/generate";
import { streamGeminiChat } from "@/cut/lib/geminiChat";
import { AI_MODELS } from "@/cut/lib/aiModels";
import { saveAssetToLibrary } from "@/cut/lib/library";
+import { refsFromDroppedFiles } from "@/cut/lib/refMedia";
import { revealRef } from "@/cut/lib/refReveal";
import { useEditor } from "@/cut/lib/store";
import { cn } from "@/lib/utils";
+import { cardIconButton } from "@/cut/components/iconButton";
import { MentionTextarea, RefChips, RefThumb, RefTokenChip } from "./AssetRefs";
// Chat attachments are asset refs — anything in the project, the library, or
@@ -297,7 +299,18 @@ function ChatSession({
const [input, setInput] = useState("");
const [attachments, setAttachments] = useState<AssetRef[]>([]);
const candidates = useRefCandidates();
- const { active: dropActive, attachTarget, targetProps } = useAssetDrop((ref) => setAttachments((prev) => addRefOnce(prev, ref)));
+ const { active: dropActive, attachTarget, targetProps } = useAssetDrop(
+ (ref) => setAttachments((prev) => addRefOnce(prev, ref)),
+ // OS files dropped on the chat attach as references (media files import
+ // into the project on the way; text files ride as-is).
+ (files) => {
+ const projectId = useEditor.getState().projectId;
+ if (!projectId) return;
+ void refsFromDroppedFiles(projectId, files).then((refs) =>
+ setAttachments((prev) => refs.reduce(addRefOnce, prev))
+ );
+ }
+ );
const sessionKeyRef = useRef<string | null>(null);
// Resume from the saved thread when this id exists in history.
const [initialThread] = useState<ChatThread | undefined>(() =>
@@ -645,7 +658,7 @@ function MessageCopy({ text }: { text: string }) {
<button
aria-label="Copy message"
title="Copy"
- className="ai-msg-copy grid size-6 place-items-center rounded-md text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100 hover:bg-muted hover:text-foreground"
+ className={cn("ai-msg-copy", cardIconButton, "opacity-0 group-hover:opacity-100")}
onClick={() => {
void navigator.clipboard.writeText(text).then(() => {
setCopied(true);
diff --git a/site/src/cut/components/AssetRefs.tsx b/site/src/cut/components/AssetRefs.tsx
index 6ea5e1e0..5fecccfe 100644
--- a/site/src/cut/components/AssetRefs.tsx
+++ b/site/src/cut/components/AssetRefs.tsx
@@ -1,7 +1,7 @@
"use client";
import { useEffect, useMemo, useRef, useState } from "react";
-import { Check, Copy, Music, X } from "lucide-react";
+import { Check, Copy, FileText, Music, X } from "lucide-react";
import {
highlightMentions,
mentionToken,
@@ -19,7 +19,8 @@ import { cn } from "@/lib/utils";
// Every surface that takes references (AI chat, image/video creators)
// composes these.
-/** Square media preview for a ref: video poster frame, image, or audio glyph. */
+/** Square media preview for a ref: video poster frame, image, or a glyph for
+ * audio and text files. */
export function RefThumb({ item, className }: { item: AssetRef; className?: string }) {
return (
<div
@@ -39,6 +40,10 @@ export function RefThumb({ item, className }: { item: AssetRef; className?: stri
) : item.kind === "image" ? (
// eslint-disable-next-line @next/next/no-img-element -- refs point at engine/static files, not Next-optimizable images
<img src={item.url} alt={item.name} loading="lazy" className="size-full object-cover" />
+ ) : item.kind === "text" ? (
+ <div className="grid size-full place-items-center bg-gradient-to-br from-slate-100 to-slate-50 text-slate-500">
+ <FileText className="size-4.5" />
+ </div>
) : (
<div className="grid size-full place-items-center bg-gradient-to-br from-emerald-100 to-emerald-50 text-emerald-600">
<Music className="size-4.5" />
diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsx
index 614c9369..4aa34f3f 100644
--- a/site/src/cut/components/Editor.tsx
+++ b/site/src/cut/components/Editor.tsx
@@ -7,7 +7,7 @@ import { Button } from "@/components/ui/button";
import { apiFetch } from "@/cut/lib/api";
import { renderPreviewProxy } from "@/cut/lib/exportClient";
import { useExport } from "@/cut/lib/exportStore";
-import { hasRefDrag } from "@/cut/lib/assetRef";
+import { fileZoneAt, hasRefDrag } from "@/cut/lib/assetRef";
import { enrichAsset, importFileToProject } from "@/cut/lib/media";
import { backTarget, useCutBase } from "@/cut/lib/nav";
import { getClipSpans, projectDuration, serializeDoc, useEditor } from "@/cut/lib/store";
@@ -272,6 +272,13 @@ export function Editor({
e.preventDefault();
dragDepth.current = 0;
useEditor.getState().setDropActive(false);
+ // A drop on a file-taking composer (generate/chat attachments) belongs
+ // to it; everything else imports into the project as before.
+ const zone = fileZoneAt(e.clientX, e.clientY);
+ if (zone) {
+ zone(Array.from(e.dataTransfer.files));
+ return;
+ }
void importFiles(e.dataTransfer.files, timelineDropTime(e));
};
window.addEventListener("dragenter", enter);
diff --git a/site/src/cut/lib/assetRef.ts b/site/src/cut/lib/assetRef.ts
index 5ab82436..7e620af1 100644
--- a/site/src/cut/lib/assetRef.ts
+++ b/site/src/cut/lib/assetRef.ts
@@ -10,10 +10,10 @@ import { useEditor } from "./store";
import type { MediaAsset } from "./types";
// One reference model for every piece of media in the app. A ref names an
-// asset wherever it lives — the open project, the shared library, or the
-// bundled stock catalog — with enough to preview it (url, kind, duration) and
-// to hand it to whatever wants it: an AI chat attachment, an image/video
-// generation reference, or a timeline drop.
+// asset wherever it lives — the open project, the shared library, the bundled
+// stock catalog, or a file dropped straight from the desktop — with enough to
+// preview it (url, kind, duration) and to hand it to whatever wants it: an AI
+// chat attachment, an image/video generation reference, or a timeline drop.
//
// Refs travel two ways:
// - Native HTML5 drags (cards, tiles, chat) carry a REF_MIME JSON payload;
@@ -25,8 +25,10 @@ import type { MediaAsset } from "./types";
// `@"asset name"` by name. `refToken` makes the token, `parseMentions`
// resolves tokens back to refs on send.
-export type AssetRefScope = "project" | "library" | "stock";
-export type AssetRefKind = "video" | "audio" | "image";
+/** "file" marks a transient ref made from a desktop drop (a text file riding a
+ * composer) — it lives only in the composer's state, never in a catalog. */
+export type AssetRefScope = "project" | "library" | "stock" | "file";
+export type AssetRefKind = "video" | "audio" | "image" | "text";
export interface AssetRef {
scope: AssetRefScope;
@@ -78,6 +80,16 @@ export const refFromStockVideo = (v: StockVideo): AssetRef => ({
duration: v.duration,
});
+/** A transient ref for a text file dropped from the desktop: the contents stay
+ * behind an object URL and are read at send time. */
+export const refFromTextFile = (file: File): AssetRef => ({
+ scope: "file",
+ id: crypto.randomUUID().slice(0, 8),
+ name: file.name,
+ kind: "text",
+ url: URL.createObjectURL(file),
+});
+
export const sameRef = (a: AssetRef, b: AssetRef) => a.scope === b.scope && a.id === b.id;
export const addRefOnce = (list: AssetRef[], ref: AssetRef): AssetRef[] =>
@@ -146,11 +158,27 @@ export function clearRefDrag() {
interface RefZone {
el: HTMLElement;
onDrop: (ref: AssetRef) => void;
+ /** Present when the zone also takes OS file drops (composer attachments). */
+ onFiles?: (files: File[]) => void;
setActive: (active: boolean) => void;
}
const zones = new Set<RefZone>();
+/** The file-accepting zone under a window drop, if any. Rect-based, because
+ * the editor's import veil overlays the window during OS drags and would
+ * swallow an elementFromPoint check. Lets the editor's window-level drop
+ * handler hand files to the composer they landed on instead of importing them
+ * onto the timeline. */
+export function fileZoneAt(x: number, y: number): ((files: File[]) => void) | null {
+ for (const z of zones) {
+ if (!z.onFiles) continue;
+ const r = z.el.getBoundingClientRect();
+ if (x >= r.left && x <= r.right && y >= r.top && y <= r.bottom) return z.onFiles;
+ }
+ return null;
+}
+
function zoneAt(x: number, y: number): RefZone | null {
const hit = document.elementFromPoint(x, y);
if (!hit) return null;
@@ -182,8 +210,14 @@ export function startPointerRefDrag(ref: AssetRef) {
}
/** Make an element accept asset refs from both drag transports:
- * `<div ref={attachTarget} {...targetProps}>` — `active` styles the highlight. */
-export function useAssetDrop(onDrop: (ref: AssetRef) => void): {
+ * `<div ref={attachTarget} {...targetProps}>` — `active` styles the highlight.
+ * Pass `onFiles` to also take OS file drops: the zone highlights during the
+ * drag and the editor's window-level drop handler delivers the files here
+ * (via `fileZoneAt`) instead of importing them onto the timeline. */
+export function useAssetDrop(
+ onDrop: (ref: AssetRef) => void,
+ onFiles?: (files: File[]) => void
+): {
active: boolean;
attachTarget: (el: HTMLElement | null) => void;
targetProps: Pick<
@@ -195,19 +229,28 @@ export function useAssetDrop(onDrop: (ref: AssetRef) => void): {
const [el, setEl] = useState<HTMLElement | null>(null);
const depth = useRef(0);
const cb = useRef(onDrop);
+ const filesCb = useRef(onFiles);
useEffect(() => {
cb.current = onDrop;
+ filesCb.current = onFiles;
});
- // Register the element as a drop zone for pointer-drag delivery.
+ // Register the element as a drop zone for pointer-drag delivery (and, when
+ // it takes files, for the editor's window-drop routing).
+ const takesFiles = !!onFiles;
useEffect(() => {
if (!el) return;
- const zone: RefZone = { el, onDrop: (r) => cb.current(r), setActive };
+ const zone: RefZone = {
+ el,
+ onDrop: (r) => cb.current(r),
+ ...(takesFiles && { onFiles: (f: File[]) => filesCb.current?.(f) }),
+ setActive,
+ };
zones.add(zone);
return () => {
zones.delete(zone);
};
- }, [el]);
+ }, [el, takesFiles]);
const attachTarget = useCallback((node: HTMLElement | null) => setEl(node), []);
@@ -218,20 +261,25 @@ export function useAssetDrop(onDrop: (ref: AssetRef) => void): {
depth.current = 0;
setActive(false);
};
+ // File-taking zones also light up for OS file drags; the drop itself is
+ // delivered by the editor's window-level handler through `fileZoneAt`, so
+ // here it only clears the highlight and lets the event bubble.
+ const accepts = (e: React.DragEvent) =>
+ hasRefDrag(e) || (takesFiles && Array.from(e.dataTransfer.types).includes("Files"));
return {
onDragEnter: (e) => {
- if (!hasRefDrag(e)) return;
+ if (!accepts(e)) return;
e.preventDefault();
depth.current += 1;
setActive(true);
},
onDragOver: (e) => {
- if (!hasRefDrag(e)) return;
+ if (!accepts(e)) return;
e.preventDefault();
e.dataTransfer.dropEffect = "copy";
},
onDragLeave: (e) => {
- if (!hasRefDrag(e)) return;
+ if (!accepts(e)) return;
depth.current -= 1;
if (depth.current <= 0) done();
},
@@ -243,7 +291,7 @@ export function useAssetDrop(onDrop: (ref: AssetRef) => void): {
cb.current(ref);
},
};
- }, []);
+ }, [takesFiles]);
return { active, attachTarget, targetProps };
}
diff --git a/site/src/cut/lib/geminiChat.ts b/site/src/cut/lib/geminiChat.ts
index 45be1486..50349583 100644
--- a/site/src/cut/lib/geminiChat.ts
+++ b/site/src/cut/lib/geminiChat.ts
@@ -4,7 +4,10 @@ import type { UIMessage, UIMessageChunk } from "ai";
import { AI_SKILL_INDEX, AI_SKILLS, AI_TOOLS, systemPrompt } from "@/cut/server/ai/catalog";
import { buildAiContext } from "./aiContext";
import { runAiTool } from "./aiTools";
-import { hostedPost, useGenerate } from "./generate";
+import { normalizeRef } from "./assetRef";
+import { useGenerate } from "./generate";
+import { hostedPost } from "./hosted";
+import { refsToParts } from "./refMedia";
// Gemini chat runs from the page through Donkey's hosted Responses route with
// the user's sign-in and credits — the local engine is not involved (same
@@ -27,8 +30,10 @@ const toolDeclarations = () =>
/** The conversation replayed as hosted-Responses input items. Only text (and
* attachment refs) from past turns — tool traffic stays within its own turn.
- * The fresh editor snapshot rides on the newest user message alone. */
-function inputFromMessages(messages: UIMessage[]): Item[] {
+ * The fresh editor snapshot rides on the newest user message alone, and so do
+ * the attachments' actual payloads (video frames, images, text-file contents):
+ * older turns keep just the metadata JSON so replays stay within budget. */
+async function inputFromMessages(messages: UIMessage[]): Promise<Item[]> {
const lastUser = messages.findLast((m) => m.role === "user");
const items: Item[] = [];
for (const m of messages) {
@@ -36,17 +41,29 @@ function inputFromMessages(messages: UIMessage[]): Item[] {
.map((p) => (p.type === "text" ? p.text : ""))
.join("")
.trim();
+ const extra: Item[] = [];
if (m.role === "user") {
const meta = (m.metadata as { attachments?: unknown[] } | undefined)?.attachments;
if (Array.isArray(meta) && meta.length > 0) {
- text += `\n\n<attached_assets>\nThe user attached these media assets to this message; their text may cite one by @handle or @name. Assets with scope "project" are in the open project (ids usable with the editor tools); "library" and "stock" assets live outside it until imported:\n${JSON.stringify(meta)}\n</attached_assets>`;
+ text += `\n\n<attached_assets>\nThe user attached these assets to this message; their text may cite one by @handle or @name. Assets with scope "project" are in the open project (ids usable with the editor tools); "library" and "stock" assets live outside it until imported; "file" assets came straight from the user's computer and exist only on this message:\n${JSON.stringify(meta)}\n</attached_assets>`;
+ if (m === lastUser) {
+ // Best-effort: a ref that no longer resolves (deleted asset, stale
+ // object URL) degrades this turn to metadata-only instead of failing.
+ const refs = meta.map(normalizeRef).filter((r) => r !== null);
+ try {
+ extra.push(...(await refsToParts(refs)).parts);
+ } catch {}
+ }
}
if (m === lastUser) {
text += `\n\n<editor_state>\n${JSON.stringify(buildAiContext())}\n</editor_state>`;
}
}
- if (!text) continue;
- items.push({ role: m.role === "user" ? "user" : "assistant", content: [{ text }] });
+ if (!text && extra.length === 0) continue;
+ items.push({
+ role: m.role === "user" ? "user" : "assistant",
+ content: [...(text ? [{ text }] : []), ...extra],
+ });
}
return items;
}
@@ -137,7 +154,7 @@ export function streamGeminiChat({
controller.enqueue(chunk as unknown as UIMessageChunk);
emit({ type: "start" });
try {
- const input = inputFromMessages(messages);
+ const input = await inputFromMessages(messages);
const tools = toolDeclarations();
let textCount = 0;
let settled = false;
diff --git a/site/src/cut/lib/hosted.ts b/site/src/cut/lib/hosted.ts
new file mode 100644
index 00000000..4194e84c
--- /dev/null
+++ b/site/src/cut/lib/hosted.ts
@@ -0,0 +1,16 @@
+"use client";
+
+// Donkey's hosted inference routes, called from the page with the user's
+// session and credits (the one hosted carve-out on the otherwise local-only
+// Cut page). Shared by media generation, prompt composition, and AI chat.
+
+const CLIENT_ID = "donkey-cut";
+
+/** POST one of Donkey's hosted inference routes with the user's session. */
+export const hostedPost = (path: string, body: unknown, signal?: AbortSignal) =>
+ fetch(path, {
+ method: "POST",
+ headers: { "Content-Type": "application/json", "x-donkey-client-id": CLIENT_ID },
+ body: JSON.stringify(body),
+ signal,
+ });
diff --git a/site/src/cut/lib/media.ts b/site/src/cut/lib/media.ts
index 60981731..ed7495bf 100644
--- a/site/src/cut/lib/media.ts
+++ b/site/src/cut/lib/media.ts
@@ -80,6 +80,10 @@ export function isImageFile(file: File) {
return file.type.startsWith("image/") || /\.(png|jpe?g|webp|gif|avif|bmp)$/i.test(file.name);
}
+export function isTextFile(file: File) {
+ return file.type.startsWith("text/") || /\.(txt|md|markdown|srt|vtt|csv|json)$/i.test(file.name);
+}
+
/** Upload a raw file into the project folder, probe it, and return the asset.
* Thumbnails/waveform are filled in asynchronously via `enrichAsset`. */
export async function importFileToProject(
diff --git a/site/src/cut/lib/refMedia.ts b/site/src/cut/lib/refMedia.ts
index 991c6b3b..e8e1b72d 100644
--- a/site/src/cut/lib/refMedia.ts
+++ b/site/src/cut/lib/refMedia.ts
@@ -1,11 +1,15 @@
"use client";
-import type { AssetRef } from "./assetRef";
+import { refFromAsset, refFromTextFile, type AssetRef } from "./assetRef";
+import { enrichAsset, importFileToProject, isMediaFile, isTextFile } from "./media";
+import { useEditor } from "./store";
-// Turn an asset ref into the inline-image shape the hosted generation routes
-// take (`inputs.images = [{ data, mimeType }]`). Stock images upload as-is;
-// video refs (project clips, library media, generated stills) upload a single
-// captured frame — the browser reads the same media URLs the previews use.
+// Turn refs and dropped files into what the hosted models take. Generation
+// routes read `inputs.images = [{ data, mimeType }]`: stock images upload
+// as-is; video refs (project clips, library media, generated stills) upload a
+// single captured frame — the browser reads the same media URLs the previews
+// use. Responses calls (prompt composition, chat) read content parts, where
+// text refs contribute their contents.
export interface InlineImage {
/** Base64 payload, no data: prefix. */
@@ -111,10 +115,10 @@ function captureFrame(url: string, duration?: number): Promise<InlineImage> {
}
/** A single reference image for `ref`: the file itself for images, a captured
- * poster frame for videos. Audio has no picture and rejects. */
+ * poster frame for videos. Audio and text have no picture and reject. */
export async function refToInlineImage(ref: AssetRef): Promise<InlineImage> {
- if (ref.kind === "audio") {
- throw new Error(`“${ref.name}” is audio — it can't be a visual reference.`);
+ if (ref.kind === "audio" || ref.kind === "text") {
+ throw new Error(`“${ref.name}” has no picture — it can't be a visual reference.`);
}
if (ref.kind === "image") {
const res = await fetch(ref.url);
@@ -129,3 +133,69 @@ export async function refToInlineImage(ref: AssetRef): Promise<InlineImage> {
export function refsToInlineImages(refs: AssetRef[]): Promise<InlineImage[]> {
return Promise.all(refs.map(refToInlineImage));
}
+
+/** The refs that can ride to a visual model as input images. */
+export const visualRefs = (refs: AssetRef[]): AssetRef[] =>
+ refs.filter((r) => r.kind === "image" || r.kind === "video");
+
+/** Attach OS files dropped on a composer, returned as refs in drop order.
+ * Media files import into the project first (they land in the Media panel like
+ * any user import); text files become transient file refs read at send time.
+ * Files that are neither, and failed imports, are skipped. */
+export async function refsFromDroppedFiles(projectId: string, files: File[]): Promise<AssetRef[]> {
+ const refs: AssetRef[] = [];
+ for (const file of files) {
+ try {
+ if (isTextFile(file) && !isMediaFile(file)) {
+ refs.push(refFromTextFile(file));
+ continue;
+ }
+ const asset = await importFileToProject(projectId, file);
+ if (!asset) continue;
+ useEditor.getState().addAsset(asset);
+ void enrichAsset(asset);
+ refs.push(refFromAsset(asset));
+ } catch (err) {
+ console.error(`Attach failed for ${file.name}:`, err);
+ }
+ }
+ return refs;
+}
+
+/** A text ref's contents (a dropped script, notes, subtitles…). */
+export async function readRefText(ref: AssetRef): Promise<string> {
+ const res = await fetch(ref.url);
+ if (!res.ok) throw new Error(`Could not read “${ref.name}”.`);
+ return res.text();
+}
+
+/** A ref list as hosted-Responses content parts, for any Gemini call that
+ * should actually see the attachments: each visual ref contributes a numbered
+ * label plus its picture (image as-is, video by poster frame), each text ref
+ * its contents, and audio a name-only marker. `visuals` returns the pictures
+ * in label order (`Image 1` = visuals[0]) so a model can pick among them. */
+export async function refsToParts(
+ refs: AssetRef[]
+): Promise<{ parts: Record<string, unknown>[]; visuals: InlineImage[] }> {
+ const parts: Record<string, unknown>[] = [];
+ const visuals: InlineImage[] = [];
+ for (const ref of refs) {
+ if (ref.kind === "audio") {
+ parts.push({ text: `Attached audio "${ref.name}" (audio content not included).` });
+ continue;
+ }
+ if (ref.kind === "text") {
+ parts.push({ text: `Attached file "${ref.name}":\n${await readRefText(ref)}` });
+ continue;
+ }
+ const image = await refToInlineImage(ref);
+ visuals.push(image);
+ parts.push({
+ text:
+ `Image ${visuals.length} — ` +
+ (ref.kind === "video" ? `a frame of video "${ref.name}":` : `image "${ref.name}":`),
+ });
+ parts.push({ type: "input_image", dataBase64: image.data, mimeType: image.mimeType });
+ }
+ return { parts, visuals };
+}