The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Shorts Studio, Mixed Media: one session, render, stitch or take per click
Claude64df8be2cd9c
diff --git a/src/app/api/mixed-media/preview/route.ts b/src/app/api/mixed-media/preview/route.tsindex 8a887349..39a4381d 100644--- a/src/app/api/mixed-media/preview/route.ts+++ b/src/app/api/mixed-media/preview/route.ts@@ -1,10 +1,10 @@import { createMixedPreview } from "@/server/mixed-media";-import { MixedBodySchema, body, handle } from "@/server/shorts-schemas";+import { MixedBodySchema, body, handle, once } from "@/server/shorts-schemas";/** Generate one frame with the current settings before the full video. */export async function POST(request: Request) {return handle(async () => {const input = await body(request, MixedBodySchema, "Pick a preset and upload a clip first");- return Response.json(await createMixedPreview(input), { status: 201 });+ return Response.json(await once("mixed-preview", input.requestId, () => createMixedPreview(input)), { status: 201 });});}diff --git a/src/app/api/mixed-media/route.ts b/src/app/api/mixed-media/route.tsindex 02255477..1c2759fa 100644--- a/src/app/api/mixed-media/route.ts+++ b/src/app/api/mixed-media/route.ts@@ -1,11 +1,12 @@import { createMixed } from "@/server/mixed-media";-import { MixedBodySchema, body, handle } from "@/server/shorts-schemas";+import { MixedBodySchema, body, handle, once } from "@/server/shorts-schemas";/** Render a Mixed Media video (open: per frame; cloud: cut → restyle → original sound). */export async function POST(request: Request) {return handle(async () => {const input = await body(request, MixedBodySchema, "Pick a preset, upload a clip and choose up to 10 seconds");- const { final, items } = await createMixed(input);+ // A repeated requestId (a second click on Generate video) gets the render the first one started.+ const { final, items } = await once("mixed-render", input.requestId, () => createMixed(input));return Response.json({ final, items }, { status: 201 });});}diff --git a/src/app/api/shorts/sessions/[id]/segments/[index]/route.ts b/src/app/api/shorts/sessions/[id]/segments/[index]/route.tsindex 301e9822..8f22022f 100644--- a/src/app/api/shorts/sessions/[id]/segments/[index]/route.ts+++ b/src/app/api/shorts/sessions/[id]/segments/[index]/route.ts@@ -1,12 +1,13 @@import { regenerateSegment, ShortsError } from "@/server/shorts";-import { handle } from "@/server/shorts-schemas";+import { NonceSchema, handle, once, optionalBody } from "@/server/shorts-schemas";-/** Regenerate: one more take of this segment. */-export async function POST(_req: Request, ctx: RouteContext<"/api/shorts/sessions/[id]/segments/[index]">) {+/** Regenerate: one more take of this segment (a repeated requestId gets the first answer, not a second take). */+export async function POST(request: Request, ctx: RouteContext<"/api/shorts/sessions/[id]/segments/[index]">) {return handle(async () => {const { id, index } = await ctx.params;const i = Number(index);if (!Number.isInteger(i) || i < 0) throw new ShortsError("No such segment", 404);- return Response.json(regenerateSegment(id, i), { status: 201 });+ const { requestId } = await optionalBody(request, NonceSchema);+ return Response.json(await once(`shorts-take:${id}:${i}`, requestId, () => regenerateSegment(id, i)), { status: 201 });});}diff --git a/src/app/api/shorts/sessions/[id]/stitch/route.ts b/src/app/api/shorts/sessions/[id]/stitch/route.tsindex c06b5507..cb2861f3 100644--- a/src/app/api/shorts/sessions/[id]/stitch/route.ts+++ b/src/app/api/shorts/sessions/[id]/stitch/route.ts@@ -1,10 +1,11 @@import { stitchSession } from "@/server/shorts";-import { handle } from "@/server/shorts-schemas";+import { NonceSchema, handle, once, optionalBody } from "@/server/shorts-schemas";-/** Stitch again: join the chosen takes and put the original sound back. */-export async function POST(_req: Request, ctx: RouteContext<"/api/shorts/sessions/[id]/stitch">) {+/** Stitch again: join the chosen takes and put the original sound back (a repeated requestId gets the first answer). */+export async function POST(request: Request, ctx: RouteContext<"/api/shorts/sessions/[id]/stitch">) {return handle(async () => {const { id } = await ctx.params;- return Response.json(stitchSession(id), { status: 201 });+ const { requestId } = await optionalBody(request, NonceSchema);+ return Response.json(await once(`shorts-stitch:${id}`, requestId, () => stitchSession(id)), { status: 201 });});}diff --git a/src/app/api/shorts/sessions/route.ts b/src/app/api/shorts/sessions/route.tsindex 6d9f41fe..35ce9261 100644--- a/src/app/api/shorts/sessions/route.ts+++ b/src/app/api/shorts/sessions/route.ts@@ -1,6 +1,6 @@import { connection } from "next/server";import { createSession, listSessions } from "@/server/shorts";-import { ShortsBodySchema, body, handle } from "@/server/shorts-schemas";+import { ShortsBodySchema, body, handle, once } from "@/server/shorts-schemas";/** Shorts sessions, newest first (History). */export async function GET() {@@ -12,6 +12,7 @@ export async function GET() {export async function POST(request: Request) {return handle(async () => {const input = await body(request, ShortsBodySchema, "Pick a preset, upload a clip and choose the part to restyle");- return Response.json(await createSession(input), { status: 201 });+ // A repeated requestId (a second click on Generate) gets the session the first one started.+ return Response.json(await once("shorts-session", input.requestId, () => createSession(input)), { status: 201 });});}diff --git a/src/components/mixed-media/hooks.ts b/src/components/mixed-media/hooks.tsindex 2fdaee5b..30c0b3c4 100644--- a/src/components/mixed-media/hooks.ts+++ b/src/components/mixed-media/hooks.ts@@ -20,6 +20,8 @@ export interface MixedBody {modelId?: string;anchor?: string;frameUrl?: string;+ /** Client nonce: a repeat of it gets the first answer (see useSubmitGuard). */+ requestId?: string;}export interface MixedEstimate {diff --git a/src/components/mixed-media/mixed-studio.tsx b/src/components/mixed-media/mixed-studio.tsxindex ddc7527d..2826ff56 100644--- a/src/components/mixed-media/mixed-studio.tsx+++ b/src/components/mixed-media/mixed-studio.tsx@@ -9,6 +9,7 @@ import { EngineSwitch } from "@/components/studio/engine-switch";import { MediaThumb } from "@/components/studio/result-media";import { VideoTrimmer, type VideoTrimmerHandle } from "@/components/studio/video-trimmer";import { LookCard } from "@/components/shorts/preset-card";+import { useSubmitGuard } from "@/components/shorts/hooks";import { ClipBar, ClipDrop, costText, Field, Segmented, tabKeys } from "@/components/shorts/ui";import { clipDuration, useSourceClip } from "@/components/shorts/use-source-clip";import { uploadFile, useEngine } from "@/lib/api";@@ -332,33 +333,41 @@ function Editor({? (estimate.error as Error).message: null;- const makePreview = async () => {+ // One preview and one render per click: a second click while one is on its way does nothing,+ // and the server answers a repeated request id with what the first one started.+ const previewGuard = useSubmitGuard();+ const renderGuard = useSubmitGuard();+ const previewBusy = actions.preview.isPending || grabbing;+ const makePreview = () => {if (blocker || !body) return void toast(blocker ?? "Not ready yet", { id: "mm-blocker" });- let frameUrl: string | undefined;- if (engine === "cloud") {- setGrabbing(true);- try {- const blob = await trimmer.current?.grabFrame(range!.startTime);- if (!blob) return void toast.error("This browser can't read frames of this clip — try an MP4 (H.264), or generate the full video");- frameUrl = (await uploadFile(new File([blob], "frame.jpg", { type: "image/jpeg" }))).url;- } catch (e) {- return void toast.error((e as Error).message);- } finally {- setGrabbing(false);+ if (previewBusy) return;+ void previewGuard(JSON.stringify(body), async (requestId) => {+ let frameUrl: string | undefined;+ if (engine === "cloud") {+ setGrabbing(true);+ try {+ const blob = await trimmer.current?.grabFrame(range!.startTime);+ if (!blob) throw new Error("This browser can't read frames of this clip — try an MP4 (H.264), or generate the full video");+ frameUrl = (await uploadFile(new File([blob], "frame.jpg", { type: "image/jpeg" }))).url;+ } finally {+ setGrabbing(false);+ }}- }- actions.preview.mutate({ ...body, frameUrl }, { onSuccess: (g) => setPreviewId(g.id), onError: (e) => toast.error((e as Error).message) });+ const g = await actions.preview.mutateAsync({ ...body, frameUrl, requestId });+ setPreviewId(g.id);+ }).catch((e: Error) => toast.error(e.message));};const generate = () => {if (blocker || !body) return void toast(blocker ?? "Not ready yet", { id: "mm-blocker" });- actions.render.mutate(body, {- onSuccess: (r) => {+ if (actions.render.isPending) return;+ void renderGuard(JSON.stringify(body), (requestId) => actions.render.mutateAsync({ ...body, requestId }))+ .then((r) => {+ if (!r) return;setRenderId(r.final.id);toast("Rendering your video", { description: "It shows up in History too." });- },- onError: (e) => toast.error((e as Error).message),- });+ })+ .catch((e: Error) => toast.error(e.message));};return (@@ -520,13 +529,14 @@ function Editor({<buttontype="button"onClick={makePreview}- aria-disabled={!!blocker || actions.preview.isPending || grabbing}+ disabled={previewBusy}+ aria-disabled={!!blocker || previewBusy}className={cn("flex h-9 w-full items-center justify-center gap-2 rounded-full border text-[13px] font-medium",blocker ? "text-subtle-foreground" : "bg-background hover:bg-accent",)}>- {actions.preview.isPending || grabbing ? <Loader2 className="size-4 animate-spin" /> : <ImageIcon className="size-4" />}+ {previewBusy ? <Loader2 className="size-4 animate-spin" /> : <ImageIcon className="size-4" />}{preview ? "Generate another preview frame" : "Generate preview frame"}</button></div>@@ -548,6 +558,7 @@ function Editor({<buttontype="button"onClick={generate}+ disabled={actions.render.isPending}aria-disabled={!!blocker || actions.render.isPending}aria-describedby={blocker ? "mm-blocker" : undefined}className={cn(diff --git a/src/components/shorts/hooks.ts b/src/components/shorts/hooks.tsindex b09f76d9..0a554615 100644--- a/src/components/shorts/hooks.ts+++ b/src/components/shorts/hooks.ts@@ -1,7 +1,8 @@"use client";import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";-import { useDeferredValue } from "react";+import { nanoid } from "nanoid";+import { useCallback, useDeferredValue, useRef } from "react";import type { ShortsCustomPreset, ShortsRange, ShortsRatio, ShortsSession } from "@/lib/catalog/shorts";import type { Engine, Generation } from "@/lib/catalog/types";import { useGenerationEvents } from "@/lib/api";@@ -26,6 +27,8 @@ export interface ShortsBody {aspectRatio: ShortsRatio;language: string;modelId?: string;+ /** Client nonce: a repeat of it gets the first answer (see useSubmitGuard). */+ requestId?: string;}export interface ShortsEstimate {@@ -58,6 +61,32 @@ export interface ShortsSessionCard {const active = (g?: Generation) => !!g && (g.status === "queued" || g.status === "running");+/**+ * One paid submit at a time. A second click while the first is on its way does nothing, and the+ * request carries a nonce that stays the same for the same `key` until a submit succeeds, so the+ * server answers a repeat (a lost response, a retry) with the first result instead of a second run.+ * `hold` keeps it busy after success (the page is navigating away).+ */+export function useSubmitGuard() {+ const busy = useRef(false);+ const last = useRef<{ key: string; id: string } | null>(null);+ return useCallback(async <T>(key: string, fn: (requestId: string) => Promise<T>, opts: { hold?: boolean } = {}): Promise<T | undefined> => {+ if (busy.current) return undefined;+ busy.current = true;+ const id = last.current?.key === key ? last.current.id : nanoid(16);+ last.current = { key, id };+ let ok = false;+ try {+ const out = await fn(id);+ ok = true;+ last.current = null;+ return out;+ } finally {+ if (!ok || !opts.hold) busy.current = false;+ }+ }, []);+}+/** Price and shape of a session before it starts (debounced by React's deferred value). */export function useShortsEstimate(body: ShortsBody | null) {const key = useDeferredValue(body ? JSON.stringify(body) : null);@@ -122,7 +151,7 @@ export function useShortsActions(id?: string) {onSuccess: () => void qc.invalidateQueries({ queryKey: ["shorts", "sessions"] }),}),regenerate: useMutation({- mutationFn: (index: number) => send<ShortsSessionView>(`/api/shorts/sessions/${id}/segments/${index}`, "POST"),+ mutationFn: (v: { index: number; requestId?: string }) => send<ShortsSessionView>(`/api/shorts/sessions/${id}/segments/${v.index}`, "POST", { requestId: v.requestId }),onSuccess: put,}),primary: useMutation({@@ -130,7 +159,7 @@ export function useShortsActions(id?: string) {onSuccess: put,}),stitch: useMutation({- mutationFn: () => send<ShortsSessionView>(`/api/shorts/sessions/${id}/stitch`, "POST"),+ mutationFn: (v: { requestId?: string } = {}) => send<ShortsSessionView>(`/api/shorts/sessions/${id}/stitch`, "POST", { requestId: v.requestId }),onSuccess: put,}),rename: useMutation({diff --git a/src/components/shorts/session-view.tsx b/src/components/shorts/session-view.tsxindex b01b67ea..adde8515 100644--- a/src/components/shorts/session-view.tsx+++ b/src/components/shorts/session-view.tsx@@ -26,7 +26,7 @@ import type { Generation } from "@/lib/catalog/types";import { formatCost, ratioValue, timeAgo } from "@/lib/format";import { downloadHref, downloadName } from "@/lib/library";import { cn } from "@/lib/utils";-import { useShortsActions, useShortsSession, type ShortsSessionView as View } from "./hooks";+import { useShortsActions, useShortsSession, useSubmitGuard, type ShortsSessionView as View } from "./hooks";import { Steps } from "./ui";const STEPS = ["Choose preset", "Upload video", "Download"];@@ -112,11 +112,21 @@ function Session({ s }: { s: View }) {const overall = (segStates.reduce((n, x) => n + (x.status === "done" ? 1 : x.progress), 0) + (finalState?.status === "done" ? 1 : (finalState?.progress ?? 0))) / (segStates.length + 1);const parts = s.segments.map((g) => g.primary).filter((id) => videoOf(gens[id]));- const stitchAgain = () =>- actions.stitch.mutate(undefined, {- onSuccess: () => toast("Stitching your short"),- onError: (e) => toast.error((e as Error).message),- });+ // One stitch and one new take per click (the server also answers a repeated request id with the first result).+ const stitchGuard = useSubmitGuard();+ const takeGuard = useSubmitGuard();+ const stitchAgain = () => {+ if (!canStitch || actions.stitch.isPending) return;+ void stitchGuard(`stitch:${s.segments.map((g) => g.primary).join(",")}`, (requestId) => actions.stitch.mutateAsync({ requestId }))+ .then((v) => v && toast("Stitching your short"))+ .catch((e: Error) => toast.error(e.message));+ };+ const regenerate = (i: number) => {+ if (actions.regenerate.isPending) return;+ void takeGuard(`take:${i}:${s.segments[i].takes.length}`, (requestId) => actions.regenerate.mutateAsync({ index: i, requestId }))+ .then((v) => v && toast(`New take of segment ${i + 1} on the way`))+ .catch((e: Error) => toast.error(e.message));+ };return (<Frame@@ -176,6 +186,7 @@ function Session({ s }: { s: View }) {<buttontype="button"onClick={stitchAgain}+ disabled={actions.stitch.isPending}aria-disabled={!canStitch || actions.stitch.isPending}className={cn("inline-flex h-9 items-center gap-1.5 rounded-full border px-4 text-[13px] font-medium",@@ -229,13 +240,9 @@ function Session({ s }: { s: View }) {cost={s.regenerateUsd}demo={Object.values(gens).some((g) => g.provider === "mock")}onOpen={setOpen}- onRegenerate={() =>- actions.regenerate.mutate(i, {- onSuccess: () => toast(`New take of segment ${i + 1} on the way`),- onError: (e) => toast.error((e as Error).message),- })- }- regenerating={actions.regenerate.isPending && actions.regenerate.variables === i}+ onRegenerate={() => regenerate(i)}+ regenerating={actions.regenerate.isPending && actions.regenerate.variables?.index === i}+ busy={actions.regenerate.isPending}onPrimary={(gid) => actions.primary.mutate({ index: i, generationId: gid }, { onError: (e) => toast.error((e as Error).message) })}/>))}@@ -283,6 +290,7 @@ function SegmentCard({onOpen,onRegenerate,regenerating,+ busy,onPrimary,}: {seg: ShortsSessionSegment;@@ -295,6 +303,8 @@ function SegmentCard({onOpen: (g: Generation) => void;onRegenerate: () => void;regenerating: boolean;+ /** A new take (of any segment) is on its way. */+ busy: boolean;onPrimary: (id: string) => void;}) {const primary = gens[seg.primary];@@ -370,7 +380,7 @@ function SegmentCard({<buttontype="button"onClick={onRegenerate}- disabled={regenerating}+ disabled={busy}className="inline-flex h-8 items-center gap-1.5 rounded-full border bg-background px-3 text-[12px] font-medium hover:bg-accent disabled:opacity-60">{regenerating ? <Loader2 className="size-3.5 animate-spin" /> : <RotateCcw className="size-3.5" />}diff --git a/src/components/shorts/shorts-studio.tsx b/src/components/shorts/shorts-studio.tsxindex a6dcdcd6..f48e1751 100644--- a/src/components/shorts/shorts-studio.tsx+++ b/src/components/shorts/shorts-studio.tsx@@ -25,7 +25,7 @@ import type { Engine } from "@/lib/catalog/types";import type { TrimRange } from "@/lib/trim-range";import { cn } from "@/lib/utils";import { CustomPresetDialog } from "./custom-preset-dialog";-import { useShortsActions, useShortsEstimate, useShortsPresets, type ShortsBody } from "./hooks";+import { useShortsActions, useShortsEstimate, useShortsPresets, useSubmitGuard, type ShortsBody } from "./hooks";import { CreateCard, CustomCard, LookCard } from "./preset-card";import { ShortsHistory } from "./history";import { ClipBar, ClipDrop, costText, Field, Segmented, Steps, tabKeys } from "./ui";@@ -338,12 +338,21 @@ function SetupPanel({? (estimate.error as Error).message: null;+ const guard = useSubmitGuard();+ const [leaving, setLeaving] = useState(false);+ const busy = actions.create.isPending || leaving;const generate = () => {if (blocker) return void toast(blocker, { id: "shorts-blocker" });- actions.create.mutate(estimateBody!, {- onSuccess: (s) => router.push(`/shorts/${s.id}`),- onError: (e) => toast.error((e as Error).message),- });+ if (busy || !estimateBody) return;+ // One session per click: a second click while this one is on its way does nothing (and the+ // server answers a repeated request id with the session it already started).+ void guard(JSON.stringify(estimateBody), (requestId) => actions.create.mutateAsync({ ...estimateBody, requestId }), { hold: true })+ .then((s) => {+ if (!s) return;+ setLeaving(true);+ router.push(`/shorts/${s.id}`);+ })+ .catch((e: Error) => toast.error(e.message));};return (@@ -479,15 +488,16 @@ function SetupPanel({<buttontype="button"onClick={generate}- aria-disabled={!!blocker || actions.create.isPending}+ disabled={busy}+ aria-disabled={!!blocker || busy}aria-describedby={blocker ? "shorts-blocker" : undefined}className={cn("flex h-11 w-full items-center justify-center gap-2 rounded-full text-[14px] font-medium transition-colors",blocker ? "bg-muted text-subtle-foreground" : "bg-primary text-primary-foreground hover:bg-primary/90",)}>- {actions.create.isPending ? <Loader2 className="size-4 animate-spin" /> : <Sparkles className="size-4" />}- Generate short+ {busy ? <Loader2 className="size-4 animate-spin" /> : <Sparkles className="size-4" />}+ {busy ? "Starting your short…" : "Generate short"}<ArrowRight className="size-4" /></button>{blocker && (diff --git a/src/server/shorts-schemas.ts b/src/server/shorts-schemas.tsindex b140bde1..5356b747 100644--- a/src/server/shorts-schemas.ts+++ b/src/server/shorts-schemas.ts@@ -8,6 +8,8 @@ import { ShortsError } from "./shorts";const fileUrl = z.string().startsWith("/api/files/").max(500);const seconds = z.number().finite().min(0).max(3600);+/** A client nonce for one submit: a repeated id gets the first answer instead of a second paid run (see once()). */+const requestId = z.string().trim().min(8).max(64).optional();const source = z.object({url: fileUrl,@@ -24,6 +26,7 @@ export const ShortsBodySchema = z.object({aspectRatio: z.enum(["9:16", "16:9"]).default("9:16"),language: z.string().max(40).default("auto"),modelId: z.string().max(80).optional(),+ requestId,});/** The estimate is asked for before the upload finishes: any URL stands in. */@@ -49,8 +52,12 @@ export const MixedBodySchema = z.object({anchor: fileUrl.optional(),frameUrl: fileUrl.optional(),seed: z.number().int().min(0).max(2 ** 48).optional(),+ requestId,});+/** Bodies of the session actions that only carry a nonce (stitch again, regenerate a segment). */+export const NonceSchema = z.object({ requestId }).default({});+export const MixedEstimateSchema = MixedBodySchema.extend({ source: source.extend({ url: z.string().max(500).default("/api/files/placeholder.mp4") }) });/** A user-facing error answer: ShortsError keeps its status; anything else from the planner is a 422. */@@ -66,6 +73,45 @@ export async function body<S extends z.ZodType>(request: Request, schema: S, mesreturn parsed.data;}+/** Parse an optional JSON body (none, or an empty one, is `{}`). */+export async function optionalBody<S extends z.ZodType>(request: Request, schema: S): Promise<z.infer<S>> {+ const text = await request.text().catch(() => "");+ let raw: unknown = {};+ try {+ raw = text.trim() ? JSON.parse(text) : {};+ } catch {+ throw new ShortsError("That request body isn't JSON", 400);+ }+ const parsed = schema.safeParse(raw);+ if (!parsed.success) throw new ShortsError("Bad request", 400);+ return parsed.data;+}++declare global {+ var __fuobeShortsRequests: Map<string, { at: number; result: Promise<unknown> }> | undefined;+}+const requests = () => (globalThis.__fuobeShortsRequests ??= new Map());+const REQUEST_TTL = 10 * 60_000;++/**+ * Run `fn` once per client request id: a repeat of the same id (a double click that got through, a+ * retried POST) gets the first call's answer — the same session or render — instead of starting a+ * second paid run. A call that failed can be tried again with the same id. Without an id, it just runs.+ */+export function once<T>(scope: string, id: string | undefined, fn: () => Promise<T> | T): Promise<T> {+ if (!id) return Promise.resolve().then(fn);+ const map = requests();+ const now = Date.now();+ for (const [k, v] of map) if (now - v.at > REQUEST_TTL) map.delete(k);+ const key = `${scope}:${id}`;+ const hit = map.get(key);+ if (hit) return hit.result as Promise<T>;+ const result = Promise.resolve().then(fn);+ map.set(key, { at: now, result });+ result.catch(() => map.delete(key));+ return result;+}+/** Run a route body, answering errors as `{ error }`. */export async function handle(fn: () => Promise<Response> | Response): Promise<Response> {try {diff --git a/src/server/shorts.ts b/src/server/shorts.tsindex 0e757b1f..b67141aa 100644--- a/src/server/shorts.ts+++ b/src/server/shorts.ts@@ -12,6 +12,7 @@ import {planTake,rangeProblem,sessionPlanInput,+ stitchCurrent,SHORTS,SHORTS_MODELS,type PlanStep,@@ -489,6 +490,11 @@ export function stitchSession(id: string): ShortsSessionView {if (g.status !== "succeeded" || !url) throw new ShortsError(`Segment ${i + 1} didn't render — regenerate it first`, 409);return { url };});+ // A second "Stitch again" while the same takes are still being stitched would pay for the same video twice.+ const last = s.stitches[s.stitches.length - 1];+ if (last && stitchCurrent(s) && [...last.ids, last.final].some((gid) => ["queued", "running"].includes(getGeneration(gid)?.status ?? ""))) {+ throw new ShortsError("These takes are already being stitched", 409);+ }const plan = planStitch(sessionPlanInput(s), clips, `-s${s.stitches.length}`);const now = Date.now();let stitch: ShortsStitch;diff --git a/tests/shorts-api.test.ts b/tests/shorts-api.test.tsindex 9491aae2..1275cfba 100644--- a/tests/shorts-api.test.ts+++ b/tests/shorts-api.test.ts@@ -165,6 +165,40 @@ describe("Shorts sessions", () => {expect(await settle(last.final)).toMatchObject({ status: "succeeded", op: "mux" });});+ it("starts one session per request id, and one stitch per set of takes", async () => {+ const before = shorts.listSessions().length;+ const req = () => sessionsRoute.POST(json("POST", body({ requestId: "dbl-click-0001" })));+ // A double click that got through: both requests arrive before either is answered.+ const [a, b] = await Promise.all([req(), req()]);+ const [sa, sb] = [await a.json(), await b.json()];+ expect(sa.id).toBe(sb.id);+ expect(shorts.listSessions().length).toBe(before + 1);+ // A different id is a new session.+ const c = await (await sessionsRoute.POST(json("POST", body({ requestId: "dbl-click-0002" })))).json();+ expect(c.id).not.toBe(sa.id);+ // Stitch again with the same takes while that stitch is still running: refused, not paid twice.+ await settle(sa.stitches[0].final);+ const fresh = shorts.regenerateSegment(sa.id, 0).segments[0].takes.at(-1)!.look;+ await settle(fresh);+ shorts.makePrimary(sa.id, 0, fresh);+ const st = (id: string) => stitchRoute.POST(json("POST", { requestId: id }), params({ id: sa.id }));+ const [s1, s2] = await Promise.all([st("stitch-nonce-1"), st("stitch-nonce-1")]);+ expect((await s1.json()).stitches).toHaveLength(2);+ expect((await s2.json()).stitches).toHaveLength(2);+ const again = await st("stitch-nonce-2");+ expect(again.status).toBe(409);+ expect((await again.json()).error).toBe("These takes are already being stitched");+ // Regenerate with the same id twice: one new take.+ const r = (rid: string) => regenRoute.POST(json("POST", { requestId: rid }), params({ id: sa.id, index: "1" }));+ const [r1, r2] = await Promise.all([r("take-nonce-1"), r("take-nonce-1")]);+ expect((await r1.json()).segments[1].takes).toHaveLength(2);+ expect((await r2.json()).segments[1].takes).toHaveLength(2);+ const view = shorts.getSession(sa.id);+ await Promise.all([settle(view.stitches[1].final), settle(view.segments[1].takes[1].look)]);+ shorts.deleteSession(sa.id);+ shorts.deleteSession(c.id);+ });+it("won't stitch while a segment is still rendering", async () => {const s = shorts.regenerateSegment(sessionId, 0);const take = s.segments[0].takes.at(-1)!.look;@@ -280,6 +314,14 @@ describe("Mixed Media renders", () => {expect(await settle(final.id)).toMatchObject({ status: "succeeded", feature: "mixed-media" });});+ it("starts one render per request id", async () => {+ const req = () => mixedRoute.POST(json("POST", mm({ requestId: "mm-render-0001" })));+ const [a, b] = await Promise.all([req(), req()]);+ const [ra, rb] = [await a.json(), await b.json()];+ expect(ra.final.id).toBe(rb.final.id);+ await settle(ra.final.id);+ });+it("asks for a grabbed frame before a cloud preview", async () => {const res = await mixedPreviewRoute.POST(json("POST", mm({ engine: "cloud" })));expect(res.status).toBe(400);