Skip to content

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.

feat(create): Swap Character zweistufig mit SCAIL 2 und Kling 3.0 Pro (Port des Web-Stands Teil A)

purple365b1bc2053f
diff --git a/e2e/swap-character.spec.ts b/e2e/swap-character.spec.ts
index 9db570fc..ca6bf0dc 100644
--- a/e2e/swap-character.spec.ts
+++ b/e2e/swap-character.spec.ts
@@ -3,14 +3,18 @@ import { tauriMockInit, DEFAULT_ASSISTANT_REPLY, DEFAULT_MODEL_NAME } from './su
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.
+ * Swap Character (07.11.2026, port of the web's C52; two steps with SCAIL 2
+ * and Kling since 14.11.2026) in the real app, Tauri stubbed, cloud mocked:
+ * the pill, the panel in the web's order, the marks on the first frame, the
+ * frame step (Build first frame, Does this look right?, Continue), Kling for
+ * one person only, and Create only with every input, the consent and the
+ * confirmed frame. Nothing is booked: the frame step runs against the mock,
+ * and 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
+ * Media come from LU_SWAP_MEDIA_DIR (clip.mp4, face1.png, face2.png and
+ * frame-new.jpg, the built frame the mock hands back) when it is set; without
+ * it the spec uses a 1x1 picture and a short clip the browser records from a
+ * canvas, 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.
*/
@@ -19,27 +23,102 @@ const PNG_1PX = Buffer.from(
'base64',
)
-/** The three swap models as a server that knows them lists them. */
+/** The swap models and the frame model as a server that knows them lists them. */
const SWAP_CATALOG = [
+ ['scail-2', 'SCAIL 2'],
+ ['kling-v3-pro-motion-control', 'Kling 3.0 Pro \u2022 Motion Control'],
['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 }))
+ .concat([{ id: 'nano-banana-pro-edit', label: 'Nano Banana Pro', kind: 'image', ops: ['studio'], quote_required: true, t2v: false, i2v: false }])
-async function media(name: string, mimeType: string) {
+async function media(name: string, mimeType: string, page?: Page) {
const dir = process.env.LU_SWAP_MEDIA_DIR
if (dir) {
const { readFileSync } = await import('node:fs')
return { name, mimeType, buffer: readFileSync(`${dir}/${name}`) }
}
+ if (mimeType.startsWith('video') && page) return { name: 'clip.webm', mimeType: 'video/webm', buffer: await recordedClip(page) }
return { name, mimeType, buffer: mimeType.startsWith('image') ? PNG_1PX : Buffer.from('stub') }
}
-async function openSwap(page: Page) {
+/** A short real video without a file on disk: the page records a canvas with
+ * two figures for under a second. The first frame step needs a clip the
+ * WebView can decode; a stub of bytes has no first frame. */
+async function recordedClip(page: Page): Promise<Buffer> {
+ const b64 = await page.evaluate(async () => {
+ const canvas = document.createElement('canvas')
+ canvas.width = 320
+ canvas.height = 180
+ const ctx = canvas.getContext('2d')!
+ const paint = (t: number) => {
+ ctx.fillStyle = '#d8d4cc'
+ ctx.fillRect(0, 0, 320, 180)
+ ctx.fillStyle = '#6b4f3a'
+ ctx.beginPath(); ctx.arc(140 + t, 70, 28, 0, Math.PI * 2); ctx.fill()
+ ctx.fillStyle = '#2f2a28'
+ ctx.beginPath(); ctx.arc(215 - t, 76, 28, 0, Math.PI * 2); ctx.fill()
+ }
+ paint(0)
+ const rec = new MediaRecorder(canvas.captureStream(15), { mimeType: 'video/webm' })
+ const parts: Blob[] = []
+ rec.ondataavailable = (e) => parts.push(e.data)
+ const done = new Promise<void>((r) => { rec.onstop = () => r() })
+ rec.start()
+ for (let i = 0; i < 12; i++) { paint(i); await new Promise((r) => setTimeout(r, 60)) }
+ rec.stop()
+ await done
+ const bytes = new Uint8Array(await new Blob(parts, { type: 'video/webm' }).arrayBuffer())
+ let bin = ''
+ for (const x of bytes) bin += String.fromCharCode(x)
+ return btoa(bin)
+ })
+ return Buffer.from(b64, 'base64')
+}
+
+/** What the mock saw of the frame step: every submit body. */
+interface Seen { submits: Array<{ model: string; prompt: string; params: Record<string, unknown> }>; uploads: number }
+
+async function openSwap(page: Page): Promise<Seen> {
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 })
+ // The frame step against the mock: upload, submit, poll, and the built
+ // frame. Registered after routeCloud, so these answer first; anything
+ // else falls back to the shared mock.
+ const seen: Seen = { submits: [], uploads: 0 }
+ const cors = { 'access-control-allow-origin': '*', 'access-control-allow-headers': '*', 'access-control-allow-methods': 'GET,POST,OPTIONS' }
+ const frameImage = await media('frame-new.jpg', 'image/jpeg')
+ await page.route('https://lu-labs.ai/**', async (route) => {
+ const req = route.request()
+ const path = new URL(req.url()).pathname
+ if (req.method() === 'OPTIONS') return route.fallback()
+ const json = (body: unknown, status = 200) => route.fulfill({ status, headers: { ...cors, 'content-type': 'application/json' }, body: JSON.stringify(body) })
+ if (path === '/api/jobs/upload' && req.method() === 'POST') {
+ seen.uploads++
+ return json({ path: `e2e-user-1/staged-${seen.uploads}.bin` })
+ }
+ if (path === '/api/jobs' && req.method() === 'POST') {
+ const body = req.postDataJSON() as Seen['submits'][number]
+ seen.submits.push(body)
+ // Only the frame step may book here; a video run would be a real Create.
+ if (body.params?.swap_step !== 'frame') return json({ error: 'e2e: only the frame step is mocked' }, 400)
+ return json({ id: `job-frame-${seen.submits.length}`, status: 'queued', created_at: new Date().toISOString(), quota: { kind: 'image', cost: 14000, used: 0, limit: 2_550_000 } }, 202)
+ }
+ const job = /^\/api\/jobs\/(job-frame-\d+)$/.exec(path)
+ if (job && req.method() === 'GET') {
+ return json({ job: {
+ id: job[1], kind: 'image', model: 'nano-banana-pro-edit', provider: 'upstream', status: 'succeeded',
+ result_url: `https://lu-labs.ai/e2e/${job[1]}.jpg`, attestation: null, cost_units: 14000,
+ created_at: new Date().toISOString(), completed_at: new Date().toISOString(), error: null,
+ } })
+ }
+ if (/^\/e2e\/job-frame-\d+\.jpg$/.test(path)) {
+ return route.fulfill({ status: 200, headers: { ...cors, 'content-type': frameImage.mimeType }, body: frameImage.buffer })
+ }
+ return route.fallback()
+ })
await page.goto('/')
await expect(cloudSwitch(page)).toBeVisible({ timeout: 20_000 })
await signInViaGate(page)
@@ -47,11 +126,14 @@ async function openSwap(page: Page) {
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 })
+ return seen
}
-async function shoot(page: Page, name: string) {
+async function shoot(page: Page, name: string, focus?: string) {
const dir = process.env.LU_SWAP_SHOTS_DIR
if (!dir) return
+ // The part the shot is about, scrolled into the panel's view.
+ if (focus) await page.locator(focus).first().evaluate((el) => el.scrollIntoView({ block: 'end' }))
for (const theme of ['dark', 'light'] as const) {
await page.evaluate((t) => {
document.documentElement.classList.toggle('dark', t === 'dark')
@@ -66,41 +148,131 @@ async function shoot(page: Page, name: string) {
})
}
-test('Swap Character: panel, people, consent and price before Create', async ({ page }) => {
- await openSwap(page)
+/** A tap on the first frame at a share of its width and height. */
+async function tapFrame(page: Page, x: number, y: number) {
+ const frame = page.getByRole('group', { name: /First frame of your video/ })
+ const box = await frame.boundingBox()
+ if (!box) throw new Error('first frame not on screen')
+ await frame.click({ position: { x: box.width * x, y: box.height * y } })
+}
+
+test('Swap Character in two steps: marks, first frame, Continue, Kling for one person', async ({ page }) => {
+ const seen = 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')
+ // SCAIL 2 is the default, the notes stand grey.
+ await expect(panel.locator('[data-swap-tips]')).toContainText('Up to 3 people with SCAIL-2, one person with Kling (highest resolution).')
+ await expect(panel).toHaveAttribute('data-swap-two-step', 'true')
+ await expect(page.getByRole('radio', { name: '720p' })).toHaveAttribute('aria-checked', 'true')
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'))
+ // The original video: the first frame is drawn in the WebView.
+ await panel.locator('input[type=file][accept^="video"]').setInputFiles(await media('clip.mp4', 'video/mp4', page))
+ await expect(page.getByText('Tap each person you want to replace')).toBeVisible({ timeout: 20_000 })
+ // Two people tapped: numbered marks, their place becomes the role.
+ await tapFrame(page, 0.45, 0.35)
+ await tapFrame(page, 0.68, 0.38)
+ await expect(page.getByRole('button', { name: 'Remove mark 2' })).toBeVisible()
+ await expect(page.locator('[data-swap-frame-count]')).toHaveText('2 of 4 people marked. Tap a number to remove it.')
+ await expect(page.getByRole('textbox', { name: 'Who person 1 replaces' })).toHaveAttribute('placeholder', /^the person on the left/)
+ await expect(page.getByRole('textbox', { name: 'Who person 2 replaces' })).toHaveAttribute('placeholder', /^the person on the right/)
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 page.locator('[data-swap-photo-input="2"]').setInputFiles(await media('face2.png', 'image/png'))
+ await expect(page.getByRole('button', { name: 'Change photo of person 2' })).toBeVisible()
+ // The slider prices frame and video together.
+ await expect(page.locator('[data-clip-price]')).toContainText('credits · frame + video')
+ await expect(page.locator('[data-clip-split]')).toContainText('First frame 14,000')
+
+ // Kling stands greyed out for two people, SCAIL 2 is recommended.
+ await page.getByRole('button', { name: /SCAIL 2/ }).first().click()
+ const kling = page.getByRole('option', { name: /Kling 3.0 Pro/ })
+ await expect(kling).toBeDisabled()
+ await expect(kling).toContainText('one person only')
+ await expect(page.getByRole('option', { name: /SCAIL 2/ })).toContainText('Recommended')
+ await page.keyboard.press('Escape')
+ await expect(kling).toBeHidden()
+
+ // The frame step waits for the tick, Create waits for the frame.
+ const build = page.getByRole('button', { name: /Build first frame/ })
+ await expect(build).toBeDisabled()
+ await shoot(page, 'swap-two-marks')
+ await page.getByRole('checkbox').check()
+ await expect(build).toBeEnabled()
+ await expect(build).toHaveAttribute('title', 'Build first frame · 14,000 credits')
+ await expect(create).toBeDisabled()
+ await build.click()
+ await expect(page.getByText('Does this look right?')).toBeVisible({ timeout: 20_000 })
+ expect(seen.submits).toHaveLength(1)
+ expect(seen.submits[0].model).toBe('nano-banana-pro-edit')
+ expect(seen.submits[0].params).toMatchObject({ op: 'studio', swap_step: 'frame', swap_consent: true, max_credits: 14000 })
+ expect(seen.submits[0].params.image_paths).toHaveLength(3)
+ expect(seen.submits[0].prompt).toContain('replace the person on the left with the person from the second image and replace the person on the right with the person from the third image')
+ await expect(page.getByRole('img', { name: 'New first frame' })).toBeVisible()
+ await expect(page.getByRole('button', { name: /Try again · 14k credits/ })).toBeEnabled()
+ await expect(page.getByRole('textbox', { name: "What's wrong?" })).toHaveAttribute('placeholder', "What's wrong? (optional)")
await expect(create).toBeDisabled()
+ await shoot(page, 'swap-review', '[data-swap-built]')
- // A second person without a photo keeps Create off.
+ // Continue: now Create is armed, its price names the video.
+ await page.getByRole('button', { name: /Continue/ }).click()
+ await expect(page.getByText('First frame ready. Create starts the video.')).toBeVisible()
+ await expect(create).toBeEnabled({ timeout: 15_000 })
+ await shoot(page, 'swap-ready-scail2', '[data-swap-built]')
+
+ // Kling for one person: the second mark goes, the built frame expires.
+ await page.getByRole('button', { name: 'Remove mark 2' }).click()
+ await expect(page.locator('[data-swap-frame-count]')).toHaveText('1 of 4 people marked. Tap a number to remove it.')
+ await expect(create).toBeDisabled()
+ await page.getByRole('button', { name: /SCAIL 2/ }).first().click()
+ await expect(page.getByRole('option', { name: /Kling 3.0 Pro/ })).toBeEnabled()
+ await page.getByRole('option', { name: /Kling 3.0 Pro/ }).click()
+ await expect(page.getByRole('radiogroup', { name: 'Resolution' })).toHaveCount(0)
+ await expect(page.getByRole('checkbox')).toBeChecked()
+ await page.getByRole('button', { name: /Build first frame/ }).click()
+ await expect(page.getByText('Does this look right?')).toBeVisible({ timeout: 20_000 })
+ expect(seen.submits).toHaveLength(2)
+ // One mark left: "the person", one photo.
+ expect(seen.submits[1].prompt).toMatch(/^Replace the person in the first image with the person from the second image\./)
+ expect(seen.submits[1].params.image_paths).toHaveLength(2)
+ await page.getByRole('button', { name: /Continue/ }).click()
+ await expect(create).toBeEnabled({ timeout: 15_000 })
+ await expect(page.locator('[data-clip-split]')).toContainText('16,800/s')
+ await shoot(page, 'swap-kling-one-person', '[data-swap-built]')
+
+ // Nothing but the frame step ever went to the queue.
+ expect(seen.submits.every((b) => b.params.swap_step === 'frame')).toBe(true)
+})
+
+test('Swap Character with OpenJutsu: one step, people up to four, consent before Create', async ({ page }) => {
+ await openSwap(page)
+ const panel = page.locator('[data-swap-controls]')
+ const create = page.getByRole('button', { name: /^Create/ }).last()
+ await page.getByRole('button', { name: /SCAIL 2/ }).first().click()
+ await page.getByRole('option', { name: /OpenJutsu/ }).click()
+ await expect(panel).not.toHaveAttribute('data-swap-two-step', 'true')
+
+ await page.locator('[data-swap-photo-input="1"]').setInputFiles(await media('face1.png', 'image/png'))
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 page.getByRole('textbox', { name: 'Who person 2 replaces' }).fill('the woman on the right')
+ // Without the video Create stays off.
+ await expect(create).toBeDisabled()
+ await panel.locator('input[type=file][accept^="video"]').setInputFiles(await media('clip.mp4', 'video/mp4', page))
+ // No frame step on OpenJutsu: Create is armed and names its price.
+ await expect(page.locator('[data-swap-built]')).toHaveCount(0)
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.ts
index 9cf8e881..b687bd36 100644
--- a/src/api/cloud/jobs.ts
+++ b/src/api/cloud/jobs.ts
@@ -72,6 +72,10 @@ export interface CloudJobParams {
// customer confirmed the rights and the consent of the people shown.
clip_seconds?: number
swap_consent?: boolean
+ /** Swap Character on SCAIL 2 or Kling (14.11.2026): 'frame' builds the first
+ * frame with the new people (Nano Banana Pro), 'video' runs the clip on it.
+ * Either step needs swap_consent on the server. */
+ swap_step?: 'frame' | 'video'
}
export interface CloudJobSubmit {
diff --git a/src/components/create/experimental/ClipLength.tsx b/src/components/create/experimental/ClipLength.tsx
index c398b675..03516ba3 100644
--- a/src/components/create/experimental/ClipLength.tsx
+++ b/src/components/create/experimental/ClipLength.tsx
@@ -1,6 +1,8 @@
import { AlertTriangle } from 'lucide-react'
import { modelLabel } from '../../../lib/render/preset-models'
-import { swapClipCredits, swapClipLimits, swapClipSeconds, swapCreditsPerSecond, swapPricedSeconds } from '../../../lib/render/swap'
+import {
+ SWAP_FRAME_MODELS, swapClipCredits, swapClipLimits, swapClipSeconds, swapCreditsPerSecond, swapPricedSeconds, swapWholeSeconds,
+} 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);
@@ -10,7 +12,7 @@ import { swapClipCredits, swapClipLimits, swapClipSeconds, swapCreditsPerSecond,
// same seconds the Create button and the server count (swapPricedSeconds).
export function ClipLength({
- model, options, videoSeconds, chosen, onChange, photos = 0, span, disabled = false,
+ model, options, videoSeconds, chosen, onChange, photos = 0, span, disabled = false, frameCredits = null,
}: {
model: string
options: Record<string, unknown>
@@ -25,18 +27,26 @@ export function ClipLength({
* span of the one model. */
span?: { min: number; max: number }
disabled?: boolean
+ /** Swap Character on SCAIL 2 or Kling: the frame step costs extra. Then the
+ * total here reads "frame + video", the Create button names the video
+ * only. */
+ frameCredits?: number | null
}) {
const own = swapClipLimits(model)
+ const frameModel = SWAP_FRAME_MODELS.includes(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
+ // SCAIL 2 and Kling run on whole seconds (swapWholeSeconds): a clip of
+ // 5.96 s reads 6 s, one of 6.006 s too.
+ : frameModel ? swapWholeSeconds(model, chosen, videoSeconds) : swapClipSeconds(model, chosen, videoSeconds)
+ const video = videoSeconds ? (frameModel ? swapWholeSeconds(model, null, 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 videoCredits = swapClipCredits(model, options, videoSeconds ? swapPricedSeconds(model, chosen, videoSeconds) : Math.min(value, own.max), photos)
+ const total = videoCredits == null ? null : videoCredits + (frameCredits ?? 0)
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)
@@ -53,7 +63,9 @@ export function ClipLength({
{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>
+ {frameCredits != null
+ ? <span className="t-control text-gray-500"> credits · frame + video</span>
+ : <span className="t-control text-gray-500"> credits · {perSecond.toLocaleString('en-US')}/s</span>}
</span>
)}
</div>
@@ -100,6 +112,11 @@ export function ClipLength({
Your video is {video} s. {name} needs at least {own.min} s.
</p>
)}
+ {frameCredits != null && videoCredits != null && perSecond != null && (
+ <p className="mt-0.5 text-right t-control text-gray-500 tabular-nums" data-clip-split>
+ First frame {frameCredits.toLocaleString('en-US')} · video {videoCredits.toLocaleString('en-US')} ({perSecond.toLocaleString('en-US')}/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&apos;s minimum.</p>
)}
diff --git a/src/components/create/experimental/Composer.tsx b/src/components/create/experimental/Composer.tsx
index f8ca0e45..019d9f2d 100644
--- a/src/components/create/experimental/Composer.tsx
+++ b/src/components/create/experimental/Composer.tsx
@@ -18,6 +18,7 @@ import { createRunModel, intentRequiredInputs, isStudioModel } from '../../../li
import { STUDIO_MODELS } from '../../../lib/render/studio-contract'
import { swapBilledPhotos, swapPricedSeconds, swapShortCredits } from '../../../lib/render/swap'
import { swapReady } from '../../../lib/create/swap-run'
+import { swapConfirmedFrame } from '../../../lib/create/swap-frame'
import { effectiveVideoDurations, snapToVideoDuration } from '../../../lib/render/video-duration'
import { mediaSeconds, useStudioPrice } from './useStudioPrice'
import { getJob } from '../../../api/cloud/jobs'
@@ -111,6 +112,9 @@ export function Composer({ onOpenAdvanced, onOpenWorkflows }: Props) {
const swapFigures = useCreateStore((s) => s.swapFigures)
const swapSeconds = useCreateStore((s) => s.swapSeconds)
const swapConsent = useCreateStore((s) => s.swapConsent)
+ // SCAIL 2 and Kling: the video starts only on the confirmed first frame,
+ // and only while it fits video, photos and marks.
+ const swapBuilt = useCreateStore((s) => s.swapBuilt)
const managerNoticeSeen = useWorkflowStore((s) => s.managerNoticeSeen)
const { generate, cancel, quota, mlxMissing, modelsLoaded } = useCreateExp()
const imageModels = useCreateStore((s) => s.imageModelList)
@@ -342,7 +346,10 @@ export function Composer({ onOpenAdvanced, onOpenWorkflows }: Props) {
: 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 })
+ ? !!studioPick && swapReady(studioPick, {
+ hasVideo: !!videoInput, figures: swapFigures, consent: swapConsent,
+ frameJobId: swapConfirmedFrame(swapBuilt, videoInput?.url, swapFigures),
+ })
: 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
diff --git a/src/components/create/experimental/ModelChip.tsx b/src/components/create/experimental/ModelChip.tsx
index d8317fcd..6e725f3e 100644
--- a/src/components/create/experimental/ModelChip.tsx
+++ b/src/components/create/experimental/ModelChip.tsx
@@ -14,6 +14,7 @@ import { useSettingsStore } from '../../../stores/settingsStore'
import { useUIStore } from '../../../stores/uiStore'
import { useContentPolicy } from '../../../hooks/useContentPolicy'
import { Select, type SelectOption, type SelectTag } from '../ui/Select'
+import { SWAP_MAIN_MODEL, swapMaxPeople } from '../../../lib/render/swap'
import { TYPE_LABEL } from './badges'
import { UNFILTERED_MARK_LABEL } from '../../../lib/unfiltered-mark'
import { useLocalPick } from './localPick'
@@ -88,6 +89,7 @@ function CloudModelChip() {
// Subscribed, not read once: the music sublabel must follow the length
// slider live so the shown price is the billed price (A3).
const musicDuration = useCreateStore((s) => s.musicDuration)
+ const swapPeople = useCreateStore((s) => s.swapFigures.length)
const models = useCloudCatalogStore((s) => s.models)
const contentPolicy = useContentPolicy()
@@ -154,13 +156,19 @@ function CloudModelChip() {
: intent === 'edit' ? 'edit'
: intent === 'animate' ? 'animate'
: 'generate'
+ // Swap Character: the order is the recommendation (SCAIL 2 first), and a
+ // model for fewer people than are marked stands greyed out with the reason.
+ const swap = intent === 'swap_character'
+ const swapTooMany = (id: string) => swap && swapPeople > swapMaxPeople(id)
+ const swapLimitText = (id: string) => (swapMaxPeople(id) === 1 ? 'one person only' : `up to ${swapMaxPeople(id)} people`)
const options: SelectOption[] = roleIntent
- ? groupForPicker(roleModels).map(({ model: m, group }) => ({
+ ? (swap ? roleModels.map((model) => ({ model, group: undefined as string | undefined })) : groupForPicker(roleModels)).map(({ model: m, group }) => ({
value: m.id,
label: m.label,
- sublabel: pickerCostHint(m, musicDuration),
+ sublabel: swapTooMany(m.id) ? swapLimitText(m.id) : pickerCostHint(m, musicDuration),
+ disabled: swapTooMany(m.id),
group,
- tags: tierMarks(m),
+ tags: swap && m.id === SWAP_MAIN_MODEL ? [{ label: 'Recommended', tone: 'accent' as const }, ...tierMarks(m)] : tierMarks(m),
badge: m.adult
? noRefusalsBadge(contentPolicy === 'off')
: CLOUD_BADGE,
@@ -196,7 +204,9 @@ function CloudModelChip() {
<Select
size="sm"
searchable
- align="right"
+ // Swap Character: the list is wider (recommendation, the reason for a
+ // greyed out model) and opens to the right, into the panel.
+ align={swap ? 'left' : 'right'}
className="min-w-[150px] max-w-[230px]"
options={options}
value={value}
diff --git a/src/components/create/experimental/SpecialIntentControls.tsx b/src/components/create/experimental/SpecialIntentControls.tsx
index 665b9fbd..f52c026f 100644
--- a/src/components/create/experimental/SpecialIntentControls.tsx
+++ b/src/components/create/experimental/SpecialIntentControls.tsx
@@ -38,9 +38,11 @@ import { createRunModel, studioShownValue } from '../../../lib/render/create-stu
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,
+ SWAP_AUTO_MODELS, SWAP_CONSENT_TEXT, SWAP_INTENT, SWAP_OPENJUTSU_MODEL, SWAP_TIPS, swapAutoModel, swapBilledPhotos,
+ swapDefaultOptions, swapFigureRoles, swapMaxPeople, swapNeedsConsent, swapReadsRoles, swapUsesFrame,
} from '../../../lib/render/swap'
+import { swapFrameCredits } from '../../../lib/create/swap-frame'
+import { SwapFrameBuild, SwapFramePicker, useSwapFirstFrame } from './SwapFrameSteps'
import { mediaSeconds } from './useStudioPrice'
import { ClipLength } from './ClipLength'
import { galleryLabelShort } from '../../../lib/render/gallery-label'
@@ -1737,13 +1739,15 @@ function MotionControls() {
)
}
-// ── Swap Character (07.11.2026, port of the web's C52) ─────────────────────
+// ── Swap Character (07.11.2026, port of the web's C52; two steps since
+// 14.11.2026) ───────────────────────────────────────────────────────────────
//
// 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.
+// first frame to tap each person to replace, the people (photo and role each),
+// the length with its price, the consent box for the models that need it, and
+// on SCAIL 2 and Kling the frame step (build, check, Continue). Create and its
+// price stand in the Composer's action bar below.
export function SwapControls() {
const videoInput = useCreateStore((s) => s.videoInput)
@@ -1758,7 +1762,12 @@ export function SwapControls() {
const opModel = useCreateStore((s) => s.cloudOpModel)
const setOpModel = useCreateStore((s) => s.setCloudOpModel)
const isGenerating = useCreateStore((s) => s.isGenerating)
+ const frame = useCreateStore((s) => s.swapFrame)
const model = createRunModel('swap_character', { image: '', video: '', op: opModel })
+ // SCAIL 2 and Kling: the first frame first, then the video (SwapFrameSteps).
+ const twoStep = swapUsesFrame(SWAP_INTENT, model)
+ // The first frame to tap; for OpenJutsu too, whose roles come from it.
+ useSwapFirstFrame()
// 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(() => {
@@ -1769,20 +1778,32 @@ export function SwapControls() {
}, [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)
+ // The model follows the number of people: up to 3 SCAIL 2, with 4
+ // OpenJutsu. Only between these two; Kling or Wan picked by hand stays. It
+ // switches only when the target changes, not on opening the panel: an own
+ // pick (OpenJutsu for 2 people) stays.
+ const auto = SWAP_AUTO_MODELS.includes(model)
+ const target = swapAutoModel(figures.length)
const known = !!STUDIO_MODELS[model]
+ const lastTarget = useRef(target)
useEffect(() => {
+ if (lastTarget.current === target) return
+ lastTarget.current = target
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
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [auto, known, target])
+ // What Swap presets (SCAIL 2: 720p) stands in the store, so slider, button
+ // and run see the same number.
+ useEffect(() => {
+ if (!known) return
+ const preset = swapDefaultOptions(SWAP_INTENT, model)
+ const missing = Object.entries(preset).filter(([k]) => options[k] === undefined)
+ if (missing.length) setOptions({ ...options, ...Object.fromEntries(missing) })
+ }, [known, model, options, setOptions])
+ // One tap more than the model can do: onto the model that can do that many.
+ const fitPeople = (people: number) => {
+ if (people > swapMaxPeople(model)) setOpModel(swapAutoModel(people))
+ }
if (!known) {
// The server's catalogue does not list the swap models yet.
@@ -1794,17 +1815,22 @@ export function SwapControls() {
}
const maxPeople = swapMaxPeople(model)
- const roles = swapReadsRoles(model)
+ const roles = swapReadsRoles(model) || twoStep
+ const placed = swapFigureRoles(figures.map((f) => ({ ...f, role: '' })))
+ const frameCredits = twoStep ? swapFrameCredits(frame?.width ?? 9, frame?.height ?? 16, figures.length) : null
+ // The marks in the first frame: up to the limit of Swap (OpenJutsu: 4).
+ const markMax = swapMaxPeople(SWAP_OPENJUTSU_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>
+ <div className="flex flex-col items-center gap-2.5" data-swap-controls data-swap-two-step={twoStep || undefined}>
+ {/* Grey, not a warning (the desktop's house rule, lib/hinweis.ts). */}
+ <div 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>
+ <ul className="space-y-0.5">{SWAP_TIPS.map((t) => <li key={t}>{t}</li>)}</ul>
+ </div>
<div className="flex w-full items-center justify-between gap-2 flex-wrap">
<DrivingVideoChip empty="Add original video" />
{resolutions.length > 1 && (
@@ -1819,6 +1845,8 @@ export function SwapControls() {
)}
</div>
+ {videoInput && <SwapFramePicker max={markMax} onCount={fitPeople} />}
+
<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}>
@@ -1831,7 +1859,9 @@ export function SwapControls() {
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)'}
+ placeholder={placed[i]
+ ? `${placed[i]} (or describe who)`
+ : 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"
/>
@@ -1852,22 +1882,26 @@ export function SwapControls() {
</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>
+ {/* SCAIL 2 and Kling: people come in by a tap on the first frame.
+ Without a video, and with OpenJutsu, also by this button. */}
+ {(!twoStep || !videoInput) && (
+ <button
+ type="button"
+ disabled={figures.length >= 4 || isGenerating}
+ onClick={() => {
+ // Not every model takes several people. The switch is said in
+ // the sentence below, it does not happen silently.
+ fitPeople(figures.length + 1)
+ 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.
+ {modelLabel(model)} replaces {maxPeople === 1 ? 'one person' : `up to ${maxPeople} people`}.
</span>
)}
</div>
@@ -1880,15 +1914,13 @@ export function SwapControls() {
chosen={swapSeconds}
onChange={setSwapSeconds}
photos={swapBilledPhotos(model, figures.length)}
- span={span}
disabled={isGenerating}
+ frameCredits={frameCredits}
/>
- {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) && (
+ // A real person is swapped for a photo: the customer confirms rights
+ // and consent first (the server asks too, for the frame step as for
+ // the video).
<label className="flex w-full items-start gap-2 t-control text-gray-300 cursor-pointer" data-swap-consent>
<input
type="checkbox"
@@ -1900,6 +1932,7 @@ export function SwapControls() {
<span>{SWAP_CONSENT_TEXT}</span>
</label>
)}
+ {twoStep && <SwapFrameBuild model={model} />}
</div>
)
}
diff --git a/src/components/create/experimental/SwapFrameSteps.tsx b/src/components/create/experimental/SwapFrameSteps.tsx
new file mode 100644
index 00000000..8e5b3078
--- /dev/null
+++ b/src/components/create/experimental/SwapFrameSteps.tsx
@@ -0,0 +1,287 @@
+import { useEffect, useMemo, useRef, useState } from 'react'
+import { Check, ImageIcon, RotateCcw } from 'lucide-react'
+import { useCreateStore, type SwapFigure } from '../../../stores/createStore'
+import { cancelJob, pollJob, submitCloudJob, uploadInput } from '../../../api/cloud/jobs'
+import { describeSubmitError, failedJobText } from '../../../lib/create/engine'
+import { runSwapFrame, swapFrameCredits, swapKeyOf } from '../../../lib/create/swap-frame'
+import { swapFigureRoles, swapMaxPeople, swapShortCredits, SWAP_TAP_TEXT } from '../../../lib/render/swap'
+import { signalCreditsExhausted } from '../../../lib/credits-exhausted'
+import { HINWEIS_TEXT } from '../../../lib/hinweis'
+import { useCreateExp } from './CreateContext'
+import { cn } from '../ui/cn'
+
+// Swap Character in two steps (14.11.2026, part A of the Character Hub, port
+// of the web's SwapFrameSteps). First the customer taps each person to
+// replace in the first frame of the video. Then Nano Banana Pro builds that
+// frame with the new people ("Build first frame"), the customer checks it
+// ("Does this look right?") and confirms with Continue. Only then does Create
+// arm for the video.
+
+/** The first frame of a video as a JPEG, drawn in the WebView (<video> at the
+ * start, painted onto a canvas). At most 2048 pixels on the long side. The
+ * desktop's video is a `blob:` URL of the picked file (mediaRef.ts), same
+ * origin, so the canvas stays readable. */
+export function firstVideoFrame(url: string, maxSide = 2048): Promise<{ url: string; width: number; height: number }> {
+ return new Promise((resolve, reject) => {
+ const video = document.createElement('video')
+ let done = false
+ const fail = () => reject(new Error('Could not read the first frame of your video.'))
+ const finish = (fn: () => void) => {
+ if (done) return
+ done = true
+ clearTimeout(timer)
+ fn()
+ video.removeAttribute('src')
+ video.load()
+ }
+ const timer = setTimeout(() => finish(fail), 15_000)
+ const draw = () => finish(() => {
+ const w = video.videoWidth, h = video.videoHeight
+ if (!w || !h) { fail(); return }
+ const scale = Math.min(1, maxSide / Math.max(w, h))
+ const canvas = document.createElement('canvas')
+ canvas.width = Math.round(w * scale)
+ canvas.height = Math.round(h * scale)
+ const ctx = canvas.getContext('2d')
+ if (!ctx) { fail(); return }
+ try {
+ ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
+ resolve({ url: canvas.toDataURL('image/jpeg', 0.92), width: canvas.width, height: canvas.height })
+ } catch {
+ fail()
+ }
+ })
+ video.muted = true
+ video.playsInline = true
+ video.preload = 'auto'
+ video.onloadeddata = () => { if (video.currentTime === 0) draw() }
+ video.onseeked = draw
+ video.onloadedmetadata = () => { try { video.currentTime = 0 } catch { /* the first frame comes with loadeddata */ } }
+ video.onerror = () => finish(fail)
+ video.src = url
+ })
+}
+
+/** Draws the first frame as soon as a video is there and puts it in the store. */
+export function useSwapFirstFrame(): void {
+ const videoInput = useCreateStore((s) => s.videoInput)
+ const swapFrame = useCreateStore((s) => s.swapFrame)
+ const setSwapFrame = useCreateStore((s) => s.setSwapFrame)
+ useEffect(() => {
+ if (!videoInput) { if (swapFrame) setSwapFrame(null); return }
+ if (swapFrame?.videoUrl === videoInput.url) return
+ let alive = true
+ void firstVideoFrame(videoInput.url)
+ .then((f) => { if (alive) setSwapFrame({ ...f, videoUrl: videoInput.url }) })
+ .catch(() => { if (alive) setSwapFrame(null) })
+ return () => { alive = false }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [videoInput?.url])
+}
+
+/** The first frame, large, with a numbered mark per tapped person. A tap sets
+ * a mark, a tap on the mark takes it away again. */
+export function SwapFramePicker({ max, onCount }: { max: number; onCount: (people: number) => void }) {
+ const frame = useCreateStore((s) => s.swapFrame)
+ const figures = useCreateStore((s) => s.swapFigures)
+ const setFigures = useCreateStore((s) => s.setSwapFigures)
+ const isGenerating = useCreateStore((s) => s.isGenerating)
+ const box = useRef<HTMLDivElement>(null)
+ if (!frame) {
+ return (
+ <div className="flex h-24 w-full items-center justify-center rounded-lg border border-dashed border-white/10 t-control text-gray-500" data-swap-frame="loading">
+ Reading the first frame…
+ </div>
+ )
+ }
+ const marked = figures.filter((f) => f.mark).length
+
+ const add = (x: number, y: number) => {
+ if (isGenerating || marked >= max) return
+ const mark = { x: Math.min(1, Math.max(0, x)), y: Math.min(1, Math.max(0, y)) }
+ // The first person without a mark gets it, else a new one joins.
+ const free = figures.findIndex((f) => !f.mark)
+ const next: SwapFigure[] = free >= 0
+ ? figures.map((f, i) => (i === free ? { ...f, mark } : f))
+ : [...figures, { image: null, role: '', mark }]
+ onCount(next.length)
+ setFigures(next)
+ }
+ const remove = (index: number) => {
+ if (isGenerating) return
+ // The last person stays and only loses the mark (then: the main person).
+ const next = figures.length > 1 ? figures.filter((_, i) => i !== index) : figures.map((f) => ({ ...f, mark: null }))
+ onCount(next.length)
+ setFigures(next)
+ }
+
+ return (
+ <div className="flex w-full flex-col items-center gap-1.5" data-swap-frame="picker">
+ <p className="t-control text-gray-300">{SWAP_TAP_TEXT}</p>
+ <div
+ ref={box}
+ role="group"
+ aria-label={`First frame of your video. ${SWAP_TAP_TEXT}.`}
+ onClick={(e) => {
+ const r = box.current?.getBoundingClientRect()
+ if (!r || !r.width || !r.height) return
+ add((e.clientX - r.left) / r.width, (e.clientY - r.top) / r.height)
+ }}
+ className={cn('relative max-w-full overflow-hidden rounded-lg border border-white/10 bg-white/[0.03]', marked < max && 'cursor-crosshair')}
+ style={{ aspectRatio: `${frame.width} / ${frame.height}`, height: `min(46vh, 420px, calc(min(100vw - 58px, 560px) * ${(frame.height / frame.width).toFixed(4)}))` }}
+ >
+ <img src={frame.url} alt="" draggable={false} className="pointer-events-none h-full w-full select-none object-cover" />
+ {figures.map((f, i) => f.mark && (
+ <button
+ key={i}
+ type="button"
+ aria-label={`Remove mark ${i + 1}`}
+ data-swap-mark={i + 1}
+ onClick={(e) => { e.stopPropagation(); remove(i) }}
+ // 44 px to hit with a finger or a trackpad, the circle inside is what shows.
+ className="absolute grid h-11 w-11 -translate-x-1/2 -translate-y-1/2 place-items-center rounded-full"
+ style={{ left: `${f.mark.x * 100}%`, top: `${f.mark.y * 100}%` }}
+ >
+ <span className="grid h-7 w-7 place-items-center rounded-full bg-lu-accent t-control font-semibold text-white shadow-[0_0_0_2px_rgba(255,255,255,0.9),0_2px_8px_rgba(0,0,0,0.45)]">{i + 1}</span>
+ </button>
+ ))}
+ </div>
+ <p className="t-control text-gray-500" data-swap-frame-count={marked}>
+ {marked === 0 ? 'No mark: the main person is replaced.' : `${marked} of ${max} ${max === 1 ? 'person' : 'people'} marked. Tap a number to remove it.`}
+ </p>
+ </div>
+ )
+}
+
+const QUIET_BUTTON = 't-control inline-flex h-11 shrink-0 items-center gap-1.5 rounded-[var(--radius-control)] border border-white/[0.1] px-3 text-gray-300 hover:border-white/20 hover:text-gray-100 disabled:opacity-40'
+const PRIMARY_BUTTON = 'lu-primary t-control inline-flex h-11 shrink-0 items-center gap-1.5 rounded-[var(--radius-control)] px-4 font-medium disabled:opacity-40'
+
+/** Build, check, confirm the frame. Stands below the consent box. */
+export function SwapFrameBuild({ model }: { model: string }) {
+ const { refreshQuota } = useCreateExp()
+ const videoInput = useCreateStore((s) => s.videoInput)
+ const frame = useCreateStore((s) => s.swapFrame)
+ const figures = useCreateStore((s) => s.swapFigures)
+ const consent = useCreateStore((s) => s.swapConsent)
+ const built = useCreateStore((s) => s.swapBuilt)
+ const setBuilt = useCreateStore((s) => s.setSwapBuilt)
+ const isGenerating = useCreateStore((s) => s.isGenerating)
+ const [busy, setBusy] = useState(false)
+ const [step, setStep] = useState('')
+ const [error, setError] = useState<string | null>(null)
+ const [extra, setExtra] = useState('')
+ const abort = useRef<AbortController | null>(null)
+ useEffect(() => () => abort.current?.abort(), [])
+
+ const key = useMemo(() => swapKeyOf(videoInput?.url, figures), [videoInput?.url, figures])
+ // When video, photo, mark or role change, the built frame expires.
+ useEffect(() => {
+ if (built && built.key !== key) setBuilt(null)
+ }, [built, key, setBuilt])
+ const current = built && built.key === key ? built : null
+ const credits = swapFrameCredits(frame?.width ?? 9, frame?.height ?? 16, figures.length)
+ const price = credits != null ? `${swapShortCredits(credits)} credits` : ''
+ const ready = !!frame && figures.every((f) => !!f.image) && figures.length <= swapMaxPeople(model) && consent && !busy && !isGenerating
+
+ const build = async (retry: boolean) => {
+ if (!ready) return
+ setBusy(true)
+ setError(null)
+ const ac = new AbortController()
+ abort.current = ac
+ try {
+ const job = await runSwapFrame({
+ frame,
+ figures: figures.map((f) => ({ imageUrl: f.image?.url ?? null, role: f.role, mark: f.mark ?? null })),
+ model,
+ consent,
+ extra: retry ? extra : undefined,
+ credits,
+ }, { uploadInput: (file, role) => uploadInput(file, role, { signal: ac.signal }), submitCloudJob, pollJob, cancelJob, signal: ac.signal, onStep: setStep })
+ if (job.status === 'succeeded' && job.result_url) {
+ setBuilt({ jobId: job.id, url: job.result_url, key, confirmed: false })
+ setExtra('')
+ } else if (job.status !== 'canceled') {
+ setError(failedJobText(job))
+ }
+ } catch (err) {
+ const failure = describeSubmitError(err, signalCreditsExhausted)
+ if (failure.text) setError(failure.text === 'Canceled.' ? null : failure.text)
+ } finally {
+ setBusy(false)
+ setStep('')
+ void refreshQuota()
+ }
+ }
+
+ const roles = swapFigureRoles(figures)
+ const who = figures.length > 1 ? `${figures.length} people` : roles[0] || 'the main person'
+
+ if (current?.confirmed) {
+ return (
+ <div className="flex w-full items-center gap-2 rounded-lg border border-white/[0.08] px-2 py-1.5" data-swap-built="confirmed">
+ <img src={current.url} alt="New first frame" className="h-10 w-10 shrink-0 rounded-md object-cover" />
+ <span className="flex min-w-0 flex-1 items-center gap-1.5 t-body text-gray-200">
+ <Check size={14} className="shrink-0 text-lu-accent" /> First frame ready. Create starts the video.
+ </span>
+ <button type="button" disabled={isGenerating} onClick={() => setBuilt({ ...current, confirmed: false })}
+ className="t-control h-11 shrink-0 rounded-md px-2 text-gray-500 hover:text-gray-200 disabled:opacity-40">
+ Change
+ </button>
+ </div>
+ )
+ }
+
+ if (current) {
+ return (
+ <div className="w-full space-y-2 rounded-lg border border-white/[0.08] p-2.5" data-swap-built="review">
+ <p className="t-control font-semibold text-gray-100">Does this look right?</p>
+ <div className="grid grid-cols-2 gap-2">
+ {[{ src: frame?.url, label: 'Original' }, { src: current.url, label: 'New first frame' }].map((p) => (
+ <figure key={p.label} className="flex flex-col items-center gap-1">
+ {p.src ? <img src={p.src} alt={p.label} className="max-h-[38vh] w-full rounded-md bg-white/[0.03] object-contain" /> : <ImageIcon size={18} />}
+ <figcaption className="t-control text-gray-500">{p.label}</figcaption>
+ </figure>
+ ))}
+ </div>
+ <input
+ type="text"
+ value={extra}
+ maxLength={500}
+ disabled={busy}
+ aria-label="What's wrong?"
+ placeholder="What's wrong? (optional)"
+ onChange={(e) => setExtra(e.target.value)}
+ className="t-control h-11 w-full rounded-md border border-white/[0.08] bg-white/[0.03] px-2 text-gray-200 placeholder:text-gray-500"
+ />
+ {error && <p className={cn('t-body', HINWEIS_TEXT.fehler)} role="alert">{error}</p>}
+ <div className="flex flex-wrap items-center justify-end gap-2">
+ <button type="button" disabled={!ready} onClick={() => void build(true)} data-swap-retry className={QUIET_BUTTON}>
+ <RotateCcw size={13} /> {busy ? step || 'Building…' : `Try again · ${price}`}
+ </button>
+ <button type="button" disabled={busy} onClick={() => setBuilt({ ...current, confirmed: true })} data-swap-continue className={PRIMARY_BUTTON}>
+ <Check size={14} /> Continue
+ </button>
+ </div>
+ </div>
+ )
+ }
+
+ return (
+ <div className="flex w-full flex-col gap-1.5" data-swap-built="none">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <span className="t-body min-w-0 flex-1 text-gray-500">
+ Step 1: put {who} into the first frame. You check it before the video starts.
+ </span>
+ <button type="button" disabled={!ready} onClick={() => void build(false)} data-swap-build
+ title={price ? `Build first frame · ${credits!.toLocaleString('en-US')} credits` : 'Build first frame'}
+ className={ready ? PRIMARY_BUTTON : cn(QUIET_BUTTON, 'cursor-not-allowed text-gray-500')}>
+ <ImageIcon size={14} />
+ {busy ? step || 'Building…' : 'Build first frame'}
+ {!busy && price && <span className="t-micro tabular-nums rounded-md bg-black/10 px-1.5 py-0.5 leading-none">{swapShortCredits(credits!)}</span>}
+ </button>
+ </div>
+ {error && <p className={cn('t-body', HINWEIS_TEXT.fehler)} role="alert">{error}</p>}
+ </div>
+ )
+}
diff --git a/src/components/create/experimental/__tests__/swap-character-panel.test.tsx b/src/components/create/experimental/__tests__/swap-character-panel.test.tsx
index 0911d034..5c085500 100644
--- a/src/components/create/experimental/__tests__/swap-character-panel.test.tsx
+++ b/src/components/create/experimental/__tests__/swap-character-panel.test.tsx
@@ -1,24 +1,27 @@
// @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.
+ * Swap Character on the desktop (07.11.2026, port of the web's C52; two steps
+ * with SCAIL 2 and Kling since 14.11.2026): the panel in the web's order
+ * (notes, video and resolution, first frame, people, length, consent, frame
+ * step), the marks, the model picker, and Create only once the video, a photo
+ * for every person, the consent and (SCAIL 2, Kling) the confirmed first
+ * frame are there. Nothing is rendered or booked: the Composer's generate and
+ * the cloud calls of the frame step are fakes, 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'
+import { render, cleanup, screen, fireEvent, act, waitFor } 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 },
}
+const refreshQuota = vi.fn(async () => {})
vi.mock('../CreateContext', () => ({
useCreateExp: () => ({
- generate: vi.fn(), cancel: vi.fn(), makeVoice: vi.fn(), quota: QUOTA,
+ generate: vi.fn(), cancel: vi.fn(), makeVoice: vi.fn(), quota: QUOTA, refreshQuota,
samplerList: [], schedulerList: [], loraList: [], vaeList: [], refreshModelLists: vi.fn(),
connected: true, modelsLoaded: true, modelLoadError: null, mlxMissing: null,
installCapability: vi.fn(), installModelBundle: vi.fn(),
@@ -28,18 +31,35 @@ vi.mock('../../../../api/backend', async (orig) => ({
...((await orig()) as Record<string, unknown>),
openExternal: vi.fn(),
}))
+// The frame step: never a real run, every cloud call a fake.
+const cloud = vi.hoisted(() => ({
+ uploadInput: vi.fn(async (_b: Blob, role: string) => `u/${role}-${Math.random().toString(36).slice(2, 6)}`),
+ submitCloudJob: vi.fn(async (_s: unknown) => ({ id: 'bild-1', quota: { cost: 14000 } })),
+ pollJob: vi.fn(async (id: string) => ({ id, status: 'succeeded', result_url: 'https://ours.example/bild.jpg' })),
+ cancelJob: vi.fn(async () => ({ status: 'canceled' })),
+}))
+vi.mock('../../../../api/cloud/jobs', async (orig) => ({ ...((await orig()) as Record<string, unknown>), ...cloud }))
+// jsdom plays no video: the length the WebView would measure.
+const videoLength = vi.hoisted(() => ({ seconds: undefined as number | undefined }))
+vi.mock('../useStudioPrice', async (orig) => ({
+ ...((await orig()) as Record<string, unknown>),
+ mediaSeconds: async () => videoLength.seconds,
+}))
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'
+import { SWAP_CONSENT_TEXT, SWAP_OPENJUTSU_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' }
+const FRAME = { url: 'data:image/jpeg;base64,eA==', width: 1080, height: 1920, videoUrl: 'blob:dance' }
beforeEach(() => {
+ for (const f of Object.values(cloud)) f.mockClear()
+ videoLength.seconds = undefined
useCloudCatalogStore.setState({ models: neuerServer() })
useCreateStore.setState({
isGenerating: false, batchRun: null, error: null, gallery: [], source: null, videoInput: null, prompt: '',
@@ -48,40 +68,45 @@ beforeEach(() => {
cloudOpModel: '',
} as never)
useCreateStore.getState().setIntent('swap_character')
- useCreateStore.setState({ swapFigures: [{ image: null, role: '' }], swapSeconds: null, swapConsent: false })
+ useCreateStore.setState({ swapFigures: [{ image: null, role: '' }], swapSeconds: null, swapConsent: false, swapBuilt: null, swapFrame: null })
})
afterEach(() => cleanup())
function open() {
- render(<Composer onOpenAdvanced={() => {}} onOpenWorkflows={() => {}} />)
+ return 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', () => {
+ it('stands in the web order: notes, video, people, length, consent; no prompt field; SCAIL 2 at 720p', () => {
open()
expect(panel()).toBeTruthy()
expect(document.querySelector('textarea')).toBeNull()
- const order = ['[data-swap-tips]', '[data-swap-figures]', '[data-clip-length]', '[data-swap-consent]']
+ const order = ['[data-swap-tips]', '[data-swap-figures]', '[data-clip-length]', '[data-swap-consent]', '[data-swap-built]']
.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(' '))
+ // The notes, one line each, grey and not a warning.
+ const tips = panel().querySelector('[data-swap-tips]') as HTMLElement
+ expect([...tips.querySelectorAll('li')].map((li) => li.textContent)).toEqual([...SWAP_TIPS])
+ expect(tips.className).toMatch(/text-gray-500/)
+ expect(tips.className).not.toMatch(/amber|yellow/)
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.
+ // SCAIL 2 is the default, preset to 720p in the store.
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).
+ expect([...res.querySelectorAll('[role=radio]')].map((b) => b.textContent)).toEqual(['480p', '720p'])
+ expect(res.querySelector('[aria-checked=true]')?.textContent).toBe('720p')
+ expect(useCreateStore.getState().cloudStudioOptions.resolution).toBe('720p')
const slider = document.getElementById('swap-length') as HTMLInputElement
- expect([slider.min, slider.max]).toEqual(['2', '120'])
+ expect([slider.min, slider.max]).toEqual(['1', '120'])
})
- it('adds people up to four, each with a photo field and a role', () => {
+ it('OpenJutsu: adds people up to four, each with a photo field and a role', () => {
+ useCreateStore.getState().setCloudOpModel(SWAP_OPENJUTSU_MODEL)
open()
const add = () => screen.getByRole('button', { name: /Add person/ }) as HTMLButtonElement
expect(add().textContent).toBe('+ Add person (1/4)')
@@ -97,71 +122,201 @@ describe('the Swap Character panel', () => {
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')
+ it('switches Kling to SCAIL 2 when a second person comes, and SCAIL 2 to OpenJutsu at the fourth', () => {
+ useCreateStore.getState().setCloudOpModel('kling-v3-pro-motion-control')
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)
+ expect(useCreateStore.getState().cloudOpModel).toBe('scail-2')
+ fireEvent.click(screen.getByRole('button', { name: /Add person/ }))
+ expect(useCreateStore.getState().cloudOpModel).toBe('scail-2')
+ fireEvent.click(screen.getByRole('button', { name: /Add person/ }))
+ expect(useCreateStore.getState().cloudOpModel).toBe(SWAP_OPENJUTSU_MODEL)
})
- it('arms Create only with the video, every photo and the consent', () => {
+ it('OpenJutsu (one step) arms Create with the video, every photo and the consent', () => {
+ useCreateStore.getState().setCloudOpModel(SWAP_OPENJUTSU_MODEL)
open()
expect(create().disabled).toBe(true)
- act(() => { useCreateStore.setState({ videoInput: clip } as never) })
+ act(() => { useCreateStore.setState({ videoInput: clip, swapFrame: FRAME } 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.
+ // No frame step on OpenJutsu.
+ expect(document.querySelector('[data-swap-built]')).toBeNull()
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')
+ it('shows the consent box on SCAIL 2 and Kling too', () => {
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', () => {
+ expect(document.querySelector('[data-swap-consent]')).toBeTruthy()
+ cleanup()
+ useCreateStore.getState().setCloudOpModel('kling-v3-pro-motion-control')
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)
+ expect(document.querySelector('[data-swap-consent]')).toBeTruthy()
})
- it('names the live price beside the length: credits and credits per second', () => {
+ it('OpenJutsu: names the live price beside the length (15 s, not 120 s)', () => {
+ useCreateStore.getState().setCloudOpModel(SWAP_OPENJUTSU_MODEL)
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')
})
+
+ it('SCAIL 2: frame and video together beside the length', () => {
+ useCreateStore.setState({ swapSeconds: 6 })
+ open()
+ const box = document.querySelector('[data-clip-length]')!
+ // 6 s at 720p (8,000/s) plus the first frame (Nano Banana Pro 2k, 14,000).
+ expect(box.querySelector('[data-clip-price]')?.textContent).toBe('62,000 credits · frame + video')
+ expect(box.querySelector('[data-clip-split]')?.textContent).toBe('First frame 14,000 · video 48,000 (8,000/s)')
+ })
+
+ it('Kling 6 s: 100,800 credits for the video', () => {
+ useCreateStore.getState().setCloudOpModel('kling-v3-pro-motion-control')
+ useCreateStore.setState({ swapSeconds: 6 })
+ open()
+ expect(document.querySelector('[data-clip-split]')?.textContent).toBe('First frame 14,000 · video 100,800 (16,800/s)')
+ })
+})
+
+describe('two steps in the panel (14.11.2026)', () => {
+ let rect: { mockRestore: () => void }
+ beforeEach(() => {
+ // jsdom measures nothing: the first frame is 100 x 200 pixels here.
+ rect = vi.spyOn(Element.prototype, 'getBoundingClientRect').mockReturnValue({ left: 0, top: 0, width: 100, height: 200, right: 100, bottom: 200, x: 0, y: 0, toJSON: () => ({}) } as DOMRect)
+ })
+ afterEach(() => { rect.mockRestore() })
+
+ const frameBox = () => screen.getByRole('group', { name: /First frame of your video/ })
+
+ it('tap people: numbered marks, the place becomes the role, a tap on the mark removes it', () => {
+ useCreateStore.setState({ videoInput: clip, swapFrame: FRAME } as never)
+ const { rerender } = open()
+ expect(screen.getByText('Tap each person you want to replace')).toBeTruthy()
+ fireEvent.click(frameBox(), { clientX: 80, clientY: 60 })
+ fireEvent.click(frameBox(), { clientX: 20, clientY: 70 })
+ rerender(<Composer onOpenAdvanced={() => {}} onOpenWorkflows={() => {}} />)
+ const figs = useCreateStore.getState().swapFigures
+ expect(figs).toHaveLength(2)
+ expect(figs.map((f) => f.mark)).toEqual([{ x: 0.8, y: 0.3 }, { x: 0.2, y: 0.35 }])
+ expect((screen.getByRole('textbox', { name: 'Who person 1 replaces' }) as HTMLInputElement).placeholder).toMatch(/^the person on the right/)
+ expect((screen.getByRole('textbox', { name: 'Who person 2 replaces' }) as HTMLInputElement).placeholder).toMatch(/^the person on the left/)
+ // SCAIL 2: people come in by a tap, no Add person button.
+ expect(screen.queryByRole('button', { name: /Add person/ })).toBeNull()
+ // 44 px to hit.
+ const mark = screen.getByRole('button', { name: 'Remove mark 1' })
+ expect(mark.className).toMatch(/h-11 w-11/)
+ fireEvent.click(mark)
+ expect(useCreateStore.getState().swapFigures).toHaveLength(1)
+ expect(useCreateStore.getState().swapFigures[0].mark).toEqual({ x: 0.2, y: 0.35 })
+ })
+
+ it('the fourth mark switches to OpenJutsu, no more than 4; Kling stays with one person', () => {
+ useCreateStore.setState({ videoInput: clip, swapFrame: FRAME, cloudOpModel: 'kling-v3-pro-motion-control' } as never)
+ open()
+ fireEvent.click(frameBox(), { clientX: 10, clientY: 10 })
+ expect(useCreateStore.getState().cloudOpModel).toBe('kling-v3-pro-motion-control')
+ fireEvent.click(frameBox(), { clientX: 50, clientY: 10 })
+ // Two people Kling cannot do: SCAIL 2 takes over.
+ expect(useCreateStore.getState().cloudOpModel).toBe('scail-2')
+ fireEvent.click(frameBox(), { clientX: 90, clientY: 10 })
+ fireEvent.click(frameBox(), { clientX: 30, clientY: 90 })
+ expect(useCreateStore.getState().swapFigures).toHaveLength(4)
+ expect(useCreateStore.getState().cloudOpModel).toBe(SWAP_OPENJUTSU_MODEL)
+ fireEvent.click(frameBox(), { clientX: 60, clientY: 90 })
+ expect(useCreateStore.getState().swapFigures).toHaveLength(4)
+ })
+
+ it('the picker shows Kling greyed out with "one person only" for several people, SCAIL 2 recommended', () => {
+ useCreateStore.setState({ videoInput: clip, swapFrame: FRAME, swapFigures: [{ image: null, role: '' }, { image: null, role: '' }] } as never)
+ open()
+ const chip = [...document.querySelectorAll('button')].find((b) => /SCAIL 2/.test(b.textContent ?? '') && !b.closest('[role=listbox]'))!
+ fireEvent.click(chip)
+ const kling = screen.getByText('Kling 3.0 Pro \u2022 Motion Control').closest('button') as HTMLButtonElement
+ expect(kling.disabled).toBe(true)
+ expect(kling.textContent).toMatch(/one person only/)
+ fireEvent.click(kling)
+ expect(useCreateStore.getState().cloudOpModel).not.toBe('kling-v3-pro-motion-control')
+ const scail = screen.getAllByText(/SCAIL 2/).map((el) => el.closest('button')).find((b) => b?.textContent?.includes('Recommended'))
+ expect(scail).toBeTruthy()
+ })
+
+ it('Build first frame, Does this look right?, Try again, Continue: only then Create', async () => {
+ videoLength.seconds = 6.006
+ useCreateStore.setState({
+ videoInput: clip, swapFrame: FRAME, swapSeconds: null,
+ swapFigures: [{ image: photo, role: '', mark: { x: 0.3, y: 0.4 } }], swapConsent: false,
+ } as never)
+ open()
+ await act(async () => {})
+ expect(create().disabled).toBe(true)
+ const build = () => screen.getByRole('button', { name: /Build first frame/ }) as HTMLButtonElement
+ // The tick stands before the frame step and counts for it too.
+ expect(build().disabled).toBe(true)
+ const box = document.querySelector('[data-swap-consent]')!
+ expect(box.compareDocumentPosition(build()) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
+ fireEvent.click(box.querySelector('input')!)
+ expect(build().disabled).toBe(false)
+ expect(build().title).toBe('Build first frame · 14,000 credits')
+ expect(build().textContent).toMatch(/Build first frame\s*14k/)
+ expect(create().disabled).toBe(true)
+ await act(async () => { fireEvent.click(build()) })
+ await screen.findByText('Does this look right?')
+ expect(cloud.submitCloudJob).toHaveBeenCalledTimes(1)
+ const first = cloud.submitCloudJob.mock.calls[0][0] as { model: string; prompt: string; params: Record<string, unknown> }
+ expect(first.model).toBe('nano-banana-pro-edit')
+ expect(first.params).toMatchObject({ swap_step: 'frame', swap_consent: true, max_credits: 14000, studio_options: { aspect_ratio: '9:16', resolution: '2k', output_format: 'jpeg' } })
+ expect(first.params.image_paths as string[]).toHaveLength(2)
+ expect(first.prompt).toMatch(/^Replace the person in the first image/)
+ expect(screen.getByRole('img', { name: 'Original' })).toBeTruthy()
+ expect((screen.getByRole('img', { name: 'New first frame' }) as HTMLImageElement).src).toBe('https://ours.example/bild.jpg')
+ expect(create().disabled).toBe(true)
+
+ // Try again with a sentence on what is wrong: a new image job.
+ fireEvent.change(screen.getByRole('textbox', { name: "What's wrong?" }), { target: { value: 'head turned to the side' } })
+ const again = screen.getByRole('button', { name: /Try again · 14k credits/ })
+ await act(async () => { fireEvent.click(again) })
+ await waitFor(() => expect(cloud.submitCloudJob).toHaveBeenCalledTimes(2))
+ expect((cloud.submitCloudJob.mock.calls[1][0] as { prompt: string }).prompt).toMatch(/Fix this from the last attempt: head turned to the side$/)
+ await screen.findByText('Does this look right?')
+
+ fireEvent.click(screen.getByRole('button', { name: /Continue/ }))
+ expect(screen.getByText(/First frame ready/)).toBeTruthy()
+ expect(create().disabled).toBe(false)
+
+ // Another role: the frame no longer fits and expires.
+ fireEvent.change(screen.getByRole('textbox', { name: 'Who person 1 replaces' }), { target: { value: 'the man in red' } })
+ expect(create().disabled).toBe(true)
+ await waitFor(() => expect(useCreateStore.getState().swapBuilt).toBeNull())
+ expect(screen.getByRole('button', { name: /Build first frame/ })).toBeTruthy()
+ })
+
+ it('another video drops the first frame, the marks and the built frame', () => {
+ useCreateStore.setState({
+ videoInput: clip, swapFrame: FRAME, swapBuilt: { jobId: 'b', url: 'x', key: 'k', confirmed: true },
+ swapFigures: [{ image: photo, role: '', mark: { x: 0.5, y: 0.5 } }],
+ } as never)
+ useCreateStore.getState().setVideoInput({ name: 'other.mp4', url: 'blob:w', blob: new Blob(['w']) })
+ const s = useCreateStore.getState()
+ expect(s.swapFrame).toBeNull()
+ expect(s.swapBuilt).toBeNull()
+ expect(s.swapFigures[0].mark).toBeNull()
+ expect(s.swapFigures[0].image).toBe(photo)
+ })
})
describe('the Swap Stage', () => {
diff --git a/src/components/create/ui/Select.tsx b/src/components/create/ui/Select.tsx
index 01af9f25..e8b619b2 100644
--- a/src/components/create/ui/Select.tsx
+++ b/src/components/create/ui/Select.tsx
@@ -17,6 +17,9 @@ export interface SelectOption {
badge?: SelectTag
/** Kleine Marken hinter dem Namen, nur in der aufgeklappten Liste (etwa Stufe und Herkunft). */
tags?: SelectTag[]
+ /** Listed, but not pickable right now; `sublabel` says why (Swap Character:
+ * Kling "one person only" with several people). */
+ disabled?: boolean
}
/** Eine Marke im Etiketten-Stil der Modellwaehler (index.css, .lu-picker-tag):
@@ -258,12 +261,15 @@ export function Select({
type="button"
role="option"
aria-selected={selected}
+ aria-disabled={option.disabled || undefined}
+ disabled={option.disabled}
title={option.title}
onClick={() => {
+ if (option.disabled) return
onChange(option.value)
closeMenu()
}}
- className="lu-picker-row w-[calc(100%-8px)] text-left"
+ className={cn('lu-picker-row w-[calc(100%-8px)] text-left', option.disabled && 'cursor-not-allowed opacity-45')}
>
{option.badge && <Badge tag={option.badge} />}
diff --git a/src/hooks/__tests__/useCloudCreate-swap.test.ts b/src/hooks/__tests__/useCloudCreate-swap.test.ts
index ad64c494..c8c60a27 100644
--- a/src/hooks/__tests__/useCloudCreate-swap.test.ts
+++ b/src/hooks/__tests__/useCloudCreate-swap.test.ts
@@ -54,6 +54,10 @@ const hoisted = vi.hoisted(() => {
result_url: 'https://storage.example/out.mp4', created_at: new Date().toISOString(),
})),
cancelJob: vi.fn(async () => ({ status: 'canceled' })),
+ adoptInput: vi.fn(async (jobId: string, role: string) => {
+ hochgeladen.push(`adopt ${jobId} ${role}`)
+ return `user-1/adopted-${jobId}.jpg`
+ }),
studioQuote: vi.fn(async (..._args: unknown[]) => ({ credits: 42 })),
}
})
@@ -73,6 +77,7 @@ vi.mock('../../api/cloud/jobs', () => ({
submitCloudJob: hoisted.submitCloudJob,
pollJob: hoisted.pollJob,
cancelJob: hoisted.cancelJob,
+ adoptInput: hoisted.adoptInput,
CloudJobError: hoisted.FakeCloudJobError,
QuoteChangedError: hoisted.FakeQuoteChangedError,
}))
@@ -87,7 +92,14 @@ vi.mock('../../api/cloud/studio', () => ({
StudioQuoteChangedError: hoisted.FakeQuoteChangedError,
}))
+// The length of the video as the WebView measures it (no <video> in node).
+vi.mock('../../components/create/experimental/useStudioPrice', async (orig) => ({
+ ...((await orig()) as Record<string, unknown>),
+ mediaSeconds: async () => 6.006,
+}))
+
import { useCloudCreate } from '../useCloudCreate'
+import { swapKeyOf } from '../../lib/create/swap-frame'
import { useCreateStore } from '../../stores/createStore'
import { useCloudCatalogStore } from '../../stores/cloudCatalogStore'
import { neuerServer } from '../../lib/render/__tests__/fixtures/test-catalogs'
@@ -112,11 +124,12 @@ beforeEach(() => {
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 })
+ useCreateStore.setState({ swapFigures: [{ image: null, role: '' }], swapSeconds: null, swapConsent: false, swapBuilt: null, swapFrame: null })
})
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.getState().setCloudOpModel('openjutsu-character-swap')
useCreateStore.setState({
videoInput: CLIP, swapSeconds: 10, swapConsent: true,
swapFigures: [{ image: FOTO, role: 'the woman on the left' }, { image: FOTO, role: '' }],
@@ -175,6 +188,7 @@ describe('Swap Character from the Create tab', () => {
})
it('never sends the Stage source of another tab', async () => {
+ useCreateStore.getState().setCloudOpModel('openjutsu-character-swap')
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()
@@ -182,10 +196,69 @@ describe('Swap Character from the Create tab', () => {
})
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)) })
+ useCloudCatalogStore.setState({ models: neuerServer().filter((m) => !['openjutsu-character-swap', 'wan-2.2-animate-replace', 'scail-2', 'kling-v3-pro-motion-control'].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)
})
+
+ it('SCAIL 2 (the default) waits for the confirmed first frame, before any upload', async () => {
+ useCreateStore.setState({ videoInput: CLIP, swapConsent: true, swapFigures: [{ image: FOTO, role: '' }] })
+ await useCloudCreate().generate()
+ expect(useCreateStore.getState().error).toBe('Build the first frame and check it before you start the video.')
+ expect(hoisted.uploadInput).not.toHaveBeenCalled()
+ expect(submitted).toHaveLength(0)
+ // A frame that is built but not confirmed, or built for other inputs, does not count.
+ const figures = [{ image: FOTO, role: '', mark: { x: 0.3, y: 0.5 } }]
+ useCreateStore.setState({ swapFigures: figures, swapBuilt: { jobId: 'f1', url: 'https://x/f.jpg', key: swapKeyOf(CLIP.url, figures), confirmed: false } })
+ await useCloudCreate().generate()
+ expect(submitted).toHaveLength(0)
+ useCreateStore.setState({ swapBuilt: { jobId: 'f1', url: 'https://x/f.jpg', key: swapKeyOf('blob:other', figures), confirmed: true } })
+ await useCloudCreate().generate()
+ expect(submitted).toHaveLength(0)
+ })
+
+ it('SCAIL 2 runs on the confirmed first frame: adopted, video step, 720p replace, whole seconds', async () => {
+ const figures = [{ image: FOTO, role: '', mark: { x: 0.2, y: 0.5 } }, { image: FOTO, role: '', mark: { x: 0.8, y: 0.5 } }]
+ useCreateStore.setState({
+ videoInput: CLIP, swapConsent: true, swapFigures: figures,
+ swapBuilt: { jobId: 'frame-7', url: 'https://x/f.jpg', key: swapKeyOf(CLIP.url, figures), confirmed: true },
+ })
+ await useCloudCreate().generate()
+ expect(useCreateStore.getState().error).toBeNull()
+ expect(submitted).toHaveLength(1)
+ const p = submitted[0].params
+ expect(submitted[0].model).toBe('scail-2')
+ expect(submitted[0].prompt).toBe('')
+ expect(p.source_path).toBe('user-1/adopted-frame-7.jpg')
+ expect(p.image_paths).toBeUndefined()
+ expect(p.video_path).toBe('user-1/staged-video.mp4')
+ expect(p.swap_step).toBe('video')
+ expect(p.swap_consent).toBe(true)
+ expect(p.clip_seconds).toBe(6)
+ expect(p.studio_options).toEqual({ resolution: '720p', mode: 'replace' })
+ // The photos do not go up again: only the video, and the frame by adopt.
+ expect(hochgeladen).toEqual(['video', 'adopt frame-7 image'])
+ // The quote sees the same fields, the video step too.
+ expect(hoisted.studioQuote.mock.calls[0][2]).toMatchObject({ swap_step: 'video', clip_seconds: 6, source_path: p.source_path })
+ })
+
+ it('Kling runs on the confirmed first frame without a prompt, orientation by the video, original sound', async () => {
+ useCreateStore.getState().setCloudOpModel('kling-v3-pro-motion-control')
+ const figures = [{ image: FOTO, role: '' }]
+ useCreateStore.setState({
+ videoInput: CLIP, swapConsent: true, swapSeconds: 4, swapFigures: figures,
+ swapBuilt: { jobId: 'frame-8', url: 'https://x/f.jpg', key: swapKeyOf(CLIP.url, figures), confirmed: true },
+ })
+ await useCloudCreate().generate()
+ expect(submitted).toHaveLength(1)
+ const p = submitted[0].params
+ expect(submitted[0].model).toBe('kling-v3-pro-motion-control')
+ expect(submitted[0].prompt).toBe('')
+ expect(p.studio_options).toEqual({ character_orientation: 'video', keep_original_sound: true })
+ expect(p.clip_seconds).toBe(4)
+ expect(p.swap_step).toBe('video')
+ expect(p.source_path).toBe('user-1/adopted-frame-8.jpg')
+ })
})
diff --git a/src/hooks/useCloudCreate.ts b/src/hooks/useCloudCreate.ts
index 5b0e9023..62f51480 100644
--- a/src/hooks/useCloudCreate.ts
+++ b/src/hooks/useCloudCreate.ts
@@ -20,6 +20,7 @@ import type { CloudSubmitIntent } from '../lib/pending-cloud-jobs'
import { useCreateStore, type GalleryItem } from '../stores/createStore'
import { intentToJob, galleryItemFromJob } from '../lib/render/cloud-jobs'
import {
+ adoptInput,
cancelJob,
getJob,
pollJob,
@@ -40,8 +41,10 @@ import { intentRoles, intentRequiredInputs, isStudioModel, resolveIntentPick, st
import { 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 { isSwapIntent, swapUsesFrame, SWAP_GALLERY_LABEL } from '../lib/render/swap'
+import { adoptSwapFrame, swapInputError, swapRunParams } from '../lib/create/swap-run'
+import { swapConfirmedFrame } from '../lib/create/swap-frame'
+import { mediaSeconds } from '../components/create/experimental/useStudioPrice'
import { IMPROVING_PROMPT } from '../lib/render/improve-prompt'
import { improveKindForRun } from '../lib/render/music-ui'
import { intentTakesPrompt } from '../components/create/experimental/intents'
@@ -418,7 +421,10 @@ export function useCloudCreate(opts: { onQuotaChange?: () => void } = {}) {
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 })
+ const invalid = swapInputError(studioModel, {
+ hasVideo: !!s.videoInput, figures: s.swapFigures, consent: s.swapConsent,
+ frameJobId: swapConfirmedFrame(s.swapBuilt, s.videoInput?.url, s.swapFigures),
+ })
if (invalid) {
s.setError(invalid)
return
@@ -602,17 +608,30 @@ export function useCloudCreate(opts: { onQuotaChange?: () => void } = {}) {
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.
+ // The people of the panel: a photo each (a list with roles for
+ // OpenJutsu, the first photo as the still for a one-person model), or
+ // on SCAIL 2 and Kling the confirmed first frame (adopted as an own
+ // result), the options the mode presets and fixes, the length and the
+ // consent. The length of the video as the slider and the button
+ // measured it (SCAIL 2 and Kling run on whole seconds below it).
+ const videoSeconds = s.videoInput && swapUsesFrame(intent, studioModel)
+ ? await mediaSeconds(s.videoInput.url, 'video').catch(() => undefined)
+ : undefined
Object.assign(params, await swapRunParams(
studioModel,
- { hasVideo: !!s.videoInput, figures: s.swapFigures, consent: s.swapConsent, chosenSeconds: s.swapSeconds },
+ {
+ hasVideo: !!s.videoInput, figures: s.swapFigures, consent: s.swapConsent, chosenSeconds: s.swapSeconds,
+ videoSeconds, frameJobId: swapConfirmedFrame(s.swapBuilt, s.videoInput?.url, s.swapFigures),
+ },
studioOptionsFiltered ?? {},
async (image, i, total) => {
s.setProgress(7, `Uploading photos… ${i + 1}/${total}`)
return uploadInput(dataUrlToBlob(image.url), 'source', ...uploadEnds(ac))
},
+ async (jobId) => {
+ s.setProgress(7, 'Uploading first frame…')
+ return adoptSwapFrame(adoptInput, jobId)
+ },
))
if (ac.signal.aborted) return
}
@@ -731,7 +750,7 @@ export function useCloudCreate(opts: { onQuotaChange?: () => void } = {}) {
const quoteFields: Record<string, unknown> = {}
// 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) {
+ 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', 'swap_step'] as const) {
if (params[k] !== undefined) quoteFields[k] = params[k]
}
const quote = await studioQuote(studioModel, runPrompt, {
diff --git a/src/lib/create/__tests__/swap.test.ts b/src/lib/create/__tests__/swap.test.ts
index cc95faba..3110a5db 100644
--- a/src/lib/create/__tests__/swap.test.ts
+++ b/src/lib/create/__tests__/swap.test.ts
@@ -1,18 +1,27 @@
/**
- * 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).
+ * Swap Character on the desktop (07.11.2026, port of the web's C52; two steps
+ * with SCAIL 2 and Kling since 14.11.2026): model choice, limits, the check
+ * before a run, what a run sends, the price against the provider's own
+ * examples (OpenJutsu 0.15/0.17/0.20/0.40 $ per input second, at least 3 s,
+ * plus 0.02 $ per photo; Kling 0.168 $/s; SCAIL 2 720p 0.08 $/s), the marks,
+ * the sentence of the frame step and the frame step itself.
*
* 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,
+ SWAP_CONSENT_MISSING, SWAP_CONSENT_MODELS, SWAP_FRAME_MODEL, SWAP_KLING_MODEL, SWAP_LONG_MODEL, SWAP_MAIN_MODEL,
+ SWAP_OPENJUTSU_MODEL, SWAP_MODELS, SWAP_TIPS,
+ swapAutoModel, swapBilledPhotos, swapClipCredits, swapClipLimits, swapClipSeconds, swapConsentRequired,
+ swapCreditsPerSecond, swapDefaultOptions, swapFigureRoles, swapFixedOptions, swapFrameAspect, swapFrameKey,
+ swapFrameOptions, swapFramePrompt, swapMarkRoles, swapMaxPeople, swapNeedsConsent, swapPanelFields,
+ swapPricedSeconds, swapPrompt, swapReadsRoles, swapRoles, swapShortCredits, swapUsesFrame, swapWholeSeconds,
} from '../../render/swap'
import { swapInputError, swapReady, swapRunParams } from '../swap-run'
+import { runSwapFrame, swapConfirmedFrame, swapFrameCredits, swapFrameProblem, swapFrameSubmit, swapKeyOf } from '../swap-frame'
+import { presetModels, roleForModel } from '../../render/preset-models'
+import { useCloudCatalogStore } from '../../../stores/cloudCatalogStore'
+import { neuerServer } from '../../render/__tests__/fixtures/test-catalogs'
import { STUDIO_MODELS, studioCredits, studioFields, studioOptions, studioPreviewCredits } from '../../render/studio-contract'
import { createStudioCost } from '../../render/create-studio'
@@ -23,60 +32,75 @@ 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_OPENJUTSU_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_OPENJUTSU_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)
+ const f = studioFields(SWAP_OPENJUTSU_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(studioOptions(SWAP_OPENJUTSU_MODEL, '', undefined, false)).toEqual({ resolution: '768p' })
+ expect(swapReadsRoles(SWAP_OPENJUTSU_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')
+ expect(() => studioOptions(SWAP_OPENJUTSU_MODEL, '', { roles: ['a'.repeat(200)] }, false)).not.toThrow()
+ expect(() => studioOptions(SWAP_OPENJUTSU_MODEL, '', { roles: ['a'.repeat(201)] }, false)).toThrow('Invalid roles')
+ expect(() => studioOptions(SWAP_OPENJUTSU_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('runs SCAIL 2 first, then Kling, OpenJutsu and Wan 2.2 Animate (14.11.2026)', () => {
+ expect([...SWAP_MODELS]).toEqual(['scail-2', 'kling-v3-pro-motion-control', 'openjutsu-character-swap', 'wan-2.2-animate-replace'])
+ expect(SWAP_MAIN_MODEL).toBe('scail-2')
+ })
+
+ it('up to 3 people SCAIL 2 (long clips too), with 4 OpenJutsu; Kling never by itself', () => {
+ expect(swapAutoModel(0)).toBe('scail-2')
+ expect(swapAutoModel(1)).toBe('scail-2')
+ expect(swapAutoModel(3)).toBe('scail-2')
+ expect(swapAutoModel(4)).toBe(SWAP_OPENJUTSU_MODEL)
+ expect(swapClipLimits('scail-2').max).toBe(120)
+ })
+
+ it('the notes before the start, grey', () => {
+ expect([...SWAP_TIPS]).toEqual([
+ 'One continuous shot, no hard cuts. Everyone you replace must be visible in the first frame.',
+ 'Up to 3 people with SCAIL-2, one person with Kling (highest resolution).',
+ 'Subtitles burned into the video may disappear. Heavy make-up or costumes can blend back in.',
+ ])
})
it('knows the span of each model', () => {
- expect(swapClipLimits(SWAP_MAIN_MODEL)).toEqual({ min: 2, max: 15, billedMin: 3 })
+ expect(swapClipLimits(SWAP_OPENJUTSU_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_OPENJUTSU_MODEL)).toBe(4)
expect(swapMaxPeople(SWAP_LONG_MODEL)).toBe(1)
- expect(swapMaxPeople('scail-2')).toBe(1)
+ expect(swapMaxPeople('scail-2')).toBe(3)
+ expect(swapMaxPeople(SWAP_KLING_MODEL)).toBe(1)
+ expect(swapClipLimits(SWAP_KLING_MODEL)).toEqual({ min: 3, max: 30, billedMin: 3 })
})
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_OPENJUTSU_MODEL, null)).toBe(15)
+ expect(swapClipSeconds(SWAP_OPENJUTSU_MODEL, 40)).toBe(15)
+ expect(swapClipSeconds(SWAP_OPENJUTSU_MODEL, 1)).toBe(2)
+ expect(swapClipSeconds(SWAP_OPENJUTSU_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)
+ expect(swapPricedSeconds(SWAP_OPENJUTSU_MODEL, null, 40)).toBe(15)
+ expect(swapPricedSeconds(SWAP_OPENJUTSU_MODEL, 10, 40)).toBe(10)
+ expect(swapPricedSeconds(SWAP_OPENJUTSU_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({})
+ expect(swapFixedOptions('swap_character', SWAP_OPENJUTSU_MODEL)).toEqual({})
// Motion Control keeps SCAIL 2 as animate.
expect(swapFixedOptions('motion', 'scail-2')).toEqual({})
expect(swapPanelFields('swap_character')).toEqual(['roles', 'resolution', 'mode'])
@@ -86,28 +110,28 @@ describe('model choice and limits', () => {
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))
+ expect(studioCredits(SWAP_OPENJUTSU_MODEL, { resolution: '480p' }, 10, 1, 100, 1)).toBe(credits(1.52))
+ expect(swapClipCredits(SWAP_OPENJUTSU_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))
+ expect(studioCredits(SWAP_OPENJUTSU_MODEL, { resolution: '768p' }, 10, 1, 100, 2)).toBe(credits(2.04))
+ expect(swapClipCredits(SWAP_OPENJUTSU_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))
+ expect(studioCredits(SWAP_OPENJUTSU_MODEL, { resolution: '768p' }, 15, 1, 100, 1)).toBe(credits(3.02))
+ expect(swapClipCredits(SWAP_OPENJUTSU_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))
+ expect(studioPreviewCredits(SWAP_OPENJUTSU_MODEL, {}, 10, 1, 100, 2)).toBe(credits(2.04))
+ expect(createStudioCost(SWAP_OPENJUTSU_MODEL, { resolution: '480p' }, 100, 10, 1, swapBilledPhotos(SWAP_OPENJUTSU_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))
+ expect(swapClipCredits(SWAP_OPENJUTSU_MODEL, { resolution: '768p' }, 2, 1)).toBe(credits(0.62))
+ expect(swapClipCredits(SWAP_OPENJUTSU_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', () => {
@@ -136,38 +160,52 @@ 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: '' }] }))
+ expect(swapInputError(SWAP_OPENJUTSU_MODEL, { ...ok, hasVideo: false })).toBe('Add the original video first.')
+ expect(swapInputError(SWAP_OPENJUTSU_MODEL, { ...ok, figures: [{ image: null, role: '' }] })).toBe('Add a photo of the new person.')
+ expect(swapInputError(SWAP_OPENJUTSU_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)
+ expect(swapInputError(SWAP_OPENJUTSU_MODEL, { ...ok, consent: false })).toBe(SWAP_CONSENT_MISSING)
+ expect(swapInputError(SWAP_OPENJUTSU_MODEL, ok)).toBeNull()
+ expect(swapReady(SWAP_OPENJUTSU_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.')
+ .toBe('This model replaces one person. Use SCAIL-2 for up to 3 people, or remove the others.')
+ expect(swapInputError(SWAP_KLING_MODEL, { ...ok, frameJobId: 'f', figures: [...one, ...one] })).toMatch(/replaces one person/)
+ expect(swapInputError('scail-2', { ...ok, frameJobId: 'f', figures: [...one, ...one, ...one, ...one] })).toBe('This model replaces at most 3 people.')
+ expect(swapInputError('scail-2', { ...ok, frameJobId: 'f', figures: [...one, ...one, ...one] })).toBeNull()
})
it('refuses a role over 200 characters', () => {
- expect(swapInputError(SWAP_MAIN_MODEL, { ...ok, figures: [{ image: PHOTO, role: 'r'.repeat(201) }] }))
+ expect(swapInputError(SWAP_OPENJUTSU_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()
+ it('asks consent for every swap model, SCAIL 2 and Kling now too (gap: SCAIL 2 was missing)', () => {
+ expect([...SWAP_CONSENT_MODELS]).toEqual(['scail-2', SWAP_KLING_MODEL, SWAP_OPENJUTSU_MODEL, SWAP_LONG_MODEL])
+ expect(swapNeedsConsent('scail-2')).toBe(true)
+ expect(swapNeedsConsent(SWAP_KLING_MODEL)).toBe(true)
+ expect(swapInputError('scail-2', { ...ok, consent: false, frameJobId: 'f' })).toBe(SWAP_CONSENT_MISSING)
+ expect(swapInputError(SWAP_KLING_MODEL, { ...ok, consent: false, frameJobId: 'f' })).toBe(SWAP_CONSENT_MISSING)
expect(swapInputError(SWAP_LONG_MODEL, { ...ok, consent: false })).toBe(SWAP_CONSENT_MISSING)
})
+
+ it('SCAIL 2 and Kling start the video only on a confirmed first frame', () => {
+ expect(swapInputError('scail-2', ok)).toMatch(/Build the first frame/)
+ expect(swapReady('scail-2', ok)).toBe(false)
+ expect(swapInputError('scail-2', { ...ok, frameJobId: 'f' })).toBeNull()
+ expect(swapInputError(SWAP_KLING_MODEL, { ...ok, frameJobId: 'f' })).toBeNull()
+ // OpenJutsu and Wan run in one step as before.
+ expect(swapInputError(SWAP_LONG_MODEL, ok)).toBeNull()
+ })
})
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, {
+ const out = await swapRunParams(SWAP_OPENJUTSU_MODEL, {
hasVideo: true, consent: true, chosenSeconds: 10,
figures: [{ image: PHOTO, role: 'the woman on the left' }, { image: PHOTO, role: '' }],
}, { resolution: '480p' }, upload)
@@ -178,11 +216,11 @@ describe('what a run sends', () => {
swap_consent: true,
})
// The options pass the contract the server checks.
- expect(() => studioOptions(SWAP_MAIN_MODEL, '', out.studio_options, false)).not.toThrow()
+ expect(() => studioOptions(SWAP_OPENJUTSU_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)
+ const out = await swapRunParams(SWAP_OPENJUTSU_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)
@@ -199,10 +237,265 @@ describe('what a run sends', () => {
})
})
- 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')
+ it('OpenJutsu takes its roles from the marks', async () => {
+ const out = await swapRunParams(SWAP_OPENJUTSU_MODEL, {
+ hasVideo: true, consent: true, chosenSeconds: null,
+ figures: [{ image: PHOTO, role: '', mark: { x: 0.9, y: 0.5 } }, { image: PHOTO, role: '', mark: { x: 0.1, y: 0.5 } }],
+ }, {}, upload)
+ expect(out.studio_options).toEqual({ roles: ['the person on the right', 'the person on the left'] })
+ })
+
+ it('SCAIL 2: the confirmed frame as the still (adopt), replace, 720p, whole seconds, the video step', async () => {
+ const log: string[] = []
+ const out = await swapRunParams('scail-2', {
+ hasVideo: true, consent: true, chosenSeconds: null, videoSeconds: 6.006, frameJobId: 'bild-1',
+ figures: [{ image: PHOTO, role: '' }, { image: PHOTO, role: '' }],
+ }, {}, async (_i, n) => { log.push(`upload ${n}`); return 'x' }, async (id) => { log.push(`adopt ${id}`); return `u/job-${id}-image` })
+ expect(out).toEqual({
+ source_path: 'u/job-bild-1-image',
+ swap_step: 'video',
+ studio_options: { resolution: '720p', mode: 'replace' },
+ clip_seconds: 6,
+ swap_consent: true,
+ })
+ // The photos do not go up again, only the frame is adopted.
+ expect(log).toEqual(['adopt bild-1'])
+ })
+
+ it('SCAIL 2: an own resolution stays', async () => {
+ const out = await swapRunParams('scail-2', { hasVideo: true, consent: true, chosenSeconds: null, frameJobId: 'b', figures: one }, { resolution: '480p' }, upload, async () => 'a')
+ expect(out.studio_options).toEqual({ resolution: '480p', mode: 'replace' })
+ })
+
+ it('Kling: orientation of the video and the original sound, the chosen whole seconds', async () => {
+ const out = await swapRunParams(SWAP_KLING_MODEL, {
+ hasVideo: true, consent: true, chosenSeconds: 8, videoSeconds: 12.4, frameJobId: 'b', figures: one,
+ }, {}, upload, async () => 'u/frame')
+ expect(out).toEqual({
+ source_path: 'u/frame', swap_step: 'video', clip_seconds: 8, swap_consent: true,
+ studio_options: { character_orientation: 'video', keep_original_sound: true },
+ })
+ expect(studioOptions(SWAP_KLING_MODEL, '', out.studio_options)).toMatchObject({ keep_original_sound: true })
+ })
+})
+
+describe('two steps (14.11.2026): models and people', () => {
+ it('Kling 3.0 Pro Motion Control is in the catalogue as the provider describes it', () => {
+ const m = STUDIO_MODELS[SWAP_KLING_MODEL]
+ expect(m.label).toBe('Kling 3.0 Pro \u2022 Motion Control')
+ expect(m.kind).toBe('video')
+ expect(m.endpoint).toBe('kwaivgi/kling-v3.0-pro/motion-control')
+ expect(m.inputs).toEqual({ image: 'source_path', video: 'video_path' })
+ expect(m.defaults).toEqual({ character_orientation: 'video', keep_original_sound: true })
+ expect(m.price).toMatchObject({ mode: 'input', rates: { default: 0.168 }, minSeconds: 3, maxSeconds: 30 })
+ // No prompt needed, orientation by the video is valid.
+ expect(studioOptions(SWAP_KLING_MODEL, '', {}).character_orientation).toBe('video')
+ expect(() => studioOptions(SWAP_KLING_MODEL, '', { character_orientation: 'sideways' })).toThrow()
+ // In Motion Control too, behind SCAIL 2 (on a server that lists it).
+ useCloudCatalogStore.setState({ models: neuerServer() })
+ expect(presetModels('motion').map((x) => x.id).slice(0, 2)).toEqual(['scail-2', SWAP_KLING_MODEL])
+ expect(roleForModel(SWAP_KLING_MODEL)).toBe('motion')
+ })
+
+ it('Nano Banana Pro builds the frame and is in the catalogue', () => {
+ expect(SWAP_FRAME_MODEL).toBe('nano-banana-pro-edit')
+ expect(STUDIO_MODELS[SWAP_FRAME_MODEL]).toMatchObject({ kind: 'image', inputs: { images: 'image_paths' }, endpoint: 'google/nano-banana-pro/edit' })
+ })
+
+ it('only SCAIL 2 and Kling run in two steps, and only in Swap Character', () => {
+ expect(swapUsesFrame('swap_character', 'scail-2')).toBe(true)
+ expect(swapUsesFrame('swap_character', SWAP_KLING_MODEL)).toBe(true)
+ expect(swapUsesFrame('swap_character', SWAP_OPENJUTSU_MODEL)).toBe(false)
+ expect(swapUsesFrame('swap_character', SWAP_LONG_MODEL)).toBe(false)
+ expect(swapUsesFrame('motion', 'scail-2')).toBe(false)
+ })
+
+ it('Kling: orientation of the video, original sound, no sentence; SCAIL 2: replace, 720p', () => {
+ expect(swapFixedOptions('swap_character', SWAP_KLING_MODEL)).toEqual({ character_orientation: 'video', keep_original_sound: true })
+ expect(swapFixedOptions('motion', SWAP_KLING_MODEL)).toEqual({})
+ expect(swapDefaultOptions('swap_character', 'scail-2')).toEqual({ resolution: '720p' })
+ expect(swapDefaultOptions('motion', 'scail-2')).toEqual({})
+ expect(swapPrompt('swap_character', SWAP_KLING_MODEL, 'make it nice')).toBe('')
+ expect(swapPrompt('swap_character', 'scail-2', 'make it nice')).toBe('')
+ expect(swapPrompt('swap_character', SWAP_OPENJUTSU_MODEL, 'make it nice')).toBe('make it nice')
+ })
+})
+
+describe('marks in the first frame become roles', () => {
+ it('sorted by x: left, middle, right; with one mark "the person"', () => {
+ expect(swapMarkRoles([])).toEqual([])
+ expect(swapMarkRoles([{ x: 0.7, y: 0.4 }])).toEqual(['the person'])
+ expect(swapMarkRoles([{ x: 0.8, y: 0.5 }, { x: 0.2, y: 0.5 }])).toEqual(['the person on the right', 'the person on the left'])
+ expect(swapMarkRoles([{ x: 0.5, y: 0.1 }, { x: 0.9, y: 0.9 }, { x: 0.1, y: 0.5 }]))
+ .toEqual(['the person in the middle', 'the person on the right', 'the person on the left'])
+ expect(swapMarkRoles([{ x: 0.4, y: 0 }, { x: 0.1, y: 0 }, { x: 0.9, y: 0 }, { x: 0.6, y: 0 }]))
+ .toEqual(['the second person from the left', 'the first person from the left', 'the fourth person from the left', 'the third person from the left'])
+ })
+
+ it('an own role wins, without a mark the role stays empty (the main person)', () => {
+ expect(swapFigureRoles([
+ { role: '', mark: { x: 0.8, y: 0.5 } },
+ { role: 'the woman with the phone', mark: { x: 0.2, y: 0.5 } },
+ ])).toEqual(['the person on the right', 'the woman with the phone'])
+ expect(swapFigureRoles([{ role: '' }])).toEqual([''])
+ expect(swapFigureRoles([{ role: ' ', mark: null }])).toEqual([''])
+ })
+})
+
+describe('the sentence of the frame step', () => {
+ it('one person: the proven template, word for word (hair sentence of 14.11.)', () => {
+ expect(swapFramePrompt(['the person'])).toBe(
+ 'Replace the person in the first image with the person from the second image. Keep the face identity, hair and facial features from the second image exactly. '
+ + "Use the hair of the person from the second image and remove all of the original person's hair completely, even long hair. No headset, no microphone. Keep everything else from the first image identical: same pose, the same head angle as in the first image, "
+ + 'same head size, mouth position, camera angle, framing, distance, clothing, background, lighting, colors, text overlays and phone-camera quality. '
+ + 'It must look like the same raw phone video frame, just with the other person.',
+ )
+ expect(swapFramePrompt([''])).toContain('Replace the person in the first image')
+ expect(swapFramePrompt([])).toContain('Replace the person in the first image')
+ })
+
+ it('several people: a photo each, plural', () => {
+ const two = swapFramePrompt(['the person on the left', 'the person on the right'])
+ expect(two).toContain('In the first image, replace the person on the left with the person from the second image and replace the person on the right with the person from the third image.')
+ expect(two).toContain("Use each new person's own hair from their image and remove all of the original people's hair completely, even long hair.")
+ expect(two).toContain('No headsets, no microphones.')
+ expect(two).toContain('same poses, the same head angles as in the first image')
+ expect(two).toContain('just with the other people.')
+ const three = swapFramePrompt(['a', 'b', 'c'])
+ expect(three).toContain('replace a with the person from the second image, replace b with the person from the third image and replace c with the person from the fourth image.')
+ })
+
+ it('"What\'s wrong?" goes at the end', () => {
+ expect(swapFramePrompt(['the person'], 'head turned to the side like the original'))
+ .toMatch(/just with the other person\. Fix this from the last attempt: head turned to the side like the original$/)
+ expect(swapFramePrompt(['the person'], ' ')).toMatch(/other person\.$/)
+ })
+
+ it('aspect ratio: the allowed one closest to the video', () => {
+ expect(swapFrameAspect(1080, 1920)).toBe('9:16')
+ expect(swapFrameAspect(1920, 1080)).toBe('16:9')
+ expect(swapFrameAspect(1000, 1000)).toBe('1:1')
+ expect(swapFrameAspect(1440, 1920)).toBe('3:4')
+ expect(swapFrameAspect(2560, 1080)).toBe('21:9')
+ expect(swapFrameAspect(0, 0)).toBe('9:16')
+ expect(swapFrameOptions(1080, 1920)).toEqual({ aspect_ratio: '9:16', resolution: '2k', output_format: 'jpeg' })
+ expect(studioOptions(SWAP_FRAME_MODEL, 'x', swapFrameOptions(1080, 1920))).toMatchObject({ resolution: '2k', output_format: 'jpeg' })
+ })
+})
+
+describe('prices (catalogue)', () => {
+ it('Kling 6 s = 1.008 $; SCAIL 2 720p 6 s = 0.48 $', () => {
+ expect(studioCredits(SWAP_KLING_MODEL, studioOptions(SWAP_KLING_MODEL, '', {}), 6)).toBe(100800)
+ expect(studioCredits('scail-2', studioOptions('scail-2', '', { mode: 'replace', resolution: '720p' }), 6)).toBe(48000)
+ expect(swapCreditsPerSecond(SWAP_KLING_MODEL, {})).toBe(16800)
+ expect(swapCreditsPerSecond('scail-2', { resolution: '720p' })).toBe(8000)
+ expect(swapClipCredits(SWAP_KLING_MODEL, {}, 6, 0)).toBe(100800)
+ expect(swapClipCredits('scail-2', { resolution: '720p' }, 6, 0)).toBe(48000)
+ // Kling: at least 3 s billed, at most 30 s.
+ expect(studioCredits(SWAP_KLING_MODEL, studioOptions(SWAP_KLING_MODEL, '', {}), 2)).toBe(50400)
+ expect(() => studioCredits(SWAP_KLING_MODEL, studioOptions(SWAP_KLING_MODEL, '', {}), 31)).toThrow()
+ })
+
+ it('the frame step costs what the catalogue names for Nano Banana Pro 2k', () => {
+ expect(swapFrameCredits(1080, 1920, 1)).toBe(Math.round(STUDIO_MODELS[SWAP_FRAME_MODEL].price.rates['2k'] * 100000))
+ expect(swapFrameCredits(1080, 1920, 1)).toBe(14000)
+ expect(swapFrameCredits(1080, 1920, 3)).toBe(swapFrameCredits(1080, 1920, 1))
+ })
+
+ it('whole seconds just below: slider, button and server see the same number', () => {
+ // 6.006 s the provider billed as 7 s; now 6 run.
+ expect(swapWholeSeconds('scail-2', null, 6.006)).toBe(6)
+ expect(swapPricedSeconds('scail-2', null, 6.006)).toBe(6)
+ expect(swapPricedSeconds(SWAP_KLING_MODEL, null, 6.006)).toBe(6)
+ expect(swapPricedSeconds('scail-2', null, 5.995)).toBe(6)
+ expect(swapPricedSeconds('scail-2', 4, 9.5)).toBe(4)
+ // More than 0.1 s over: the started second counts.
+ expect(swapPricedSeconds('scail-2', null, 9.5)).toBe(10)
+ expect(swapPricedSeconds('scail-2', null, 6.09)).toBe(6)
+ expect(swapPricedSeconds('scail-2', null, 6.11)).toBe(7)
+ expect(swapPricedSeconds('scail-2', null, 2.5)).toBe(3)
+ expect(swapPricedSeconds(SWAP_KLING_MODEL, null, 45)).toBe(30)
+ // The other models stay unrounded.
+ expect(swapPricedSeconds(SWAP_OPENJUTSU_MODEL, null, 6.006)).toBe(6.006)
+ })
+})
+
+describe('consent on the server', () => {
+ it('asked for swap runs, not for Motion Control (the same rule as the web server)', () => {
+ expect(swapConsentRequired(SWAP_OPENJUTSU_MODEL, {})).toBe(true)
+ expect(swapConsentRequired(SWAP_LONG_MODEL, {})).toBe(true)
+ expect(swapConsentRequired('scail-2', { studio_options: { mode: 'replace' } })).toBe(true)
+ expect(swapConsentRequired('scail-2', { studio_options: { mode: 'animate' } })).toBe(false)
+ expect(swapConsentRequired('scail-2', {})).toBe(false)
+ expect(swapConsentRequired(SWAP_KLING_MODEL, {})).toBe(false)
+ expect(swapConsentRequired(SWAP_KLING_MODEL, { swap_step: 'video' })).toBe(true)
+ expect(swapConsentRequired(SWAP_FRAME_MODEL, { swap_step: 'frame' })).toBe(true)
+ expect(swapConsentRequired(SWAP_FRAME_MODEL, {})).toBe(false)
+ })
+})
+
+describe('the frame step', () => {
+ const FOTO = 'data:image/png;base64,AA'
+ const FRAME = { url: FOTO, width: 1080, height: 1920 }
+ const request = (over: Partial<Parameters<typeof swapFrameProblem>[0]> = {}) => ({
+ frame: FRAME, figures: [{ imageUrl: FOTO, role: '', mark: { x: 0.3, y: 0.4 } }], model: 'scail-2', consent: true, credits: 14000, ...over,
+ })
+
+ it('wants the frame, the photos, the limit of the model and the tick, before the frame step too', () => {
+ expect(swapFrameProblem(request())).toBeNull()
+ expect(swapFrameProblem(request({ frame: null }))).toBe('Add the original video first.')
+ expect(swapFrameProblem(request({ figures: [{ imageUrl: null, role: '' }] }))).toBe('Add a photo of the new person.')
+ expect(swapFrameProblem(request({ figures: [{ imageUrl: FOTO, role: '' }, { imageUrl: null, role: '' }] }))).toBe('Add a photo for person 2, or remove that person.')
+ expect(swapFrameProblem(request({ consent: false }))).toBe(SWAP_CONSENT_MISSING)
+ expect(swapFrameProblem(request({ model: SWAP_KLING_MODEL, figures: [{ imageUrl: FOTO, role: '' }, { imageUrl: FOTO, role: '' }] }))).toMatch(/one person/)
+ })
+
+ it('the body: first frame first, then the photos; 2k, JPEG, aspect ratio, the frame step with tick and ceiling', () => {
+ const submit = swapFrameSubmit('u/frame', ['u/a', 'u/b'], request({
+ figures: [{ imageUrl: FOTO, role: '', mark: { x: 0.8, y: 0.5 } }, { imageUrl: FOTO, role: '', mark: { x: 0.2, y: 0.5 } }],
+ extra: 'no glasses',
+ }))
+ expect(submit.kind).toBe('image')
+ expect(submit.model).toBe('nano-banana-pro-edit')
+ expect(submit.params).toEqual({
+ op: 'studio', image_paths: ['u/frame', 'u/a', 'u/b'],
+ studio_options: { aspect_ratio: '9:16', resolution: '2k', output_format: 'jpeg' },
+ swap_step: 'frame', swap_consent: true, max_credits: 14000, label: 'Swap Character first frame',
+ })
+ expect(submit.prompt).toContain('replace the person on the right with the person from the second image and replace the person on the left with the person from the third image')
+ expect(submit.prompt).toMatch(/Fix this from the last attempt: no glasses$/)
+ })
+
+ it('uploads, submits and waits; without the tick nothing starts', async () => {
+ const calls: string[] = []
+ const deps = {
+ uploadInput: async (_b: Blob, role: string) => { calls.push(`upload ${role}`); return `u/${calls.length}` },
+ submitCloudJob: async (s: { model: string; params: { swap_step?: string } }) => { calls.push(`submit ${s.model} ${s.params.swap_step}`); return { id: 'job-9' } },
+ pollJob: async (id: string) => { calls.push(`poll ${id}`); return { id, status: 'succeeded', result_url: 'https://ours/x.jpg' } as never },
+ cancelJob: async () => ({ status: 'canceled' }),
+ }
+ const job = await runSwapFrame(request(), deps as never)
+ expect(job.id).toBe('job-9')
+ expect(calls).toEqual(['upload source', 'upload source', 'submit nano-banana-pro-edit frame', 'poll job-9'])
+ calls.length = 0
+ await expect(runSwapFrame(request({ consent: false }), deps as never)).rejects.toThrow(SWAP_CONSENT_MISSING)
+ expect(calls).toEqual([])
+ })
+
+ it('another video, photo, mark or role makes the built frame expire', () => {
+ const fig = (url: string, role = '', mark: { x: number; y: number } | null = null) => ({ image: { url }, role, mark })
+ const base = swapKeyOf('blob:v1', [fig('data:a')])
+ expect(swapKeyOf('blob:v1', [fig('data:a')])).toBe(base)
+ expect(swapKeyOf('blob:v2', [fig('data:a')])).not.toBe(base)
+ expect(swapKeyOf('blob:v1', [fig('data:b')])).not.toBe(base)
+ expect(swapKeyOf('blob:v1', [fig('data:a', 'the man')])).not.toBe(base)
+ expect(swapKeyOf('blob:v1', [fig('data:a', '', { x: 0.5, y: 0.5 })])).not.toBe(base)
+ expect(swapFrameKey('v', [{ imageUrl: null, role: '' }])).toBe(swapFrameKey('v', [{ imageUrl: null, role: '' }]))
+ // Only a confirmed frame of the same inputs counts for the video run.
+ const built = { jobId: 'j', key: base, confirmed: true }
+ expect(swapConfirmedFrame(built, 'blob:v1', [fig('data:a')])).toBe('j')
+ expect(swapConfirmedFrame({ ...built, confirmed: false }, 'blob:v1', [fig('data:a')])).toBeNull()
+ expect(swapConfirmedFrame(built, 'blob:v2', [fig('data:a')])).toBeNull()
+ expect(swapConfirmedFrame(null, 'blob:v1', [fig('data:a')])).toBeNull()
})
})
diff --git a/src/lib/create/swap-frame.ts b/src/lib/create/swap-frame.ts
new file mode 100644
index 00000000..304b1bbb
--- /dev/null
+++ b/src/lib/create/swap-frame.ts
@@ -0,0 +1,130 @@
+// Swap Character in two steps (14.11.2026, part A of the Character Hub, port
+// of the web's lib/create/swap-frame.ts).
+//
+// SCAIL 2 and Kling Motion Control swap people cleanly when their image is the
+// first frame of the video with the new people already in it (real runs of
+// 13./14.11.: two and three people swapped, stable over the whole clip). Nano
+// Banana Pro builds that frame from the first frame and the photos of the
+// people. The customer sees it before the video run ("Does this look right?"),
+// can have it built again and confirms it with Continue. Only then does Create
+// start the video, with this frame as an own result (adopt).
+//
+// The frame step without React and without the store, like swap-run.ts:
+// upload, submit and poll come from outside. The server and worker parts
+// (studio-prepare, swap-length, submit-job) live on the web only; the desktop
+// sends the same params.
+
+import type { CloudJob, CloudJobSubmit, UploadRole } from '../../api/cloud/jobs'
+import { studioPreviewCredits } from '../render/studio-contract'
+import { dataUrlToBlob } from '../render/data-url'
+import {
+ swapFigureRoles, swapFrameKey, swapFrameOptions, swapFramePrompt, swapMaxPeople,
+ SWAP_CONSENT_MISSING, SWAP_FRAME_MODEL, type SwapMark,
+} from '../render/swap'
+
+/** A person as the frame step reads it. */
+export interface SwapFrameFigure { imageUrl: string | null; role: string; mark?: SwapMark | null }
+
+/** What the frame step needs. */
+export interface SwapFrameRequest {
+ /** The first frame of the video as a data: URL, with its size. */
+ frame: { url: string; width: number; height: number } | null
+ figures: SwapFrameFigure[]
+ /** The video model, for its limit of people. */
+ model: string
+ consent: boolean
+ /** "What's wrong?" on a second try. */
+ extra?: string
+ /** The price the button shows: the ceiling of the booking. */
+ credits: number | null
+}
+
+/** The price of the frame step from the catalogue (Nano Banana Pro, 2k). */
+export function swapFrameCredits(width: number, height: number, people: number): number | null {
+ return studioPreviewCredits(SWAP_FRAME_MODEL, swapFrameOptions(width, height), undefined, people + 1)
+}
+
+/** What is missing before the frame step can start, as a sentence for the
+ * customer. */
+export function swapFrameProblem(req: SwapFrameRequest): string | null {
+ if (!req.frame) return 'Add the original video first.'
+ if (!req.figures.length || req.figures.some((f) => !f.imageUrl)) {
+ const missing = req.figures.findIndex((f) => !f.imageUrl)
+ return missing <= 0 ? 'Add a photo of the new person.' : `Add a photo for person ${missing + 1}, or remove that person.`
+ }
+ if (req.figures.length > swapMaxPeople(req.model)) {
+ return swapMaxPeople(req.model) === 1
+ ? 'This model replaces one person. Use SCAIL-2 for up to 3 people, or remove the others.'
+ : `This model replaces at most ${swapMaxPeople(req.model)} people.`
+ }
+ if (req.figures.some((f) => f.role.length > 200)) return 'Keep each role under 200 characters.'
+ if (!req.consent) return SWAP_CONSENT_MISSING
+ return null
+}
+
+/** The body for POST /api/jobs: the first frame first, then the photo of each
+ * person, in the order of the people. */
+export function swapFrameSubmit(framePath: string, figurePaths: string[], req: SwapFrameRequest): CloudJobSubmit {
+ const roles = swapFigureRoles(req.figures)
+ return {
+ kind: 'image',
+ model: SWAP_FRAME_MODEL,
+ prompt: swapFramePrompt(roles, req.extra),
+ params: {
+ op: 'studio',
+ image_paths: [framePath, ...figurePaths],
+ studio_options: swapFrameOptions(req.frame?.width ?? 0, req.frame?.height ?? 0),
+ swap_step: 'frame',
+ swap_consent: true,
+ ...(req.credits != null ? { max_credits: req.credits } : {}),
+ label: 'Swap Character first frame',
+ },
+ }
+}
+
+/** The fingerprint of the current inputs (lib/render/swap.ts, swapFrameKey). */
+export function swapKeyOf(videoUrl: string | undefined, figures: { image: { url: string } | null; role: string; mark?: SwapMark | null }[]): string {
+ return swapFrameKey(videoUrl ?? '', figures.map((f) => ({ imageUrl: f.image?.url ?? null, role: f.role, mark: f.mark ?? null })))
+}
+
+/** The confirmed frame job, if it still fits the inputs, else null. */
+export function swapConfirmedFrame(
+ built: { jobId: string; key: string; confirmed: boolean } | null,
+ videoUrl: string | undefined,
+ figures: { image: { url: string } | null; role: string; mark?: SwapMark | null }[],
+): string | null {
+ return built?.confirmed && built.key === swapKeyOf(videoUrl, figures) ? built.jobId : null
+}
+
+/** The three ways to the queue, handed in like the engine's RunDeps. Not
+ * imported from engine.ts: the Create tab's start (useCloudCreate) reads this
+ * file, and the engine pulls the chat's catalogue mirror with it. */
+export interface SwapFrameDeps {
+ submitCloudJob: (submit: CloudJobSubmit) => Promise<{ id: string }>
+ pollJob: (id: string, opts: { signal?: AbortSignal; timeoutMs?: number }) => Promise<CloudJob>
+ cancelJob: (id: string) => Promise<unknown>
+ uploadInput: (file: Blob, role: UploadRole) => Promise<string>
+ signal?: AbortSignal
+ onStep?: (text: string) => void
+}
+
+/** Uploads the frame and the photos, starts the frame step and waits for it.
+ * Throws with the text for the customer when something is missing. */
+export async function runSwapFrame(req: SwapFrameRequest, deps: SwapFrameDeps): Promise<CloudJob> {
+ const problem = swapFrameProblem(req)
+ if (problem) throw new Error(problem)
+ deps.onStep?.('Uploading…')
+ const framePath = await deps.uploadInput(dataUrlToBlob(req.frame!.url), 'source')
+ const figurePaths: string[] = []
+ for (const f of req.figures) figurePaths.push(await deps.uploadInput(dataUrlToBlob(f.imageUrl!), 'source'))
+ if (deps.signal?.aborted) throw new Error('Canceled.')
+ deps.onStep?.('Building the first frame…')
+ const { id } = await deps.submitCloudJob(swapFrameSubmit(framePath, figurePaths, req))
+ // A Cancel during the submit found no id yet: the job just taken is
+ // canceled at once, so its credits go back (as runCloudJob in engine.ts).
+ if (deps.signal?.aborted) {
+ void deps.cancelJob(id).catch(() => {})
+ throw new Error('Canceled.')
+ }
+ return deps.pollJob(id, { signal: deps.signal, timeoutMs: 10 * 60_000 })
+}
diff --git a/src/lib/create/swap-run.ts b/src/lib/create/swap-run.ts
index fb71f5c9..349c8db9 100644
--- a/src/lib/create/swap-run.ts
+++ b/src/lib/create/swap-run.ts
@@ -9,13 +9,13 @@
import { STUDIO_MODELS } from '../render/studio-contract'
import {
- swapClipSeconds, swapFixedOptions, swapMaxPeople, swapNeedsConsent, swapReadsRoles, swapRoles,
- SWAP_CONSENT_MISSING, SWAP_INTENT,
+ swapClipSeconds, swapDefaultOptions, swapFigureRoles, swapFixedOptions, swapMaxPeople, swapNeedsConsent,
+ swapReadsRoles, swapRoles, swapUsesFrame, swapWholeSeconds, SWAP_CONSENT_MISSING, SWAP_INTENT, type SwapMark,
} 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 SwapRunFigure<T> { image: T | null; role: string; mark?: SwapMark | null }
export interface SwapRunState<T> {
/** The original video is there. */
@@ -23,6 +23,9 @@ export interface SwapRunState<T> {
figures: SwapRunFigure<T>[]
/** The consent box is ticked. */
consent: boolean
+ /** SCAIL 2 and Kling (two steps): the job of the confirmed first frame, only
+ * while it still fits video, photos, marks and roles (swapConfirmedFrame). */
+ frameJobId?: string | null
}
/** Why this run cannot start, or null. The same order as the web engine. */
@@ -36,39 +39,73 @@ export function swapInputError<T>(model: string, s: SwapRunState<T>): string | n
// 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 one person. Use SCAIL-2 for up to 3 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
+ // Two steps: build and confirm the first frame, then the video.
+ if (swapUsesFrame(SWAP_INTENT, model) && !s.frameJobId) return 'Build the first frame and check it before you start the video.'
return null
}
+/** The confirmed first frame as an input of the video run: the server copies
+ * the own result into the customer's folder (POST /api/jobs/adopt). A frame
+ * that is gone (404) or not finished (409) reads like the engine's adopt. */
+export async function adoptSwapFrame(adopt: (jobId: string, role: 'image') => Promise<string>, jobId: string): Promise<string> {
+ try {
+ return await adopt(jobId, 'image')
+ } catch (err) {
+ const status = (err as { status?: unknown } | null)?.status
+ if (status === 404 || status === 409) throw new Error('That first frame has expired. Build it again.')
+ throw err
+ }
+}
+
/** 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
}
+type SwapParams = Pick<CloudJobParams, 'image_paths' | 'source_path' | 'studio_options' | 'clip_seconds' | 'swap_consent' | 'swap_step'>
+
/** 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. */
+ * OpenJutsu, the first photo as the still for a one-person model), the
+ * options the mode presets and 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.
+ *
+ * SCAIL 2 and Kling (two steps): the confirmed first frame is the image of
+ * the run. It is an own result; the server copies it into the customer's
+ * folder (`adopt`, POST /api/jobs/adopt), no outside address goes to the
+ * provider. The length runs on whole seconds of the measured video. */
export async function swapRunParams<T>(
model: string,
- s: SwapRunState<T> & { chosenSeconds: number | null },
+ s: SwapRunState<T> & { chosenSeconds: number | null; videoSeconds?: number },
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'> = {}
+ adopt?: (jobId: string) => Promise<string>,
+): Promise<SwapParams> {
+ const out: SwapParams = {}
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')) {
+ // What Swap presets (SCAIL 2: 720p) while the customer picks nothing; what
+ // the mode fixes wins (SCAIL 2: replace).
+ let options: Record<string, unknown> = { ...swapDefaultOptions(SWAP_INTENT, model), ...studioOptions, ...swapFixedOptions(SWAP_INTENT, model) }
+ const twoStep = swapUsesFrame(SWAP_INTENT, model)
+ if (twoStep) {
+ if (s.frameJobId) {
+ if (!adopt) throw new Error('Build the first frame and check it before you start the video.')
+ out.source_path = await adopt(s.frameJobId)
+ }
+ out.swap_step = 'video'
+ } else 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
+ // Roles: what the customer writes, else where their mark sits in the frame.
+ const placed = swapFigureRoles(figures)
+ const roles = swapReadsRoles(model) ? swapRoles(placed.map((role) => ({ role }))) : undefined
if (roles) options = { ...options, roles }
} else if (figures.length && reads.includes('source_path')) {
out.source_path = await upload(figures[0].image, 0, 1)
@@ -76,7 +113,9 @@ export async function swapRunParams<T>(
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)
+ out.clip_seconds = twoStep
+ ? swapWholeSeconds(model, s.chosenSeconds, s.videoSeconds)
+ : 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.ts
index f2f0a3d9..177e5b11 100644
--- a/src/lib/render/__tests__/alter-server.test.ts
+++ b/src/lib/render/__tests__/alter-server.test.ts
@@ -32,8 +32,9 @@ describe('der alte Katalog ist wirklich der alte', () => {
expect(m.weights, m.id).toBeUndefined()
}
const ids = new Set(alt.map((m) => m.id))
- // Eight from 02.10.2026, plus the two Swap Character models (07.11.2026).
- expect(neueIds()).toHaveLength(10)
+ // Eight from 02.10.2026, plus the two Swap Character models (07.11.2026),
+ // plus Kling Motion Control and Nano Banana Pro (14.11.2026).
+ expect(neueIds()).toHaveLength(12)
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/preset-models.ts b/src/lib/render/preset-models.ts
index bca722db..41bc4d3f 100644
--- a/src/lib/render/preset-models.ts
+++ b/src/lib/render/preset-models.ts
@@ -112,8 +112,10 @@ const ROLE_MEMBERS: Record<StepRole, () => string[]> = {
'preset-wan-2.2-spicy-extend', 'wan-2.2-spicy-extend', 'ltx-2-extend', 'pixverse-extend',
'wan-3.0-extend', 'seedance-2.5-extend',
],
- // Movement from a driving clip onto a character image.
- motion: () => ['scail-2', 'wan-2.2-animate-2', 'wan-2.2-animate', 'steady-dancer', 'p-video-animate', 'dreamactor-v2'],
+ // Movement from a driving clip onto a character image. Kling 3.0 Pro Motion
+ // Control (14.11.2026): the character moves like in the clip, at the highest
+ // resolution of the list.
+ motion: () => ['scail-2', 'kling-v3-pro-motion-control', 'wan-2.2-animate-2', 'wan-2.2-animate', 'steady-dancer', 'p-video-animate', 'dreamactor-v2'],
// A clip goes in, the same clip comes back changed. Wan DITTO picks a style
// from a list, MiniMax H3 follows a sentence.
restyle: () => ['wan-ditto', 'minimax-h3-video-edit'],
@@ -123,7 +125,8 @@ const ROLE_MEMBERS: Record<StepRole, () => string[]> = {
// 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).
+ // The one role that shares models with another (SCAIL 2 and Kling Motion
+ // Control are Motion, see SWAP_ROLES).
'swap-character': () => [...SWAP_MODELS],
}
diff --git a/src/lib/render/provider-schemas.json b/src/lib/render/provider-schemas.json
index 2d7518c2..ea1e716d 100644
--- a/src/lib/render/provider-schemas.json
+++ b/src/lib/render/provider-schemas.json
@@ -9483,5 +9483,153 @@
"resolution",
"seed"
]
+ },
+ "kwaivgi/kling-v3.0-pro/motion-control": {
+ "additionalProperties": false,
+ "properties": {
+ "character_orientation": {
+ "default": "video",
+ "description": "Generate the orientation of the characters in the video, which can be selected to match the image or the video.",
+ "enum": [
+ "image",
+ "video"
+ ],
+ "type": "string",
+ "x-ui-component": "select"
+ },
+ "element_list": {
+ "description": "Element reference list.",
+ "items": {
+ "properties": {
+ "element_id": {
+ "description": "Element ID returned by kwaivgi/kling-elements or kwaivgi/kling-elements-advanced.",
+ "type": "string"
+ }
+ },
+ "type": "object",
+ "x-order-properties": [
+ "element_id"
+ ]
+ },
+ "maxItems": 3,
+ "type": "array",
+ "x-ui-component": "array"
+ },
+ "image": {
+ "description": "Supported image formats:.jpg /.jpeg /.png The size of the image file should not exceed 10MB, the width and height of the image should be no less than 300px, and the aspect ratio of the image should be between 1:2.5 and 2.5:1",
+ "type": "string"
+ },
+ "keep_original_sound": {
+ "default": true,
+ "description": "Whether to retain the original video sound",
+ "type": "boolean"
+ },
+ "negative_prompt": {
+ "description": "The negative prompt for the generation.",
+ "type": "string"
+ },
+ "prompt": {
+ "description": "The positive prompt for the generation.",
+ "type": "string"
+ },
+ "video": {
+ "description": "The motion reference video. Supported formats: .mp4/.mov, up to 100MB, width and height between 340px and 3850px. Duration 3-30 seconds when character_orientation is \"video\", 3-10 seconds when it is \"image\"; longer videos are trimmed. The generated video length follows the reference video.",
+ "type": "string",
+ "x-hint": "When character_orientation is \u201dvideo\u201c: maximum 30 seconds,When character_orientation is \u201cimage\u201d: maximum 10 seconds."
+ }
+ },
+ "required": [
+ "image",
+ "video"
+ ],
+ "type": "object",
+ "x-order-properties": [
+ "image",
+ "video",
+ "element_list",
+ "character_orientation",
+ "prompt",
+ "negative_prompt",
+ "keep_original_sound"
+ ]
+ },
+ "google/nano-banana-pro/edit": {
+ "additionalProperties": false,
+ "properties": {
+ "aspect_ratio": {
+ "description": "The aspect ratio of the generated image. If not specified, it is determined automatically from the input image.",
+ "enum": [
+ "1:1",
+ "3:2",
+ "2:3",
+ "3:4",
+ "4:3",
+ "4:5",
+ "5:4",
+ "9:16",
+ "16:9",
+ "21:9"
+ ],
+ "type": "string",
+ "x-placeholder": "Select aspect ratio"
+ },
+ "enable_base64_output": {
+ "default": false,
+ "description": "If set to `true`, the prediction's `output` strings are returned as **naked base64** (no `data:<mime>;base64,` prefix). When `false` (default), outputs are returned as URLs pointing to our CDN.",
+ "disabled": true,
+ "type": "boolean"
+ },
+ "enable_sync_mode": {
+ "default": false,
+ "description": "If set to `true`, the request attempts to wait for the generated result and return outputs in the same response. If the result is not ready within the sync wait window, the API can return a timeout body while the task continues processing. This option is only available via the API and is supported only by some models.",
+ "disabled": true,
+ "type": "boolean"
+ },
+ "images": {
+ "description": "List of URLs of input images for editing. The maximum number of images is 14.",
+ "items": {
+ "type": "string"
+ },
+ "maxItems": 14,
+ "type": "array"
+ },
+ "output_format": {
+ "default": "png",
+ "description": "The format of the output image.",
+ "enum": [
+ "png",
+ "jpeg"
+ ],
+ "type": "string"
+ },
+ "prompt": {
+ "description": "The positive prompt for the generation.",
+ "type": "string"
+ },
+ "resolution": {
+ "default": "1k",
+ "description": "The resolution of the output image.",
+ "enum": [
+ "1k",
+ "2k",
+ "4k"
+ ],
+ "type": "string"
+ }
+ },
+ "required": [
+ "prompt",
+ "images"
+ ],
+ "type": "object",
+ "x-order-properties": [
+ "prompt",
+ "images",
+ "aspect_ratio",
+ "resolution",
+ "output_format",
+ "enable_sync_mode",
+ "enable_base64_output"
+ ]
}
}
diff --git a/src/lib/render/studio-models.json b/src/lib/render/studio-models.json
index ab076430..17caff97 100644
--- a/src/lib/render/studio-models.json
+++ b/src/lib/render/studio-models.json
@@ -191,6 +191,31 @@
},
"baselineUsd": 0.2
},
+ "kling-v3-pro-motion-control": {
+ "label": "Kling 3.0 Pro \u2022 Motion Control",
+ "endpoint": "kwaivgi/kling-v3.0-pro/motion-control",
+ "kind": "video",
+ "adult": false,
+ "tier": "best",
+ "weights": "closed",
+ "price": {
+ "mode": "input",
+ "rates": {
+ "default": 0.168
+ },
+ "maxSeconds": 30,
+ "minSeconds": 3
+ },
+ "inputs": {
+ "image": "source_path",
+ "video": "video_path"
+ },
+ "defaults": {
+ "character_orientation": "video",
+ "keep_original_sound": true
+ },
+ "baselineUsd": 0.84
+ },
"openjutsu-character-swap": {
"label": "OpenJutsu \u2022 Character Swap",
"endpoint": "base/openjutsu/character-swap",
@@ -1354,5 +1379,26 @@
"resolution": "480p"
},
"baselineUsd": 0.5
+ },
+ "nano-banana-pro-edit": {
+ "label": "Nano Banana Pro",
+ "endpoint": "google/nano-banana-pro/edit",
+ "kind": "image",
+ "adult": false,
+ "tier": "best",
+ "weights": "closed",
+ "price": {
+ "mode": "flat",
+ "rates": {
+ "1k": 0.14,
+ "2k": 0.14,
+ "4k": 0.24
+ }
+ },
+ "inputs": {
+ "images": "image_paths"
+ },
+ "defaults": {},
+ "baselineUsd": 0.14
}
}
diff --git a/src/lib/render/studio-roles.ts b/src/lib/render/studio-roles.ts
index f632231d..161d735f 100644
--- a/src/lib/render/studio-roles.ts
+++ b/src/lib/render/studio-roles.ts
@@ -50,4 +50,8 @@ export function studioReferenceVideo(): string[] {
* hinein, kein Pinsel noetig. */
export const STUDIO_EDIT_MODELS: readonly string[] = [
'minimax-h3-edit', 'qwen-image-3-edit', 'seedream-5-edit', 'qwen-image-2.1-edit',
+ // 14.11.2026: Nano Banana Pro, as on the web. It also builds the first frame
+ // of Swap Character (lib/render/swap.ts, SWAP_FRAME_MODEL). Listed only when
+ // the server's catalogue carries it.
+ 'nano-banana-pro-edit',
]
diff --git a/src/lib/render/swap.ts b/src/lib/render/swap.ts
index b728800c..349ec2aa 100644
--- a/src/lib/render/swap.ts
+++ b/src/lib/render/swap.ts
@@ -1,19 +1,23 @@
// 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
+// Port of the web app's lib/render/swap.ts (07.11.2026, C52; two steps with
+// SCAIL 2 and Kling since 14.11.2026), 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.
+// Models, the recommended first (after the real runs of 13./14.11.2026):
+// scail-2 1 to 3 people, mode replace, up to 120 s. Its
+// image is the first frame of the video with
+// the new people already in it (Nano Banana
+// Pro builds it first, the customer checks it).
+// kling-v3-pro-motion-control the same two steps for one person, at the
+// highest resolution, chosen by hand only.
+// openjutsu-character-swap 1 to 4 people, one photo and an optional role
+// each, at most the first 15 seconds, one step.
+// wan-2.2-animate-replace one person, up to 120 seconds, mode replace,
+// one step.
import { STUDIO_MODELS, studioSchema } from './studio-contract'
@@ -25,29 +29,56 @@ export function isSwapIntent(intent: string): intent is SwapIntent {
}
/** The models of Swap Character, the recommended first. */
-export const SWAP_MODELS: readonly string[] = ['openjutsu-character-swap', 'wan-2.2-animate-replace', 'scail-2']
+export const SWAP_MODELS: readonly string[] = ['scail-2', 'kling-v3-pro-motion-control', 'openjutsu-character-swap', 'wan-2.2-animate-replace']
-/** The main model, and the one for videos longer than it reads. */
-export const SWAP_MAIN_MODEL = 'openjutsu-character-swap'
+/** The recommended model (up to 3 people, up to 120 s). */
+export const SWAP_MAIN_MODEL = 'scail-2'
+/** One person at the highest resolution, picked by hand only. */
+export const SWAP_KLING_MODEL = 'kling-v3-pro-motion-control'
+/** Four people with roles, at most 15 s, one step. */
+export const SWAP_OPENJUTSU_MODEL = 'openjutsu-character-swap'
+/** One person, long and cheap, one step. */
export const SWAP_LONG_MODEL = 'wan-2.2-animate-replace'
+/** The first frame models: their image is the first frame of the video with
+ * the new people already in it (two steps). */
+export const SWAP_FRAME_MODELS: readonly string[] = [SWAP_MAIN_MODEL, SWAP_KLING_MODEL]
+
+/** Does Swap Character run in two steps on this model (the frame first, then
+ * the video)? */
+export function swapUsesFrame(intent: string, model: string): boolean {
+ return isSwapIntent(intent) && SWAP_FRAME_MODELS.includes(model)
+}
+
/** 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. */
+ * person in front of a new background, which is Motion Control. Kling
+ * follows the orientation of the video and keeps the original sound. */
export function swapFixedOptions(intent: string, model: string): Record<string, unknown> {
- if (isSwapIntent(intent) && (model === 'scail-2' || model === SWAP_LONG_MODEL)) return { mode: 'replace' }
+ if (!isSwapIntent(intent)) return {}
+ if (model === SWAP_MAIN_MODEL || model === SWAP_LONG_MODEL) return { mode: 'replace' }
+ if (model === SWAP_KLING_MODEL) return { character_orientation: 'video', keep_original_sound: true }
return {}
}
+/** What Swap Character presets on a model while the customer picks nothing:
+ * SCAIL 2 at 720p (as in the real run). */
+export function swapDefaultOptions(intent: string, model: string): Record<string, unknown> {
+ return isSwapIntent(intent) && model === SWAP_MAIN_MODEL ? { resolution: '720p' } : {}
+}
+
/** 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. */
+/** How many people a model swaps in one run. SCAIL 2 is tested for real with
+ * 2 and 3 people (13./14.11.2026), Kling is made for one. */
export function swapMaxPeople(model: string): number {
- return model === SWAP_MAIN_MODEL ? 4 : 1
+ if (model === SWAP_OPENJUTSU_MODEL) return 4
+ if (model === SWAP_MAIN_MODEL) return 3
+ return 1
}
/** Does the model read one role per photo (`roles`)? */
@@ -55,14 +86,15 @@ 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
+/** The model Swap Character picks for this many people: up to 3 SCAIL 2 (long
+ * clips up to 120 s too), with 4 OpenJutsu. Kling only the customer picks. */
+export function swapAutoModel(figures: number): string {
+ return figures > swapMaxPeople(SWAP_MAIN_MODEL) ? SWAP_OPENJUTSU_MODEL : SWAP_MAIN_MODEL
}
+/** The models the panel switches between by itself. */
+export const SWAP_AUTO_MODELS: readonly string[] = [SWAP_MAIN_MODEL, SWAP_OPENJUTSU_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.
@@ -76,13 +108,14 @@ export interface SwapClipLimits {
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). */
+/** The limits of a model, from the catalogue (studio-models.json). OpenJutsu
+ * needs at least 2 seconds of video, Kling reads 3 to 30 seconds (their model
+ * pages). */
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
+ const min = model === SWAP_OPENJUTSU_MODEL ? 2 : model === SWAP_KLING_MODEL ? 3 : 1
return { min, max, billedMin }
}
@@ -98,12 +131,26 @@ export function swapClipSeconds(model: string, chosen: number | null, videoSecon
/** 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. */
+ * The slider, the Create button and the server count the same. A first frame
+ * model runs on whole seconds (swapWholeSeconds). */
export function swapPricedSeconds(model: string, chosen: number | null, videoSeconds: number): number {
+ if (SWAP_FRAME_MODELS.includes(model)) return swapWholeSeconds(model, chosen, videoSeconds)
const { max } = swapClipLimits(model)
return Math.min(videoSeconds, chosen ?? max, max)
}
+/** Whole seconds for SCAIL 2 and Kling in Swap. The provider bills every
+ * started second (6.006 s cost like 7 s, real run of 13.11.2026). When the
+ * clip reaches less than 0.1 s past a whole second, the server cuts it to one
+ * frame below that second; otherwise the started second counts. A chosen
+ * length always cuts to one frame below. Slider, button and booking name
+ * exactly this number. */
+export function swapWholeSeconds(model: string, chosen: number | null, videoSeconds?: number): number {
+ const { max } = swapClipLimits(model)
+ const s = Math.min(videoSeconds && Number.isFinite(videoSeconds) ? videoSeconds : max, chosen ?? max, max)
+ return Math.max(1, Math.ceil(s - 0.1))
+}
+
/** Credits per second at the resolution picked. */
export function swapCreditsPerSecond(model: string, options: Record<string, unknown>): number | null {
const m = STUDIO_MODELS[model]
@@ -151,6 +198,38 @@ export interface SwapFigureSpec { role: string }
const ORDINAL = ['first', 'second', 'third', 'fourth']
+/** Where the customer tapped in the first frame, as a share of width and
+ * height (0 to 1). */
+export interface SwapMark { x: number; y: number }
+
+const PLACE_2 = ['the person on the left', 'the person on the right']
+const PLACE_3 = ['the person on the left', 'the person in the middle', 'the person on the right']
+
+/** A description per mark from where it sits, in the order of the marks:
+ * sorted by x, left, in the middle, right. With one mark "the person". This
+ * is the default role, the customer can write over it. No detection runs and
+ * nothing is billed. */
+export function swapMarkRoles(marks: readonly SwapMark[]): string[] {
+ if (marks.length <= 1) return marks.map(() => 'the person')
+ const order = marks.map((m, i) => ({ x: m.x, i })).sort((a, b) => a.x - b.x || a.i - b.i)
+ const out: string[] = new Array(marks.length)
+ order.forEach(({ i }, rank) => {
+ out[i] = marks.length === 2 ? PLACE_2[rank]
+ : marks.length === 3 ? PLACE_3[rank]
+ : `the ${ORDINAL[rank] ?? `${rank + 1}th`} person from the left`
+ })
+ return out
+}
+
+/** The role of each person: what the customer writes, else where their mark
+ * sits. People without a mark keep their own role (empty: the main person). */
+export function swapFigureRoles(figures: readonly { role: string; mark?: SwapMark | null }[]): string[] {
+ const marked = figures.map((f, i) => ({ f, i })).filter(({ f }) => f.mark)
+ const placed = swapMarkRoles(marked.map(({ f }) => f.mark!))
+ const byIndex = new Map(marked.map(({ i }, k) => [i, placed[k]]))
+ return figures.map((f, i) => f.role.trim().slice(0, 200) || byIndex.get(i) || '')
+}
+
/** 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
@@ -161,23 +240,122 @@ export function swapRoles(figures: SwapFigureSpec[]): string[] | undefined {
return roles.map((r, i) => r || `the ${ORDINAL[i] ?? `${i + 1}th`} person from the left`)
}
+/** The prompt of a swap run. A first frame model gets none: the built frame
+ * says it all (Kling ran without a prompt in the real test, SCAIL 2 replace
+ * needs none). Any other model gets the customer's text as it is. */
+export function swapPrompt(intent: string, model: string, prompt: string): string {
+ return swapUsesFrame(intent, model) ? '' : prompt
+}
+
/** 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. */
+ * 06.11. and 13./14.11.2026), so it is not learned from a failed run. Grey,
+ * not a warning. */
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.',
+ 'One continuous shot, no hard cuts. Everyone you replace must be visible in the first frame.',
+ 'Up to 3 people with SCAIL-2, one person with Kling (highest resolution).',
+ 'Subtitles burned into the video may disappear. Heavy make-up or costumes can blend back in.',
] as const
+/** The line above the first frame. */
+export const SWAP_TAP_TEXT = 'Tap each person you want to replace'
+
+// The first frame (two steps).
+
+/** The image model that builds the first frame with the new people. */
+export const SWAP_FRAME_MODEL = 'nano-banana-pro-edit'
+
+/** The aspect ratios Nano Banana Pro knows (the provider's schema). */
+const FRAME_ASPECTS = ['1:1', '3:2', '2:3', '3:4', '4:3', '4:5', '5:4', '9:16', '16:9', '21:9'] as const
+
+/** The allowed aspect ratio closest to the video. */
+export function swapFrameAspect(width: number, height: number): string {
+ if (!(width > 0) || !(height > 0)) return '9:16'
+ const want = Math.log(width / height)
+ let best: string = FRAME_ASPECTS[0], gap = Infinity
+ for (const a of FRAME_ASPECTS) {
+ const [w, h] = a.split(':').map(Number)
+ const d = Math.abs(Math.log(w / h) - want)
+ if (d < gap - 1e-9) { best = a; gap = d }
+ }
+ return best
+}
+
+/** The options of the frame step. 2k and JPEG as in the real test. */
+export function swapFrameOptions(width: number, height: number): Record<string, unknown> {
+ return { aspect_ratio: swapFrameAspect(width, height), resolution: '2k', output_format: 'jpeg' }
+}
+
+const IMAGE_ORDINAL = ['second', 'third', 'fourth', 'fifth']
+
+/** The sentence of the frame step (template from the real runs of
+ * 13./14.11.: without "No headset" and "same head angle" came headsets and
+ * frontal heads). The first image is the video frame, from the second on a
+ * photo per person. What the customer writes under "What's wrong?" goes at
+ * the end. */
+export function swapFramePrompt(roles: readonly string[], extra?: string): string {
+ const who = roles.length ? roles.map((r) => r.trim() || 'the person') : ['the person']
+ const one = who.length === 1
+ const replace = one
+ ? `Replace ${who[0]} in the first image with the person from the second image.`
+ : `In the first image, ${who.map((r, i) => `replace ${r} with the person from the ${IMAGE_ORDINAL[i]} image`).join(', ').replace(/, ([^,]*)$/, ' and $1')}.`
+ const keep = one
+ ? 'Keep the face identity, hair and facial features from the second image exactly.'
+ : 'Keep the face identity, hair and facial features of each new person from their image exactly.'
+ const rest = one
+ ? 'Keep everything else from the first image identical: same pose, the same head angle as in the first image, same head size, mouth position, camera angle, framing, distance, clothing, background, lighting, colors, text overlays and phone-camera quality. It must look like the same raw phone video frame, just with the other person.'
+ : `Every other person stays unchanged. Keep everything else from the first image identical: same poses, the same head angles as in the first image, same head sizes, mouth positions, camera angle, framing, distance, clothing, background, lighting, colors, text overlays and phone-camera quality. It must look like the same raw phone video frame, just with the other people.`
+ const fix = extra?.trim() ? `Fix this from the last attempt: ${extra.trim().slice(0, 500)}` : ''
+ return [
+ replace, keep,
+ one
+ ? "Use the hair of the person from the second image and remove all of the original person's hair completely, even long hair."
+ : "Use each new person's own hair from their image and remove all of the original people's hair completely, even long hair.",
+ one ? 'No headset, no microphone.' : 'No headsets, no microphones.',
+ rest, fix,
+ ].filter(Boolean).join(' ')
+}
+
+/** A fingerprint of the inputs of the frame step. When the video, a photo, a
+ * mark or a role changes, the built frame no longer fits and expires. */
+export function swapFrameKey(videoUrl: string, figures: readonly { imageUrl: string | null; role: string; mark?: SwapMark | null }[]): string {
+ const parts = [videoUrl, ...figures.map((f) => `${hash(f.imageUrl ?? '')}|${f.role}|${f.mark ? `${f.mark.x.toFixed(3)},${f.mark.y.toFixed(3)}` : ''}`)]
+ return parts.join('#')
+}
+function hash(text: string): string {
+ let h = 5381
+ for (let i = 0; i < text.length; i++) h = ((h * 33) ^ text.charCodeAt(i)) >>> 0
+ return `${text.length}:${h.toString(36)}`
+}
+
/** 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.
+// and the frame step wait for the tick. The tick is runtime only and never
+// stored. SCAIL 2 was missing until 14.11.2026 (gap: SCAIL 2 replace ran
+// without the tick).
-/** The models whose run needs the customer's confirmation. */
-export const SWAP_CONSENT_MODELS: readonly string[] = [SWAP_MAIN_MODEL, SWAP_LONG_MODEL]
+/** The models whose swap run needs the customer's confirmation. */
+export const SWAP_CONSENT_MODELS: readonly string[] = [SWAP_MAIN_MODEL, SWAP_KLING_MODEL, SWAP_OPENJUTSU_MODEL, SWAP_LONG_MODEL]
+
+/** The models that only swap and always need the tick. */
+const ALWAYS_CONSENT = [SWAP_OPENJUTSU_MODEL, SWAP_LONG_MODEL]
+
+/** The steps of the two step swap, as the run names them to the server. */
+export type SwapStep = 'frame' | 'video'
+
+/** Does the server ask for the tick on this run? SCAIL 2 and Kling also run in
+ * Motion Control (animate), there without. In Swap yes: SCAIL 2 in mode
+ * replace, and every run that names itself a swap step (swap_step), the
+ * frame step with Nano Banana Pro too. The same rule as the web server. */
+export function swapConsentRequired(model: string, params: { swap_step?: unknown; studio_options?: unknown }): boolean {
+ if (ALWAYS_CONSENT.includes(model)) return true
+ if (params.swap_step !== undefined) return true
+ const options = params.studio_options as Record<string, unknown> | undefined
+ return model === SWAP_MAIN_MODEL && options?.mode === 'replace'
+}
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.'
diff --git a/src/stores/createStore.ts b/src/stores/createStore.ts
index e28bb630..ac0e0947 100644
--- a/src/stores/createStore.ts
+++ b/src/stores/createStore.ts
@@ -112,7 +112,21 @@ export type CloudOp = 'character' | 'lipsync' | 'music' | 'extend' | 'motion' |
/** 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 }
+export interface SwapFigure {
+ image: ImageRef | null
+ role: string
+ /** Where the customer tapped this person in the first frame (0 to 1). */
+ mark?: { x: number; y: number } | null
+}
+
+/** Swap Character in two steps (14.11.2026, as on the web): the first frame
+ * of the video, drawn in the WebView. */
+export interface SwapFrame { url: string; width: number; height: number; videoUrl: string }
+
+/** The built first frame with the new people: a run of its own. `key` are the
+ * inputs it came from (lib/render/swap.ts, swapFrameKey); once they no longer
+ * match, it has expired. */
+export interface SwapBuilt { jobId: string; url: string; key: string; confirmed: boolean }
const ONE_FIGURE: SwapFigure[] = [{ image: null, role: '' }]
@@ -481,6 +495,11 @@ export interface CreateState {
* the people shown (lib/render/swap.ts SWAP_CONSENT_TEXT). Runtime-only,
* never persisted: every session confirms again. */
swapConsent: boolean
+ /** Swap Character: the first frame of the video. Runtime-only. */
+ swapFrame: SwapFrame | null
+ /** Swap Character: the built and (after Continue) confirmed first frame.
+ * Runtime-only. */
+ swapBuilt: SwapBuilt | null
/** Music track length in seconds (billed per second on the cloud). */
musicDuration: number
/** Music: optional lyrics passed to models that take them. Runtime-only. */
@@ -740,6 +759,8 @@ export interface CreateState {
setSwapSeconds: (seconds: number | null) => void
setSwapFigures: (figures: SwapFigure[]) => void
setSwapConsent: (consent: boolean) => void
+ setSwapFrame: (frame: SwapFrame | null) => void
+ setSwapBuilt: (built: SwapBuilt | null) => void
bumpCharactersVersion: () => void
setLoraListKey: (names: readonly string[]) => void
setCloudOpModel: (id: string) => void
@@ -1238,6 +1259,8 @@ export const useCreateStore = create<CreateState>()(
swapSeconds: null as number | null,
swapFigures: ONE_FIGURE,
swapConsent: false,
+ swapFrame: null as SwapFrame | null,
+ swapBuilt: null as SwapBuilt | null,
musicDuration: 60,
musicLyrics: '',
talkingWords: '',
@@ -1614,15 +1637,22 @@ 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.
+ // Another video: the chosen length, the first frame, the marks and the
+ // built frame belonged to the old one.
setVideoInput: (videoInput) => {
releaseReplacedMediaRef(get().videoInput, videoInput)
- set(videoInput?.url === get().videoInput?.url ? { videoInput } : { videoInput, swapSeconds: null })
+ const figures = get().swapFigures
+ set(videoInput?.url === get().videoInput?.url ? { videoInput } : {
+ videoInput, swapSeconds: null, swapFrame: null, swapBuilt: null,
+ swapFigures: figures.some((f) => f.mark) ? figures.map((f) => ({ ...f, mark: null })) : figures,
+ })
},
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 }),
+ setSwapFrame: (swapFrame) => set({ swapFrame }),
+ setSwapBuilt: (swapBuilt) => set({ swapBuilt }),
bumpCharactersVersion: () => set((s) => ({ charactersVersion: s.charactersVersion + 1 })),
setLoraListKey: (names) => set((s) => {
const key = names.join('\n')