The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
feat(create): Swap Character als Cloud-Unterkategorie (Port des Web-Stands C52)
purpledf853a5f8da2
diff --git a/e2e/swap-character.spec.ts b/e2e/swap-character.spec.tsnew file mode 100644index 00000000..9db570fc--- /dev/null+++ b/e2e/swap-character.spec.ts@@ -0,0 +1,106 @@+import { test, expect, type Page } from '@playwright/test'+import { tauriMockInit, DEFAULT_ASSISTANT_REPLY, DEFAULT_MODEL_NAME } from './support/tauri-mock'+import { routeCloud, seedOnboardingDone, signInViaGate, cloudSwitch } from './support/cloud-mock'++/**+ * Swap Character (07.11.2026, port of the web's C52) in the real app, Tauri+ * stubbed, cloud mocked: the pill, the panel in the web's order, people up to+ * four, Create only with every input and the consent, its price on the button.+ * Nothing is booked: the spec never presses Create.+ *+ * Media come from LU_SWAP_MEDIA_DIR (clip.mp4, face1.png, face2.png) when it is+ * set; without it the spec uses a 1x1 picture and a stub clip, which tests the+ * same panel and only looks plainer. LU_SWAP_SHOTS_DIR, when set, receives+ * screenshots of the tab in the dark and the light theme.+ */++const PNG_1PX = Buffer.from(+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==',+ 'base64',+)++/** The three swap models as a server that knows them lists them. */+const SWAP_CATALOG = [+ ['openjutsu-character-swap', 'OpenJutsu Character Swap'],+ ['wan-2.2-animate-replace', 'Wan 2.2 Animate Replace'],+ ['scail-2', 'SCAIL 2'],+].map(([id, label]) => ({ id, label, kind: 'video', ops: ['studio'], quote_required: true, t2v: false, i2v: false }))++async function media(name: string, mimeType: string) {+ const dir = process.env.LU_SWAP_MEDIA_DIR+ if (dir) {+ const { readFileSync } = await import('node:fs')+ return { name, mimeType, buffer: readFileSync(`${dir}/${name}`) }+ }+ return { name, mimeType, buffer: mimeType.startsWith('image') ? PNG_1PX : Buffer.from('stub') }+}++async function openSwap(page: Page) {+ await page.setViewportSize({ width: 1296, height: 900 })+ await page.addInitScript(tauriMockInit, { assistantReply: DEFAULT_ASSISTANT_REPLY, modelName: DEFAULT_MODEL_NAME })+ await seedOnboardingDone(page)+ await routeCloud(page, { license: 'active', access: true, mediaLive: true, extraCatalogModels: SWAP_CATALOG })+ await page.goto('/')+ await expect(cloudSwitch(page)).toBeVisible({ timeout: 20_000 })+ await signInViaGate(page)+ await expect(cloudSwitch(page)).toBeChecked({ timeout: 20_000 })+ await page.getByRole('button', { name: /^Create$/ }).click()+ await page.getByRole('radio', { name: 'Swap Character', exact: true }).click()+ await expect(page.locator('[data-swap-controls]')).toBeVisible({ timeout: 15_000 })+}++async function shoot(page: Page, name: string) {+ const dir = process.env.LU_SWAP_SHOTS_DIR+ if (!dir) return+ for (const theme of ['dark', 'light'] as const) {+ await page.evaluate((t) => {+ document.documentElement.classList.toggle('dark', t === 'dark')+ document.documentElement.classList.toggle('light', t === 'light')+ }, theme)+ await page.waitForTimeout(250)+ await page.screenshot({ path: `${dir}/desktop-app-${name}-${theme}.png` })+ }+ await page.evaluate(() => {+ document.documentElement.classList.add('dark')+ document.documentElement.classList.remove('light')+ })+}++test('Swap Character: panel, people, consent and price before Create', async ({ page }) => {+ await openSwap(page)+ const panel = page.locator('[data-swap-controls]')+ const create = page.getByRole('button', { name: /^Create/ }).last()++ await expect(panel.locator('[data-swap-tips]')).toContainText('People only: animals are refused')+ await expect(page.locator('[data-swap-stage]')).toBeVisible()+ await expect(create).toBeDisabled()+ await shoot(page, 'swap-empty')++ // The original video, then one photo: still waits for the consent.+ await panel.locator('input[type=file][accept^="video"]').setInputFiles(await media('clip.mp4', 'video/mp4'))+ await page.locator('[data-swap-photo-input="1"]').setInputFiles(await media('face1.png', 'image/png'))+ await expect(page.getByRole('button', { name: 'Change photo of person 1' })).toBeVisible()+ await expect(create).toBeDisabled()++ // A second person without a photo keeps Create off.+ await page.getByRole('button', { name: /Add person/ }).click()+ await expect(page.getByRole('button', { name: /Add person/ })).toHaveText('+ Add person (2/4)')+ await page.getByRole('checkbox').check()+ await expect(create).toBeDisabled()+ await page.locator('[data-swap-photo-input="2"]').setInputFiles(await media('face2.png', 'image/png'))+ await page.getByRole('textbox', { name: 'Who person 1 replaces' }).fill('the woman on the left')+ await page.getByRole('textbox', { name: 'Who person 2 replaces' }).fill('the man in black')++ // Everything in: Create is armed and names its price.+ await expect(create).toBeEnabled({ timeout: 15_000 })+ await expect(page.locator('[data-clip-price]')).toContainText('credits')+ await shoot(page, 'swap-ready')++ // Up to four people, no more.+ await page.getByRole('button', { name: /Add person/ }).click()+ await page.getByRole('button', { name: /Add person/ }).click()+ await expect(page.getByRole('button', { name: /Add person/ })).toHaveText('+ Add person (4/4)')+ await expect(page.getByRole('button', { name: /Add person/ })).toBeDisabled()+ await expect(create).toBeDisabled()+ await shoot(page, 'swap-four-people')+})diff --git a/src/api/cloud/jobs.ts b/src/api/cloud/jobs.tsindex df1c6d21..9cf8e881 100644--- a/src/api/cloud/jobs.ts+++ b/src/api/cloud/jobs.ts@@ -66,6 +66,12 @@ export interface CloudJobParams {trigger_word?: string // character trainingname?: string // character shelf labelloras?: { id: string; scale?: number }[] // OWN user_loras rows — server resolves to URLs+ // Swap Character (07.11.2026). The server cuts the video to the first+ // clip_seconds seconds (1 to 120), runs and bills exactly that. The models+ // of SWAP_CONSENT_MODELS (lib/render/swap.ts) need swap_consent true: the+ // customer confirmed the rights and the consent of the people shown.+ clip_seconds?: number+ swap_consent?: boolean}export interface CloudJobSubmit {diff --git a/src/components/cloud/CloudTeaserModal.tsx b/src/components/cloud/CloudTeaserModal.tsxindex d23547e9..b6b27010 100644--- a/src/components/cloud/CloudTeaserModal.tsx+++ b/src/components/cloud/CloudTeaserModal.tsx@@ -57,6 +57,10 @@ const INTENT_COPY: Record<Extract<CloudTeaserTarget, { surface: 'intent' }>['inttitle: 'Motion Control',line: 'Your character copies the moves from any dance or pose video.',},+ swap_character: {+ title: 'Swap Character',+ line: 'Put a new person into a real video. Same moves, same scene, same sound.',+ },}/**diff --git a/src/components/create/experimental/ClipLength.tsx b/src/components/create/experimental/ClipLength.tsxnew file mode 100644index 00000000..c398b675--- /dev/null+++ b/src/components/create/experimental/ClipLength.tsx@@ -0,0 +1,108 @@+import { AlertTriangle } from 'lucide-react'+import { modelLabel } from '../../../lib/render/preset-models'+import { swapClipCredits, swapClipLimits, swapClipSeconds, swapCreditsPerSecond, swapPricedSeconds } from '../../../lib/render/swap'++// The length of a Swap Character run (port of the web's ClipLength, C52).+// The slider always shows the whole span (2 s up to the longest model, 120 s);+// what the customer's own video does not have is drawn faint. Where the model+// reads less than the video is long, one sentence says so instead of cutting+// silently. Credits for the chosen length and per second stand beside it, the+// same seconds the Create button and the server count (swapPricedSeconds).++export function ClipLength({+ model, options, videoSeconds, chosen, onChange, photos = 0, span, disabled = false,+}: {+ model: string+ options: Record<string, unknown>+ /** Length of the customer's video, measured in the app. */+ videoSeconds?: number+ chosen: number | null+ onChange: (seconds: number) => void+ /** Photos billed one by one (the main model). */+ photos?: number+ /** The span of the slider when more than one model stands behind it (up to+ * 15 s the main model, longer Wan 2.2 Animate up to 120 s). Without it the+ * span of the one model. */+ span?: { min: number; max: number }+ disabled?: boolean+}) {+ const own = swapClipLimits(model)+ const { min, max } = span ?? own+ const value = span+ // Without a choice the run takes the whole video up to the limit of the+ // model on duty (15 s on the main model), not the end of the slider: the+ // slider spans both models, the price is the one model's.+ ? Math.max(min, Math.min(chosen ?? own.max, max, videoSeconds ? Math.max(min, Math.floor(videoSeconds)) : max))+ : swapClipSeconds(model, chosen, videoSeconds)+ const video = videoSeconds ? Math.floor(videoSeconds) : undefined+ const perSecond = swapCreditsPerSecond(model, options)+ const total = swapClipCredits(model, options, videoSeconds ? swapPricedSeconds(model, chosen, videoSeconds) : Math.min(value, own.max), photos)+ const name = modelLabel(model)+ const at = (v: number) => (max > min ? Math.min(100, Math.max(0, ((v - min) / (max - min)) * 100)) : 0)+ const pos = at(value)+ // Faint from the end of the customer's video on.+ const end = video !== undefined && video < max ? at(Math.max(min, video)) : 100++ return (+ <div className="w-full" data-clip-length>+ <div className="flex items-baseline justify-between gap-3">+ <label htmlFor="swap-length" className="t-control text-gray-400">+ Length <span className="t-mono text-gray-200">{value} s</span>+ {video !== undefined && <span className="text-gray-500"> of {video} s</span>}+ </label>+ {total != null && perSecond != null && (+ <span className="text-right" data-clip-price>+ <span className="t-mono text-gray-200">{total.toLocaleString('en-US')}</span>+ <span className="t-control text-gray-500"> credits · {perSecond.toLocaleString('en-US')}/s</span>+ </span>+ )}+ </div>+ <div className="relative mt-1 h-5 flex items-center">+ <div className="absolute inset-x-0 h-1 rounded-full bg-white/[0.04]" />+ <div className="absolute h-1 rounded-full bg-white/10" style={{ left: 0, width: `${end}%` }} />+ <div className="absolute h-1 rounded-full bg-lu-accent" style={{ left: 0, width: `${pos}%` }} />+ <input+ id="swap-length"+ type="range"+ min={min}+ max={max}+ step={1}+ value={value}+ disabled={disabled}+ aria-valuetext={`${value} seconds`}+ onChange={(e) => {+ const v = Number(e.target.value)+ // Past the end of the video there is nothing to take.+ onChange(video !== undefined ? Math.min(v, Math.max(min, video)) : v)+ }}+ className="absolute inset-x-0 w-full cursor-pointer disabled:cursor-not-allowed"+ style={{ zIndex: 2, opacity: 0, top: '-4px', height: '28px' }}+ />+ <div+ className="absolute w-3.5 h-3.5 rounded-full pointer-events-none bg-gray-200 border border-lu-accent"+ style={{ left: `calc(${pos}% - 7px)`, zIndex: 1, boxShadow: '0 1px 4px rgba(0,0,0,0.4)' }}+ />+ </div>+ <div className="mt-0.5 flex justify-between t-control text-gray-500 tabular-nums">+ <span>{min} s</span>+ <span>{name}: {own.min} to {own.max} s</span>+ <span>{max} s</span>+ </div>+ {video !== undefined && video > own.max && value >= own.max && (+ <p className="mt-1.5 flex items-start gap-1.5 t-body text-gray-500 dark:text-gray-400" data-clip-note="too-long">+ <AlertTriangle size={13} className="mt-0.5 shrink-0" />+ Your video is {video} s. {name} reads at most {own.max} s, so only the first {Math.min(value, own.max)} s are used.+ </p>+ )}+ {video !== undefined && video < own.min && (+ <p className="mt-1.5 flex items-start gap-1.5 t-body text-gray-500 dark:text-gray-400" data-clip-note="too-short">+ <AlertTriangle size={13} className="mt-0.5 shrink-0" />+ Your video is {video} s. {name} needs at least {own.min} s.+ </p>+ )}+ {value < own.billedMin && (+ <p className="mt-1 t-body text-gray-500" data-clip-note="billed-min">Billed as {own.billedMin} s, the provider's minimum.</p>+ )}+ </div>+ )+}diff --git a/src/components/create/experimental/Composer.tsx b/src/components/create/experimental/Composer.tsxindex e7637755..f8ca0e45 100644--- a/src/components/create/experimental/Composer.tsx+++ b/src/components/create/experimental/Composer.tsx@@ -16,6 +16,8 @@ import { runImageCount } from '../../../lib/render/image-count'import { useCloudCatalogStore, cloudModelById, defaultCloudModel, editNeedsMask, modelForOp, runCredits, lengthCredits, lengthPrice } from '../../../stores/cloudCatalogStore'import { createRunModel, intentRequiredInputs, isStudioModel } from '../../../lib/render/create-studio'import { STUDIO_MODELS } from '../../../lib/render/studio-contract'+import { swapBilledPhotos, swapPricedSeconds, swapShortCredits } from '../../../lib/render/swap'+import { swapReady } from '../../../lib/create/swap-run'import { effectiveVideoDurations, snapToVideoDuration } from '../../../lib/render/video-duration'import { mediaSeconds, useStudioPrice } from './useStudioPrice'import { getJob } from '../../../api/cloud/jobs'@@ -105,6 +107,10 @@ export function Composer({ onOpenAdvanced, onOpenWorkflows }: Props) {const videoInput = useCreateStore((s) => s.videoInput)const extendSource = useCreateStore((s) => s.extendSource)const musicDuration = useCreateStore((s) => s.musicDuration)+ // Swap Character: the people, the chosen length and the consent.+ const swapFigures = useCreateStore((s) => s.swapFigures)+ const swapSeconds = useCreateStore((s) => s.swapSeconds)+ const swapConsent = useCreateStore((s) => s.swapConsent)const managerNoticeSeen = useWorkflowStore((s) => s.managerNoticeSeen)const { generate, cancel, quota, mlxMissing, modelsLoaded } = useCreateExp()const imageModels = useCreateStore((s) => s.imageModelList)@@ -136,7 +142,8 @@ export function Composer({ onOpenAdvanced, onOpenWorkflows }: Props) {// 2.5.8 categories with their own composer surfaces + input contracts.const special =intent === 'character' || intent === 'lipsync' || intent === 'music' ||- intent === 'extend' || intent === 'motion'+ intent === 'extend' || intent === 'motion' || intent === 'swap_character'+ const swap = intent === 'swap_character'const characterUse = intent === 'character' && characterTab === 'use'let { kind: intentKind, op: intentOp } = intentToJob(intent)if (characterUse) {@@ -189,7 +196,7 @@ export function Composer({ onOpenAdvanced, onOpenWorkflows }: Props) {const lengthRate = backend === 'cloud' && !studioPick ? lengthPrice(runModel, intentOp) : undefinedconst mediaUrl =intent === 'lipsync' ? (lengthRate?.basis === 'video' ? videoInput?.url : audioInput?.url)- : intent === 'motion' ? videoInput?.url+ : intent === 'motion' || swap ? videoInput?.url: intent === 'extend' ? extendSource?.url: undefinedconst mediaKind = intent === 'lipsync' && lengthRate?.basis !== 'video' ? ('audio' as const) : ('video' as const)@@ -240,7 +247,11 @@ export function Composer({ onOpenAdvanced, onOpenWorkflows }: Props) {const cloudImageCount = useCreateStore((s) => s.cloudImageCount)const extraPhotos = intent === 'edit' || intent === 'animate' ? references.length : 0const imageCount = backend === 'cloud' ? runImageCount(intent, cloudImageCount, characterUse) : 1- const studioPrice = useStudioPrice(studioPick, cloudStudioOptions, prompt, runSeconds ?? inputSeconds, extraPhotos)+ // Swap: the chosen length counts, not the whole video, and every photo is+ // billed on its own (the same seconds as the slider and the server).+ const priceSeconds = swap && studioPick && inputSeconds !== undefined ? swapPricedSeconds(studioPick, swapSeconds, inputSeconds) : inputSeconds+ const billedPhotos = swap && studioPick ? swapBilledPhotos(studioPick, swapFigures.length) : 0+ const studioPrice = useStudioPrice(studioPick, cloudStudioOptions, prompt, runSeconds ?? priceSeconds, extraPhotos, billedPhotos)const setCloudStudioCredits = useCreateStore((s) => s.setCloudStudioCredits)// Der Preis der gemessenen Laenge, bei einer Stimme der Zeichen des Textes.// Er steht im selben Speicher wie ein Studio-Preis, geht als Deckel mit dem@@ -328,7 +339,11 @@ export function Composer({ onOpenAdvanced, onOpenWorkflows }: Props) {? (backend === 'cloud' ? !!extendSource : hasStart): intent === 'motion'? hasStart && !!videoInput- : true+ : swap+ // Studio models only: without one in the server's catalogue the+ // tab says so (SwapControls) and the button stays off.+ ? !!studioPick && swapReady(studioPick, { hasVideo: !!videoInput, figures: swapFigures, consent: swapConsent })+ : true// A half-installed bundle is pickable long before it is usable: the lane// list refills as soon as the diffusion model lands, while the VAE it needs// is still coming down. Measured on the box 2026-08-15 at 88 percent of the@@ -390,7 +405,8 @@ export function Composer({ onOpenAdvanced, onOpenWorkflows }: Props) {Befund und hier nicht behoben. */}<div className="mx-auto w-full max-w-[660px] space-y-2.5">{special && <SpecialControls intent={intent} />}- {!isUtility && <LaneControls />}+ {/* Swap Character's options are its own panel above (SpecialControls). */}+ {!isUtility && !swap && <LaneControls />}<CharacterNote />{inputNote && (<p className="t-body text-gray-500 text-center px-3.5" data-testid="lane-input-note">{laneCaption}</p>@@ -596,7 +612,11 @@ export function Composer({ onOpenAdvanced, onOpenWorkflows }: Props) {// The span carries the hint: a disabled button takes no pointer,// so a title on the button itself would never show.<span className="inline-flex" title={macSetupFirst ? MAC_SETUP_FIRST : (missingSource ?? (upscaleReady ? undefined : UPSCALE_MODEL_FIRST))}>- <Button variant="primary" size="lg" icon={Sparkles} disabled={!canGenerate} onClick={guardedGenerate}>Create</Button>+ <Button variant="primary" size="lg" icon={Sparkles} disabled={!canGenerate} onClick={guardedGenerate}>+ {/* Swap Character names its price on the button (the web's+ CreateButton): a paid video run, priced by its length. */}+ {swap && backend === 'cloud' && priceSeconds !== undefined && studioPrice ? `Create · ${swapShortCredits(studioPrice.credits)}` : 'Create'}+ </Button></span>)}</div>diff --git a/src/components/create/experimental/SpecialIntentControls.tsx b/src/components/create/experimental/SpecialIntentControls.tsxindex 913af035..665b9fbd 100644--- a/src/components/create/experimental/SpecialIntentControls.tsx+++ b/src/components/create/experimental/SpecialIntentControls.tsx@@ -12,7 +12,7 @@ import { AnimatePresence, motion } from 'framer-motion'import {AudioLines, Download, Film, ImagePlus, Info, Loader2, Mic, Music2, Trash2, Upload, Wand2, X,} from 'lucide-react'-import { useCreateStore, type CreateIntent, type GalleryItem } from '../../../stores/createStore'+import { useCreateStore, type CreateIntent, type GalleryItem, type SwapFigure } from '../../../stores/createStore'import { useCloudCatalogStore, cloudModelById, lengthCredits, lengthPrice, modelForOp } from '../../../stores/cloudCatalogStore'import { listLoras, deleteLora, downloadLora, type CloudLora, type LoraDownloadProgress } from '../../../api/cloud/loras'import { errorText } from '../../../types/json-guards'@@ -35,6 +35,14 @@ import { isWindows, isMacOS } from '../../../api/backend'import { LOCAL_MUSIC_TEXT, SECONDS_LENGTH, musicHowtoLines, musicLength, musicText } from '../../../lib/render/music-ui'import { MAC_MUSIC_MIN_SECONDS } from '../../../lib/mac-music'import { createRunModel, studioShownValue } from '../../../lib/render/create-studio'+import { STUDIO_MODELS, studioFields } from '../../../lib/render/studio-contract'+import { modelLabel } from '../../../lib/render/preset-models'+import {+ SWAP_CONSENT_TEXT, SWAP_LONG_MODEL, SWAP_MAIN_MODEL, SWAP_TIPS, swapAutoModel, swapBilledPhotos, swapClipLimits,+ swapMaxPeople, swapNeedsConsent, swapReadsRoles,+} from '../../../lib/render/swap'+import { mediaSeconds } from './useStudioPrice'+import { ClipLength } from './ClipLength'import { galleryLabelShort } from '../../../lib/render/gallery-label'import { TRAIN_VRAM_PRESETS, LOW_VRAM_NOTE, trainStepsNote, trainVramSuggestion, type TrainVramPreset } from '../../../lib/trainer-presets'import { STYLE_MODE_NOTE, STYLE_NAME_PLACEHOLDER, STYLE_TRIGGER_HINT_OFF, STYLE_TRIGGER_HINT_ON, STYLE_TRIGGER_LABEL, TRAIN_KINDS, trainPresetsFor, type TrainKind } from '../../../lib/train-kind'@@ -69,6 +77,7 @@ export function SpecialControls({ intent }: { intent: CreateIntent }) {case 'music': return <MusicControls />case 'extend': return <ExtendControls />case 'motion': return <MotionControls />+ case 'swap_character': return <SwapControls />default: return null}}@@ -1728,6 +1737,199 @@ function MotionControls() {)}+// ── Swap Character (07.11.2026, port of the web's C52) ─────────────────────+//+// The order of the web panel: the notes first (what the models cannot do, so+// it is not learned from a failed run), the video and the resolution, the+// people (photo and role each, up to four), the length with its price, and+// the consent box for the models that need it. Create and its price stand in+// the Composer's action bar below.++export function SwapControls() {+ const videoInput = useCreateStore((s) => s.videoInput)+ const figures = useCreateStore((s) => s.swapFigures)+ const setFigures = useCreateStore((s) => s.setSwapFigures)+ const swapSeconds = useCreateStore((s) => s.swapSeconds)+ const setSwapSeconds = useCreateStore((s) => s.setSwapSeconds)+ const consent = useCreateStore((s) => s.swapConsent)+ const setConsent = useCreateStore((s) => s.setSwapConsent)+ const options = useCreateStore((s) => s.cloudStudioOptions)+ const setOptions = useCreateStore((s) => s.setCloudStudioOptions)+ const opModel = useCreateStore((s) => s.cloudOpModel)+ const setOpModel = useCreateStore((s) => s.setCloudOpModel)+ const isGenerating = useCreateStore((s) => s.isGenerating)+ const model = createRunModel('swap_character', { image: '', video: '', op: opModel })+ // The length of the customer's video, measured in the app (as the price).+ const [measured, setMeasured] = useState<{ url: string; seconds: number | undefined } | null>(null)+ useEffect(() => {+ let alive = true+ if (!videoInput) return+ void mediaSeconds(videoInput.url, 'video').then((v) => { if (alive) setMeasured({ url: videoInput.url, seconds: v }) })+ return () => { alive = false }+ }, [videoInput])+ const videoSeconds = measured && videoInput && measured.url === videoInput.url ? measured.seconds : undefined++ // The model follows the length and the number of people: up to 15 s the+ // main model, longer Wan 2.2 Animate (one person). Only between these two;+ // SCAIL 2 picked by hand stays. It switches when the limit is crossed, not+ // on every move of the slider, and a sentence below says so.+ const auto = model === SWAP_MAIN_MODEL || model === SWAP_LONG_MODEL+ const wanted = videoSeconds !== undefined ? Math.min(videoSeconds, swapSeconds ?? Infinity) : swapSeconds ?? undefined+ const target = swapAutoModel(wanted, figures.length)+ const known = !!STUDIO_MODELS[model]+ useEffect(() => {+ if (auto && known && target !== model) setOpModel(target)+ }, [auto, known, target, model, setOpModel])+ const span = auto+ ? { min: swapClipLimits(SWAP_MAIN_MODEL).min, max: figures.length > 1 ? swapClipLimits(SWAP_MAIN_MODEL).max : swapClipLimits(SWAP_LONG_MODEL).max }+ : undefined++ if (!known) {+ // The server's catalogue does not list the swap models yet.+ return (+ <p className="t-body text-gray-500 text-center" data-swap-unavailable>+ Swap Character is not available on this LU Cloud yet.+ </p>+ )+ }++ const maxPeople = swapMaxPeople(model)+ const roles = swapReadsRoles(model)+ const resolutions = (studioFields(model).resolution?.enum ?? []) as string[]+ const resolution = String(studioShownValue(model, options, 'resolution') ?? '')+ const setFigure = (i: number, patch: Partial<SwapFigure>) => setFigures(figures.map((f, j) => (j === i ? { ...f, ...patch } : f)))++ return (+ <div className="flex flex-col items-center gap-2.5" data-swap-controls>+ <p className="flex w-full items-start gap-1.5 t-control text-gray-500" data-swap-tips>+ <Info size={12} className="mt-[2px] shrink-0" />+ <span>{SWAP_TIPS.join(' ')}</span>+ </p>+ <div className="flex w-full items-center justify-between gap-2 flex-wrap">+ <DrivingVideoChip empty="Add original video" />+ {resolutions.length > 1 && (+ <Segmented+ size="sm"+ layoutId="swap-resolution"+ ariaLabel="Resolution"+ value={resolution}+ onChange={(v) => setOptions({ ...options, resolution: v })}+ options={resolutions.map((r) => ({ value: r, label: r }))}+ />+ )}+ </div>++ <div className="w-full space-y-1" data-swap-figures={figures.length}>+ {figures.map((f, i) => (+ <div key={i} className="flex items-center gap-2" data-swap-figure={i + 1}>+ <span className="grid h-6 w-6 shrink-0 place-items-center rounded-full bg-lu-accent/15 t-micro font-semibold text-lu-accent">{i + 1}</span>+ <FigurePhoto image={f.image} index={i} onImage={(image) => setFigure(i, { image })} />+ {roles ? (+ <input+ type="text"+ value={f.role}+ maxLength={200}+ disabled={isGenerating}+ aria-label={`Who person ${i + 1} replaces`}+ placeholder={figures.length > 1 ? 'Who? e.g. the woman in black on the left' : 'Optional: who to replace (default: the most prominent person)'}+ onChange={(e) => setFigure(i, { role: e.target.value })}+ className="t-control h-[var(--control-h-sm)] min-w-0 flex-1 rounded-md border border-white/[0.08] bg-white/[0.03] px-2 text-gray-200 placeholder:text-gray-500"+ />+ ) : (+ <span className="t-body flex-1 text-gray-500">{i === 0 ? 'Replaces the main person' : ''}</span>+ )}+ {figures.length > 1 && (+ <button+ type="button"+ aria-label={`Remove person ${i + 1}`}+ disabled={isGenerating}+ onClick={() => setFigures(figures.filter((_, j) => j !== i))}+ className="rounded p-1 text-gray-500 hover:text-gray-200"+ >+ <X size={13} />+ </button>+ )}+ </div>+ ))}+ <div className="flex items-center gap-2">+ <button+ type="button"+ disabled={figures.length >= 4 || isGenerating}+ onClick={() => {+ // Several people only the main model can do. The switch is+ // said in the sentence below, it does not happen silently.+ if (maxPeople < 2) setOpModel(SWAP_MAIN_MODEL)+ setFigures([...figures, { image: null, role: '' }])+ }}+ className="t-control h-[var(--control-h-sm)] rounded-md px-2 text-gray-400 hover:text-gray-200 disabled:opacity-40"+ >+ + Add person ({figures.length}/4)+ </button>+ {figures.length > 1 && maxPeople < figures.length && (+ <span className="t-body text-gray-500 dark:text-gray-400" data-swap-note="one-person-model">+ {modelLabel(model)} replaces one person.+ </span>+ )}+ </div>+ </div>++ <ClipLength+ model={model}+ options={options}+ videoSeconds={videoSeconds}+ chosen={swapSeconds}+ onChange={setSwapSeconds}+ photos={swapBilledPhotos(model, figures.length)}+ span={span}+ disabled={isGenerating}+ />+ {auto && model === SWAP_LONG_MODEL && (+ <p className="w-full t-body text-gray-500" data-swap-note="long-model">+ Longer than 15 s: {modelLabel(SWAP_LONG_MODEL)} runs the whole clip (one person, up to 120 s). Set 15 s or less for {modelLabel(SWAP_MAIN_MODEL)}.+ </p>+ )}+ {swapNeedsConsent(model) && (+ <label className="flex w-full items-start gap-2 t-control text-gray-300 cursor-pointer" data-swap-consent>+ <input+ type="checkbox"+ checked={consent}+ disabled={isGenerating}+ onChange={(e) => setConsent(e.target.checked)}+ className="mt-[3px] shrink-0 accent-[var(--color-lu-accent)]"+ />+ <span>{SWAP_CONSENT_TEXT}</span>+ </label>+ )}+ </div>+ )+}++/** The photo of one person: a small field to click, with a preview. */+function FigurePhoto({ image, index, onImage }: { image: SwapFigure['image']; index: number; onImage: (image: SwapFigure['image']) => void }) {+ const ref = useRef<HTMLInputElement>(null)+ return (+ <button+ type="button"+ aria-label={image ? `Change photo of person ${index + 1}` : `Add photo of person ${index + 1}`}+ onClick={() => ref.current?.click()}+ className={cn(+ 'relative grid h-9 w-7 shrink-0 place-items-center overflow-hidden rounded-md border',+ image ? 'border-white/10' : 'border-dashed border-white/20 text-gray-500 hover:text-gray-300',+ )}+ >+ {image ? <img src={image.url} alt={`New person ${index + 1}`} className="h-full w-full object-cover" /> : <ImagePlus size={14} />}+ <input+ ref={ref}+ type="file"+ accept="image/*"+ className="hidden"+ data-swap-photo-input={index + 1}+ onChange={(e) => { const f = e.target.files?.[0]; if (f) void loadImageRef(f).then(onImage); e.target.value = '' }}+ />+ </button>+ )+}+/** C7: says under the trigger field what it did to the typed word ("Jörg" is* trained as "Joerg"), so the word on screen is visibly the word learned. */function TriggerWordNote() {diff --git a/src/components/create/experimental/Stage.tsx b/src/components/create/experimental/Stage.tsxindex 7ffe3021..bfd8ef37 100644--- a/src/components/create/experimental/Stage.tsx+++ b/src/components/create/experimental/Stage.tsx@@ -6,6 +6,7 @@ import { useModelStore } from '../../../stores/modelStore'import { createRunModel } from '../../../lib/render/create-studio'import { musicText } from '../../../lib/render/music-ui'import { useCreateExp } from './CreateContext'+import { SwapStage } from './SwapStage'import { INTENT_MAP } from './intents'import { editNeedsMask, defaultCloudModel, modelForOp } from '../../../stores/cloudCatalogStore'import { stageShowsSetupCard, laneModelCount } from './stageGate'@@ -196,6 +197,9 @@ export function Stage({ displayed, onOpenMaskEditor, onEditResult, onAnimateResubody = <SourcePreview onOpenMaskEditor={onOpenMaskEditor} />howtoAtFoot = truehowtoOnlyWide = true+ } else if (intent === 'swap_character' && !(displayed && displayed.intent === 'swap_character')) {+ // Swap Character: original + new people -> result, until a swap is there.+ body = <SwapStage />} else if (displayed) {body = (<ResultViewdiff --git a/src/components/create/experimental/StudioParams.tsx b/src/components/create/experimental/StudioParams.tsxindex 49ec7851..503fa9bf 100644--- a/src/components/create/experimental/StudioParams.tsx+++ b/src/components/create/experimental/StudioParams.tsx@@ -12,12 +12,17 @@ import { modelHint, modelLabel } from '../../../lib/render/preset-models'import { studioShownValue } from '../../../lib/render/create-studio'import { STUDIO_MODELS } from '../../../lib/render/studio-contract'import { musicText } from '../../../lib/render/music-ui'+import { swapPanelFields } from '../../../lib/render/swap'export function StudioParams({ model }: { model: string }) {const options = useCreateStore((s) => s.cloudStudioOptions)const setOptions = useCreateStore((s) => s.setCloudStudioOptions)const isGenerating = useCreateStore((s) => s.isGenerating)- const fields = studioFieldsInOrder(model)+ // Swap Character shows a role per person and the resolution in its own+ // panel, and fixes the mode (lib/render/swap.ts): none of them twice here.+ const intent = useCreateStore((s) => s.intent())+ const inPanel = swapPanelFields(intent)+ const fields = studioFieldsInOrder(model).filter(([key]) => !inPanel.includes(key))const hint = modelHint(model)// Mureka Song calls its style field "prompt" while the prompt field carries// the lyrics. The control is named for what it does.diff --git a/src/components/create/experimental/SwapStage.tsx b/src/components/create/experimental/SwapStage.tsxnew file mode 100644index 00000000..3b0ee506--- /dev/null+++ b/src/components/create/experimental/SwapStage.tsx@@ -0,0 +1,107 @@+import { useRef } from 'react'+import { ArrowRight, Film, ImagePlus, Sparkles } from 'lucide-react'+import { useCreateStore } from '../../../stores/createStore'+import { loadImageRef } from './loadImage'+import { mediaRefFrom } from './mediaRef'+import { cn } from '../ui/cn'++// The Stage of Swap Character while no swap lies on it (port of the web's+// SwapStage, C52). One look says what happens here: the original, the new+// people, the result. What is already added stands in its place, the rest as+// an empty frame. The empty frames are upload fields themselves, the bigger+// target. Several people show as small numbered tiles; photo and role are set+// in the panel below.++const CARD = 'relative flex aspect-[9/16] h-[clamp(44px,calc(100cqh-64px),240px)] max-w-[28vw] shrink-0 flex-col items-center justify-center overflow-hidden rounded-xl border'+const EMPTY = 'border-dashed border-white/15 bg-white/[0.02] text-gray-500'+const FILLED = 'border-white/10 bg-white/5'++function Caption({ children }: { children: React.ReactNode }) {+ return <span className="t-control text-gray-400">{children}</span>+}++function Pick({ accept, label, onFile, children, className }: {+ accept: string; label: string; onFile: (file: File) => void; children: React.ReactNode; className: string+}) {+ const ref = useRef<HTMLInputElement>(null)+ return (+ <button type="button" aria-label={label} onClick={() => ref.current?.click()} className={cn(className, 'cursor-pointer hover:border-lu-accent/60')}>+ {children}+ <input+ ref={ref}+ type="file"+ accept={accept}+ className="hidden"+ onChange={(e) => { const f = e.target.files?.[0]; if (f) onFile(f); e.target.value = '' }}+ />+ </button>+ )+}++export function SwapStage() {+ const videoInput = useCreateStore((s) => s.videoInput)+ const setVideoInput = useCreateStore((s) => s.setVideoInput)+ const figures = useCreateStore((s) => s.swapFigures)+ const setFigures = useCreateStore((s) => s.setSwapFigures)+ const first = figures[0]?.image ?? null+ const many = figures.length > 1++ return (+ <div className="flex-1 min-h-0 flex flex-col items-center justify-center gap-2 px-4 py-2 [container-type:size]" data-swap-stage>+ <div className="flex items-center gap-2 sm:gap-3">+ <figure className="flex flex-col items-center gap-1.5">+ <Pick+ accept="video/mp4,video/webm,video/quicktime"+ label={videoInput ? 'Change original video' : 'Add original video'}+ onFile={(f) => setVideoInput(mediaRefFrom(f))}+ className={cn(CARD, videoInput ? FILLED : EMPTY)}+ >+ {videoInput+ ? <video src={videoInput.url} muted loop autoPlay playsInline className="h-full w-full object-cover" />+ : <><Film size={20} /><span className="t-control mt-1.5 px-2 text-center">Your video</span></>}+ </Pick>+ <Caption>Original</Caption>+ </figure>++ <span className="text-gray-500" aria-hidden>+</span>++ <figure className="flex flex-col items-center gap-1.5">+ {many ? (+ <div className={cn(CARD, FILLED, 'grid grid-cols-2 gap-1 p-1')} data-swap-figure-grid>+ {figures.map((f, i) => (+ <div key={i} className="relative h-full w-full overflow-hidden rounded-md bg-white/5">+ {f.image+ ? <img src={f.image.url} alt={`New person ${i + 1}`} className="h-full w-full object-cover" />+ : <ImagePlus size={12} className="m-auto mt-[40%] text-gray-500" />}+ <span className="absolute left-0.5 top-0.5 grid h-4 w-4 place-items-center rounded-full bg-lu-accent t-micro font-semibold text-gray-950">{i + 1}</span>+ </div>+ ))}+ </div>+ ) : (+ <Pick+ accept="image/*"+ label={first ? 'Change photo of the new person' : 'Add photo of the new person'}+ onFile={(f) => { void loadImageRef(f).then((image) => setFigures(figures.map((g, i) => (i === 0 ? { ...g, image } : g)))) }}+ className={cn(CARD, first ? FILLED : EMPTY)}+ >+ {first+ ? <img src={first.url} alt="New person" className="h-full w-full object-cover" />+ : <><ImagePlus size={20} /><span className="t-control mt-1.5 px-2 text-center">New person</span></>}+ </Pick>+ )}+ <Caption>{many ? `${figures.length} new people` : 'New person'}</Caption>+ </figure>++ <ArrowRight size={16} className="text-gray-500" aria-hidden />++ <figure className="flex flex-col items-center gap-1.5">+ <div className={cn(CARD, 'border-lu-accent/40 bg-lu-accent/[0.06] text-lu-accent')}>+ <Sparkles size={20} />+ </div>+ <Caption>Result</Caption>+ </figure>+ </div>+ <p className="t-body max-w-[420px] truncate text-center text-gray-500">Same scene and motion, a different person.</p>+ </div>+ )+}diff --git a/src/components/create/experimental/__tests__/cloud-features-off-means-no-cloud-in-local.test.tsx b/src/components/create/experimental/__tests__/cloud-features-off-means-no-cloud-in-local.test.tsxindex e18df2a7..3c4c0ca2 100644--- a/src/components/create/experimental/__tests__/cloud-features-off-means-no-cloud-in-local.test.tsx+++ b/src/components/create/experimental/__tests__/cloud-features-off-means-no-cloud-in-local.test.tsx@@ -64,9 +64,13 @@ describe('the rule', () => {})describe('the bar', () => {- it('on: Erase carries the cloud tag and opens the Cloud sheet, Enhance is a local tab', () => {+ it('on: Erase and Swap carry the cloud tag and open the Cloud sheet, Enhance is a local tab', () => {render(<IntentBar />)- expect(cloudTagged().map((b) => b.textContent)).toEqual(['Erase'])+ // Swap Character (07.11.2026) has no local lane either: a cloud pill.+ expect(cloudTagged().map((b) => b.textContent)).toEqual(['Erase', 'Swap'])+ fireEvent.click(screen.getByRole('radio', { name: /Swap Character/ }))+ expect(useUIStore.getState().cloudTeaser).toEqual({ surface: 'intent', intent: 'swap_character' })+ useUIStore.setState({ cloudTeaser: null })fireEvent.click(screen.getByRole('radio', { name: /Erase Object/ }))expect(useUIStore.getState().cloudTeaser).toEqual({ surface: 'intent', intent: 'eraser' })useUIStore.setState({ cloudTeaser: null })diff --git a/src/components/create/experimental/__tests__/intents.test.ts b/src/components/create/experimental/__tests__/intents.test.tsindex 98167e3f..ccd20d5b 100644--- a/src/components/create/experimental/__tests__/intents.test.ts+++ b/src/components/create/experimental/__tests__/intents.test.ts@@ -106,7 +106,9 @@ describe('intent gating on a local MLX Mac (no ComfyUI)', () => {it('the hosted-only tools AND the 2.5.8 lanes become cloud teasers', () => {// Same locked pill + ", runs on LU Cloud" label the 2.6.0 bar already// uses — visible, honest, and it opens the teaser sheet on tap.- expect(teasers('local', true)).toEqual(['upscale', 'eraser', 'lipsync', 'music', 'extend', 'motion'])+ // Swap Character (07.11.2026) is hosted-only like Erase, so it is a teaser+ // here too.+ expect(teasers('local', true)).toEqual(['upscale', 'eraser', 'lipsync', 'music', 'extend', 'motion', 'swap_character'])})it('every Mac teaser has a cloud endpoint to teased about', () => {diff --git a/src/components/create/experimental/__tests__/swap-character-panel.test.tsx b/src/components/create/experimental/__tests__/swap-character-panel.test.tsxnew file mode 100644index 00000000..0911d034--- /dev/null+++ b/src/components/create/experimental/__tests__/swap-character-panel.test.tsx@@ -0,0 +1,179 @@+// @vitest-environment jsdom+/**+ * Swap Character on the desktop (07.11.2026, port of the web's C52): the+ * panel in the web's order (notes, video and resolution, people, length,+ * consent), people up to four, and Create only once the video, a photo for+ * every person and the consent are there. Nothing is rendered or booked:+ * the Composer's generate is a fake, the catalogue a fixture.+ *+ * Run: npx vitest run src/components/create/experimental/__tests__/swap-character-panel.test.tsx+ */+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { render, cleanup, screen, fireEvent, act } from '@testing-library/react'++const QUOTA = {+ tier: 'pro', period: 'month', limits: { credits: 10_000_000 }, costs: { image: 1000, video: 10000 },+ used: { credits_used: 0 }, remaining: { credits: 10_000_000 },+}++vi.mock('../CreateContext', () => ({+ useCreateExp: () => ({+ generate: vi.fn(), cancel: vi.fn(), makeVoice: vi.fn(), quota: QUOTA,+ samplerList: [], schedulerList: [], loraList: [], vaeList: [], refreshModelLists: vi.fn(),+ connected: true, modelsLoaded: true, modelLoadError: null, mlxMissing: null,+ installCapability: vi.fn(), installModelBundle: vi.fn(),+ }),+}))+vi.mock('../../../../api/backend', async (orig) => ({+ ...((await orig()) as Record<string, unknown>),+ openExternal: vi.fn(),+}))++import { Composer } from '../Composer'+import { SwapStage } from '../SwapStage'+import { useCreateStore } from '../../../../stores/createStore'+import { useCloudCatalogStore } from '../../../../stores/cloudCatalogStore'+import { neuerServer } from '../../../../lib/render/__tests__/fixtures/test-catalogs'+import { SWAP_CONSENT_TEXT, SWAP_LONG_MODEL, SWAP_MAIN_MODEL, SWAP_TIPS } from '../../../../lib/render/swap'++const photo = { filename: 'face.png', url: 'data:image/png;base64,AA', width: 512, height: 768 }+const clip = { blob: new Blob(['x'], { type: 'video/mp4' }), name: 'dance.mp4', url: 'blob:dance' }++beforeEach(() => {+ useCloudCatalogStore.setState({ models: neuerServer() })+ useCreateStore.setState({+ isGenerating: false, batchRun: null, error: null, gallery: [], source: null, videoInput: null, prompt: '',+ backend: 'cloud', cloudStudioOptions: {}, cloudStudioCredits: null,+ // No pick of an earlier test: the tab resolves to its first model.+ cloudOpModel: '',+ } as never)+ useCreateStore.getState().setIntent('swap_character')+ useCreateStore.setState({ swapFigures: [{ image: null, role: '' }], swapSeconds: null, swapConsent: false })+})+afterEach(() => cleanup())++function open() {+ render(<Composer onOpenAdvanced={() => {}} onOpenWorkflows={() => {}} />)+}+const create = () => screen.getByRole('button', { name: /^Create/ }) as HTMLButtonElement+const panel = () => document.querySelector('[data-swap-controls]') as HTMLElement++describe('the Swap Character panel', () => {+ it('stands in the web order: notes, video, people, length, consent; no prompt field', () => {+ open()+ expect(panel()).toBeTruthy()+ expect(document.querySelector('textarea')).toBeNull()+ const order = ['[data-swap-tips]', '[data-swap-figures]', '[data-clip-length]', '[data-swap-consent]']+ .map((sel) => panel().querySelector(sel) as HTMLElement)+ for (const el of order) expect(el).toBeTruthy()+ for (let i = 1; i < order.length; i++) {+ expect(order[i - 1].compareDocumentPosition(order[i]) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()+ }+ expect(panel().textContent).toContain(SWAP_TIPS.join(' '))+ expect(screen.getByText('Add original video')).toBeTruthy()+ expect(screen.getByText(SWAP_CONSENT_TEXT)).toBeTruthy()+ // The resolution comes from the schema of the running model, 768p default.+ const res = screen.getByRole('radiogroup', { name: 'Resolution' })+ expect([...res.querySelectorAll('[role=radio]')].map((b) => b.textContent)).toEqual(['480p', '540p', '768p', '1080p'])+ expect(res.querySelector('[aria-checked=true]')?.textContent).toBe('768p')+ // The length slider spans 2 to 120 s (main model up to 15, Wan beyond).+ const slider = document.getElementById('swap-length') as HTMLInputElement+ expect([slider.min, slider.max]).toEqual(['2', '120'])+ })++ it('adds people up to four, each with a photo field and a role', () => {+ open()+ const add = () => screen.getByRole('button', { name: /Add person/ }) as HTMLButtonElement+ expect(add().textContent).toBe('+ Add person (1/4)')+ fireEvent.click(add())+ fireEvent.click(add())+ fireEvent.click(add())+ expect(useCreateStore.getState().swapFigures).toHaveLength(4)+ expect(add().textContent).toBe('+ Add person (4/4)')+ expect(add().disabled).toBe(true)+ fireEvent.click(add())+ expect(useCreateStore.getState().swapFigures).toHaveLength(4)+ for (let i = 1; i <= 4; i++) {+ expect(screen.getByRole('button', { name: `Add photo of person ${i}` })).toBeTruthy()+ expect(screen.getByRole('textbox', { name: `Who person ${i} replaces` })).toBeTruthy()+ }+ // Remove brings it back down.+ fireEvent.click(screen.getByRole('button', { name: 'Remove person 2' }))+ expect(useCreateStore.getState().swapFigures).toHaveLength(3)+ })++ it('switches a one-person model to the main model when a second person comes, and says so on SCAIL 2', () => {+ useCreateStore.getState().setCloudOpModel('scail-2')+ open()+ expect(screen.getByRole('button', { name: /Add person/ })).toBeTruthy()+ fireEvent.click(screen.getByRole('button', { name: /Add person/ }))+ expect(useCreateStore.getState().cloudOpModel).toBe(SWAP_MAIN_MODEL)+ })++ it('arms Create only with the video, every photo and the consent', () => {+ open()+ expect(create().disabled).toBe(true)+ act(() => { useCreateStore.setState({ videoInput: clip } as never) })+ expect(create().disabled).toBe(true)+ act(() => { useCreateStore.setState({ swapFigures: [{ image: photo, role: '' }, { image: null, role: '' }] }) })+ expect(create().disabled).toBe(true)+ act(() => { useCreateStore.setState({ swapFigures: [{ image: photo, role: '' }, { image: photo, role: 'the man on the right' }] }) })+ // Every photo is there, the box is not ticked yet.+ expect(create().disabled).toBe(true)+ fireEvent.click(screen.getByRole('checkbox'))+ expect(useCreateStore.getState().swapConsent).toBe(true)+ expect(create().disabled).toBe(false)+ // Untick: off again.+ fireEvent.click(screen.getByRole('checkbox'))+ expect(create().disabled).toBe(true)+ })++ it('shows no consent box on SCAIL 2, the one model that does not ask', () => {+ useCreateStore.getState().setCloudOpModel('scail-2')+ open()+ expect(document.querySelector('[data-swap-consent]')).toBeNull()+ act(() => { useCreateStore.setState({ videoInput: clip, swapFigures: [{ image: photo, role: '' }] } as never) })+ expect(create().disabled).toBe(false)+ })++ it('moves to Wan 2.2 Animate past 15 s with one person, and says so', () => {+ open()+ act(() => { useCreateStore.getState().setSwapSeconds(40) })+ expect(useCreateStore.getState().cloudOpModel).toBe(SWAP_LONG_MODEL)+ expect(document.querySelector('[data-swap-note="long-model"]')).toBeTruthy()+ // Wan reads 480p and 720p only.+ const res = screen.getByRole('radiogroup', { name: 'Resolution' })+ expect([...res.querySelectorAll('[role=radio]')].map((b) => b.textContent)).toEqual(['480p', '720p'])+ // A second person brings the main model back.+ fireEvent.click(screen.getByRole('button', { name: /Add person/ }))+ expect(useCreateStore.getState().cloudOpModel).toBe(SWAP_MAIN_MODEL)+ })++ it('names the live price beside the length: credits and credits per second', () => {+ open()+ // No video and no choice yet: the main model runs its whole 15 s at+ // 768p, with one photo: 15 x 0.20 $ + 0.02 $ = 3.02 $. Not the 120 s at+ // the end of the slider, which only the long model reads.+ const price = () => (document.querySelector('[data-clip-price]') as HTMLElement).textContent+ const slider = () => document.getElementById('swap-length') as HTMLInputElement+ expect(slider().value).toBe('15')+ expect(price()).toBe('302,000 credits · 20,000/s')+ act(() => { useCreateStore.getState().setSwapSeconds(10) })+ // 10 s: 2.00 $ + 0.02 $.+ expect(price()).toBe('202,000 credits · 20,000/s')+ })+})++describe('the Swap Stage', () => {+ it('shows original + new person -> result, and one tile per person when there are several', () => {+ render(<SwapStage />)+ expect(screen.getByRole('button', { name: 'Add original video' })).toBeTruthy()+ expect(screen.getByRole('button', { name: 'Add photo of the new person' })).toBeTruthy()+ expect(screen.getByText('Result')).toBeTruthy()+ cleanup()+ useCreateStore.setState({ swapFigures: [{ image: photo, role: '' }, { image: null, role: '' }, { image: photo, role: '' }] })+ render(<SwapStage />)+ expect(document.querySelector('[data-swap-figure-grid]')?.children).toHaveLength(3)+ expect(screen.getByText('3 new people')).toBeTruthy()+ })+})diff --git a/src/components/create/experimental/intents.ts b/src/components/create/experimental/intents.tsindex de9b7d10..4123a168 100644--- a/src/components/create/experimental/intents.ts+++ b/src/components/create/experimental/intents.ts@@ -1,6 +1,6 @@import {Image as ImageIcon, Wand2, Scissors, Video, Film, Maximize2, Eraser,- UserRound, Mic, Music, FastForward, PersonStanding,+ UserRound, Mic, Music, FastForward, PersonStanding, Replace,} from 'lucide-react'import type { LucideIcon } from 'lucide-react'import type { CreateBackend, CreateIntent } from '../../../stores/createStore'@@ -178,6 +178,19 @@ export const INTENTS: IntentMeta[] = [cloudOnly: true, hasLocalLane: true, requiresModels: 'motion',examples: [],},+ {+ // Swap Character (07.11.2026, port of the web's C52): a real video keeps+ // its motion, camera, sound and scene, and its people become the people+ // of the customer's photos. Studio models only (lib/render/swap.ts), no+ // local lane: in local mode it is a locked cloud pill like Erase. The+ // pill says "Swap" (the web's desktop word), the full name stands in+ // title and aria-label; the bar has no room for two more words.+ id: 'swap_character', label: 'Swap Character', short: 'Swap', icon: Replace,+ placeholder: '',+ needsSource: false, needsPrompt: false, allowsMask: false, isVideo: true,+ cloudOnly: true,+ examples: [],+ },]export const INTENT_MAP: Record<CreateIntent, IntentMeta> =diff --git a/src/components/create/experimental/laneHint.ts b/src/components/create/experimental/laneHint.tsindex 4995298e..7438f080 100644--- a/src/components/create/experimental/laneHint.ts+++ b/src/components/create/experimental/laneHint.ts@@ -13,7 +13,7 @@ import type { TrainKind } from '../../../lib/train-kind'/** Captions that name the inputs a lane is waiting for. These go stale the* moment the chips are filled, so they hide once the lane reports ready. */const INPUT_HINT_INTENTS: ReadonlySet<CreateIntent> =- new Set(['character', 'lipsync', 'motion'] as CreateIntent[])+ new Set(['character', 'lipsync', 'motion', 'swap_character'] as CreateIntent[])/*** Does the caption name inputs the lane waits for? Such a caption stands@@ -58,6 +58,8 @@ export function noPromptHint(id: CreateIntent, backend: CreateBackend = 'local',return backend === 'local'? 'Add a character image and a driving dance/pose video above, then hit Create. The prompt is optional.': 'No prompt needed. Add a character image and a driving dance/pose video above, then hit Create.'+ case 'swap_character':+ return 'No prompt needed. Add the video and a photo of each new person above, then hit Create.'default:return 'No prompt needed. Just hit Create to remove the background.'}diff --git a/src/components/create/experimental/useStudioPrice.ts b/src/components/create/experimental/useStudioPrice.tsindex 97ac70fe..68794f98 100644--- a/src/components/create/experimental/useStudioPrice.ts+++ b/src/components/create/experimental/useStudioPrice.ts@@ -99,6 +99,8 @@ export function useStudioPrice(seconds: number | undefined,/** Fotos der Referenzleiste neben dem Standbild. */extraPhotos = 0,+ /** Bilder, die einzeln kosten (price.perReference, Swap Character). */+ referenceCount = 0,): StudioPrice | null {// Die Bildzahl, die der Start wirklich schickt: der Anbieter rechnet sie ein// (MiniMax H3 Reference, je Bild). Ohne sie bliebe der Vorab-Preis aus.@@ -116,7 +118,7 @@ export function useStudioPrice(const [error, setError] = useState<{ key: string; message: string } | null>(null)const abort = useRef<AbortController | null>(null)const debouncedPromptLen = useDebouncedValue(prompt.length, PROMPT_DEBOUNCE_MS)- const key = model ? JSON.stringify([model, options, debouncedPromptLen, seconds, images, quotesImages]) : ''+ const key = model ? JSON.stringify([model, options, debouncedPromptLen, seconds, images, quotesImages, referenceCount]) : ''useEffect(() => {abort.current?.abort()@@ -176,8 +178,8 @@ export function useStudioPrice(if (!model) return nullif (error && error.key === key) {- return { credits: createStudioCost(model, options, Array.from(prompt).length, seconds, images ?? 1), live: false, error: error.message }+ return { credits: createStudioCost(model, options, Array.from(prompt).length, seconds, images ?? 1, referenceCount), live: false, error: error.message }}if (live && live.key === key) return { credits: live.credits, live: true }- return { credits: createStudioCost(model, options, Array.from(prompt).length, seconds, images ?? 1), live: false }+ return { credits: createStudioCost(model, options, Array.from(prompt).length, seconds, images ?? 1, referenceCount), live: false }}diff --git a/src/hooks/__tests__/useCloudCreate-swap.test.ts b/src/hooks/__tests__/useCloudCreate-swap.test.tsnew file mode 100644index 00000000..ad64c494--- /dev/null+++ b/src/hooks/__tests__/useCloudCreate-swap.test.ts@@ -0,0 +1,191 @@+/**+ * Swap Character (07.11.2026, port of the web's C52) through the Create+ * tab's start: what goes to the server, what stops before any upload.+ * Nothing is rendered or booked: upload, quote and submit are mocked.+ */+import { describe, it, expect, vi, beforeEach } from 'vitest'++vi.mock('react', async (orig) => {+ const actual = (await orig()) as Record<string, unknown>+ return { ...actual, useCallback: (fn: unknown) => fn }+})++// A full, hand-written mock (no `...actual` spread): the real ../../api/cloud/jobs+// pulls in the Supabase client (api/cloud/supabase.ts), which touches+// `localStorage` at import time and blows up outside a browser-like test+// environment. The established pattern in this directory (see+// useCloudCreate-b3-adult-gate-fires-before-upload.test.ts) is a fake+// CloudJobError/QuoteChangedError pair instead of the real classes.+const hoisted = vi.hoisted(() => {+ class FakeCloudJobError extends Error {+ status: number+ code?: string+ constructor(message: string, status: number, meta?: { code?: string }) {+ super(message)+ this.status = status+ this.code = meta?.code+ }+ }+ class FakeQuoteChangedError extends FakeCloudJobError {+ credits: number+ constructor(message: string, credits: number) {+ super(message, 409, { code: 'quote_changed' })+ this.credits = credits+ }+ }+ const submitted: Array<{ kind: string; model: string; prompt: string; params: Record<string, unknown> }> = []+ const hochgeladen: string[] = []+ return {+ FakeCloudJobError,+ FakeQuoteChangedError,+ submitted,+ hochgeladen,+ uploadInput: vi.fn(async (_blob: unknown, slot: string) => {+ hochgeladen.push(slot)+ return `user-1/staged-${slot}.${slot === 'audio' ? 'mp3' : slot === 'video' ? 'mp4' : 'png'}`+ }),+ getJob: vi.fn(async () => ({ id: 'quelle', result_url: 'https://storage.example/clip.mp4' })),+ submitCloudJob: vi.fn(async (payload: (typeof submitted)[number]) => {+ submitted.push(payload)+ return { id: 'job-test', quota: { cost: 1000, used: 1000, limit: 100000 } }+ }),+ pollJob: vi.fn(async () => ({+ id: 'job-test', kind: 'video', model: 'longcat-avatar', status: 'succeeded',+ result_url: 'https://storage.example/out.mp4', created_at: new Date().toISOString(),+ })),+ cancelJob: vi.fn(async () => ({ status: 'canceled' })),+ studioQuote: vi.fn(async (..._args: unknown[]) => ({ credits: 42 })),+ }+})+const { submitted, hochgeladen } = hoisted++// Sidesteps loadContentPolicy's own call into ../../api/cloud/jobs+// (getContentPolicy). 'off' keeps clientSafety() to its CSAM-only floor,+// same as an account whose policy has not loaded yet.+vi.mock('../useContentPolicy', () => ({+ contentPolicySnapshot: () => 'off' as const,+ loadContentPolicy: async () => 'off' as const,+}))++vi.mock('../../api/cloud/jobs', () => ({+ uploadInput: hoisted.uploadInput,+ getJob: hoisted.getJob,+ submitCloudJob: hoisted.submitCloudJob,+ pollJob: hoisted.pollJob,+ cancelJob: hoisted.cancelJob,+ CloudJobError: hoisted.FakeCloudJobError,+ QuoteChangedError: hoisted.FakeQuoteChangedError,+}))++// Review A1/B3 (Runde 2): useCloudCreate now quotes a Studio run right+// before booking (see useCloudCreate.ts, the "Confirming the price…" step)+// and uses that number as max_credits. A fixed 42 keeps every existing+// assertion below about the OTHER params fields unaffected; the dedicated+// max_credits/quote_changed behavior gets its own tests further down.+vi.mock('../../api/cloud/studio', () => ({+ studioQuote: hoisted.studioQuote,+ StudioQuoteChangedError: hoisted.FakeQuoteChangedError,+}))++import { useCloudCreate } from '../useCloudCreate'+import { useCreateStore } from '../../stores/createStore'+import { useCloudCatalogStore } from '../../stores/cloudCatalogStore'+import { neuerServer } from '../../lib/render/__tests__/fixtures/test-catalogs'+import { SWAP_CONSENT_MISSING } from '../../lib/render/swap'++const FOTO = { filename: 'face.png', url: 'data:image/png;base64,AA', width: 512, height: 768 }+const CLIP = { name: 'dance.mp4', url: 'blob:dance', blob: new Blob(['x'], { type: 'video/mp4' }) }++beforeEach(() => {+ submitted.length = 0+ hochgeladen.length = 0+ hoisted.studioQuote.mockClear()+ hoisted.studioQuote.mockResolvedValue({ credits: 42 })+ hoisted.uploadInput.mockClear()+ hoisted.submitCloudJob.mockClear()+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, blob: async () => new Blob(['x']) })))+ useCreateStore.setState({+ isGenerating: false, error: null, backend: 'cloud',+ source: null, audioInput: null, videoInput: null, voiceFromJob: null,+ extendSource: null, gallery: [], cloudStudioOptions: {}, cloudStudioCredits: null, cloudOpModel: '',+ })+ useCreateStore.getState().setPrompt('left from another tab')+ useCloudCatalogStore.setState({ models: neuerServer() })+ useCreateStore.getState().setIntent('swap_character')+ useCreateStore.setState({ swapFigures: [{ image: null, role: '' }], swapSeconds: null, swapConsent: false })+})++describe('Swap Character from the Create tab', () => {+ it('sends a studio run with every photo, the roles, the length and the consent, and no prompt', async () => {+ useCreateStore.setState({+ videoInput: CLIP, swapSeconds: 10, swapConsent: true,+ swapFigures: [{ image: FOTO, role: 'the woman on the left' }, { image: FOTO, role: '' }],+ cloudStudioOptions: { resolution: '480p' },+ })+ await useCloudCreate().generate()+ expect(useCreateStore.getState().error).toBeNull()+ expect(submitted).toHaveLength(1)+ const p = submitted[0].params+ expect(submitted[0].model).toBe('openjutsu-character-swap')+ expect(submitted[0].kind).toBe('video')+ expect(submitted[0].prompt).toBe('')+ expect(p.op).toBe('studio')+ expect(p.video_path).toBe('user-1/staged-video.mp4')+ expect(p.image_paths).toEqual(['user-1/staged-source.png', 'user-1/staged-source.png'])+ expect(p.source_path).toBeUndefined()+ expect(p.studio_options).toEqual({ resolution: '480p', roles: ['the woman on the left', 'the second person from the left'] })+ expect(p.clip_seconds).toBe(10)+ expect(p.swap_consent).toBe(true)+ expect(p.label).toBe('Swap Character')+ expect(p.max_credits).toBe(42)+ expect(hochgeladen).toEqual(['video', 'source', 'source'])+ // The quote sees what the run sends: the cut length and the roles.+ const quoted = hoisted.studioQuote.mock.calls[0] as unknown[]+ expect(quoted[0]).toBe('openjutsu-character-swap')+ expect(quoted[2]).toMatchObject({ clip_seconds: 10, swap_consent: true, image_paths: p.image_paths, studio_options: p.studio_options })+ })++ it('runs Wan 2.2 Animate as replace with the photo as still', async () => {+ useCreateStore.getState().setCloudOpModel('wan-2.2-animate-replace')+ useCreateStore.setState({ videoInput: CLIP, swapSeconds: 60, swapConsent: true, swapFigures: [{ image: FOTO, role: '' }] })+ await useCloudCreate().generate()+ expect(submitted).toHaveLength(1)+ const p = submitted[0].params+ expect(submitted[0].model).toBe('wan-2.2-animate-replace')+ expect(p.source_path).toBe('user-1/staged-source.png')+ expect(p.image_paths).toBeUndefined()+ expect(p.studio_options).toEqual({ mode: 'replace' })+ expect(p.clip_seconds).toBe(60)+ expect(p.swap_consent).toBe(true)+ })++ it('stops before any upload without the consent, with the server sentence', async () => {+ useCreateStore.setState({ videoInput: CLIP, swapFigures: [{ image: FOTO, role: '' }], swapConsent: false })+ await useCloudCreate().generate()+ expect(useCreateStore.getState().error).toBe(SWAP_CONSENT_MISSING)+ expect(hoisted.uploadInput).not.toHaveBeenCalled()+ expect(submitted).toHaveLength(0)+ })++ it('stops before any upload while a person has no photo', async () => {+ useCreateStore.setState({ videoInput: CLIP, swapConsent: true, swapFigures: [{ image: FOTO, role: '' }, { image: null, role: '' }] })+ await useCloudCreate().generate()+ expect(useCreateStore.getState().error).toBe('Add a photo for person 2, or remove that person.')+ expect(hoisted.uploadInput).not.toHaveBeenCalled()+ })++ it('never sends the Stage source of another tab', async () => {+ useCreateStore.setState({ source: { ...FOTO, filename: 'other.png' }, videoInput: CLIP, swapConsent: true, swapFigures: [{ image: FOTO, role: '' }] })+ await useCloudCreate().generate()+ expect(submitted[0].params.source_path).toBeUndefined()+ expect(submitted[0].params.image_paths).toEqual(['user-1/staged-source.png'])+ })++ it('refuses on a server whose catalogue does not list the swap models', async () => {+ useCloudCatalogStore.setState({ models: neuerServer().filter((m) => !['openjutsu-character-swap', 'wan-2.2-animate-replace', 'scail-2'].includes(m.id)) })+ useCreateStore.setState({ videoInput: CLIP, swapConsent: true, swapFigures: [{ image: FOTO, role: '' }] })+ await useCloudCreate().generate()+ expect(useCreateStore.getState().error).toBe('Swap Character needs a newer LU Cloud. Try again later.')+ expect(submitted).toHaveLength(0)+ })+})diff --git a/src/hooks/useCloudCreate.ts b/src/hooks/useCloudCreate.tsindex 59e11271..5b0e9023 100644--- a/src/hooks/useCloudCreate.ts+++ b/src/hooks/useCloudCreate.ts@@ -40,6 +40,8 @@ import { intentRoles, intentRequiredInputs, isStudioModel, resolveIntentPick, stimport { bumpSeed, runImageCount } from '../lib/render/image-count'import { STUDIO_MODELS, studioFields } from '../lib/render/studio-contract'import { modelLabel } from '../lib/render/preset-models'+import { isSwapIntent, SWAP_GALLERY_LABEL } from '../lib/render/swap'+import { swapInputError, swapRunParams } from '../lib/create/swap-run'import { IMPROVING_PROMPT } from '../lib/render/improve-prompt'import { improveKindForRun } from '../lib/render/music-ui'import { intentTakesPrompt } from '../components/create/experimental/intents'@@ -407,7 +409,21 @@ export function useCloudCreate(opts: { onQuotaChange?: () => void } = {}) {s.setError('Pick one of your cloud videos to extend.')return}- if (op === 'motion' && (!s.source || !s.videoInput)) {+ // Swap Character (07.11.2026): runs studio models only. A server whose+ // catalogue does not list them yet leaves the pick without a studio model;+ // that run would go out as a plain motion job, so it stops here.+ const swap = isSwapIntent(intent)+ if (swap) {+ if (!studioModel) {+ s.setError('Swap Character needs a newer LU Cloud. Try again later.')+ return+ }+ const invalid = swapInputError(studioModel, { hasVideo: !!s.videoInput, figures: s.swapFigures, consent: s.swapConsent })+ if (invalid) {+ s.setError(invalid)+ return+ }+ } else if (op === 'motion' && (!s.source || !s.videoInput)) {s.setError('Motion control needs a character image and a driving video.')return}@@ -530,7 +546,8 @@ export function useCloudCreate(opts: { onQuotaChange?: () => void } = {}) {// Also exactly what a Studio role's `image` input needs (source_path),// the SAME staged upload, studio-contract.ts just names it a schema// field instead of a fixed param.- if (op !== 'generate' && s.source) {+ // Swap reads its own people (below), never the Stage's source.+ if (op !== 'generate' && s.source && !swap) {params.source_path = await uploadInput(dataUrlToBlob(s.source.url), 'source', ...uploadEnds(ac))// Ein Studio-Modell, das eine Bilderliste liest (Edit mit mehreren// Vorlagen, Referenz zu Video), bekommt das Standbild der Oberflaeche als@@ -584,6 +601,21 @@ export function useCloudCreate(opts: { onQuotaChange?: () => void } = {}) {s.setProgress(6, 'Uploading video…')params.video_path = await uploadInput(s.videoInput.blob, 'video', ...uploadEnds(ac))}+ if (swap && studioModel) {+ // The people of the panel: a photo each (a list with roles for the+ // main model, the first photo as the still for a one-person model),+ // the options the mode fixes, the length and the consent.+ Object.assign(params, await swapRunParams(+ studioModel,+ { hasVideo: !!s.videoInput, figures: s.swapFigures, consent: s.swapConsent, chosenSeconds: s.swapSeconds },+ studioOptionsFiltered ?? {},+ async (image, i, total) => {+ s.setProgress(7, `Uploading photos… ${i + 1}/${total}`)+ return uploadInput(dataUrlToBlob(image.url), 'source', ...uploadEnds(ac))+ },+ ))+ if (ac.signal.aborted) return+ }if (op === 'lipsync') {if (s.audioInput) {s.setProgress(8, 'Uploading audio…')@@ -697,12 +729,15 @@ export function useCloudCreate(opts: { onQuotaChange?: () => void } = {}) {if (studioModel) {s.setProgress(9, 'Confirming the price…')const quoteFields: Record<string, unknown> = {}- for (const k of ['source_path', 'image_paths', 'mask_path', 'audio_path', 'audio2_path', 'video_path', 'last_image_path', 'shot_type'] as const) {+ // clip_seconds: the server cuts a swap video for the quote as for the+ // run, so both price the same seconds.+ for (const k of ['source_path', 'image_paths', 'mask_path', 'audio_path', 'audio2_path', 'video_path', 'last_image_path', 'shot_type', 'clip_seconds', 'swap_consent'] as const) {if (params[k] !== undefined) quoteFields[k] = params[k]}const quote = await studioQuote(studioModel, runPrompt, {op: 'studio',- studio_options: studioOptionsFiltered ?? {},+ // A swap run carries its roles and fixed mode in params.studio_options.+ studio_options: params.studio_options ?? studioOptionsFiltered ?? {},...quoteFields,})// Review A kleiner Punkt 1 (Runde 3, 20.09.2026): the cap is the@@ -749,7 +784,7 @@ export function useCloudCreate(opts: { onQuotaChange?: () => void } = {}) {// list view (GET /api/jobs), not the only source of the gallery name.let label: string | undefinedif (studioModel) {- label = prompt.trim() ? undefined : modelLabel(studioModel)+ label = swap ? SWAP_GALLERY_LABEL : prompt.trim() ? undefined : modelLabel(studioModel)if (label) params.label = label} else if (OP_GALLERY_LABEL[op]) {label = OP_GALLERY_LABEL[op]diff --git a/src/lib/__tests__/howto-lines-follow-the-film.test.ts b/src/lib/__tests__/howto-lines-follow-the-film.test.tsindex a6d71070..d9ff1a5f 100644--- a/src/lib/__tests__/howto-lines-follow-the-film.test.ts+++ b/src/lib/__tests__/howto-lines-follow-the-film.test.ts@@ -4,15 +4,23 @@ import { resolve } from 'node:path'import { HOWTO, HOWTO_GUIDE_BASE, HOWTO_VIDEO_BASE, howtoGuideUrl, howtoLineAt, howtoVideoUrl, stageHowtoTopic } from '../howto'import { INTENTS } from '../../components/create/experimental/intents'+// Swap Character (07.11.2026) has no film yet: it is recorded once the tab is+// live on the cloud. Until then the tab names none (stageHowtoTopic below+// finds no topic, and its Stage shows no how-to line), instead of a link to+// a film that is not there.+const NO_FILM_YET = new Set(['swap_character'])+const FILMED = INTENTS.filter((i) => !NO_FILM_YET.has(i.id))+describe('how it works', () => {it('has a film for every Create tab, for Code and for Agent', () => {- for (const intent of INTENTS) expect(HOWTO[intent.id], intent.id).toBeTruthy()+ for (const intent of FILMED) expect(HOWTO[intent.id], intent.id).toBeTruthy()+ for (const id of NO_FILM_YET) expect(stageHowtoTopic(id, 'cloud'), id).toBeNull()expect(HOWTO.code.films.map((f) => f.label)).toEqual(['Modes', 'Slash commands'])expect(HOWTO.agent).toBeTruthy()})it('names each Create film after the tab it stands on', () => {- for (const intent of INTENTS) expect(HOWTO[intent.id].title).toBe(`How ${intent.short} works`)+ for (const intent of FILMED) expect(HOWTO[intent.id].title).toBe(`How ${intent.short} works`)})it('keeps the lines of every film in the order they are shown', () => {diff --git a/src/lib/create/__tests__/swap.test.ts b/src/lib/create/__tests__/swap.test.tsnew file mode 100644index 00000000..cc95faba--- /dev/null+++ b/src/lib/create/__tests__/swap.test.ts@@ -0,0 +1,208 @@+/**+ * Swap Character on the desktop (07.11.2026, port of the web's C52): model+ * choice, limits, the check before a run, what a run sends, and the price+ * against the provider's own examples (0.15/0.17/0.20/0.40 $ per input+ * second, at least 3 s, plus 0.02 $ per photo).+ *+ * Pure: no store, no network. The upload is a fake that hands back a path.+ */+import { describe, expect, it } from 'vitest'+import {+ SWAP_CONSENT_MISSING, SWAP_CONSENT_MODELS, SWAP_LONG_MODEL, SWAP_MAIN_MODEL, SWAP_MODELS,+ swapAutoModel, swapBilledPhotos, swapClipCredits, swapClipLimits, swapClipSeconds, swapFixedOptions,+ swapMaxPeople, swapNeedsConsent, swapPanelFields, swapPricedSeconds, swapReadsRoles, swapRoles, swapShortCredits,+} from '../../render/swap'+import { swapInputError, swapReady, swapRunParams } from '../swap-run'+import { STUDIO_MODELS, studioCredits, studioFields, studioOptions, studioPreviewCredits } from '../../render/studio-contract'+import { createStudioCost } from '../../render/create-studio'++const PHOTO = { url: 'data:image/png;base64,AA' }+const one = [{ image: PHOTO, role: '' }]+const credits = (usd: number) => Math.round(usd * 100000)++describe('the catalogue', () => {+ it('knows both new models under neutral endpoints, and SCAIL 2', () => {+ for (const id of SWAP_MODELS) expect(STUDIO_MODELS[id], id).toBeDefined()+ expect(STUDIO_MODELS[SWAP_MAIN_MODEL].endpoint).toBe('base/openjutsu/character-swap')+ expect(STUDIO_MODELS[SWAP_LONG_MODEL].endpoint).toBe('base/wan-2.2/animate')+ expect(STUDIO_MODELS[SWAP_MAIN_MODEL].inputs).toEqual({ video: 'video_path', images: 'image_paths' })+ expect(STUDIO_MODELS[SWAP_LONG_MODEL].defaults).toEqual({ mode: 'replace' })+ })++ it('offers roles, resolution 480p to 1080p (768p default) and seed on the main model', () => {+ const f = studioFields(SWAP_MAIN_MODEL)+ expect(Object.keys(f).sort()).toEqual(['resolution', 'roles', 'seed'])+ expect(f.resolution.enum).toEqual(['480p', '540p', '768p', '1080p'])+ expect(studioOptions(SWAP_MAIN_MODEL, '', undefined, false)).toEqual({ resolution: '768p' })+ expect(swapReadsRoles(SWAP_MAIN_MODEL)).toBe(true)+ expect(swapReadsRoles(SWAP_LONG_MODEL)).toBe(false)+ })++ it('holds each role to 200 characters (maxLength in the contract)', () => {+ expect(() => studioOptions(SWAP_MAIN_MODEL, '', { roles: ['a'.repeat(200)] }, false)).not.toThrow()+ expect(() => studioOptions(SWAP_MAIN_MODEL, '', { roles: ['a'.repeat(201)] }, false)).toThrow('Invalid roles')+ expect(() => studioOptions(SWAP_MAIN_MODEL, '', { roles: ['a', 'b', 'c', 'd', 'e'] }, false)).toThrow('Invalid roles')+ })+})++describe('model choice and limits', () => {+ it('runs up to 15 s on the main model, longer on Wan 2.2 Animate, several people always on the main model', () => {+ expect(swapAutoModel(undefined, 1)).toBe(SWAP_MAIN_MODEL)+ expect(swapAutoModel(15, 1)).toBe(SWAP_MAIN_MODEL)+ expect(swapAutoModel(15.4, 1)).toBe(SWAP_LONG_MODEL)+ expect(swapAutoModel(60, 1)).toBe(SWAP_LONG_MODEL)+ expect(swapAutoModel(60, 2)).toBe(SWAP_MAIN_MODEL)+ })++ it('knows the span of each model', () => {+ expect(swapClipLimits(SWAP_MAIN_MODEL)).toEqual({ min: 2, max: 15, billedMin: 3 })+ expect(swapClipLimits(SWAP_LONG_MODEL)).toEqual({ min: 1, max: 120, billedMin: 3 })+ expect(swapMaxPeople(SWAP_MAIN_MODEL)).toBe(4)+ expect(swapMaxPeople(SWAP_LONG_MODEL)).toBe(1)+ expect(swapMaxPeople('scail-2')).toBe(1)+ })++ it('clips the length to the model and the video', () => {+ expect(swapClipSeconds(SWAP_MAIN_MODEL, null)).toBe(15)+ expect(swapClipSeconds(SWAP_MAIN_MODEL, 40)).toBe(15)+ expect(swapClipSeconds(SWAP_MAIN_MODEL, 1)).toBe(2)+ expect(swapClipSeconds(SWAP_MAIN_MODEL, null, 9.7)).toBe(9)+ expect(swapClipSeconds(SWAP_LONG_MODEL, 90, 200)).toBe(90)+ expect(swapPricedSeconds(SWAP_MAIN_MODEL, null, 40)).toBe(15)+ expect(swapPricedSeconds(SWAP_MAIN_MODEL, 10, 40)).toBe(10)+ expect(swapPricedSeconds(SWAP_MAIN_MODEL, null, 8.2)).toBe(8.2)+ })++ it('fixes mode replace on Wan 2.2 Animate and SCAIL 2, nothing on the main model', () => {+ expect(swapFixedOptions('swap_character', SWAP_LONG_MODEL)).toEqual({ mode: 'replace' })+ expect(swapFixedOptions('swap_character', 'scail-2')).toEqual({ mode: 'replace' })+ expect(swapFixedOptions('swap_character', SWAP_MAIN_MODEL)).toEqual({})+ // Motion Control keeps SCAIL 2 as animate.+ expect(swapFixedOptions('motion', 'scail-2')).toEqual({})+ expect(swapPanelFields('swap_character')).toEqual(['roles', 'resolution', 'mode'])+ expect(swapPanelFields('motion')).toEqual([])+ })+})++describe('the price, against the provider page', () => {+ it('10 s at 480p with 1 photo is 1.52 $', () => {+ expect(studioCredits(SWAP_MAIN_MODEL, { resolution: '480p' }, 10, 1, 100, 1)).toBe(credits(1.52))+ expect(swapClipCredits(SWAP_MAIN_MODEL, { resolution: '480p' }, 10, 1)).toBe(credits(1.52))+ })++ it('10 s at 768p with 2 photos is 2.04 $', () => {+ expect(studioCredits(SWAP_MAIN_MODEL, { resolution: '768p' }, 10, 1, 100, 2)).toBe(credits(2.04))+ expect(swapClipCredits(SWAP_MAIN_MODEL, { resolution: '768p' }, 10, 2)).toBe(credits(2.04))+ })++ it('15 s at 768p with 1 photo is 3.02 $', () => {+ expect(studioCredits(SWAP_MAIN_MODEL, { resolution: '768p' }, 15, 1, 100, 1)).toBe(credits(3.02))+ expect(swapClipCredits(SWAP_MAIN_MODEL, { resolution: '768p' }, 15, 1)).toBe(credits(3.02))+ })++ it('the preview of the Create button counts the same (default 768p, photos billed)', () => {+ expect(studioPreviewCredits(SWAP_MAIN_MODEL, {}, 10, 1, 100, 2)).toBe(credits(2.04))+ expect(createStudioCost(SWAP_MAIN_MODEL, { resolution: '480p' }, 100, 10, 1, swapBilledPhotos(SWAP_MAIN_MODEL, 1))).toBe(credits(1.52))+ })++ it('bills at least 3 s and every started second', () => {+ expect(swapClipCredits(SWAP_MAIN_MODEL, { resolution: '768p' }, 2, 1)).toBe(credits(0.62))+ expect(swapClipCredits(SWAP_MAIN_MODEL, { resolution: '768p' }, 9.2, 1)).toBe(credits(2.02))+ })++ it('bills no photo on Wan 2.2 Animate, 0.08 $ per second at 720p', () => {+ expect(swapBilledPhotos(SWAP_LONG_MODEL, 1)).toBe(0)+ expect(swapClipCredits(SWAP_LONG_MODEL, { resolution: '720p' }, 60, 0)).toBe(credits(4.8))+ expect(studioCredits(SWAP_LONG_MODEL, { resolution: '720p', mode: 'replace' }, 60)).toBe(credits(4.8))+ })++ it('writes the price short for the button', () => {+ expect(swapShortCredits(950)).toBe('950')+ expect(swapShortCredits(152000)).toBe('152k')+ expect(swapShortCredits(1520)).toBe('1.5k')+ })+})++describe('roles', () => {+ it('sends none while every role is empty, and fills an empty one from the left once one is set', () => {+ expect(swapRoles([{ role: '' }])).toBeUndefined()+ expect(swapRoles([{ role: ' ' }, { role: '' }])).toBeUndefined()+ expect(swapRoles([{ role: 'the man in red' }, { role: '' }])).toEqual(['the man in red', 'the second person from the left'])+ expect(swapRoles([{ role: 'x'.repeat(250) }])![0]).toHaveLength(200)+ })+})++describe('the check before a run', () => {+ const ok = { hasVideo: true, figures: one, consent: true }++ it('wants the video, a photo for every person and the consent', () => {+ expect(swapInputError(SWAP_MAIN_MODEL, { ...ok, hasVideo: false })).toBe('Add the original video first.')+ expect(swapInputError(SWAP_MAIN_MODEL, { ...ok, figures: [{ image: null, role: '' }] })).toBe('Add a photo of the new person.')+ expect(swapInputError(SWAP_MAIN_MODEL, { ...ok, figures: [...one, { image: null, role: '' }] }))+ .toBe('Add a photo for person 2, or remove that person.')+ expect(swapInputError(SWAP_MAIN_MODEL, { ...ok, consent: false })).toBe(SWAP_CONSENT_MISSING)+ expect(swapInputError(SWAP_MAIN_MODEL, ok)).toBeNull()+ expect(swapReady(SWAP_MAIN_MODEL, ok)).toBe(true)+ })++ it('refuses several people on a one-person model instead of switching silently', () => {+ expect(swapInputError(SWAP_LONG_MODEL, { ...ok, figures: [...one, ...one] }))+ .toBe('This model replaces one person. Use OpenJutsu for up to 4 people, or remove the others.')+ })++ it('refuses a role over 200 characters', () => {+ expect(swapInputError(SWAP_MAIN_MODEL, { ...ok, figures: [{ image: PHOTO, role: 'r'.repeat(201) }] }))+ .toBe('Keep each role under 200 characters.')+ })++ it('asks consent for the two new models only, SCAIL 2 runs without', () => {+ expect([...SWAP_CONSENT_MODELS]).toEqual([SWAP_MAIN_MODEL, SWAP_LONG_MODEL])+ expect(swapNeedsConsent('scail-2')).toBe(false)+ expect(swapInputError('scail-2', { ...ok, consent: false })).toBeNull()+ expect(swapInputError(SWAP_LONG_MODEL, { ...ok, consent: false })).toBe(SWAP_CONSENT_MISSING)+ })+})++describe('what a run sends', () => {+ const upload = async (_image: unknown, i: number) => `user-1/photo-${i + 1}.png`++ it('main model: every photo in order, the roles, the length and the consent', async () => {+ const out = await swapRunParams(SWAP_MAIN_MODEL, {+ hasVideo: true, consent: true, chosenSeconds: 10,+ figures: [{ image: PHOTO, role: 'the woman on the left' }, { image: PHOTO, role: '' }],+ }, { resolution: '480p' }, upload)+ expect(out).toEqual({+ image_paths: ['user-1/photo-1.png', 'user-1/photo-2.png'],+ studio_options: { resolution: '480p', roles: ['the woman on the left', 'the second person from the left'] },+ clip_seconds: 10,+ swap_consent: true,+ })+ // The options pass the contract the server checks.+ expect(() => studioOptions(SWAP_MAIN_MODEL, '', out.studio_options, false)).not.toThrow()+ })++ it('main model with one photo and no role: no roles, the whole 15 s', async () => {+ const out = await swapRunParams(SWAP_MAIN_MODEL, { hasVideo: true, consent: true, chosenSeconds: null, figures: one }, {}, upload)+ expect(out.image_paths).toEqual(['user-1/photo-1.png'])+ expect(out.studio_options).toEqual({})+ expect(out.clip_seconds).toBe(15)+ expect(out.source_path).toBeUndefined()+ })++ it('Wan 2.2 Animate: the photo as still, mode replace, up to 120 s', async () => {+ const out = await swapRunParams(SWAP_LONG_MODEL, { hasVideo: true, consent: true, chosenSeconds: 75, figures: one }, { resolution: '720p', mode: 'animate' }, upload)+ expect(out).toEqual({+ source_path: 'user-1/photo-1.png',+ studio_options: { resolution: '720p', mode: 'replace' },+ clip_seconds: 75,+ swap_consent: true,+ })+ })++ it('SCAIL 2: mode replace, no consent field', async () => {+ const out = await swapRunParams('scail-2', { hasVideo: true, consent: false, chosenSeconds: 30, figures: one }, {}, upload)+ expect(out.studio_options).toEqual({ mode: 'replace' })+ expect(out.swap_consent).toBeUndefined()+ expect(out.source_path).toBe('user-1/photo-1.png')+ })+})diff --git a/src/lib/create/bridge/create-store.ts b/src/lib/create/bridge/create-store.tsindex 0475890a..7bbbd4f1 100644--- a/src/lib/create/bridge/create-store.ts+++ b/src/lib/create/bridge/create-store.ts@@ -1,4 +1,10 @@// The Create subcategories as the web app names them. The web keeps// 'video_upscale' as its own intent; on the desktop the Create tab reaches it// from the gallery, and the type that carries all thirteen is StudioIntent.-export type { StudioIntent as CreateIntent } from '../../render/create-studio'+//+// Swap Character is left out, as on the web (chat-catalog ChatIntent): Create+// in chat cannot order it, it needs the customer's video and one photo per+// person, and the chat order has no such places. The Create tab runs it+// through useCloudCreate and lib/create/swap-run.ts, not through engine.ts.+import type { StudioIntent } from '../../render/create-studio'+export type CreateIntent = Exclude<StudioIntent, 'swap_character'>diff --git a/src/lib/create/swap-run.ts b/src/lib/create/swap-run.tsnew file mode 100644index 00000000..fb71f5c9--- /dev/null+++ b/src/lib/create/swap-run.ts@@ -0,0 +1,82 @@+// What a Swap Character run checks and sends. Pure, apart from the upload+// callback it is handed, so the rules are tested without a store or network.+//+// On the web these rules sit in lib/create/engine.ts (validateCreateJob,+// buildCreateParams). The desktop's engine.ts is the mirror of the web engine+// for Create in chat, which cannot order a swap; the Create tab starts its+// runs in hooks/useCloudCreate.ts and reads them from here. Sentences and+// fields are the web's, so a desktop run books and fails like a web run.++import { STUDIO_MODELS } from '../render/studio-contract'+import {+ swapClipSeconds, swapFixedOptions, swapMaxPeople, swapNeedsConsent, swapReadsRoles, swapRoles,+ SWAP_CONSENT_MISSING, SWAP_INTENT,+} from '../render/swap'+import type { CloudJobParams } from '../../api/cloud/jobs'++/** One new person as the run sees it. `image` is whatever the caller uploads. */+export interface SwapRunFigure<T> { image: T | null; role: string }++export interface SwapRunState<T> {+ /** The original video is there. */+ hasVideo: boolean+ figures: SwapRunFigure<T>[]+ /** The consent box is ticked. */+ consent: boolean+}++/** Why this run cannot start, or null. The same order as the web engine. */+export function swapInputError<T>(model: string, s: SwapRunState<T>): string | null {+ if (!s.hasVideo) return 'Add the original video first.'+ const figures = s.figures+ if (!figures.length || !figures[0].image) return 'Add a photo of the new person.'+ const missing = figures.findIndex((f) => !f.image)+ if (missing >= 0) return `Add a photo for person ${missing + 1}, or remove that person.`+ // No silent model switch: the panel switches to the main model when a+ // second person is added, and says so.+ if (figures.length > swapMaxPeople(model)) {+ return swapMaxPeople(model) === 1+ ? 'This model replaces one person. Use OpenJutsu for up to 4 people, or remove the others.'+ : `This model replaces at most ${swapMaxPeople(model)} people.`+ }+ if (figures.some((f) => f.role.length > 200)) return 'Keep each role under 200 characters.'+ if (swapNeedsConsent(model) && !s.consent) return SWAP_CONSENT_MISSING+ return null+}++/** Is the Create button armed for these inputs? The same rule as above. */+export function swapReady<T>(model: string, s: SwapRunState<T>): boolean {+ return swapInputError(model, s) === null+}++/** The part of the params a swap run adds: the photos (a list with roles for+ * the main model, the first photo as the still for a one-person model), the+ * options the mode fixes, the chosen length and the consent. Uploads go+ * through `upload` in the order of the people; `roles` and the provider's+ * picture order point at that order. */+export async function swapRunParams<T>(+ model: string,+ s: SwapRunState<T> & { chosenSeconds: number | null },+ studioOptions: Record<string, unknown>,+ upload: (image: T, index: number, total: number) => Promise<string>,+): Promise<Pick<CloudJobParams, 'image_paths' | 'source_path' | 'studio_options' | 'clip_seconds' | 'swap_consent'>> {+ const out: Pick<CloudJobParams, 'image_paths' | 'source_path' | 'studio_options' | 'clip_seconds' | 'swap_consent'> = {}+ const figures = s.figures.filter((f): f is SwapRunFigure<T> & { image: T } => f.image !== null)+ const reads = Object.values(STUDIO_MODELS[model]?.inputs ?? {})+ let options: Record<string, unknown> = { ...studioOptions, ...swapFixedOptions(SWAP_INTENT, model) }+ if (figures.length && reads.includes('image_paths')) {+ const paths: string[] = []+ for (const [i, f] of figures.entries()) paths.push(await upload(f.image, i, figures.length))+ out.image_paths = paths+ const roles = swapReadsRoles(model) ? swapRoles(figures) : undefined+ if (roles) options = { ...options, roles }+ } else if (figures.length && reads.includes('source_path')) {+ out.source_path = await upload(figures[0].image, 0, 1)+ }+ out.studio_options = options+ // The length that runs, never more than the model reads. The server cuts a+ // longer video to exactly these seconds.+ out.clip_seconds = swapClipSeconds(model, s.chosenSeconds)+ if (swapNeedsConsent(model) && s.consent) out.swap_consent = true+ return out+}diff --git a/src/lib/render/__tests__/alter-server.test.ts b/src/lib/render/__tests__/alter-server.test.tsindex 8f21aced..f2f0a3d9 100644--- a/src/lib/render/__tests__/alter-server.test.ts+++ b/src/lib/render/__tests__/alter-server.test.ts@@ -32,7 +32,8 @@ describe('der alte Katalog ist wirklich der alte', () => {expect(m.weights, m.id).toBeUndefined()}const ids = new Set(alt.map((m) => m.id))- expect(neueIds()).toHaveLength(8)+ // Eight from 02.10.2026, plus the two Swap Character models (07.11.2026).+ expect(neueIds()).toHaveLength(10)for (const id of neueIds()) expect(ids.has(id), id).toBe(false)// Der neue Katalog hat dagegen alles.expect(neuerServer().length).toBeGreaterThanOrEqual(alt.length + 8)diff --git a/src/lib/render/__tests__/cloud-jobs.test.ts b/src/lib/render/__tests__/cloud-jobs.test.tsindex cd4e37c2..1583e5eb 100644--- a/src/lib/render/__tests__/cloud-jobs.test.ts+++ b/src/lib/render/__tests__/cloud-jobs.test.ts@@ -21,6 +21,9 @@ describe('intentToJob', () => {music: { kind: 'audio', op: 'music' },extend: { kind: 'video', op: 'extend' },motion: { kind: 'video', op: 'motion' },+ // Swap Character runs studio models (op 'studio' at submit); the op here+ // says which inputs are gathered, a video as for Motion.+ swap_character: { kind: 'video', op: 'motion' },}for (const [intent, expected] of Object.entries(cases)) {expect(intentToJob(intent as CreateIntent)).toEqual(expected)diff --git a/src/lib/render/__tests__/preset-models.test.ts b/src/lib/render/__tests__/preset-models.test.tsindex 65da12a9..00c299b4 100644--- a/src/lib/render/__tests__/preset-models.test.ts+++ b/src/lib/render/__tests__/preset-models.test.ts@@ -24,7 +24,7 @@// behaupten, die die Testumgebung ohne Netz gar nicht hat.import { beforeEach, describe, expect, it } from 'vitest'import {- ALL_ROLES, classicCredits, presetModels, requiredRoleInputs, roleForModel,+ ALL_ROLES, SWAP_ROLES, classicCredits, presetModels, requiredRoleInputs, roleForModel,roleHasChoice, roleInputs,} from '../preset-models'import { CREATE_PRESETS } from '../create-presets'@@ -135,7 +135,11 @@ describe('jedes waehlbare Modell faehrt seinen Schritt', () => {it('jedes Studio-Modell gehoert zu genau einer Rolle', () => {for (const id of Object.keys(STUDIO_MODELS)) {- const roles = ALL_ROLES.filter((r) => presetModels(r).some((m) => m.id === id))+ // Swap Character uses SCAIL 2 of Motion on purpose (SWAP_ROLES, as on+ // the web). The rule holds for every other role; a model that is only+ // in a swap role belongs to that one.+ const others = ALL_ROLES.filter((r) => !SWAP_ROLES.includes(r) && presetModels(r).some((m) => m.id === id))+ const roles = others.length ? others : ALL_ROLES.filter((r) => presetModels(r).some((m) => m.id === id))expect(roles, id).toHaveLength(1)expect(roleForModel(id), id).toBe(roles[0])}diff --git a/src/lib/render/cloud-jobs.ts b/src/lib/render/cloud-jobs.tsindex cc02b688..bcd9eb00 100644--- a/src/lib/render/cloud-jobs.ts+++ b/src/lib/render/cloud-jobs.ts@@ -12,7 +12,7 @@// too and which therefore cannot name CreateIntent either.export type CreateIntentLike =| 'image' | 'edit' | 'removebg' | 'video' | 'animate' | 'upscale' | 'eraser'- | 'character' | 'lipsync' | 'music' | 'extend' | 'motion'+ | 'character' | 'lipsync' | 'music' | 'extend' | 'motion' | 'swap_character'export type RenderKind = 'image' | 'video' | 'audio'// 'upscale'/'eraser' are hosted utility endpoints (super-resolution /@@ -79,6 +79,10 @@ export function intentToJob(intent: CreateIntentLike): { kind: RenderKind; op: Rreturn { kind: 'video', op: 'extend' }case 'motion':return { kind: 'video', op: 'motion' }+ // Swap Character runs studio models only (op 'studio' at submit). The op+ // here says which inputs are gathered: a video, as for Motion.+ case 'swap_character':+ return { kind: 'video', op: 'motion' }default:return { kind: 'image', op: 'generate' }}diff --git a/src/lib/render/create-studio.ts b/src/lib/render/create-studio.tsindex a1427cdf..f2fc566c 100644--- a/src/lib/render/create-studio.ts+++ b/src/lib/render/create-studio.ts@@ -41,6 +41,7 @@ const INTENT_ROLE: Partial<Record<StudioIntent, StepRole[]>> = {music: ['music'],extend: ['extend'],motion: ['motion'],+ swap_character: ['swap-character'],video_upscale: ['upscale'],}@@ -153,8 +154,10 @@ export function createStudioCost(promptLength = 100,seconds?: number,imageCount = 1,+ /** Photos billed one by one (price.perReference, Swap Character). */+ referenceCount = 0,): number {- return studioPreviewCredits(model, options, seconds, imageCount, promptLength) ?? studioBaseCredits(model)+ return studioPreviewCredits(model, options, seconds, imageCount, promptLength, referenceCount) ?? studioBaseCredits(model)}/** What a control of this model shows: the customer's own value, else thediff --git a/src/lib/render/preset-models.ts b/src/lib/render/preset-models.tsindex b22ce1eb..bca722db 100644--- a/src/lib/render/preset-models.ts+++ b/src/lib/render/preset-models.ts@@ -15,12 +15,15 @@ import {STUDIO_EDIT_MODELS, studioImageToVideo, studioReferenceVideo, studioTextToVideo,} from './studio-roles'import type { RenderKind, RenderOp } from './cloud-jobs'+import { SWAP_MODELS } from './swap'export type StepRole =| 'image' | 'animate' | 'soundtrack' | 'speech' | 'music' | 'talking' | 'presenter'| 'duo' | 'extend' | 'motion' | 'restyle' | 'angles' | 'edit' | 'upscale'// 02.10.2026: Text zu Video, Referenz zu Video.| 'video' | 'reference'+ // 07.11.2026: Swap Character (lib/render/swap.ts).+ | 'swap-character'export interface PresetModel {id: string@@ -43,6 +46,7 @@ const ROLE_OP: Record<StepRole, RenderOp> = {extend: 'extend', motion: 'motion', restyle: 'studio', angles: 'studio',edit: 'edit', upscale: 'upscale',video: 'generate', reference: 'studio',+ 'swap-character': 'studio',}/** The staged inputs a NON-studio member consumes, as provider field -> job@@ -56,6 +60,7 @@ export const ROLE_INPUTS: Record<StepRole, Record<string, string>> = {edit: { image: 'source_path' },upscale: { video: 'video_path' },video: {}, reference: {},+ 'swap-character': {},}function studioIds(match: (id: string) => boolean): string[] {@@ -117,6 +122,9 @@ const ROLE_MEMBERS: Record<StepRole, () => string[]> = {edit: () => [...STUDIO_EDIT_MODELS, 'qwen-image-edit'],// A finished clip goes in, the same clip at more pixels comes out.upscale: () => ['video-upscaler', 'flashvsr', 'video-upscaler-pro', 'ultimate-video-upscaler', 'crystal-upscaler', 'flux-3-upscale'],+ // A real video stays, its people become the customer's (lib/render/swap.ts).+ // The one role that shares a model with another (SCAIL 2, see SWAP_ROLES).+ 'swap-character': () => [...SWAP_MODELS],}/** Classic ids that a studio entry already covers on the same endpoint. The@@ -308,6 +316,7 @@ const CLASSIC_PROMPT: Record<StepRole, boolean> = {video: true, reference: true,talking: false, presenter: false, motion: false, soundtrack: false, duo: false,angles: false, upscale: false,+ 'swap-character': false,}export function rolePrompts(role: StepRole): boolean {@@ -321,6 +330,10 @@ export function roleHasChoice(role: StepRole, openOnly = false): boolean {export const ALL_ROLES = Object.keys(ROLE_MEMBERS) as StepRole[]+/** Roles that share models with another role on purpose (as on the web).+ * The rule "every studio model in exactly one role" holds for all others. */+export const SWAP_ROLES: readonly StepRole[] = ['swap-character']+/** The role a model plays. Every studio model belongs to exactly one, which a* contract test holds true; the ad-hoc single-model workspace needs it to* know what its one step is. */diff --git a/src/lib/render/provider-schemas.json b/src/lib/render/provider-schemas.jsonindex 26116106..2d7518c2 100644--- a/src/lib/render/provider-schemas.json+++ b/src/lib/render/provider-schemas.json@@ -9428,5 +9428,60 @@"generate_audio","seed"]+ },+ "base/openjutsu/character-swap": {+ "additionalProperties": false,+ "properties": {+ "video": {+ "type": "string",+ "description": "URL of the source video. The people in it are replaced by your characters; the scene, motion and original audio are kept. Use a single shot with a person in the first frame. The output follows the video's length, up to 15 seconds."+ },+ "images": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "minItems": 1,+ "maxItems": 4,+ "description": "URLs of the character pictures, one per person to replace (up to 4). With one picture and no roles, the most prominent person is replaced. With several, or with roles, only the people you describe are replaced and everyone else stays as filmed."+ },+ "roles": {+ "type": "array",+ "items": {+ "type": "string",+ "maxLength": 200+ },+ "maxItems": 4,+ "description": "Optional. One short description per picture, in the same order, saying who it replaces, for example \"the woman in black on the left\"."+ },+ "resolution": {+ "type": "string",+ "enum": [+ "480p",+ "540p",+ "768p",+ "1080p"+ ],+ "default": "768p",+ "x-ui-component": "select",+ "description": "Output resolution. The price per second rises with it."+ },+ "seed": {+ "type": "integer",+ "description": "The random seed to use for the generation. A negative value means a random seed will be used."+ }+ },+ "required": [+ "video",+ "images"+ ],+ "type": "object",+ "x-order-properties": [+ "video",+ "images",+ "roles",+ "resolution",+ "seed"+ ]}}diff --git a/src/lib/render/studio-contract.ts b/src/lib/render/studio-contract.tsindex 31ebf0b6..540c81fe 100644--- a/src/lib/render/studio-contract.ts+++ b/src/lib/render/studio-contract.ts@@ -2,7 +2,7 @@import definitions from './studio-models.json'import schemas from './provider-schemas.json'import endpoints from './provider-endpoints.json'-export type Schema = { type?: string; properties?: Record<string, Schema>; required?: string[]; enum?: unknown[]; default?: unknown; minimum?: number; maximum?: number; minItems?: number; maxItems?: number; items?: Schema; description?: string; disabled?: boolean; format?: string }+export type Schema = { type?: string; properties?: Record<string, Schema>; required?: string[]; enum?: unknown[]; default?: unknown; minimum?: number; maximum?: number; minItems?: number; maxItems?: number; maxLength?: number; items?: Schema; description?: string; disabled?: boolean; format?: string }// Stufe und Herkunft jedes Cloud-Modells (02.10.2026, Entscheid des Inhabers).// `tier` ordnet die Waehler: 'best' steht oben, 'older' gesammelt unten.// `weights` sagt, ob genau diese Version offene Gewichte hat ('open'), nur ihre@@ -20,7 +20,11 @@ export interface StudioModel {// auf Sekunden, `blockSeconds` bildet einen angefangenen Block ab (ElevenLabs// rechnet je angefangene Minute), `minSeconds` die Mindestlaenge einer// gemessenen Eingabe. Alle vier sind an POST /model/price gemessen.- price: { mode: string; rates: Record<string, number>; maxSeconds?: number; extraImage?: number+ // `perReference` (wie im Web, 03.11.2026): jedes Bild der Bilderliste kostet+ // extra, auch das erste, weil das Video die Vorlage ist und kein Bild+ // (Swap Character: 0,02 $ je Person). Gezaehlt werden die Bilder, die der+ // Lauf wirklich schickt.+ price: { mode: string; rates: Record<string, number>; maxSeconds?: number; extraImage?: number; perReference?: numberresolutionField?: string; durationField?: string; unitDivisor?: number; blockSeconds?: number; minSeconds?: numberperUnitField?: string }}@@ -68,7 +72,7 @@ function validSize(value: unknown, schema: Schema): boolean {function validate(value: unknown, schema: Schema, name: string): void {if(name==='size'&&!schema.enum&&!validSize(value,schema))throw new Error('Size must be width*height in pixels, each side 256 to 4096')if (schema.enum && !schema.enum.includes(value)) throw new Error(`Choose a supported ${name}`)- if (schema.type === 'string' && (typeof value !== 'string' || value.length > 4000)) throw new Error(`Invalid ${name}`)+ if (schema.type === 'string' && (typeof value !== 'string' || value.length > (schema.maxLength ?? 4000))) throw new Error(`Invalid ${name}`)if (schema.type === 'boolean' && typeof value !== 'boolean') throw new Error(`Invalid ${name}`)if (schema.type === 'number' || schema.type === 'integer') {if (typeof value !== 'number' || !Number.isFinite(value) || (schema.type === 'integer' && !Number.isInteger(value)) ||@@ -107,7 +111,7 @@ export function studioOptions(id: string, prompt: string, raw: unknown, checkProfor (const k of schema.required ?? []) if (!m.inputs[k] && k !== promptField && options[k] === undefined) throw new Error(`Missing ${k}`)return options}-export function studioCredits(id: string, options: Record<string,unknown>, measuredSeconds?: number, imageCount = 1, promptLength = 100): number {+export function studioCredits(id: string, options: Record<string,unknown>, measuredSeconds?: number, imageCount = 1, promptLength = 100, referenceCount = 0): number {const m = STUDIO_MODELS[id]; if (!m) throw new Error('Unknown studio model')const resolution = String(options[m.price.resolutionField ?? 'resolution'] ?? 'default'), rate = m.price.rates[resolution]if (rate === undefined) throw new Error('Unpriced resolution')@@ -137,7 +141,7 @@ export function studioCredits(id: string, options: Record<string,unknown>, measu// Ein abgeschaltetes Feld (num_images) fehlt in den Optionen: der Anbieter nimmt dann seinen Standard 1.const units = m.price.perUnitField ? Number(options[m.price.perUnitField] ?? 1) : 1if (!Number.isFinite(units) || units <= 0) throw new Error('Invalid size')- return Math.ceil((rate * seconds * units + (m.price.extraImage ?? 0) * Math.max(0,imageCount-1)) * 100000 - 1e-8)+ return Math.ceil((rate * seconds * units + (m.price.extraImage ?? 0) * Math.max(0,imageCount-1) + (m.price.perReference ?? 0) * referenceCount) * 100000 - 1e-8)}export function studioBaseCredits(id: string): number {const schema = studioSchema(id), m = STUDIO_MODELS[id]@@ -146,6 +150,6 @@ export function studioBaseCredits(id: string): number {return studioCredits(id,options,5)}-export function studioPreviewCredits(id: string, raw: Record<string,unknown>, seconds?: number, imageCount = 1, promptLength = 100): number | null {- try { return studioCredits(id,studioOptions(id,'',raw,false),seconds,imageCount,promptLength) } catch { return null }+export function studioPreviewCredits(id: string, raw: Record<string,unknown>, seconds?: number, imageCount = 1, promptLength = 100, referenceCount = 0): number | null {+ try { return studioCredits(id,studioOptions(id,'',raw,false),seconds,imageCount,promptLength,referenceCount) } catch { return null }}diff --git a/src/lib/render/studio-models.json b/src/lib/render/studio-models.jsonindex bdb83f3b..ab076430 100644--- a/src/lib/render/studio-models.json+++ b/src/lib/render/studio-models.json@@ -191,6 +191,58 @@},"baselineUsd": 0.2},+ "openjutsu-character-swap": {+ "label": "OpenJutsu \u2022 Character Swap",+ "endpoint": "base/openjutsu/character-swap",+ "kind": "video",+ "adult": false,+ "tier": "best",+ "weights": "closed",+ "price": {+ "mode": "input",+ "rates": {+ "480p": 0.15,+ "540p": 0.17,+ "768p": 0.2,+ "1080p": 0.4+ },+ "maxSeconds": 15,+ "minSeconds": 3,+ "perReference": 0.02+ },+ "inputs": {+ "video": "video_path",+ "images": "image_paths"+ },+ "defaults": {+ "resolution": "768p"+ },+ "baselineUsd": 1.02+ },+ "wan-2.2-animate-replace": {+ "label": "Wan 2.2 Animate \u2022 Replace",+ "endpoint": "base/wan-2.2/animate",+ "kind": "video",+ "adult": false,+ "tier": "standard",+ "weights": "open",+ "price": {+ "mode": "input",+ "rates": {+ "480p": 0.04,+ "720p": 0.08+ },+ "maxSeconds": 120+ },+ "inputs": {+ "image": "source_path",+ "video": "video_path"+ },+ "defaults": {+ "mode": "replace"+ },+ "baselineUsd": 0.2+ },"wan-ditto": {"label": "Wan DITTO \u2022 Video Restyle","endpoint": "base/wan-2.1/ditto",diff --git a/src/lib/render/swap.ts b/src/lib/render/swap.tsnew file mode 100644index 00000000..b728800c--- /dev/null+++ b/src/lib/render/swap.ts@@ -0,0 +1,187 @@+// Swap Character: a real video stays as it is (motion, camera, sound, scene),+// and the people in it become the people of the customer's photos.+//+// Port of the web app's lib/render/swap.ts (07.11.2026, C52), cut to the one+// mode the desktop offers. The web also has Swap Scene and Swap Both; the+// desktop does not, so only the rules of Swap Character are here. The names,+// numbers and sentences are the web's, so a run from either app books and+// reads the same.+//+// Models, the recommended first:+// openjutsu-character-swap 1 to 4 people, one photo each and an optional+// role per photo, sound and scene kept, at most+// the first 15 seconds of the video.+// wan-2.2-animate-replace one person, up to 120 seconds, always mode+// replace.+// scail-2 one person, mode replace, chosen by hand only.++import { STUDIO_MODELS, studioSchema } from './studio-contract'++export const SWAP_INTENT = 'swap_character' as const+export type SwapIntent = typeof SWAP_INTENT++export function isSwapIntent(intent: string): intent is SwapIntent {+ return intent === SWAP_INTENT+}++/** The models of Swap Character, the recommended first. */+export const SWAP_MODELS: readonly string[] = ['openjutsu-character-swap', 'wan-2.2-animate-replace', 'scail-2']++/** The main model, and the one for videos longer than it reads. */+export const SWAP_MAIN_MODEL = 'openjutsu-character-swap'+export const SWAP_LONG_MODEL = 'wan-2.2-animate-replace'++/** What the mode fixes and the customer therefore never sees. SCAIL 2 and+ * Wan 2.2 Animate run as replace here: as animate they would put the new+ * person in front of a new background, which is Motion Control. */+export function swapFixedOptions(intent: string, model: string): Record<string, unknown> {+ if (isSwapIntent(intent) && (model === 'scail-2' || model === SWAP_LONG_MODEL)) return { mode: 'replace' }+ return {}+}++/** Fields the Swap panel shows itself (a role per person, the resolution) and+ * the settings drawer therefore leaves out. `mode` is fixed (above). */+export function swapPanelFields(intent: string): string[] {+ return isSwapIntent(intent) ? ['roles', 'resolution', 'mode'] : []+}++/** How many people a model swaps in one run. */+export function swapMaxPeople(model: string): number {+ return model === SWAP_MAIN_MODEL ? 4 : 1+}++/** Does the model read one role per photo (`roles`)? */+export function swapReadsRoles(model: string): boolean {+ return !!STUDIO_MODELS[model] && 'roles' in (studioSchema(model).properties ?? {})+}++/** The model Swap Character picks for this length and this many people: up to+ * 15 s the main model, longer Wan 2.2 Animate. Several people only the main+ * model can do; then it stays, and the first 15 s run. */+export function swapAutoModel(seconds: number | undefined, figures: number): string {+ if (figures > 1) return SWAP_MAIN_MODEL+ return seconds !== undefined && seconds > swapClipLimits(SWAP_MAIN_MODEL).max ? SWAP_LONG_MODEL : SWAP_MAIN_MODEL+}++// Length. The customer picks from the shortest length the model takes up to+// its real maximum. The server cuts the video (clip_seconds): the beginning+// of the video runs.++export interface SwapClipLimits {+ /** Shortest length the model takes. */+ min: number+ /** Longest length the model reads. */+ max: number+ /** The provider bills at least this many seconds. */+ billedMin: number+}++/** The limits of a model, from the catalogue (studio-models.json). The main+ * model needs at least 2 seconds of video (its model page). */+export function swapClipLimits(model: string): SwapClipLimits {+ const price = STUDIO_MODELS[model]?.price+ const max = price?.maxSeconds ?? 120+ const billedMin = price?.minSeconds ?? 3+ const min = model === SWAP_MAIN_MODEL ? 2 : 1+ return { min, max, billedMin }+}++/** The length that runs: the choice, else the whole video, always inside the+ * limits of the model and never longer than the video. */+export function swapClipSeconds(model: string, chosen: number | null, videoSeconds?: number): number {+ const { min, max } = swapClipLimits(model)+ const video = videoSeconds && Number.isFinite(videoSeconds) ? Math.floor(videoSeconds) : max+ const upper = Math.max(min, Math.min(max, video))+ return Math.max(min, Math.min(upper, chosen ?? upper))+}++/** The seconds the provider measures and bills (not rounded; it bills every+ * started second). Without a choice the whole video runs up to the limit of+ * the model, with one at most the chosen seconds: the server cuts longer.+ * The slider, the Create button and the server count the same. */+export function swapPricedSeconds(model: string, chosen: number | null, videoSeconds: number): number {+ const { max } = swapClipLimits(model)+ return Math.min(videoSeconds, chosen ?? max, max)+}++/** Credits per second at the resolution picked. */+export function swapCreditsPerSecond(model: string, options: Record<string, unknown>): number | null {+ const m = STUDIO_MODELS[model]+ if (!m) return null+ const resolution = String(options[m.price.resolutionField ?? 'resolution'] ?? m.defaults?.resolution ?? Object.keys(m.price.rates)[0])+ const rate = m.price.rates[resolution]+ return rate === undefined ? null : Math.round(rate * 100000)+}++/** What one photo costs on top, in credits (price.perReference). */+export function swapCreditsPerPhoto(model: string): number {+ return Math.round((STUDIO_MODELS[model]?.price.perReference ?? 0) * 100000)+}++/** The photos a run is billed for: every photo the run sends, where the+ * model bills them one by one (the main model). */+export function swapBilledPhotos(model: string, figures: number): number {+ return STUDIO_MODELS[model]?.price.perReference ? figures : 0+}++/** Credits for this many priced seconds and this many billed photos: the+ * provider's rule (every started second, at least billedMin, plus each+ * photo). The slider shows it; the price preview of the Create button gets+ * the same number from studioCredits. */+export function swapClipCredits(model: string, options: Record<string, unknown>, seconds: number, photos: number): number | null {+ const perSecond = swapCreditsPerSecond(model, options)+ if (perSecond == null) return null+ const billed = Math.max(swapClipLimits(model).billedMin, Math.ceil(seconds))+ return perSecond * billed + photos * swapCreditsPerPhoto(model)+}++/** A price in few characters for the Create button (the web's CreateButton+ * shortCredits): 950, 1.5k, 152k, 1.2M. */+export function swapShortCredits(credits: number): string {+ if (credits < 1000) return String(Math.round(credits))+ if (credits < 10_000) return `${(Math.round(credits / 100) / 10).toLocaleString('en-US')}k`+ if (credits < 1_000_000) return `${Math.round(credits / 1000).toLocaleString('en-US')}k`+ return `${(Math.round(credits / 100_000) / 10).toLocaleString('en-US')}M`+}++// People.++/** A new person: the photo, and who it replaces in the video. */+export interface SwapFigureSpec { role: string }++const ORDINAL = ['first', 'second', 'third', 'fourth']++/** The roles as the provider gets them, or undefined. One photo without a role+ * replaces the most prominent person. Once one role is set every photo needs+ * one, or a role would land on the wrong photo; an empty role therefore gets+ * its place from the left. */+export function swapRoles(figures: SwapFigureSpec[]): string[] | undefined {+ const roles = figures.map((f) => f.role.trim().slice(0, 200))+ if (roles.every((r) => !r)) return undefined+ return roles.map((r, i) => r || `the ${ORDINAL[i] ?? `${i + 1}th`} person from the left`)+}++/** What stands in the panel before the start (from the test runs of+ * 06.11.2026), so it is not learned from a failed run. */+export const SWAP_TIPS = [+ 'People only: animals are refused, or turned into a person.',+ 'One continuous shot, no hard cuts. The person must be visible in the first frame.',+] as const++/** The heading of a result in the gallery. */+export const SWAP_GALLERY_LABEL = 'Swap Character'++// Consent (07.11.2026, as on the web). The server refuses a run of these+// models without params.swap_consent === true (400, code+// swap_consent_required). The panel shows the box only for them, and Create+// waits for the tick. The tick is runtime only and never stored.++/** The models whose run needs the customer's confirmation. */+export const SWAP_CONSENT_MODELS: readonly string[] = [SWAP_MAIN_MODEL, SWAP_LONG_MODEL]++export const SWAP_CONSENT_TEXT = 'I have the rights to this video and the consent of the people shown in it and in the photos.'+export const SWAP_CONSENT_MISSING = 'Confirm that you have the rights and the consent of the people shown before you swap them.'++export function swapNeedsConsent(model: string): boolean {+ return SWAP_CONSENT_MODELS.includes(model)+}diff --git a/src/mobile/screens/create/parts/ui.tsx b/src/mobile/screens/create/parts/ui.tsxindex 21dda37c..3d18364e 100644--- a/src/mobile/screens/create/parts/ui.tsx+++ b/src/mobile/screens/create/parts/ui.tsx@@ -37,6 +37,8 @@ export const TOOL_ICON: Record<ToolId, IconType> = {music: Music,extend: FastForward,motion: PersonStanding,+ // Not a phone tool (tools.ts TOOLS leaves it out); the type names every intent.+ swap_character: RefreshCw,}/** The small round X on a thumbnail. Its target is 44 px, the mark is 22 px. */diff --git a/src/mobile/strings/create.ts b/src/mobile/strings/create.tsindex bf5175a3..a31d3c56 100644--- a/src/mobile/strings/create.ts+++ b/src/mobile/strings/create.ts@@ -77,6 +77,12 @@ const TOOL: Record<CreateIntent, ToolText> = {empty: 'Add a portrait and a video. The portrait moves like the person in the video.',show: 'Move a figure from a photo the way someone moves in a video.',},+ // Not a phone tool (TOOLS leaves it out); the type names every intent.+ swap_character: {+ name: 'Swap Character', short: 'Swap', placeholder: '',+ empty: 'Add a video and a photo of the new person.',+ show: 'Put a new person into a real video. Same moves, same scene.',+ },}/** A getter here is a text in two wordings; the store switches of the build pick one (policy/gates.ts). */diff --git a/src/stores/createStore.ts b/src/stores/createStore.tsindex 46309dac..e28bb630 100644--- a/src/stores/createStore.ts+++ b/src/stores/createStore.ts@@ -108,7 +108,13 @@ export const LOCAL_UTILITY_OPS: ReadonlySet<UtilityOp> = new Set(['upscale'])* Character-Studio (LoRA training + generation), talking character (lipsync),* music, video extend and motion control. Like `utilityOp`, an escape hatch* over the image/video mode axis: when set it wins the intent derivation. */-export type CloudOp = 'character' | 'lipsync' | 'music' | 'extend' | 'motion'+export type CloudOp = 'character' | 'lipsync' | 'music' | 'extend' | 'motion' | 'swap_character'++/** A new person for Swap Character (07.11.2026): the photo, and who it+ * replaces when several people are in the video ("the woman on the left"). */+export interface SwapFigure { image: ImageRef | null; role: string }++const ONE_FIGURE: SwapFigure[] = [{ image: null, role: '' }]/** Which of the specialized categories ALSO run on the local ComfyUI backend* (2.5.8 local lanes: ACE music, Wan S2V talking character, last-frame-chain@@ -465,6 +471,16 @@ export interface CreateState {/** Extend: the prior cloud render to continue ({jobId} → fresh signed URL* at submit). Runtime-only. */extendSource: { jobId: string; url: string; label: string } | null+ /** Swap Character: how many seconds of the video run. null = the whole+ * video, at most up to the limit of the model. Runtime-only. */+ swapSeconds: number | null+ /** Swap Character: 1 to 4 new people, a photo and a role each.+ * Runtime-only. */+ swapFigures: SwapFigure[]+ /** Swap Character: the customer confirmed the rights and the consent of+ * the people shown (lib/render/swap.ts SWAP_CONSENT_TEXT). Runtime-only,+ * never persisted: every session confirms again. */+ swapConsent: boolean/** Music track length in seconds (billed per second on the cloud). */musicDuration: number/** Music: optional lyrics passed to models that take them. Runtime-only. */@@ -721,6 +737,9 @@ export interface CreateState {setAudioInput: (m: MediaRef | null) => voidsetVoiceFromJob: (v: { jobId: string; label: string } | null) => voidsetVideoInput: (m: MediaRef | null) => void+ setSwapSeconds: (seconds: number | null) => void+ setSwapFigures: (figures: SwapFigure[]) => void+ setSwapConsent: (consent: boolean) => voidbumpCharactersVersion: () => voidsetLoraListKey: (names: readonly string[]) => voidsetCloudOpModel: (id: string) => void@@ -1216,6 +1235,9 @@ export const useCreateStore = create<CreateState>()(voiceFromJob: null as { jobId: string; label: string } | null,videoInput: null as MediaRef | null,extendSource: null as { jobId: string; url: string; label: string } | null,+ swapSeconds: null as number | null,+ swapFigures: ONE_FIGURE,+ swapConsent: false,musicDuration: 60,musicLyrics: '',talkingWords: '',@@ -1424,6 +1446,10 @@ export const useCreateStore = create<CreateState>()(return { ...base, cloudOp: 'extend' as const, mode: 'video' as const, videoSubMode: 't2v' as const, ...dropAll,...videoModelParams(s.videoModel, s.videoModelList, 'extend', s.videoSpeed) }}+ case 'swap_character':+ // Its inputs are its own slots (video, figures); the Stage's+ // source and mask are not read.+ return { ...base, cloudOp: 'swap_character' as const, mode: 'video' as const, videoSubMode: 'i2v' as const, mask: null }case 'motion': {// Keeps the source slot (the character image the video drives).// On the Mac the lane runs an LTX-2.3 pack, and its catalogue@@ -1588,10 +1614,15 @@ export const useCreateStore = create<CreateState>()(set({ audioInput, ...(audioInput ? { voiceFromJob: null } : {}) })},setVoiceFromJob: (voiceFromJob) => set({ voiceFromJob, ...(voiceFromJob ? { audioInput: null } : {}) }),+ // Another video: the chosen length belonged to the old one.setVideoInput: (videoInput) => {releaseReplacedMediaRef(get().videoInput, videoInput)- set({ videoInput })+ set(videoInput?.url === get().videoInput?.url ? { videoInput } : { videoInput, swapSeconds: null })},+ setSwapSeconds: (swapSeconds) => set({ swapSeconds: swapSeconds == null ? null : Math.max(1, Math.round(swapSeconds)) }),+ // Always at least one person, at most four (the main model's limit).+ setSwapFigures: (figures) => set({ swapFigures: (figures.length ? figures : ONE_FIGURE).slice(0, 4) }),+ setSwapConsent: (swapConsent) => set({ swapConsent }),bumpCharactersVersion: () => set((s) => ({ charactersVersion: s.charactersVersion + 1 })),setLoraListKey: (names) => set((s) => {const key = names.join('\n')diff --git a/src/stores/uiStore.ts b/src/stores/uiStore.tsindex 89abaeff..3f634e8c 100644--- a/src/stores/uiStore.ts+++ b/src/stores/uiStore.ts@@ -28,7 +28,7 @@ export interface SettingsFocus {export type CloudTeaserTarget =| {surface: 'intent'- intent: 'upscale' | 'eraser' | 'character' | 'lipsync' | 'music' | 'extend' | 'motion'+ intent: 'upscale' | 'eraser' | 'character' | 'lipsync' | 'music' | 'extend' | 'motion' | 'swap_character'}| { surface: 'create-model'; kind: 'image' | 'video'; modelId: string }