Skip to content

Open source CapCut alternative.

TypeScript

feat(cut): expose source file metadata to chat [rebuild]

David Le6f22bcf5d143
diff --git a/docs/guides/cut/ai-assistant.md b/docs/guides/cut/ai-assistant.md
index 4b20c645..ec8e24e9 100644
--- a/docs/guides/cut/ai-assistant.md
+++ b/docs/guides/cut/ai-assistant.md
@@ -70,7 +70,7 @@ Every knowledge surface is defined once — the catalog file ships in the engine
The system prompt carries the voice, the deliverable rule (below), id discipline, the undo-versus-credits asymmetry, and pointers into the skills. The skills carry the deep per-area documentation — editor overview, timeline editing, watching and cutting by content, transitions and fades, graphics (titles, shapes, stickers, composite builds), audio and subtitles, stock and generation, scene productions, editing taste, media and library, publish and export — so the always-on cost stays near 21K tokens and detail is pulled only when the model works in that area.
-The snapshot is a compact JSON picture of everything user-visible: project meta, playhead, selection, every media asset with its origin tag, the video track with gaps and transitions, overlay video, soundtrack, titles, subtitle tracks with the first 60 cues, publish metadata, and view state. Numbers are rounded to two decimals and empty fields are omitted. When a list is truncated the snapshot says so, which is the model's cue to call get-state.
+The snapshot describes the project, timeline, selection, media, captions and view. Media includes filenames, dimensions, durations and known byte sizes; a file-info tool reads missing sizes through the shared media reader. Truncated lists direct the model to the full-state tool.
## The decision layer
diff --git a/site/src/clients/chatgpt/server/catalog.test.ts b/site/src/clients/chatgpt/server/catalog.test.ts
index 494f983f..941ac30a 100644
--- a/site/src/clients/chatgpt/server/catalog.test.ts
+++ b/site/src/clients/chatgpt/server/catalog.test.ts
@@ -2,6 +2,12 @@ import { expect, test } from "bun:test";
import { AI_TOOLS, PROJECT_TOOLS } from "@/cut/server/ai/catalog";
import { COMMANDS, READ_COMMANDS, SKILL_INDEX, readSkill } from "./catalog";
+test("ChatGPT exposes file metadata as a read command", () => {
+ expect(READ_COMMANDS.has("get_asset_info")).toBe(true);
+ expect(COMMANDS.find((t) => t.name === "get_asset_info")?.inputSchema)
+ .toBe(PROJECT_TOOLS.find((t) => t.name === "get_asset_info")?.inputSchema);
+});
+
test("ChatGPT guides and command descriptions refer to available tools", () => {
const available = new Set([
...COMMANDS.map((tool) => tool.name),
diff --git a/site/src/clients/chatgpt/server/catalog.ts b/site/src/clients/chatgpt/server/catalog.ts
index 4845fd89..a4ec2f6e 100644
--- a/site/src/clients/chatgpt/server/catalog.ts
+++ b/site/src/clients/chatgpt/server/catalog.ts
@@ -50,6 +50,7 @@ export const unknownCommandNames = (names: string[]): string[] => names.filter((
/** Commands whose output matters and whose effect is on the caller's eyes:
* a read runs without saving the document. */
export const READ_COMMANDS = new Set([
+ "get_asset_info",
"watch_video",
"capture_frame",
"compare_to_source",
diff --git a/site/src/cut/components/AiPanel.tools.ts b/site/src/cut/components/AiPanel.tools.ts
index c89f2e44..01d60736 100644
--- a/site/src/cut/components/AiPanel.tools.ts
+++ b/site/src/cut/components/AiPanel.tools.ts
@@ -17,6 +17,12 @@ export const AI_PANEL_TOOLS = [
"Read the full current editor state: clips, soundtrack, overlay elements (titles, shapes, stickers), subtitles, selection, playhead, view settings, publish metadata. Use this whenever the context snapshot is not enough or might be stale.",
inputSchema: obj({}),
},
+ {
+ name: "get_asset_info",
+ description:
+ "Read a project asset's file name, kind, exact file size in bytes, duration in seconds, and pixel dimensions. Use this for file-size questions when sizeBytes is absent from the media snapshot. Reads file metadata across browser, Mac, and cloud storage.",
+ inputSchema: obj({ asset_id: str("Project asset id from media or an import result") }, ["asset_id"]),
+ },
{
name: "watch_video",
description:
diff --git a/site/src/cut/lib/aiContext.test.ts b/site/src/cut/lib/aiContext.test.ts
index 03ea6220..25affa81 100644
--- a/site/src/cut/lib/aiContext.test.ts
+++ b/site/src/cut/lib/aiContext.test.ts
@@ -2,7 +2,7 @@ import { describe, expect, test } from "bun:test";
import { buildAiContext, describeDoc } from "./aiContext";
import { richDoc } from "./fixtures/richDoc";
-import { useEditor } from "./store";
+import { storedAssets, useEditor } from "./store";
import type { MediaAsset } from "./types";
/**
@@ -39,6 +39,18 @@ describe("describeDoc", () => {
}
});
+ test("file metadata survives saving and reaches live and headless chat", async () => {
+ const doc = richDoc();
+ doc.assets[0] = { ...doc.assets[0], sizeBytes: 21_000_001, width: 320, height: 240 };
+ const assets = doc.assets.map((a) => ({ ...a, url: "" }));
+ doc.assets = storedAssets(assets);
+ await useEditor.getState().openProjectDoc("file-info", doc, assets);
+ const expected = { fileName: doc.assets[0].fileName, sizeBytes: 21_000_001, width: 320, height: 240 };
+ expect(buildAiContext({ chatId: null }).media[0]).toMatchObject(expected);
+ expect(describeDoc(doc).media[0]).toMatchObject(expected);
+ expect(describeDoc(doc).media[0].duration).toBe(doc.assets[0].duration);
+ });
+
test("another chat's unplaced media stays out of a reference, as it does out of the open project", () => {
const doc = richDoc();
doc.assets.push({ id: "g1", fileName: "g1.mp4", name: "their render", type: "video", duration: 4, origin: "chat", chatId: "thread-a" });
diff --git a/site/src/cut/lib/aiContext.ts b/site/src/cut/lib/aiContext.ts
index 92db3281..0f4b0f7d 100644
--- a/site/src/cut/lib/aiContext.ts
+++ b/site/src/cut/lib/aiContext.ts
@@ -418,6 +418,10 @@ function describeState(
id: a.id,
name: a.name,
type: a.type,
+ fileName: a.fileName,
+ ...(a.sizeBytes !== undefined ? { sizeBytes: a.sizeBytes } : {}),
+ ...(a.width !== undefined ? { width: a.width } : {}),
+ ...(a.height !== undefined ? { height: a.height } : {}),
duration: r(a.duration),
...(a.origin ? { origin: a.origin } : {}),
...(a.folderId != null ? { folderId: a.folderId } : {}),
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.ts
index 0eb3e2f3..4f38819c 100644
--- a/site/src/cut/lib/aiTools.ts
+++ b/site/src/cut/lib/aiTools.ts
@@ -159,7 +159,7 @@ import { isStylePresetTemplate } from "./stylePresets";
import { applyOverlayPatchSettled, clipLen, track0Clips, laneGapAt, getClipSpans, overlayLaneOrder, overlayLayers, parkedTransitions, projectDuration, resolveTransitions, totalDuration, useEditor } from "./store";
import { playheadAt } from "./playhead";
import { renderProjectFrame, renderProjectFrames } from "./exportRender";
-import { framesAt } from "./mediaRead";
+import { framesAt, readMediaFileSize } from "./mediaRead";
import { renderStageFrame, storeStageStill } from "./stageFrame";
import { createRasterCanvas, decodeRasterImageUrl, rasterCanvasToDataUrl } from "./raster";
import { buildAiContext, describeDoc, hiddenFromChat, placedAssetIds } from "./aiContext";
@@ -849,6 +849,16 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
return buildAiContext({ fullCues: true });
},
+ get_asset_info: async (s, input) => {
+ const asset = requireItem(s.assets, input.asset_id, "project asset");
+ if (asset.block) throw new ToolError("This placeholder has no source file.");
+ const sizeBytes = asset.sizeBytes ?? await readMediaFileSize(asset.url);
+ return {
+ assetId: asset.id, name: asset.name, fileName: asset.fileName, kind: asset.type,
+ sizeBytes, duration: round2(asset.duration), width: asset.width, height: asset.height,
+ };
+ },
+
render_preview: async (s, _input, operation) => {
if (!s.projectId || !s.loaded) throw new ToolError("No project open.");
return submitPreviewSnapshot(captureRenderSnapshot(operation ?? projectOperation(s.projectId), renderDoc(s)));
@@ -3492,6 +3502,10 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
assetId: asset.id,
name: asset.name,
kind: asset.type,
+ fileName: asset.fileName,
+ sizeBytes: asset.sizeBytes,
+ width: asset.width,
+ height: asset.height,
duration: round2(asset.type === "image" ? IMAGE_CLIP_SECONDS : asset.duration),
})),
...(text ? { sourceText: text } : {}),
diff --git a/site/src/cut/lib/assetInfo.test.ts b/site/src/cut/lib/assetInfo.test.ts
new file mode 100644
index 00000000..82300311
--- /dev/null
+++ b/site/src/cut/lib/assetInfo.test.ts
@@ -0,0 +1,36 @@
+import { afterEach, expect, test } from "bun:test";
+import { runAiTool } from "@/cut/lib/aiTools";
+import { registerBlobFile, forgetRegistered } from "@/cut/lib/backend/browser/registry";
+import { readMediaFileSize } from "@/cut/lib/mediaRead";
+import { useEditor } from "@/cut/lib/store";
+import type { MediaAsset } from "@/cut/lib/types";
+
+const initial = useEditor.getState();
+const path = "/api/cut/projects/file-info/media/test.png";
+const asset: MediaAsset = {
+ id: "asset", name: "Source", fileName: "test.png", type: "image", duration: 0,
+ width: 320, height: 240, url: "",
+};
+afterEach(() => { useEditor.setState(initial, true); forgetRegistered(path); });
+
+test("file size reads bytes without needing a decodable container", async () => {
+ expect(await readMediaFileSize(new Blob([new Uint8Array(1234)]))).toBe(1234);
+});
+
+test("existing browser assets can report file size without saved metadata", async () => {
+ const url = registerBlobFile(path, new File([new Uint8Array(4321)], "test.png"));
+ useEditor.setState({ assets: [{ ...asset, url }] });
+ expect(await runAiTool("get_asset_info", { asset_id: asset.id })).toMatchObject({
+ sizeBytes: 4321, duration: 0, width: 320, height: 240, fileName: "test.png",
+ });
+});
+
+test("saved file size needs no media request", async () => {
+ useEditor.setState({ assets: [{ ...asset, sizeBytes: 21_000_000 }] });
+ expect(await runAiTool("get_asset_info", { asset_id: asset.id })).toMatchObject({ sizeBytes: 21_000_000 });
+});
+
+test("a generated placeholder has no source file", async () => {
+ useEditor.setState({ assets: [{ ...asset, block: { label: "Scene", color: "#000000" } }] });
+ expect(runAiTool("get_asset_info", { asset_id: asset.id })).rejects.toThrow("no source file");
+});
diff --git a/site/src/cut/lib/commandBatch.ts b/site/src/cut/lib/commandBatch.ts
index e401d151..160dc8fa 100644
--- a/site/src/cut/lib/commandBatch.ts
+++ b/site/src/cut/lib/commandBatch.ts
@@ -41,6 +41,10 @@ export interface AdoptedAsset {
name: string;
kind: string;
duration: number;
+ fileName: string;
+ sizeBytes?: number;
+ width?: number;
+ height?: number;
}
/** The undo history's name for a batch: its label, or the commands that ran. */
@@ -84,7 +88,10 @@ async function adoptFiles(projectId: string, input: Record<string, unknown>): Pr
if (name && landed.length === 1) landed[0].title = name;
const { assets } = await adoptImportedFiles(projectId, { files: landed });
return {
- assets: assets.map((a) => ({ assetId: a.id, name: a.name, kind: a.type, duration: Math.round(a.duration * 100) / 100 })),
+ assets: assets.map((a) => ({
+ assetId: a.id, name: a.name, kind: a.type, duration: Math.round(a.duration * 100) / 100,
+ fileName: a.fileName, sizeBytes: a.sizeBytes, width: a.width, height: a.height,
+ })),
};
}
diff --git a/site/src/cut/lib/media.ts b/site/src/cut/lib/media.ts
index d860c2dc..d9d15432 100644
--- a/site/src/cut/lib/media.ts
+++ b/site/src/cut/lib/media.ts
@@ -23,6 +23,7 @@ import {
openMedia,
openMediaShared,
probeMediaFile,
+ readMediaFileSize,
UnreadableMediaError,
videoTrackOf,
type IdleGate,
@@ -416,6 +417,7 @@ export function assetTypeOf(file: File): AssetType | null {
type ProbedMeta = {
type: AssetType;
duration: number;
+ sizeBytes?: number;
width?: number;
height?: number;
};
@@ -437,12 +439,12 @@ async function probeMedia(type: AssetType, src: string | Blob): Promise<ProbedMe
const blob = typeof src === "string" ? await (await fetch(src)).blob() : src;
const img = await decodeRasterImage(blob);
if (!img) throw new UnreadableMediaError();
- return { type, duration: 0, width: img.width, height: img.height };
+ return { type, duration: 0, sizeBytes: blob.size, width: img.width, height: img.height };
}
const url = typeof src === "string" ? src : URL.createObjectURL(src);
try {
const dims = await loadImageMeta(url);
- return { type, duration: 0, width: dims.width, height: dims.height };
+ return { type, duration: 0, sizeBytes: await readMediaFileSize(src), width: dims.width, height: dims.height };
} finally {
if (typeof src !== "string") URL.revokeObjectURL(url);
}
@@ -452,8 +454,8 @@ async function probeMedia(type: AssetType, src: string | Blob): Promise<ProbedMe
// has landed: enrichAsset reads the peaks behind the editor, from the bytes
// the import kept, so a song is on the timeline the moment its container
// has been read.
- if (!meta.hasVideo) return { type: "audio", duration: meta.duration };
- return { type: "video", duration: meta.duration, width: meta.width, height: meta.height };
+ if (!meta.hasVideo) return { type: "audio", duration: meta.duration, sizeBytes: meta.sizeBytes };
+ return { type: "video", duration: meta.duration, sizeBytes: meta.sizeBytes, width: meta.width, height: meta.height };
}
/** Probe a media file's kind/duration/dimensions from the bytes in hand — for
@@ -523,6 +525,7 @@ export async function prepareImport(
name: file.name,
type: meta.type,
duration: meta.duration,
+ sizeBytes: file.size,
...(meta.width !== undefined ? { width: meta.width } : {}),
...(meta.height !== undefined ? { height: meta.height } : {}),
url: localUrl,
@@ -764,6 +767,7 @@ export async function importFileToProject(
name,
type: meta.type,
duration: meta.duration,
+ sizeBytes: meta.sizeBytes,
...(meta.width !== undefined ? { width: meta.width } : {}),
...(meta.height !== undefined ? { height: meta.height } : {}),
url,
@@ -1140,10 +1144,12 @@ export async function assetFromProjectFile(
const dims = await loadImageMeta(url);
asset.width = dims.width;
asset.height = dims.height;
+ asset.sizeBytes = await readMediaFileSize(url);
return asset;
}
const meta = await probeMediaFile(url);
asset.duration = meta.duration;
+ asset.sizeBytes = meta.sizeBytes;
if (!meta.hasVideo) {
asset.type = "audio";
} else {
diff --git a/site/src/cut/lib/mediaConvert.ts b/site/src/cut/lib/mediaConvert.ts
index d9c02d4b..461ba880 100644
--- a/site/src/cut/lib/mediaConvert.ts
+++ b/site/src/cut/lib/mediaConvert.ts
@@ -51,6 +51,7 @@ import {
hasUndecodableVideo,
openMedia,
probeMediaFile,
+ readMediaFileSize,
videoTrackOf,
withMedia,
} from "./mediaRead";
@@ -171,10 +172,12 @@ export async function convertAssetToMp4(
if (made.unchanged) return { assetId: asset.id, name: asset.name, ...made };
+ const url = await storedMediaUrl(projectId, made.fileName, backend);
const patch: Partial<MediaAsset> = {
fileName: made.fileName,
name: mp4DisplayName(asset.name),
- url: await storedMediaUrl(projectId, made.fileName, backend),
+ url,
+ sizeBytes: await readMediaFileSize(url),
duration: made.duration,
...(made.width !== undefined ? { width: made.width } : {}),
...(made.height !== undefined ? { height: made.height } : {}),
diff --git a/site/src/cut/lib/mediaRead.ts b/site/src/cut/lib/mediaRead.ts
index d6b014bf..a3f0f7bb 100644
--- a/site/src/cut/lib/mediaRead.ts
+++ b/site/src/cut/lib/mediaRead.ts
@@ -48,6 +48,8 @@ import { allowance, holdMemory } from "./memoryBudget";
/** What a file turns out to be, read from its container. */
export interface MediaProbe {
+ /** Total bytes in the source file, when the source is sized. */
+ sizeBytes?: number;
/** Sample-exact, from the packets — not the container's rounded metadata. */
duration: number;
hasVideo: boolean;
@@ -311,6 +313,11 @@ export async function withMedia<T>(src: string | Blob, fn: (input: Input) => Pro
}
}
+/** Read the source's byte length without decoding its contents. */
+export function readMediaFileSize(src: string | Blob): Promise<number> {
+ return withMedia(src, (input) => input.source.getSize());
+}
+
// A headless runtime (the turn runner) has no page, and there the
// decodability gate is not a gate: nothing plays in that process, rendering
// goes through ffmpeg, and the probe only reads container metadata — which
@@ -378,14 +385,15 @@ export async function probeMediaFile(src: string | Blob): Promise<MediaProbe> {
);
}
if (!video && !audio) throw new UnreadableMediaError();
- const duration = await input.computeDuration();
- if (!video) return { duration, hasVideo: false, hasAudio: true };
+ const [duration, bytes] = await Promise.all([input.computeDuration(), input.source.getSizeOrNull()]);
+ const size = bytes === null ? {} : { sizeBytes: bytes };
+ if (!video) return { ...size, duration, hasVideo: false, hasAudio: true };
const [width, height, rotation] = await Promise.all([
video.getDisplayWidth(),
video.getDisplayHeight(),
video.getRotation(),
]);
- return { duration, hasVideo: true, hasAudio: !!audio, width, height, rotation };
+ return { ...size, duration, hasVideo: true, hasAudio: !!audio, width, height, rotation };
});
}
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index 8eb3b4ec..fcf9c0ae 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -4894,12 +4894,13 @@ export const docOverlays = (() => {
export function storedAssets(assets: MediaAsset[]): StoredAsset[] {
return assets
.filter((a) => !tabOnlyUpload(a))
- .map(({ id, fileName, name, type, duration, width, height, origin, chatId, folderId, language, watch, speech, beats, sceneCuts, copiedFrom, block }) => ({
+ .map(({ id, fileName, name, type, duration, sizeBytes, width, height, origin, chatId, folderId, language, watch, speech, beats, sceneCuts, copiedFrom, block }) => ({
id,
fileName,
name,
type,
duration,
+ ...(sizeBytes !== undefined ? { sizeBytes } : {}),
...(width !== undefined ? { width } : {}),
...(height !== undefined ? { height } : {}),
...(origin !== undefined ? { origin } : {}),
diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.ts
index 8fb8364a..5d44dc4e 100644
--- a/site/src/cut/lib/types.ts
+++ b/site/src/cut/lib/types.ts
@@ -210,6 +210,8 @@ export interface StoredAsset {
name: string; // original display name
type: AssetType;
duration: number; // seconds
+ /** Source file size in bytes. */
+ sizeBytes?: number;
width?: number;
height?: number;
/** Watch metadata for video sources — what the assistant has seen. */
diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.ts
index 6e55965e..58709322 100644
--- a/site/src/cut/server/ai/catalog.ts
+++ b/site/src/cut/server/ai/catalog.ts
@@ -221,6 +221,7 @@ export const AI_SKILLS: Record<string, string> = {
Cut is a local, project-based short-video editor. Each project has an output aspect ratio "W:H" — presets 16:9, 9:16, 1:1, 4:3, 3:4, 2:1, or any custom ratio like 9:5 — rendered with the frame's short side at 1080px and switchable from the pill in the top bar; the current one is in editor_state project.aspect. The Guides button beside the timeline zoom turns on preview guides — thirds, center, safe margins, the short-form keep-out zone shared by TikTok, Reels and Shorts, and custom lines the user drags into place (set_guides) — which editor_state project.guides reports with the safeArea they leave. Layout:
- Left icon rail tabs: Media (user-imported files + Exports list), Library (shared reusable assets), Video (stock clip browser — footage + talking characters — beside the AI video generator), Image (stock images beside the AI image generator), Audio (AI voiceover + audio files), Text (title presets), Subtitles (transcript editor), Publish (caption/tags/sound metadata). Camera/mic recording lives in the top bar next to the aspect picker.
- Media shows only what the user imported. Everything Cut makes carries an origin tag (generated, voiceover, recording, stock, freeze, chat, block — see \`media\` in editor_state) and lives where it was created — media you make previews on a card in this chat, panel renders sit in their job lists; a "…" menu on each files it into Media or the Library, and every card drags onto the timeline. Deleting a chat thread deletes the chat media the user never placed or filed away.
+- Media metadata includes fileName, sizeBytes, duration, width and height when known. File size is measured in bytes; duration is in seconds. Call get_asset_info for a source whose sizeBytes is missing.
- Center: the video preview canvas (composited at the project's frame size) with draggable text overlays and subtitle captions.
- Right: the Inspector — its content follows the selection (video clip, overlay video, soundtrack clip, title, or cue).
- Bottom: the timeline (resizable by dragging its top border). Rows top-to-bottom: the video tracks in z-order (positive tracks, then track 0, then negative tracks behind it), soundtrack lanes (green), titles (purple), subtitle tracks (amber, when enabled). Every track is free-positioned in time.