Skip to content

Open source CapCut alternative.

TypeScript

feat(site): sync chat render cards through the project doc [rebuild]

David Le6141996f456e
diff --git a/docs/guides/cut/ai-assistant.md b/docs/guides/cut/ai-assistant.md
index 7aa0d686..15d84d72 100644
--- a/docs/guides/cut/ai-assistant.md
+++ b/docs/guides/cut/ai-assistant.md
@@ -68,7 +68,7 @@ Tool calls execute in the open tab against the same store the user is editing
- **One undo step per turn.** History batches while the assistant is busy, so ⌘Z reverts the whole turn rather than one call at a time.
- **Small results.** Tools return ids and rounded numbers, plus a short note when behavior surprised ("that spot was taken — slid right").
- **Frames become images.** A tool result's `image`/`images` data URLs leave the JSON and reach the model as real images on every path — the engine bridge emits MCP image blocks after the data text, and the Gemini loop rides the first on the function response and the rest as image parts. Watching happens in whatever model the user is chatting with; there is no side model.
-- **Async when rendering.** Video generation outruns the two-minute tool window, so those tools start the job and return immediately; the clip files under the chat that asked — the owning thread is captured at call time — and lands on the timeline only when the user asked for that.
+- **Async when rendering.** Video generation outruns the two-minute tool window, so those tools start the job and return immediately; the clip files under the chat that asked — the owning thread is captured at call time — and lands on the timeline only when the user asked for that. Each render's card state (running, landed, failed) mirrors into the project doc as it changes, so the chat shows the same outcome on machines that never ran the job.
- **Chat owns what it makes.** Media created by chat tools is tagged with its thread and previews on a card in the conversation. Placing it on the timeline or filing it into Media or the Library transfers ownership; deleting the thread deletes whatever it still owns.
- **Two tools stay server-side.** The skill list and skill reads are answered by the engine directly — no browser hop.
diff --git a/site/src/cut/components/AiPanel.tsx b/site/src/cut/components/AiPanel.tsx
index b93fe0a0..d2ca3bff 100644
--- a/site/src/cut/components/AiPanel.tsx
+++ b/site/src/cut/components/AiPanel.tsx
@@ -90,7 +90,7 @@ import { cn } from "@/lib/utils";
import { cardIconButton } from "@/cut/components/iconButton";
import { MentionTextarea, RefChips, RefThumb, RefTokenChip } from "./AssetRefs";
import { DictationBody } from "./MicDictation";
-import { ToolOutputAssets } from "./ChatAssets";
+import { RECORD_RUNNING_TTL_MS, ToolOutputAssets } from "./ChatAssets";
import { HostedErrorText } from "./hostedError";
import { useMicTranscription } from "@/cut/lib/micTranscribe";
@@ -1439,10 +1439,24 @@ const MessageView = memo(function MessageView({
* "something is still happening" without scrolling. */
function ThreadRenders({ threadId }: { threadId: string }) {
const jobs = useGenerate((s) => s.jobs);
- const running = jobs.filter(
+ const records = useEditor((s) => s.renders);
+ const live = jobs.filter(
(j) =>
j.kind === "video" && j.status === "running" && j.chatId === threadId,
);
+ // Renders another machine is still working on: doc-mirrored records with no
+ // local job. The TTL keeps a record whose job died from spinning forever;
+ // a mount-time clock is enough for that check.
+ const [now] = useState(() => Date.now());
+ const liveIds = new Set(jobs.map((j) => j.id));
+ const remote = records.filter(
+ (r) =>
+ r.chatId === threadId &&
+ r.status === "running" &&
+ !liveIds.has(r.id) &&
+ now - r.startedAt < RECORD_RUNNING_TTL_MS,
+ );
+ const running = [...live, ...remote];
const oldest = running.length
? Math.min(...running.map((j) => j.startedAt))
: null;
diff --git a/site/src/cut/components/ChatAssets.tsx b/site/src/cut/components/ChatAssets.tsx
index 057c6be9..e313caed 100644
--- a/site/src/cut/components/ChatAssets.tsx
+++ b/site/src/cut/components/ChatAssets.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useEffect, type ReactNode } from "react";
+import { useEffect, useState, type ReactNode } from "react";
import type React from "react";
import { Copy, ExternalLink, FileText, Film, Loader2, Maximize2, Plus } from "lucide-react";
import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
@@ -16,7 +16,7 @@ import {
import { useElapsed } from "@/cut/hooks/useElapsed";
import { useHoverPlay } from "@/cut/hooks/useHoverPlay";
import { useInView } from "@/cut/hooks/useInView";
-import { useGenerate } from "@/cut/lib/generate";
+import { useGenerate, type GenerateJob } from "@/cut/lib/generate";
import { lightboxItemFromRef, useLightbox } from "@/cut/lib/lightbox";
import { usePreviewAudio } from "@/cut/lib/previewAudio";
import { useEditor } from "@/cut/lib/store";
@@ -103,40 +103,61 @@ export function ToolOutputAssets({ output }: { output: unknown }) {
);
}
+/** How long a mirrored "running" record with no live job stays believable —
+ * another machine may genuinely still be polling the render. Past this, the
+ * job died without settling its record; show that instead of a forever
+ * spinner. */
+export const RECORD_RUNNING_TTL_MS = 30 * 60_000;
+
+/** The card's data, from whichever source knows the job: the browser-local
+ * job store when this machine ran the render, else the record the render
+ * mirrored into the doc (ProjectDoc.renders). */
+type RenderView = Pick<GenerateJob, "status" | "prompt" | "startedAt" | "error" | "assetId">;
+
/** A video render the tool started but couldn't wait out: a live card that
- * follows the generation job and becomes the clip's card when it lands.
- * Settled jobs persist per browser, so the card survives a reload; only a
- * render still in flight when the page closed has no card afterwards. */
+ * follows the generation job and becomes the clip's card when it lands. The
+ * job store covers this browser; the doc-mirrored record carries the same
+ * card to every other browser and machine. */
export function ChatVideoJobCard({ jobId }: { jobId: string }) {
const job = useGenerate((s) => s.jobs.find((j) => j.id === jobId));
- const elapsed = useElapsed(job?.status === "running" ? job.startedAt : null);
- if (!job) return null;
- if (job.status === "done") return job.assetId ? <ChatProjectAsset assetId={job.assetId} /> : null;
+ const record = useEditor((s) => s.renders.find((r) => r.id === jobId));
+ // Mount-time clock: a record already past the TTL is stale when the card
+ // appears — the check doesn't need to keep ticking.
+ const [now] = useState(() => Date.now());
+ const view: RenderView | undefined =
+ job ??
+ (record &&
+ (record.status === "running" && now - record.startedAt > RECORD_RUNNING_TTL_MS
+ ? { ...record, status: "error" as const, error: "The render was interrupted." }
+ : record));
+ const elapsed = useElapsed(view?.status === "running" ? view.startedAt : null);
+ if (!view) return null;
+ if (view.status === "done") return view.assetId ? <ChatProjectAsset assetId={view.assetId} /> : null;
return (
<div className="ai-chat-job flex w-full max-w-[280px] flex-col gap-1.5 rounded-xl border border-border p-2.5">
<div className="flex items-center gap-2">
<span className="grid size-6 shrink-0 place-items-center rounded-md bg-muted text-muted-foreground">
- {job.status === "running" ? (
+ {view.status === "running" ? (
<Loader2 className="size-3.5 animate-spin" />
) : (
<Film className="size-3.5" />
)}
</span>
- <div className="min-w-0 flex-1 truncate text-[11px] font-medium">{job.prompt}</div>
+ <div className="min-w-0 flex-1 truncate text-[11px] font-medium">{view.prompt}</div>
</div>
<div
className={cn(
"text-[10.5px] leading-snug break-words",
- job.status === "error" ? "text-red-600" : "text-muted-foreground"
+ view.status === "error" ? "text-red-600" : "text-muted-foreground"
)}
>
- {job.status === "running" ? (
+ {view.status === "running" ? (
<>
Rendering…{" "}
{elapsed && <span className="tabular-nums text-muted-foreground/80">{elapsed}</span>}
</>
) : (
- <HostedErrorText error={job.error} link={false} />
+ <HostedErrorText error={view.error} link={false} />
)}
</div>
</div>
diff --git a/site/src/cut/components/Editor.tsx b/site/src/cut/components/Editor.tsx
index ffbcf692..1e420310 100644
--- a/site/src/cut/components/Editor.tsx
+++ b/site/src/cut/components/Editor.tsx
@@ -231,6 +231,7 @@ export function Editor({
// Normalized like serializeDoc stores it (?? null): a project with no
// run holds undefined in state and null in the doc — not a change.
(s.genvideo ?? null) !== ((last.genvideo ?? null) as unknown) ||
+ s.renders !== (last.renders as unknown) ||
s.projectName !== lastName;
if (!changed) return;
last = serializeDoc(s);
diff --git a/site/src/cut/lib/generate.ts b/site/src/cut/lib/generate.ts
index d5db46bf..6eef932e 100644
--- a/site/src/cut/lib/generate.ts
+++ b/site/src/cut/lib/generate.ts
@@ -9,7 +9,12 @@ import type { AssetRef } from "./assetRef";
import { bytesFromBase64 } from "./bytes";
import { readThreadIds } from "./chatThreads";
import { composeGenPrompt, foldTextRefs } from "./composeGen";
-import { stockAssetInDoc } from "./genvideo/docWriter";
+import {
+ projectWriteMode,
+ removeRendersInDoc,
+ stockAssetInDoc,
+ upsertRenderInDoc,
+} from "./genvideo/docWriter";
import { cutAppBase } from "./hosts";
import { hostedPost } from "./hosted";
import { enrichAsset, importFileToProject, uploadProjectImage } from "./media";
@@ -17,7 +22,7 @@ import { refsToInlineImages, videoSafeInline, visualRefs, type InlineImage } fro
import { useGenNotify } from "./genNotify";
import { useImageGen } from "./imageGen";
import { useEditor } from "./store";
-import { mediaSlug, type MediaAsset } from "./types";
+import { mediaSlug, type MediaAsset, type RenderRecord } from "./types";
import { videoModel } from "./videoModels";
import { walkLadder, type VideoAttempt } from "./videoLadder";
@@ -394,9 +399,48 @@ export const useGenerate = create<GenerateState>((set, get) => {
// owner is gone drops its result instead of re-adding orphaned media.
const cancelledJobs = new Set<string>();
+ // Chat-launched video renders mirror into the project doc (doc.renders): the
+ // job store is per browser, the doc travels with the project, so the mirror
+ // is what makes the chat's render card show the same outcome everywhere.
+ // Open project → the store (autosave persists it); closed → its doc.
+ const mirrorRender = (id: string) => {
+ const j = get().jobs.find((x) => x.id === id);
+ if (!j || j.kind !== "video" || !j.chatId) return;
+ const record: RenderRecord = {
+ id: j.id,
+ chatId: j.chatId,
+ prompt: j.prompt,
+ startedAt: j.startedAt,
+ status: j.status,
+ ...(j.error !== undefined ? { error: j.error } : {}),
+ ...(j.assetId !== undefined ? { assetId: j.assetId } : {}),
+ };
+ const backend = jobBackend(j);
+ void (async () => {
+ if ((await projectWriteMode(j.projectId)) === "store")
+ useEditor.getState().upsertRender(record);
+ else await upsertRenderInDoc(j.projectId, record, backend);
+ })().catch(() => {});
+ };
+
+ const unmirrorRenders = (projectId: string, victims: GenerateJob[]) => {
+ const mirrored = victims.filter((j) => j.kind === "video" && j.chatId);
+ if (mirrored.length === 0) return;
+ const ids = mirrored.map((j) => j.id);
+ const backend = jobBackend(mirrored[0]);
+ void (async () => {
+ if ((await projectWriteMode(projectId)) === "store")
+ useEditor.getState().removeRenders(ids);
+ else await removeRendersInDoc(projectId, ids, backend);
+ })().catch(() => {});
+ };
+
const update = (id: string, patch: Partial<GenerateJob>) => {
set((s) => ({ jobs: s.jobs.map((j) => (j.id === id ? { ...j, ...patch } : j)) }));
persistJobs(get().jobs);
+ // Poll-payload and rung refreshes stay browser-local; only record-visible
+ // fields re-mirror.
+ if ("status" in patch || "assetId" in patch || "error" in patch) mirrorRender(id);
};
const fail = (id: string, err: unknown) =>
@@ -643,6 +687,7 @@ export const useGenerate = create<GenerateState>((set, get) => {
};
set((s) => ({ jobs: [job, ...s.jobs] }));
claimJobLease(job.id); // this tab started it, this tab polls it
+ mirrorRender(job.id);
// Resolves the moment the backend accepts a rung's submit (a real render
// is in flight) or, if every rung is rejected before acceptance, with the
@@ -757,6 +802,15 @@ export const useGenerate = create<GenerateState>((set, get) => {
}
set((s) => ({ jobs: s.jobs.filter((j) => !match(j)) }));
persistJobs(get().jobs);
+ // The mirrored records go with the owner — except on project deletion,
+ // where the whole doc is going away anyway.
+ if (owner.projectId === undefined) {
+ const byProject = new Map<string, GenerateJob[]>();
+ for (const j of victims) {
+ byProject.set(j.projectId, [...(byProject.get(j.projectId) ?? []), j]);
+ }
+ for (const [projectId, group] of byProject) unmirrorRenders(projectId, group);
+ }
},
resumeRunningJobs: () => {
@@ -815,8 +869,10 @@ export const useGenerate = create<GenerateState>((set, get) => {
},
dismiss: (id) => {
+ const victim = get().jobs.find((j) => j.id === id);
set((s) => ({ jobs: s.jobs.filter((j) => j.id !== id) }));
persistJobs(get().jobs);
+ if (victim) unmirrorRenders(victim.projectId, [victim]);
},
};
});
diff --git a/site/src/cut/lib/genvideo/docWriter.ts b/site/src/cut/lib/genvideo/docWriter.ts
index 293944a5..4b8582a6 100644
--- a/site/src/cut/lib/genvideo/docWriter.ts
+++ b/site/src/cut/lib/genvideo/docWriter.ts
@@ -15,9 +15,9 @@
*/
import { apiFetch, apiJson, getBackend, type CutBackend } from "../backend";
-import { storedAssets, useEditor } from "../store";
+import { RENDERS_CAP, storedAssets, useEditor } from "../store";
import { mediaUrl, SPEED_MIN } from "../types";
-import type { AudioClip, MediaAsset, ProjectDoc, VideoClip } from "../types";
+import type { AudioClip, MediaAsset, ProjectDoc, RenderRecord, VideoClip } from "../types";
import { fillSlot } from "./fillSlot";
const MIN_LEN = 0.1;
@@ -94,6 +94,38 @@ export function stockAssetInDoc(
);
}
+/** Mirror a chat-launched render's record into a closed project's doc (the
+ * open-project path writes the store and autosave persists it). */
+export function upsertRenderInDoc(
+ projectId: string,
+ record: RenderRecord,
+ backend?: CutBackend
+): Promise<void> {
+ return withProjectDoc(
+ projectId,
+ (doc) => {
+ const rest = (doc.renders ?? []).filter((r) => r.id !== record.id);
+ doc.renders = [...rest, record].slice(-RENDERS_CAP);
+ },
+ backend
+ );
+}
+
+/** Drop render records from a closed project's doc (dismissed or owner gone). */
+export function removeRendersInDoc(
+ projectId: string,
+ ids: string[],
+ backend?: CutBackend
+): Promise<void> {
+ return withProjectDoc(
+ projectId,
+ (doc) => {
+ doc.renders = (doc.renders ?? []).filter((r) => !ids.includes(r.id));
+ },
+ backend
+ );
+}
+
/** A run's asset by id, wherever the user is: the live store when the run's
* project is open, its persisted doc when not. The doc projection is rebuilt
* into a usable runtime asset (url from the media route). */
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index a0c9b384..b014ffb8 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -10,6 +10,7 @@ import type {
LookStyle,
MediaAsset,
ProjectDoc,
+ RenderRecord,
Selection,
StoredAsset,
SubtitleCue,
@@ -147,6 +148,10 @@ export interface EditorState {
/** In-progress or finished brief-to-video run; persisted on ProjectDoc.genvideo
* and driven by the genScene store. Absent when no scene was generated. */
genvideo?: VideoProject;
+ /** Chat-launched renders mirrored from the job store (ProjectDoc.renders),
+ * so their chat cards render on machines that never ran the job. Outside the
+ * undo history, like assets. */
+ renders: RenderRecord[];
loadProject: (id: string) => Promise<void>;
setProjectName: (name: string) => void;
@@ -336,6 +341,8 @@ export interface EditorState {
setAiOpen: (v: boolean) => void;
undo: () => void;
redo: () => void;
+ upsertRender: (r: RenderRecord) => void;
+ removeRenders: (ids: string[]) => void;
pushHistory: () => void;
/** Coalesce every edit until the matching `endHistoryBatch` into one undo
* step. Used so a whole assistant turn reverts with a single ⌘Z. */
@@ -351,6 +358,8 @@ export interface EditorState {
// Per-project undo/redo stacks; both reset when a project loads. Capped so a
// long session (each snapshot deep-copies every clip/cue) can't grow unbounded.
const HISTORY_CAP = 100;
+/** Most chat render records a doc keeps — settled cards past this fall off. */
+export const RENDERS_CAP = 100;
const history: DocSnapshot[] = [];
const future: DocSnapshot[] = [];
/** A checkpoint captured on pointerdown/focus but not yet committed: it lands
@@ -762,6 +771,7 @@ export const useEditor = create<EditorState>((baseSet, get) => {
dropActive: null,
aiOpen: typeof window !== "undefined" && localStorage.getItem("cut-ai-open") === "1",
genvideo: undefined,
+ renders: [],
loadProject: async (id) => {
history.length = 0;
@@ -795,6 +805,7 @@ export const useEditor = create<EditorState>((baseSet, get) => {
subtitleError: null,
exportOpen: false,
genvideo: undefined,
+ renders: [],
});
// A background scene run may still be writing this project's doc — drain
// its queued writes so the load never reads a half-written doc. Ordering
@@ -877,6 +888,7 @@ export const useEditor = create<EditorState>((baseSet, get) => {
subtitles: doc.subtitles ?? emptySubtitles(),
subtitleStatus: (doc.subtitles?.cues.length ?? 0) > 0 ? "ready" : "idle",
genvideo: doc.genvideo ?? undefined,
+ renders: Array.isArray(doc.renders) ? doc.renders : [],
loaded: true,
});
} catch (err) {
@@ -893,6 +905,13 @@ export const useEditor = create<EditorState>((baseSet, get) => {
// and the plan is never written back.
setGenvideo: (project) => set({ genvideo: project ? { ...project } : undefined }),
+ upsertRender: (r) =>
+ set((s) => ({
+ renders: [...s.renders.filter((x) => x.id !== r.id), r].slice(-RENDERS_CAP),
+ })),
+ removeRenders: (ids) =>
+ set((s) => ({ renders: s.renders.filter((x) => !ids.includes(x.id)) })),
+
placeGenClip: (assetId, startSec, endSec, opts) => {
const asset = get().assets.find((a) => a.id === assetId);
if (!asset || (asset.type !== "video" && asset.type !== "image")) return null;
@@ -2849,6 +2868,7 @@ export function serializeDoc(s: {
notes: { text: string; publishedAt: string; links: string[] };
subtitles: SubtitlesBlock;
genvideo?: VideoProject;
+ renders: RenderRecord[];
}): Partial<ProjectDoc> {
return {
name: s.projectName,
@@ -2866,6 +2886,7 @@ export function serializeDoc(s: {
// Explicit null when there is no run: absence means "keep what you have"
// to the PUT handler, so a dismissed plan could otherwise never be cleared.
genvideo: s.genvideo ?? null,
+ renders: s.renders,
};
}
diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.ts
index acc4ddd8..51297a83 100644
--- a/site/src/cut/lib/types.ts
+++ b/site/src/cut/lib/types.ts
@@ -701,6 +701,24 @@ export interface ProjectDoc {
* source of truth for the run (see lib/genvideo/types.ts). On the save wire,
* null means "clear it" (absent means keep); at rest it is never null. */
genvideo?: VideoProject | null;
+ /** Chat-launched video renders, running and settled — see RenderRecord. */
+ renders?: RenderRecord[];
+}
+
+/** A chat-launched video render, mirrored into the doc as it runs and settles.
+ * The browser-local job store covers only the machine that ran the render;
+ * this record is what lets the chat's render card show the same outcome on
+ * every browser and machine. */
+export interface RenderRecord {
+ /** The GenerateJob id the chat message's tool output points at. */
+ id: string;
+ chatId: string;
+ prompt: string;
+ startedAt: number;
+ status: "running" | "done" | "error";
+ error?: string;
+ /** The project asset the finished render landed as. */
+ assetId?: string;
}
/** A named group of projects on the home screen. */
diff --git a/site/src/cut/server/cloud/projects.ts b/site/src/cut/server/cloud/projects.ts
index c5c9d0dc..288005cf 100644
--- a/site/src/cut/server/cloud/projects.ts
+++ b/site/src/cut/server/cloud/projects.ts
@@ -172,6 +172,7 @@ export const projectsCloud = {
? { ...existing.notes, ...body.notes }
: existing.notes,
genvideo: body.genvideo !== undefined ? body.genvideo ?? undefined : existing.genvideo,
+ renders: Array.isArray(body.renders) ? body.renders : existing.renders,
};
doc.updatedAt = Date.now();
const data = { doc: asJson(doc), name: doc.name, version: { increment: 1 } };
diff --git a/site/src/cut/server/http/projects.ts b/site/src/cut/server/http/projects.ts
index 37c09bca..9f18b553 100644
--- a/site/src/cut/server/http/projects.ts
+++ b/site/src/cut/server/http/projects.ts
@@ -144,6 +144,7 @@ export const projectsApi = {
// key keeps the existing plan, and null clears it (a dismissed plan) —
// normalized to undefined so the doc at rest never stores null.
genvideo: body.genvideo !== undefined ? body.genvideo ?? undefined : existing.genvideo,
+ renders: Array.isArray(body.renders) ? body.renders : existing.renders,
};
await writeProject(id, doc);
return Response.json({ ok: true, updatedAt: doc.updatedAt });