Open source CapCut alternative.
TypeScript
feat(site): generate Cut images with nano banana pro, aspect and resolution controls
David Le67f7811c5c1e
diff --git a/site/src/cut/components/ImageGenPanel.tsx b/site/src/cut/components/ImageGenPanel.tsxindex 5eb65a2a..2cac20b4 100644--- a/site/src/cut/components/ImageGenPanel.tsx+++ b/site/src/cut/components/ImageGenPanel.tsx@@ -1,19 +1,26 @@"use client";import { useEffect, useMemo, useRef } from "react";-import { ChevronDown, Loader2, Maximize2, Sparkles, Trash2 } from "lucide-react";-import { Button } from "@/components/ui/button";import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuRadioGroup,- DropdownMenuRadioItem,- DropdownMenuTrigger,-} from "@/components/ui/dropdown-menu";+ ChevronDown,+ Loader2,+ Maximize2,+ Proportions,+ Scaling,+ Sparkles,+ Trash2,+ type LucideIcon,+} from "lucide-react";+import { Button } from "@/components/ui/button";import { clearAssetDrag, setAssetDragData } from "@/cut/lib/assetDrag";import { collectRefs, useRefCandidates, useAssetDrop } from "@/cut/lib/assetRef";import { signInUrl, useGenerate, useSignedIn } from "@/cut/lib/generate";-import { IMAGE_ASPECT_LABEL, useImageGen, type ImageAspect } from "@/cut/lib/imageGen";+import {+ IMAGE_RESOLUTION_LABEL,+ useImageGen,+ type ImageAspect,+ type ImageResolution,+} from "@/cut/lib/imageGen";import { useLightbox } from "@/cut/lib/lightbox";import { useEditor } from "@/cut/lib/store";import type { MediaAsset } from "@/cut/lib/types";@@ -28,8 +35,16 @@ import { CopyRefButton, MentionTextarea, RefChips, RefHandlePill } from "./Asset// References ride along as input images: drag any image or video in (stock// tile, media card, library clip, timeline clip) or mention it by @name.+// A short orientation word keeps the Size pill narrow enough to share a row with+// Resolution in this column; the icon carries the "aspect" meaning.+const ASPECT_SHORT: Record<ImageAspect, string> = {+ "16:9": "Landscape",+ "9:16": "Portrait",+ "1:1": "Square",+};+export function ImageGenPanel({ projectId }: { projectId: string }) {- const { prompt, aspect, refs } = useImageGen();+ const { prompt, aspect, resolution, refs } = useImageGen();const signedIn = useSignedIn();const candidates = useRefCandidates();const job = useGenerate((s) =>@@ -57,7 +72,7 @@ export function ImageGenPanel({ projectId }: { projectId: string }) {const go = () => {const { text, refs: all } = collectRefs(prompt.trim(), refs, candidates, { dropAudio: true });if (!text) return;- void useGenerate.getState().generateImage(projectId, text, { refs: all, aspect });+ void useGenerate.getState().generateImage(projectId, text, { refs: all, aspect, resolution });};return (@@ -93,27 +108,30 @@ export function ImageGenPanel({ projectId }: { projectId: string }) {/></div>- <DropdownMenu>- <DropdownMenuTrigger className="flex w-full shrink-0 items-center justify-between rounded-lg border border-input px-2.5 py-2 text-[12.5px] outline-none hover:border-ring focus-visible:border-ring">- <span className="text-muted-foreground">Size</span>- <span className="flex items-center gap-1 font-medium">- {IMAGE_ASPECT_LABEL[aspect]}- <ChevronDown className="size-3.5 text-muted-foreground" />- </span>- </DropdownMenuTrigger>- <DropdownMenuContent align="start" className="min-w-[190px]">- <DropdownMenuRadioGroup- value={aspect}- onValueChange={(v) => useImageGen.getState().setAspect(v as ImageAspect)}- >- {(Object.keys(IMAGE_ASPECT_LABEL) as ImageAspect[]).map((a) => (- <DropdownMenuRadioItem key={a} value={a} className="whitespace-nowrap">- {IMAGE_ASPECT_LABEL[a]}- </DropdownMenuRadioItem>- ))}- </DropdownMenuRadioGroup>- </DropdownMenuContent>- </DropdownMenu>+ {/* Size (aspect) and resolution, both as compact pills on one row —+ matching the audio language picker's style. */}+ <div className="flex shrink-0 items-center gap-2">+ <PillSelect+ icon={Proportions}+ title="Image size"+ value={aspect}+ options={(Object.keys(ASPECT_SHORT) as ImageAspect[]).map((a) => ({+ value: a,+ label: ASPECT_SHORT[a],+ }))}+ onChange={(v) => useImageGen.getState().setAspect(v)}+ />+ <PillSelect+ icon={Scaling}+ title="Resolution"+ value={resolution}+ options={(Object.keys(IMAGE_RESOLUTION_LABEL) as ImageResolution[]).map((r) => ({+ value: r,+ label: IMAGE_RESOLUTION_LABEL[r],+ }))}+ onChange={(v) => useImageGen.getState().setResolution(v)}+ />+ </div><ButtonclassName="w-full shrink-0"@@ -176,6 +194,46 @@ export function ImageGenPanel({ projectId }: { projectId: string }) {);}+/** A compact rounded pill wrapping a native select — an icon, the value, and a+ * chevron. Mirrors the audio language picker so the generate controls read as+ * one family. Native select keeps the option list keyboard- and OS-friendly. */+function PillSelect<T extends string>({+ icon: Icon,+ title,+ value,+ options,+ onChange,+}: {+ icon: LucideIcon;+ title: string;+ value: T;+ options: { value: T; label: string }[];+ onChange: (value: T) => void;+}) {+ return (+ <label+ className="relative inline-flex items-center gap-1.5 rounded-full border border-input py-1 pr-2 pl-2.5 text-muted-foreground transition-colors focus-within:border-ring"+ title={title}+ >+ <Icon className="size-3.5 shrink-0" />+ <span className="relative inline-flex min-w-0 items-center">+ <select+ className="max-w-full appearance-none truncate bg-transparent pr-5 text-[12.5px] text-foreground outline-none"+ value={value}+ onChange={(e) => onChange(e.target.value as T)}+ >+ {options.map((o) => (+ <option key={o.value} value={o.value}>+ {o.label}+ </option>+ ))}+ </select>+ <ChevronDown className="pointer-events-none absolute top-1/2 right-0 size-3.5 -translate-y-1/2" />+ </span>+ </label>+ );+}+/** A generated image, shown big: reference it in a prompt by its @handle, drag* it onto the timeline or into chat, click to reload its prompt, copy its* @reference, or delete it. Its name surfaces on hover so the grid stays clean. */diff --git a/site/src/cut/lib/generate.ts b/site/src/cut/lib/generate.tsindex e374959a..8d785e96 100644--- a/site/src/cut/lib/generate.ts+++ b/site/src/cut/lib/generate.ts@@ -6,6 +6,7 @@ import { apiFetch, apiJson } from "./api";import type { AssetRef } from "./assetRef";import { enrichAsset, importFileToProject } from "./media";import { refsToInlineImages } from "./refMedia";+import { useImageGen } from "./imageGen";import { useEditor } from "./store";import { mediaUrl, type MediaAsset } from "./types";@@ -45,7 +46,11 @@ interface GenerateState {generateImage: (projectId: string,prompt: string,- opts?: { refs?: AssetRef[]; aspect?: "16:9" | "9:16" | "1:1" }+ opts?: {+ refs?: AssetRef[];+ aspect?: "16:9" | "9:16" | "1:1";+ resolution?: "1K" | "2K" | "4K";+ }) => Promise<GenerateJob>;generateVideo: (projectId: string,@@ -233,14 +238,14 @@ export const useGenerate = create<GenerateState>((set, get) => {return (async () => {try {const aspect = opts?.aspect ?? useEditor.getState().aspect;- const frame =- aspect === "16:9" ? "16:9 widescreen" : aspect === "1:1" ? "1:1 square" : "9:16 vertical";+ const resolution = opts?.resolution ?? useImageGen.getState().resolution;const images = await refsToInlineImages(opts?.refs ?? []);const res = await hostedPost("/api/inference/assets", {kind: "image",- // The image route takes no aspect parameter; steer it in the prompt.- prompt: `${prompt}\n\nCompose the image in a ${frame} frame.`,+ prompt,...(images.length > 0 ? { inputs: { images } } : {}),+ // The image model takes a real frame + detail via imageConfig; no prompt steering.+ parameters: { aspectRatio: aspect, imageSize: resolution },});if (!res.ok) throw new Error(await readError(res, "Image generation failed."));const gen = (await res.json()) as GenerationResponse;diff --git a/site/src/cut/lib/imageGen.ts b/site/src/cut/lib/imageGen.tsindex 37498503..2668891e 100644--- a/site/src/cut/lib/imageGen.ts+++ b/site/src/cut/lib/imageGen.ts@@ -16,10 +16,22 @@ export const IMAGE_ASPECT_LABEL: Record<ImageAspect, string> = {"1:1": "Square (1:1)",};+/** Output detail for the next generation. The image model maps these to real+ * pixel sizes (1K ≈ 1MP, 2K ≈ 4MP, 4K ≈ 16MP). */+export type ImageResolution = "1K" | "2K" | "4K";++export const IMAGE_RESOLUTION_LABEL: Record<ImageResolution, string> = {+ "1K": "1K",+ "2K": "2K",+ "4K": "4K",+};+interface ImageGenState {prompt: string;/** The shape the next generation is composed in. */aspect: ImageAspect;+ /** The output detail the next generation renders at. */+ resolution: ImageResolution;/** Visual references attached to the next generation (dragged in or picked* via @name mentions resolved on send). */refs: AssetRef[];@@ -28,6 +40,7 @@ interface ImageGenState {openWith: (prompt: string) => void;setPrompt: (prompt: string) => void;setAspect: (aspect: ImageAspect) => void;+ setResolution: (resolution: ImageResolution) => void;addRef: (ref: AssetRef) => void;removeRef: (ref: AssetRef) => void;}@@ -35,10 +48,12 @@ interface ImageGenState {export const useImageGen = create<ImageGenState>((set) => ({prompt: "",aspect: "9:16",+ resolution: "2K",refs: [],openWith: (prompt) => set({ prompt, refs: [] }),setPrompt: (prompt) => set({ prompt }),setAspect: (aspect) => set({ aspect }),+ setResolution: (resolution) => set({ resolution }),addRef: (ref) => set((s) => ({ refs: addRefOnce(s.refs, ref) })),removeRef: (ref) => set((s) => ({ refs: s.refs.filter((r) => !sameRef(r, ref)) })),}));diff --git a/site/src/lib/credits/provider-pricing.ts b/site/src/lib/credits/provider-pricing.tsindex 1c809151..ff205eab 100644--- a/site/src/lib/credits/provider-pricing.ts+++ b/site/src/lib/credits/provider-pricing.ts@@ -278,6 +278,11 @@ const geminiModelPricing: Record<GeminiModel, ProviderCreditPricing> = {// Generative image editing/generation ("nano banana") bills per output image:// ~1290 output tokens at $30/1M ≈ $0.039 each.[geminiModels.flashImage]: { generationCostMicros: usdWithMargin("0.039") },+ // "Nano banana pro" bills per output image by resolution: $0.134 at 1K/2K, $0.24 at+ // 4K. Our per-image price can't vary by resolution, so this charges the 1K/2K rate+ // (the default is 2K); 4K currently under-bills. Make billing resolution-aware before+ // relying on heavy 4K use.+ [geminiModels.proImage]: { generationCostMicros: usdWithMargin("0.134") },};// Generative text/image-to-video (Veo). Model ids are hardcoded (gemini-models.ts), so each is priceddiff --git a/site/src/lib/inference/adapters/gemini-image.ts b/site/src/lib/inference/adapters/gemini-image.tsindex 432fe980..3ea8729d 100644--- a/site/src/lib/inference/adapters/gemini-image.ts+++ b/site/src/lib/inference/adapters/gemini-image.ts@@ -101,10 +101,14 @@ export function createGeminiImageAssetProvider();}+ const imageConfig = imageConfigFromParameters(toJsonObject(request.parameters ?? {}));const params: GenerateContentParameters = {model,contents: [{ role: "user", parts }] as unknown as GenerateContentParameters["contents"],- config: { responseModalities: [Modality.IMAGE, Modality.TEXT] },+ config: {+ responseModalities: [Modality.IMAGE, Modality.TEXT],+ ...(imageConfig ? { imageConfig } : {}),+ },};const client = clientFactory(clientConfig.options);@@ -158,6 +162,29 @@ export function createGeminiImageAssetProvider(};}+// Frame + detail the caller passes through request.parameters. aspectRatio and imageSize+// map to the model's imageConfig; imageSize is whitelisted so a stray value never earns a+// Vertex 400. Returns undefined when neither is set, so text-only calls send no config.+const IMAGE_SIZES = new Set(["1K", "2K", "4K"]);++function imageConfigFromParameters(+ parameters: JsonObject | undefined,+): { aspectRatio?: string; imageSize?: string } | undefined {+ if (!parameters) {+ return undefined;+ }+ const config: { aspectRatio?: string; imageSize?: string } = {};+ const aspectRatio = stringValue(parameters.aspectRatio);+ if (aspectRatio) {+ config.aspectRatio = aspectRatio;+ }+ const imageSize = stringValue(parameters.imageSize);+ if (imageSize && IMAGE_SIZES.has(imageSize)) {+ config.imageSize = imageSize;+ }+ return config.aspectRatio || config.imageSize ? config : undefined;+}+type InlineImage = { data: string; mimeType: string };// The image tools send inputs.images = [{ data, mimeType }]. Parse exactly that shape.diff --git a/site/src/lib/inference/gemini-models.ts b/site/src/lib/inference/gemini-models.tsindex f1024648..ecc2437a 100644--- a/site/src/lib/inference/gemini-models.ts+++ b/site/src/lib/inference/gemini-models.ts@@ -13,6 +13,10 @@ export const geminiModels = {// Generative image editing/generation ("nano banana"). Bump here when adopting a// newer image model; the backend also honors a GEMINI_IMAGE_MODEL override.flashImage: "gemini-2.5-flash-image",+ // "Nano banana pro": higher-fidelity image editing/generation that takes a real+ // aspectRatio + imageSize (1K/2K/4K) via imageConfig. Gemini 3 preview models are+ // served only on Vertex's global endpoint, which our client already targets.+ proImage: "gemini-3-pro-image-preview",} as const;export type GeminiModel = (typeof geminiModels)[keyof typeof geminiModels];@@ -64,5 +68,5 @@ export const geminiModelRoles = {// Vision grounding: a cheap structured pick over already-parsed elements.visionGrounding: geminiModels.flashLite,// Generative image editing and generation.- imageGeneration: geminiModels.flashImage,+ imageGeneration: geminiModels.proImage,} as const;