Skip to content

Open source CapCut alternative.

TypeScript

feat(cut): let chat see uploads and wait them out [rebuild]

David Le3f9e9826eb65
diff --git a/site/src/cut/components/AiPanel.tools.ts b/site/src/cut/components/AiPanel.tools.ts
index 831e9544..e6488525 100644
--- a/site/src/cut/components/AiPanel.tools.ts
+++ b/site/src/cut/components/AiPanel.tools.ts
@@ -177,6 +177,12 @@ export const AI_PANEL_TOOLS = [
"Block until this project's in-flight video renders settle (up to ~100s), then report each one: landed (with its asset id, ready to place) or failed (with the error). Call it whenever the user's ask depends on a render that `renders` in the state shows as running — \"add it when it's done\", \"assemble the clips\" — and then finish the job in the same turn; never tell the user to come back and report when a card appears. If some renders are still running when it returns, say how long they've been going and call it again on the user's go-ahead.",
inputSchema: obj({}),
},
+ {
+ name: "wait_for_uploads",
+ description:
+ "Block until this project's files finish uploading and the browser has a connection (up to ~100s), retrying uploads that failed, then report each one: done, failed with the error, or still uploading with its percent. A file still uploading (`upload` on its media entry) already plays and reads from this browser, so editing, watching and listening go ahead without waiting; wait when the ask needs the stored copy (a render or export in the cloud, a share) or when `offline` is set or a call failed on the connection. Then run what waited, in the same turn.",
+ inputSchema: obj({}),
+ },
{
name: "queue_message",
description:
diff --git a/site/src/cut/lib/aiContext.ts b/site/src/cut/lib/aiContext.ts
index 260d265e..5ac5ceaa 100644
--- a/site/src/cut/lib/aiContext.ts
+++ b/site/src/cut/lib/aiContext.ts
@@ -20,6 +20,7 @@ import { libraryFontId, listLibraryFonts, listLutChoices } from "./linkedLibrary
import { savedGradesKnown } from "./gradePresets";
import { sourceProfileOf } from "./baseFrame";
import { groupCameras } from "./groupCamera";
+import { isOffline } from "./network";
import {
clipZoom,
frameOf,
@@ -310,6 +311,9 @@ export function buildAiContext(opts?: { fullCues?: boolean; chatId?: string | nu
media: core.media,
mediaTruncated: core.mediaTruncated,
...(core.mediaInOtherChats ? { mediaInOtherChats: core.mediaInOtherChats, mediaInOtherChatsNote: core.mediaInOtherChatsNote } : {}),
+ // The browser has no connection: hosted work (renders, cloud reads,
+ // uploads) waits for it, and wait_for_uploads waits with it.
+ ...(isOffline() ? { offline: true } : {}),
// AI video renders for this project, live from the job store — what
// "rendering" claims must be grounded in. A done render names the asset
// it landed as (already in `media`); a failed one carries its error.
@@ -539,6 +543,15 @@ function describeState(
duration: roundT(a.duration),
...(a.origin ? { origin: a.origin } : {}),
...(a.folderId != null ? { folderId: a.folderId } : {}),
+ // A file on its way to storage plays and reads from the bytes in this
+ // browser; `upload` says how far it is, or what stopped it.
+ ...(live && a.upload
+ ? {
+ upload: a.upload.error
+ ? { status: "failed", error: a.upload.error }
+ : { status: "uploading", percent: Math.round(a.upload.progress * 100) },
+ }
+ : {}),
// The recording bound to this video (sync_audio): every clip of it
// plays that file, recording second = video second + offset.
...(a.soundFrom
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.ts
index 44f0135b..89d8d73f 100644
--- a/site/src/cut/lib/aiTools.ts
+++ b/site/src/cut/lib/aiTools.ts
@@ -240,7 +240,7 @@ import { renderStageFrame, storeStageStill } from "./stageFrame";
import { createRasterCanvas, decodeRasterImageUrl, rasterCanvasToDataUrl } from "./raster";
import { buildAiContext, describeCameraCard, describeDoc, hiddenFromChat, OTHER_CHATS_MEDIA_NOTE, roundT } from "./aiContext";
import { CARD_SIDES, newCard, normalizeCard, type CardSide } from "./cameraCard";
-import { CAPTION_STYLES, captionEmphasis, cueSpot, EMPHASIS_SCALE_MAX, EMPHASIS_SCALE_MIN, laneCues, subtitleLaneCount } from "./subtitles";
+import { CAPTION_STYLES, captionEmphasis, cueSpot, EMPHASIS_SCALE_MAX, EMPHASIS_SCALE_MIN, laneCues, subtitleLaneCount, trackLocale } from "./subtitles";
import { cueEmphasis, emphasisIndicesOf, emphasizedWords } from "./captionEmphasis";
import { findHighlights } from "./highlights";
import { fuseTimeline, renderFusedTimeline, speechOnsets, speechOver } from "./watch/fuse";
@@ -275,6 +275,8 @@ import {
type TextMoveId,
} from "./textMotion";
import { queueWatchSweep, withSweepPaused } from "./watch/sweep";
+import { retryFailedUploads, uploadInFlight } from "./importQueue";
+import { ConnectionLostError, fetchDropped, isOffline } from "./network";
import { synthesizeMusic } from "./audioGen";
import { composeMusicPrompt } from "./composeGen";
import { stockAssetInDoc } from "./genvideo/docWriter";
@@ -656,7 +658,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
if (svg.length > SVG_STICKER_MAX_CHARS) throw new ToolError(`svg is over ${SVG_STICKER_MAX_CHARS} characters.`);
const name = typeof input.name === "string" && input.name.trim() ? input.name.trim() : "Drawn sticker";
const drawn = await saveSvgSticker(s.projectId, svg, name).catch((e: unknown) => {
- throw new ToolError(e instanceof Error ? e.message : String(e));
+ throw new ToolError(e instanceof Error ? e.message : String(e), { cause: e });
});
assetId = drawn.id;
s = useEditor.getState();
@@ -1084,7 +1086,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
...(isNum(input.feather) ? { feather: input.feather } : {}),
...(typeof input.invert === "boolean" ? { invert: input.invert } : {}),
}).catch((e) => {
- throw new ToolError(e instanceof Error ? e.message : "Could not track the footage.");
+ throw new ToolError(e instanceof Error ? e.message : "Could not track the footage.", { cause: e });
});
},
@@ -1260,7 +1262,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
{ width: Math.round(frame.w * k), height: Math.round(frame.h * k) },
(asset) => asset.url
).catch((e) => {
- throw new ToolError(e instanceof Error ? e.message : "Could not draw the frame.");
+ throw new ToolError(e instanceof Error ? e.message : "Could not draw the frame.", { cause: e });
});
return { image: await rasterCanvasToDataUrl(canvas, "image/jpeg", 0.75), at };
},
@@ -1308,7 +1310,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
const refs = new Map<number, string>();
if (asset.type === "image") {
const still = await makeStillFrame(asset.url, "read").catch((e) => {
- throw new ToolError(e instanceof Error ? e.message : `Could not read "${asset.name}".`);
+ throw new ToolError(e instanceof Error ? e.message : `Could not read "${asset.name}".`, { cause: e });
});
for (const i of order) refs.set(i, still.frames[0].image);
} else {
@@ -1323,7 +1325,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
if (c) refs.set(i, await rasterCanvasToDataUrl(c.canvas, "image/jpeg", 0.82));
}
} catch (e) {
- throw new ToolError(e instanceof Error ? e.message : `Could not read "${asset.name}".`);
+ throw new ToolError(e instanceof Error ? e.message : `Could not read "${asset.name}".`, { cause: e });
}
}
for (let i = 0; i < wanted.length; i++)
@@ -1355,10 +1357,10 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
});
}
).catch((e) => {
- throw new ToolError(e instanceof Error ? e.message : "Could not draw the cut's frame.");
+ throw new ToolError(e instanceof Error ? e.message : "Could not draw the cut's frame.", { cause: e });
});
const images = await composeComparison(pairs).catch((e) => {
- throw new ToolError(e instanceof Error ? e.message : "Could not compose the comparison.");
+ throw new ToolError(e instanceof Error ? e.message : "Could not compose the comparison.", { cause: e });
});
return {
images,
@@ -1394,7 +1396,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
: "scan";
if (asset.type === "image") {
const body = await makeStillFrame(asset.url, detail).catch((e) => {
- throw new ToolError(e instanceof Error ? e.message : "Could not read the image.");
+ throw new ToolError(e instanceof Error ? e.message : "Could not read the image.", { cause: e });
});
return {
images: [body.frames[0].image],
@@ -1423,7 +1425,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
budgetMs: 90_000,
})
).catch((e) => {
- throw new ToolError(e instanceof Error ? e.message : "Could not watch the video.");
+ throw new ToolError(e instanceof Error ? e.message : "Could not watch the video.", { cause: e });
});
// The metadata persists on the asset (it saves with the project and
// dies with the asset), so what has been seen survives this thread.
@@ -1777,7 +1779,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
known && input.regenerate !== true
? known
: await detectAssetBeats(asset).catch((e) => {
- throw new ToolError(e instanceof Error ? e.message : "Could not read the audio.");
+ throw new ToolError(e instanceof Error ? e.message : "Could not read the audio.", { cause: e });
});
const beats = grid.beats.filter((b) => b >= from && (to === undefined || b <= to));
const toTimeline = (t: number) => roundT(clip!.start + retimeOf(clip!).tAt(t));
@@ -1941,6 +1943,9 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
truncated: heard.to < (to ?? asset.duration) - 0.05,
unheardSeconds: unheard,
...(nextUnheard ? { unheardFrom: round2(nextUnheard.from) } : {}),
+ // The language its speech is transcribed in, for a model that takes
+ // the sound as its words.
+ locale: asset.language ?? trackLocale(s.subtitles, 0),
audio: `data:${heard.inline.mimeType};base64,${heard.inline.data}`,
};
},
@@ -3552,7 +3557,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
// effects burned in. Same render path the canvas's Copy frame uses,
// so a still the assistant makes and one the user copies match.
const png = await renderStageFrame(t).catch((e) => {
- throw new ToolError(e instanceof Error ? e.message : "Could not draw the frame.");
+ throw new ToolError(e instanceof Error ? e.message : "Could not draw the frame.", { cause: e });
});
body = {
...(await storeStageStill(projectId, png, t, "Could not render the freeze frame.")),
@@ -3876,6 +3881,53 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
};
},
+ wait_for_uploads: async (s) => {
+ // Files this page is sending to storage, and failed ones a retry may
+ // land. A process with no page sends none.
+ const watched = s.assets.filter((a) => a.upload && uploadInFlight(a.id)).map((a) => a.id);
+ if (watched.length === 0 && !isOffline()) {
+ return { uploads: [], note: "No uploads in flight, and the connection is up." };
+ }
+ if (!isOffline()) {
+ retryFailedUploads();
+ }
+
+ // Poll the store: an upload settles by dropping its `upload` mark, or
+ // by carrying an error. Stay under the tool bridge's 2-minute cap.
+ const deadline = Date.now() + 100_000;
+ const settled = () =>
+ !isOffline() &&
+ watched.every((id) => {
+ const a = useEditor.getState().assets.find((x) => x.id === id);
+ return !a?.upload || a.upload.error !== undefined;
+ });
+ while (Date.now() < deadline && !settled()) {
+ await new Promise((r) => setTimeout(r, 1000));
+ }
+
+ const assets = useEditor.getState().assets;
+ const uploads = watched.map((id) => {
+ const a = assets.find((x) => x.id === id);
+ if (!a) {
+ return { assetId: id, status: "removed" as const };
+ }
+ if (!a.upload) {
+ return { assetId: id, name: a.name, status: "done" as const };
+ }
+ if (a.upload.error) {
+ return { assetId: id, name: a.name, status: "failed" as const, error: a.upload.error };
+ }
+ return { assetId: id, name: a.name, status: "uploading" as const, percent: Math.round(a.upload.progress * 100) };
+ });
+ const offline = isOffline();
+ const waiting = uploads.filter((u) => u.status === "uploading").length;
+ return {
+ uploads,
+ ...(offline ? { offline: true, note: "The browser is still offline; uploads and hosted work resume when the connection returns. Call wait_for_uploads again to keep waiting." } : {}),
+ ...(!offline && waiting > 0 ? { note: `${waiting} still uploading — call wait_for_uploads again to keep waiting.` } : {}),
+ };
+ },
+
generate_character_video: async (s, input) => {
const projectId = s.projectId;
if (!projectId) throw new ToolError("No project open.");
@@ -4144,7 +4196,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
for (const asset of assets) tagChatAsset(asset.id, chatId);
return describe(assets);
}).catch((e) => {
- throw new ToolError(e instanceof Error ? e.message : String(e));
+ throw new ToolError(e instanceof Error ? e.message : String(e), { cause: e });
});
const results = rows.filter((r) => !("notStarted" in r)).map((r) => ("value" in r ? { url: r.url, assets: r.value } : r));
const notStarted = rows.filter((r) => "notStarted" in r).map((r) => r.url);
@@ -5726,7 +5778,32 @@ export async function runAiTool(
name: string,
input: Record<string, unknown>
): Promise<unknown> {
- return dispatchTool(useEditor.getState(), name, input);
+ try {
+ return await dispatchTool(useEditor.getState(), name, input);
+ } catch (err) {
+ // A call the connection dropped passes with the connection: the model
+ // waits for it and runs the call again.
+ if (!droppedByConnection(err)) {
+ throw err;
+ }
+ const message = err instanceof Error ? err.message : String(err);
+ throw new ToolError(
+ `${message} The connection dropped while this ran. Call wait_for_uploads, which waits for the connection and the uploads, then run this call again.`,
+ { cause: err }
+ );
+ }
+}
+
+/** Whether a tool failed on the connection: a dropped request anywhere in its
+ * causes, or, while offline, anything besides the tool turning its input
+ * down (a ToolError of its own, with no failure underneath). */
+function droppedByConnection(err: unknown): boolean {
+ const dropped = (e: unknown): boolean =>
+ e instanceof ConnectionLostError || fetchDropped(e) || (e instanceof Error && e.cause !== undefined && dropped(e.cause));
+ if (dropped(err)) {
+ return true;
+ }
+ return isOffline() && !(err instanceof ToolError && err.cause === undefined);
}
async function dispatchTool(s: Editor, name: string, input: Record<string, unknown>, operation?: ProjectOperation): Promise<unknown> {
@@ -6172,7 +6249,7 @@ async function openReferenceLink(raw: unknown): Promise<ReferenceProject> {
const link = parseProjectLink(String(raw ?? ""));
if (!link) throw new ToolError("Pass a Donkey Cut project link, share link, or project id.");
return openReference(link).catch((e) => {
- throw new ToolError(e instanceof Error ? e.message : "Could not read that project.");
+ throw new ToolError(e instanceof Error ? e.message : "Could not read that project.", { cause: e });
});
}
@@ -6230,7 +6307,7 @@ async function landReferenceAssets(
): Promise<LandedAsset[]> {
if (sources.length === 0) return [];
return landReferenceAssetsInto(ref, sources, projectId, { chatId, mapped }).catch((e) => {
- throw new ToolError(e instanceof Error ? e.message : "Could not copy the reference's media.");
+ throw new ToolError(e instanceof Error ? e.message : "Could not copy the reference's media.", { cause: e });
});
}
@@ -6255,7 +6332,7 @@ async function eachScanned<T>(items: T[], run: (item: T) => Promise<void>) {
async function fetchSpeech(asset: MediaAsset, from: number, to: number) {
const heard = soundSpan(asset, from, to);
const scan = await scanSourceSpeech(heard.asset.url, { from: heard.from, to: heard.to }).catch((e) => {
- throw new ToolError(e instanceof Error ? e.message : "Could not read the audio.");
+ throw new ToolError(e instanceof Error ? e.message : "Could not read the audio.", { cause: e });
});
return {
...scan,
@@ -6313,7 +6390,7 @@ async function fetchSilences(
thresholdDb,
minSilence,
}).catch((e) => {
- throw new ToolError(e instanceof Error ? e.message : "Could not scan for silence.");
+ throw new ToolError(e instanceof Error ? e.message : "Could not scan for silence.", { cause: e });
})
);
}
@@ -6347,7 +6424,7 @@ async function audioSpanBlob(
): Promise<Blob> {
if (getBackend().kind !== "local")
return renderAudioSpanWav(asset.url, from, to).catch((e) => {
- throw new ToolError(e instanceof Error ? e.message : "Could not read the audio.");
+ throw new ToolError(e instanceof Error ? e.message : "Could not read the audio.", { cause: e });
});
const res = await apiFetch(`/api/cut/projects/${projectId}/audio`, {
method: "POST",
@@ -6364,6 +6441,7 @@ async function audioSpanBlob(
/** Bound the work per call the way a watch does; the caller listens on from
* coveredTo. */
const LISTEN_MAX_S = 600;
+const LISTEN_MIN_S = 0.5;
/**
* A span's sound, shrunk to whatever the model can take at once. The two
@@ -6387,7 +6465,9 @@ async function listenSpan(
const to = heard.to;
const end = Math.min(to ?? from + LISTEN_MAX_S, from + LISTEN_MAX_S);
let span = end - from;
- for (let attempt = 0; attempt < 3 && span > 0.5; attempt++) {
+ // The asked stretch reads at any length; a stretch shrunk to fit stops at
+ // LISTEN_MIN_S, below which nothing worth hearing is left.
+ for (let attempt = 0; attempt < 3 && span > (attempt === 0 ? 0 : LISTEN_MIN_S); attempt++) {
const blob = await audioSpanBlob(projectId, heard.asset, from, round2(from + span));
const inline = await blobToInlineAudio(blob);
if (inline) return { inline, from: roundT(heard.back(from)), to: roundT(heard.back(from + span)) };
@@ -6515,7 +6595,7 @@ function soundTarget(s: Editor, id: unknown) {
async function syncVideoSound(s: Editor, video: MediaAsset, audioId: unknown, clip: VideoClip | undefined) {
const rec = requireItem(s.assets, audioId, "audio asset");
const bound = await bindRecording(video.id, rec.id, clip).catch((e: unknown) => {
- throw new ToolError(e instanceof Error ? e.message : "Could not line the recording up.");
+ throw new ToolError(e instanceof Error ? e.message : "Could not line the recording up.", { cause: e });
});
const { assetId, ...rest } = bound;
return {
diff --git a/site/src/cut/lib/listenAudio.test.ts b/site/src/cut/lib/listenAudio.test.ts
new file mode 100644
index 00000000..be8d1bc6
--- /dev/null
+++ b/site/src/cut/lib/listenAudio.test.ts
@@ -0,0 +1,55 @@
+import { afterAll, expect, test } from "bun:test";
+import { stubModule } from "@/lib/testing/stubModule";
+import { cutMode, setCutMode } from "./backend";
+import { useEditor } from "./store";
+
+// A cloud listen reads its stretch off the browser's own render of the sound.
+// The render hands back a few bytes, so what is pinned is the span the call
+// asks for and the answer it gives.
+const spans: { from: number; to?: number }[] = [];
+let connection: "up" | "dropped" = "up";
+await stubModule<typeof import("./media")>("./media", import.meta.url, {
+ renderAudioSpanWav: async (_url: string, from: number, to?: number) => {
+ if (connection === "dropped") {
+ throw new TypeError("Failed to fetch");
+ }
+ spans.push({ from, to });
+ return new Blob([new Uint8Array(64)], { type: "audio/wav" });
+ },
+});
+await stubModule<typeof import("./watch/sweep")>("./watch/sweep", import.meta.url, { queueWatchSweep: () => {} });
+const { runAiTool } = await import("./aiTools");
+
+const ambient = cutMode();
+setCutMode("cloud");
+afterAll(() => setCutMode(ambient));
+
+const project = () =>
+ useEditor.setState({
+ projectId: "p",
+ clips: [],
+ overlays: [],
+ transitions: [],
+ audioClips: [],
+ assets: [{ id: "take", fileName: "take.mov", name: "Take", type: "video", duration: 12, url: "blob:take" }],
+ });
+
+test("half a second is a stretch short enough to listen to", async () => {
+ project();
+ const out = (await runAiTool("listen_audio", { asset_id: "take", to: 0.5 })) as { coveredTo: number; audio: string };
+ expect(spans).toEqual([{ from: 0, to: 0.5 }]);
+ expect(out.coveredTo).toBe(0.5);
+ expect(out.audio.startsWith("data:audio/wav;base64,")).toBe(true);
+});
+
+test("a listen the connection drops says to wait for it and listen again", async () => {
+ project();
+ connection = "dropped";
+ try {
+ const error = await runAiTool("listen_audio", { asset_id: "take" }).then(() => "", (e: Error) => e.message);
+ expect(error).toContain("Failed to fetch");
+ expect(error).toContain("wait_for_uploads");
+ } finally {
+ connection = "up";
+ }
+});
diff --git a/site/src/cut/lib/pi/mutationLedger.ts b/site/src/cut/lib/pi/mutationLedger.ts
index f0da9801..60114114 100644
--- a/site/src/cut/lib/pi/mutationLedger.ts
+++ b/site/src/cut/lib/pi/mutationLedger.ts
@@ -28,6 +28,7 @@ const READ_ONLY = new Set([
"stock_search",
"list_voices",
"wait_for_renders",
+ "wait_for_uploads",
"seek",
"select",
"select_items",
diff --git a/site/src/cut/lib/waitForUploads.test.ts b/site/src/cut/lib/waitForUploads.test.ts
new file mode 100644
index 00000000..8220eda4
--- /dev/null
+++ b/site/src/cut/lib/waitForUploads.test.ts
@@ -0,0 +1,53 @@
+import { expect, test } from "bun:test";
+import { stubModule } from "@/lib/testing/stubModule";
+import { useEditor } from "./store";
+import type { MediaAsset } from "./types";
+
+await stubModule<typeof import("./mediaSync")>("./mediaSync", import.meta.url, {
+ storedMediaUrl: async (_projectId: string, fileName: string) => `stored:${fileName}`,
+});
+const { runAiTool } = await import("./aiTools");
+const { startUpload } = await import("./importQueue");
+
+const take = (upload?: MediaAsset["upload"]): MediaAsset => ({
+ id: "take",
+ fileName: "take.mov",
+ name: "take.mov",
+ type: "video",
+ duration: 12,
+ url: upload ? "blob:take" : "stored:take.mov",
+ ...(upload ? { upload } : {}),
+});
+
+test("waiting on uploads returns once the files land in storage", async () => {
+ const uploading = take({ progress: 0.4 });
+ useEditor.setState({ projectId: "p", assets: [uploading] });
+ let land!: (fileName: string) => void;
+ const send = () => new Promise<string>((resolve) => (land = resolve));
+ startUpload("p", { asset: uploading, localUrl: "blob:take", send });
+ setTimeout(() => land("take.mov"), 50);
+ const out = await runAiTool("wait_for_uploads", {});
+ expect(out).toEqual({ uploads: [{ assetId: "take", name: "take.mov", status: "done" }] });
+});
+
+test("with nothing uploading the wait answers straight away", async () => {
+ useEditor.setState({ projectId: "p", assets: [take()] });
+ expect(await runAiTool("wait_for_uploads", {})).toMatchObject({ uploads: [] });
+});
+
+test("a call turned down for its input says so, offline or not", async () => {
+ useEditor.setState({ projectId: "p", assets: [take()] });
+ const online = Object.getOwnPropertyDescriptor(globalThis.navigator, "onLine");
+ Object.defineProperty(globalThis.navigator, "onLine", { value: false, configurable: true });
+ try {
+ const error = await runAiTool("listen_audio", { asset_id: "nope" }).then(() => "", (e: Error) => e.message);
+ expect(error).toContain("No project asset with id nope");
+ expect(error).not.toContain("wait_for_uploads");
+ } finally {
+ if (online) {
+ Object.defineProperty(globalThis.navigator, "onLine", online);
+ } else {
+ delete (globalThis.navigator as { onLine?: boolean }).onLine;
+ }
+ }
+});
diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.ts
index c31569e8..54ca56d0 100644
--- a/site/src/cut/server/ai/catalog.ts
+++ b/site/src/cut/server/ai/catalog.ts
@@ -546,7 +546,7 @@ Stock: stock_search browses the bundled catalogs — footage clips and images in
Generation:
- generate_image(prompt, aspect?, resolution?, reference_asset_ids?, add_to_timeline?, index?): the hosted image model renders the prompt at 16:9, 9:16, or 1:1 (default: the supported shape closest to the project aspect) and 1K/2K/4K. The still previews in the chat; placed (add_to_timeline:true or an index) it rides video track 0 as a still clip (8s default, stretchable). Great for a cover/hook frame (index 0), a background, or a b-roll still.
- generate_video(prompt, aspect?, resolution?, duration_seconds?, reference_asset_id?, add_to_timeline?, index?): the hosted video model renders a short clip with audio in one pass — ${geminiOmniResolutions.join("/")} (${geminiOmniDefaultResolution} default; the upscaled sizes cost more per second), ${geminiOmniDurationSeconds.min}–${geminiOmniDurationSeconds.max}s when duration_seconds is set and the model's own length otherwise (the user trims the clip on the timeline). With reference_asset_id it stages: the image model designs the opening frame from the reference first (that still previews in the chat), then the video model animates that exact frame. The render takes a minute or two, so the tool returns once it's started and the clip previews in the chat when it finishes (on the timeline only when asked) — tell the user it's rendering. Don't call it again for the same shot while one is in flight.
-- Every render's live status is \`renders\` in editor_state (running with elapsed seconds, done with its asset id, failed with the error) — report render progress from there, never from memory. When the user's ask depends on a running render ("assemble the clips", "add it when it's done"), call wait_for_renders and finish the job in the same turn — never hand the waiting to the user.
+- Every render's live status is \`renders\` in editor_state (running with elapsed seconds, done with its asset id, failed with the error) — report render progress from there, never from memory. When the user's ask depends on a running render ("assemble the clips", "add it when it's done"), call wait_for_renders and finish the job in the same turn — never hand the waiting to the user. A connection that drops is waited out the same way: wait_for_uploads waits for the connection and the uploads, then you run what failed again.
- generate_character_video(character_id, line, …): a stock talking character delivers a line to camera, same async render as generate_video. Characters come from stock_search kind:"character" — each has a persona; you write the line (chat deliverable rules apply: asked for "a script", write it in chat first).
References: users attach media to their message or the generate panels; project asset ids (see \`media\` in editor_state, including attachments — OS drops become project assets) pass through reference_asset_ids / reference_asset_id. Images draw from any number of references; video stages one reference into a designed opening frame and animates it; generate_music matches the sound of an audio reference or the mood of a video/image one. When the user says "use this clip/image/song" or "match this", pass the reference — don't just describe it in the prompt.
If generation fails with a sign-in or credits message, relay that plainly — generation needs a Donkey sign-in with credits. Write vivid, specific prompts (subject, style, lighting, motion); the user's request is usually shorthand, so flesh it out. A narrated multi-shot production is generate_scene — read the scene-productions skill before planning one, especially from an audio file or in a named style.`,