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): Ein-Klick-Swap im Character-Bereich (Port des Web-Stands 4395e8d1 und 4e121fc0)

purplef53af51eb334
diff --git a/e2e/character-hub.spec.ts b/e2e/character-hub.spec.ts
index 7da4ad86..4aa977d0 100644
--- a/e2e/character-hub.spec.ts
+++ b/e2e/character-hub.spec.ts
@@ -286,7 +286,7 @@ test('without the account switch: Swap says coming soon, Motion has no sound cho
expect(seen.submits).toHaveLength(0)
})
-test('with the switch: the frame step and its check stay as they were', async ({ page }) => {
+test('with the switch: Swap is one click, the check stops after the frame', async ({ page }) => {
await boot(page, { hub: true })
// The built frame of the frame step, from the mock (no booking).
const frameNew = await media('frame-new.jpg', 'image/jpeg')
@@ -316,11 +316,12 @@ test('with the switch: the frame step and its check stay as they were', async ({
await expect(page.getByRole('group', { name: /First frame of your video/ })).toBeVisible({ timeout: 20_000 })
await tapFrame(page, 0.45, 0.33)
await page.getByRole('checkbox').check()
- await page.getByRole('button', { name: /Build first frame/ }).click()
+ await page.getByRole('switch', { name: 'Check first frame before video' }).click()
+ await page.getByRole('button', { name: /^Create · / }).last().click()
await expect(page.getByText('Does this look right?')).toBeVisible({ timeout: 20_000 })
- await shoot(page, 'd-swap-pruefen', '[data-swap-built]')
- await page.getByRole('button', { name: /Continue/ }).click()
- await expect(page.getByRole('button', { name: /^Create · / }).last()).toBeEnabled({ timeout: 15_000 })
+ await shoot(page, 'd-swap-pruefen')
+ await expect(page.getByRole('button', { name: /^Continue · / })).toBeEnabled()
+ await expect(page.getByRole('button', { name: /^Try again · 14k/ })).toBeEnabled()
expect(frames).toBe(1)
})
@@ -368,7 +369,7 @@ test('phone width: the same steps, the bar in its short form', async ({ page })
await tapFrame(page, 0.45, 0.33)
await tapFrame(page, 0.66, 0.36)
await page.getByRole('checkbox').check()
- await expect(page.locator('[data-hub-bar-summary]')).toContainText('SCAIL 2 · 6 s')
+ await expect(page.locator('[data-hub-bar-summary]')).toContainText('Auto · SCAIL-2 · 720p · 6 s')
await shoot(page, 'handy-c-swap')
await page.locator('[data-hub-bar-summary]').click()
await expect(page.locator('[data-hub-bar-options]')).toBeVisible()
diff --git a/e2e/swap-character.spec.ts b/e2e/swap-character.spec.ts
index fcbca1ff..1b5c61b6 100644
--- a/e2e/swap-character.spec.ts
+++ b/e2e/swap-character.spec.ts
@@ -5,12 +5,13 @@ import { openCharacterAction } from './support/character-hub'
/**
* 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.
+ * and Kling since 14.11.2026; one click since 14.11.2026, only with the
+ * account switch) in the real app, Tauri stubbed, cloud mocked: the panel in
+ * the web's order, the marks on the first frame, one Create with the total,
+ * the switches Uncensored and Check first frame, the check (Does this look
+ * right?, Continue), the video on the new frame, Kling for one person only.
+ * Nothing is booked: frame and video run against the mock, the video job
+ * never finishes.
*
* 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
@@ -84,7 +85,7 @@ async function recordedClip(page: Page): Promise<Buffer> {
}
/** 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 }
+interface Seen { submits: Array<{ model: string; prompt: string; params: Record<string, unknown> }>; uploads: number; adopts: unknown[] }
async function openSwap(page: Page): Promise<Seen> {
await page.setViewportSize({ width: 1296, height: 900 })
@@ -95,7 +96,7 @@ async function openSwap(page: Page): Promise<Seen> {
// 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 seen: Seen = { submits: [], uploads: 0, adopts: [] }
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) => {
@@ -107,13 +108,27 @@ async function openSwap(page: Page): Promise<Seen> {
seen.uploads++
return json({ path: `e2e-user-1/staged-${seen.uploads}.bin` })
}
+ if (path === '/api/jobs/adopt' && req.method() === 'POST') {
+ seen.adopts.push(req.postDataJSON())
+ return json({ path: `e2e-user-1/adopted-${seen.adopts.length}.jpg` })
+ }
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.
+ // The video step of the chain: taken, then it keeps rendering (no result,
+ // nothing booked). Anything else but the frame step is refused.
+ if (body.params?.swap_step === 'video') {
+ return json({ id: 'job-video-1', status: 'queued', created_at: new Date().toISOString(), quota: { kind: 'video', cost: 48000, used: 0, limit: 2_550_000 } }, 202)
+ }
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)
}
+ if (path === '/api/jobs/job-video-1' && req.method() === 'GET') {
+ return json({ job: {
+ id: 'job-video-1', kind: 'video', model: 'scail-2', provider: 'upstream', status: 'running',
+ result_url: null, attestation: null, cost_units: 0, created_at: new Date().toISOString(), completed_at: null, error: null,
+ } })
+ }
const job = /^\/api\/jobs\/(job-frame-\d+)$/.exec(path)
if (job && req.method() === 'GET') {
return json({ job: {
@@ -165,15 +180,15 @@ async function tapFrame(page: Page, x: number, y: number) {
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 }) => {
+test('Swap with one click: marks, one total, the check, then the video on the new frame', async ({ page }) => {
const seen = await openSwap(page)
const panel = page.locator('[data-swap-controls]')
const create = page.getByRole('button', { name: /^Create/ }).last()
- // SCAIL 2 is the default, the notes stand grey.
+ // SCAIL 2 is the default, the notes stand grey, both switches off.
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')
- // The resolution is under More options (sketches v2).
+ await expect(page.locator('[data-swap-summary]')).toHaveText('Auto · SCAIL-2 · 720p')
+ // The resolution is under More options (sketches v2), with the engines.
await page.getByRole('button', { name: 'More options' }).click()
await expect(page.getByRole('radio', { name: '720p' })).toHaveAttribute('aria-checked', 'true')
await expect(create).toBeDisabled()
@@ -192,100 +207,86 @@ test('Swap Character in two steps: marks, first frame, Continue, Kling for one p
await page.locator('[data-swap-photo-input="1"]').setInputFiles(await media('face1.png', 'image/png'))
await page.locator('[data-swap-photo-input="2"]').setInputFiles(await media('face2.png', 'image/png'))
await expect(page.getByRole('button', { name: 'Character for person 2' })).toContainText('Photo')
- // The bar prices frame and video together.
+ // The bar prices frame and video together, the button names the total.
await expect(page.locator('[data-clip-price]')).toHaveAttribute('title', /credits$/)
await expect(page.locator('[data-clip-split]')).toContainText('frame 14k + video')
- // Kling stands greyed out for two people, SCAIL 2 is recommended.
- await page.getByRole('button', { name: /SCAIL 2/ }).first().click()
+ // Under More options: Kling stands greyed out for two people.
+ await page.getByRole('button', { name: 'Video model' }).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()
+ await expect(page.getByRole('button', { name: 'First-frame model' })).toContainText('Auto (Nano Banana Pro)')
- // 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()
+ // The switches: Uncensored off, the check off; Uncensored takes the check along.
+ const uncensored = page.getByRole('switch', { name: 'Uncensored' })
+ const check = page.getByRole('switch', { name: 'Check first frame before video' })
+ await expect(uncensored).toHaveAttribute('aria-checked', 'false')
+ await expect(check).toHaveAttribute('aria-checked', 'false')
+ await uncensored.click()
+ await expect(check).toHaveAttribute('aria-checked', 'true')
+ await uncensored.click()
+ await expect(check).toHaveAttribute('aria-checked', 'false')
+
+ // Create waits for the consent.
+ await expect(create).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(create).toBeEnabled({ timeout: 15_000 })
+ await expect(create).toContainText(/^Create · \d+k$/)
+ await shoot(page, 'swap-ready-scail2', '[data-swap-bar]')
+
+ // With the check: one press builds the frame and stops.
+ await check.click()
+ await create.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('img', { name: /^New first frame/ })).toBeVisible()
+ await expect(page.getByRole('button', { name: /Try again · 14k/ })).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]')
-
- // 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]')).toHaveAttribute('data-swap-frame-count', '1')
- 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 })
- // Kling: 16,800 credits a second, at least its billed minimum.
- await expect(page.locator('[data-clip-split]')).toHaveText(/^frame 14k \+ video \d+k$/)
- await shoot(page, 'swap-kling-one-person', '[data-swap-built]')
+ await shoot(page, 'swap-review')
- // Nothing but the frame step ever went to the queue.
- expect(seen.submits.every((b) => b.params.swap_step === 'frame')).toBe(true)
+ // Continue: the video starts on the new frame (adopted), with the consent.
+ await page.getByRole('button', { name: /^Continue/ }).click()
+ await expect(page.locator('[data-swap-one-click=running]')).toBeVisible({ timeout: 15_000 })
+ await expect(page.locator('[data-swap-step=frame]')).toHaveAttribute('data-state', 'done')
+ await expect(page.locator('[data-swap-step=video]')).toHaveAttribute('data-state', 'now')
+ expect(seen.adopts).toEqual([{ job_id: 'job-frame-1', role: 'image' }])
+ const video = seen.submits[1]
+ expect(video.model).toBe('scail-2')
+ expect(video.params).toMatchObject({ op: 'studio', swap_step: 'video', swap_consent: true, sound: 'original', source_path: 'e2e-user-1/adopted-1.jpg' })
+ expect(video.params.image_paths).toBeUndefined()
+ await shoot(page, 'swap-running')
})
-test('Swap Character with OpenJutsu: one step, people up to four, consent before Create', async ({ page }) => {
+test('Swap with OpenJutsu: four people run in one step, no switches', 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('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()
+ // Four people: OpenJutsu by itself, one step, so no frame switches.
+ await expect(page.locator('[data-swap-summary]')).toContainText('Auto · OpenJutsu')
+ await expect(page.getByRole('switch', { name: 'Uncensored' })).toHaveCount(0)
+ for (const i of [2, 3, 4]) await page.locator(`[data-swap-photo-input="${i}"]`).setInputFiles(await media('face2.png', 'image/png'))
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 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]')).toHaveAttribute('title', /credits$/)
-
- 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 expect(page.locator('[data-clip-split]')).not.toContainText('frame')
})
/** A voice of `seconds` seconds as a WAV (a quiet tone), made here so the
@@ -324,9 +325,6 @@ test('Sound in Swap: original by default, lip sync greyed out for two people, a
await expect(page.locator('[data-clip-split]')).toContainText('frame 14k + video')
await expect(page.locator('[data-clip-split]')).toContainText('lip sync')
await page.getByRole('checkbox').check()
- await page.getByRole('button', { name: /Build first frame/ }).click()
- await expect(page.getByText('Does this look right?')).toBeVisible({ timeout: 20_000 })
- await page.getByRole('button', { name: /Continue/ }).click()
const create = page.getByRole('button', { name: /^Create/ }).last()
await expect(create).toBeEnabled({ timeout: 15_000 })
await expect(create).toContainText('Create ·')
@@ -340,8 +338,8 @@ test('Sound in Swap: original by default, lip sync greyed out for two people, a
await expect(page.getByRole('radio', { name: 'Original sound' })).toHaveAttribute('aria-checked', 'true')
await shoot(page, 'swap-lipsync-blocked-two-people', '[data-sound-controls]', 'desktop-ton')
- // Create was never pressed: only the frame step went to the queue.
- expect(seen.submits.every((b) => b.params.swap_step === 'frame')).toBe(true)
+ // Create was never pressed: nothing went to the queue.
+ expect(seen.submits).toHaveLength(0)
})
test('Sound in Motion: on the cloud lanes only', async ({ page }) => {
diff --git a/src/api/cloud/jobs.ts b/src/api/cloud/jobs.ts
index dd730118..a7150efe 100644
--- a/src/api/cloud/jobs.ts
+++ b/src/api/cloud/jobs.ts
@@ -106,6 +106,9 @@ export interface CloudJob {
started_at?: string | null
completed_at: string | null
error: string | null
+ /** A filtered model refused (one click swap): the open model the server
+ * names as the way out. Only on failed jobs, only on newer servers. */
+ fallback_model?: string | null
// Die Anzeigefelder, die die Listenroute (GET /api/jobs) aus den params
// herausreicht, damit eine neu geladene Galerie den Namen des Laufs
// wiederherstellt statt jedesmal leer anzufangen.
diff --git a/src/components/create/experimental/Composer.tsx b/src/components/create/experimental/Composer.tsx
index d297b4a2..436ba9bc 100644
--- a/src/components/create/experimental/Composer.tsx
+++ b/src/components/create/experimental/Composer.tsx
@@ -79,7 +79,7 @@ const NEGATIVE_FIELD_MAX = 'min(120px, calc(9vh / var(--ui-scale, 1)))'
const MAC_EDIT_PLACEHOLDER = 'Describe what to change in this image. Paint a mask to change only that area…'
/** The window is phone-wide (the Character area's bar takes m310's short form). */
-function useNarrow(): boolean {
+export function useNarrow(): boolean {
const query = '(max-width: 520px)'
const [narrow, setNarrow] = useState(() => typeof window !== 'undefined' && !!window.matchMedia?.(query).matches)
useEffect(() => {
diff --git a/src/components/create/experimental/SpecialIntentControls.tsx b/src/components/create/experimental/SpecialIntentControls.tsx
index 223ca3a8..e3d8d200 100644
--- a/src/components/create/experimental/SpecialIntentControls.tsx
+++ b/src/components/create/experimental/SpecialIntentControls.tsx
@@ -6,7 +6,7 @@
// specialized lanes), and the surfaces below fork only where the two lanes
// genuinely differ (extend's source pick, the cloud voice maker).
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import { usePopoverPlatz } from '../../../hooks/usePopoverPlatz'
import { AnimatePresence, motion } from 'framer-motion'
import {
@@ -1762,9 +1762,19 @@ function SoundControls({ intent, people, clipSeconds, withPrice = false }: {
// → Bean ▾"), the sound, the consent in one line. The length, the model and
// the price stand in the bar at the foot (Composer, hub). The frame step
// (Build first frame, Does this look right?, Continue) is SwapFrameBuild as
-// it was; the one click flow replaces it later.
-
-export function SwapControls() {
+// it was. In the one click swap (hub/SwapOneClick.tsx, only with the
+// account switch) the same inputs stand without it: the engine comes from the
+// one click picks, the switches stand above the consent, and Create in its
+// own bar runs the whole chain.
+
+export function SwapControls({ oneClick }: {
+ oneClick?: {
+ /** The engine of the video (swapVideoModelFor), kept in the store too. */
+ model: string
+ /** "Uncensored" and "Check first frame before video". */
+ switches?: ReactNode
+ }
+} = {}) {
const videoInput = useCreateStore((s) => s.videoInput)
const setVideoInput = useCreateStore((s) => s.setVideoInput)
const figures = useCreateStore((s) => s.swapFigures)
@@ -1778,7 +1788,7 @@ export function SwapControls() {
const setOpModel = useCreateStore((s) => s.setCloudOpModel)
const isGenerating = useCreateStore((s) => s.isGenerating)
const released = useCharacterHubReleased()
- const model = createRunModel('swap_character', { image: '', video: '', op: opModel })
+ const model = oneClick?.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.
@@ -1802,7 +1812,7 @@ export function SwapControls() {
const known = !!STUDIO_MODELS[model]
const lastTarget = useRef(target)
useEffect(() => {
- if (lastTarget.current === target) return
+ if (oneClick || lastTarget.current === target) return
lastTarget.current = target
if (auto && known && target !== model) setOpModel(target)
// eslint-disable-next-line react-hooks/exhaustive-deps
@@ -1816,8 +1826,9 @@ export function SwapControls() {
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.
+ // The one click swap picks its engine by the number of people itself.
const fitPeople = (people: number) => {
- if (people > swapMaxPeople(model)) setOpModel(swapAutoModel(people))
+ if (!oneClick && people > swapMaxPeople(model)) setOpModel(swapAutoModel(people))
}
if (!released) {
@@ -1948,6 +1959,7 @@ export function SwapControls() {
<SoundControls intent={SWAP_INTENT} people={figures.length}
clipSeconds={soundClipSeconds(SWAP_INTENT, model, swapSeconds, videoSeconds)} />
+ {oneClick?.switches}
{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
@@ -1963,7 +1975,7 @@ export function SwapControls() {
<span>{SWAP_CONSENT_TEXT}</span>
</label>
)}
- {twoStep && <div className="pt-3"><SwapFrameBuild model={model} /></div>}
+ {twoStep && !oneClick && <div className="pt-3"><SwapFrameBuild model={model} /></div>}
</div>
)
}
diff --git a/src/components/create/experimental/__tests__/swap-one-click-ui.test.tsx b/src/components/create/experimental/__tests__/swap-one-click-ui.test.tsx
new file mode 100644
index 00000000..37499199
--- /dev/null
+++ b/src/components/create/experimental/__tests__/swap-one-click-ui.test.tsx
@@ -0,0 +1,262 @@
+// @vitest-environment jsdom
+/**
+ * One click swap in the Character area (only with the account switch; port
+ * of the web's swap-one-click-ui.test.tsx, 4e121fc0): ONE button with the
+ * total (frame + video), one press runs the chain, a refusal of the frame
+ * step shows the quiet sentence and books no video, the consent is a must,
+ * and without the switch the area keeps the old panel. Every way to the
+ * server is a fake, the catalogue a fixture.
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import { render, cleanup, screen, act, fireEvent, renderHook } 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 () => {})
+const generate = vi.fn(async () => {})
+vi.mock('../CreateContext', () => ({
+ useCreateExp: () => ({
+ generate, 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(),
+ }),
+}))
+vi.mock('../useStudioPrice', async (orig) => ({
+ ...((await orig()) as Record<string, unknown>),
+ mediaSeconds: async () => 6,
+ useStudioPrice: (model: string | undefined) => (model ? { credits: 48000, live: false } : null),
+}))
+const built = vi.hoisted(() => ({ models: [] as string[] }))
+vi.mock('../../../../hooks/useCloudCreate', async (orig) => ({
+ ...((await orig()) as Record<string, unknown>),
+ buildSwapVideoSubmit: vi.fn(async (model: string) => {
+ built.models.push(model)
+ return { kind: 'video', model, prompt: '', params: { op: 'studio', video_path: 'u/v', swap_step: 'video', swap_consent: true, sound: 'original', max_credits: 48000 } }
+ }),
+}))
+const cloud = vi.hoisted(() => {
+ const submits: { kind: string; model: string; params: Record<string, unknown> }[] = []
+ const state = { refuse: false }
+ return {
+ submits,
+ state,
+ uploadInput: vi.fn(async () => 'u/x'),
+ adoptInput: vi.fn(async () => 'a/x'),
+ submitCloudJob: vi.fn(async (s: { kind: string; model: string; params: Record<string, unknown> }) => { submits.push(s); return { id: `job-${submits.length}` } }),
+ pollJob: vi.fn(async (id: string) => (state.refuse
+ ? { id, kind: 'image', model: 'nano-banana-pro-edit', status: 'failed', error: 'Nano Banana Pro declined this prompt.', fallback_model: 'qwen-image-2.1-edit', result_url: null }
+ : { id, kind: id === 'job-1' ? 'image' : 'video', model: 'x', status: 'succeeded', result_url: `https://r/${id}`, error: null, attestation: null })),
+ cancelJob: vi.fn(async () => {}),
+ }
+})
+vi.mock('../../../../api/cloud/jobs', async (orig) => ({
+ ...((await orig()) as Record<string, unknown>),
+ uploadInput: cloud.uploadInput, adoptInput: cloud.adoptInput, submitCloudJob: cloud.submitCloudJob,
+ pollJob: cloud.pollJob, cancelJob: cloud.cancelJob,
+}))
+
+import { SwapOneClick, useSwapOneClickShown } from '../hub/SwapOneClick'
+import { useCreateStore } from '../../../../stores/createStore'
+import { useCloudCatalogStore } from '../../../../stores/cloudCatalogStore'
+import { useCharacterHubReleaseStore } from '../../../../lib/create/character-hub-release'
+import { neuerServer } from '../../../../lib/render/__tests__/fixtures/test-catalogs'
+import { clearSwapChain, swapChainStore } from '../../../../lib/create/swap-chain'
+import { useSwapOneClick } from '../../../../lib/create/swap-one-click'
+import { SWAP_CONSENT_TEXT } from '../../../../lib/render/swap'
+
+const PIXEL = 'data:image/jpeg;base64,/9j/4AAQ'
+const flush = () => act(async () => { for (let i = 0; i < 12; i++) await new Promise((r) => setTimeout(r, 0)) })
+
+function Panel() {
+ return <div className="lu-hub flex flex-col"><SwapOneClick onChangeCharacter={() => {}} onOpenAdvanced={() => {}} /></div>
+}
+
+const createButton = () => screen.getByRole('button', { name: /^Create/ }) as HTMLButtonElement
+
+beforeEach(() => {
+ cloud.submits.length = 0
+ cloud.state.refuse = false
+ built.models.length = 0
+ generate.mockClear()
+ cloud.uploadInput.mockClear()
+ clearSwapChain()
+ localStorage.clear()
+ useCharacterHubReleaseStore.setState({ fromMe: true, fromCatalog: null })
+ useCloudCatalogStore.setState({ models: neuerServer() })
+ useSwapOneClick.setState({ openModels: false, check: false, checkTouched: false, frameOverride: '', videoOverride: '' })
+ useCreateStore.setState({
+ isGenerating: false, batchRun: null, error: null, gallery: [], source: null, prompt: '',
+ backend: 'cloud', cloudStudioOptions: {}, cloudStudioCredits: null, cloudOpModel: '',
+ sound: 'original', audioInput: null, voiceFromJob: null, lipsyncCredits: null,
+ } as never)
+ useCreateStore.getState().setIntent('swap_character')
+ useCreateStore.setState({
+ videoInput: { name: 'clip.mp4', url: 'blob:clip', blob: new Blob(['v']) },
+ swapFrame: { url: PIXEL, width: 1280, height: 720, videoUrl: 'blob:clip' },
+ swapFigures: [
+ { image: { filename: 'b', url: PIXEL, width: 1, height: 1 }, role: '', mark: { x: 0.4, y: 0.3 }, character: 'Bean' },
+ { image: { filename: 's', url: PIXEL, width: 1, height: 1 }, role: '', mark: { x: 0.7, y: 0.3 } },
+ ],
+ swapSeconds: null, swapBuilt: null,
+ swapConsent: true,
+ })
+})
+afterEach(() => { cleanup() })
+
+describe('one button, one price', () => {
+ it('Create shows frame + video (62k) and runs the frame, then the video', async () => {
+ render(<Panel />)
+ await flush()
+ const button = createButton()
+ expect(button.disabled).toBe(false)
+ expect(button.textContent).toBe('Create · 62k')
+ expect(document.querySelector('[data-clip-split]')!.textContent).toBe('frame 14k + video 48k')
+ expect(document.querySelector('[data-swap-summary]')!.textContent).toBe('Auto · SCAIL-2 · 720p')
+ // The engine stands in the store, the video price is the ceiling.
+ expect(useCreateStore.getState().cloudOpModel).toBe('scail-2')
+ expect(useCreateStore.getState().cloudStudioCredits).toBe(48000)
+ fireEvent.click(button)
+ await flush()
+ expect(built.models).toEqual(['scail-2'])
+ expect(cloud.submits.map((s) => [s.model, s.params.swap_step, s.params.swap_consent])).toEqual([
+ ['nano-banana-pro-edit', 'frame', true], ['scail-2', 'video', true],
+ ])
+ expect(cloud.submits[1].params.source_path).toBe('a/x')
+ expect(document.querySelector('[data-swap-one-click=done]')).toBeTruthy()
+ expect(screen.getByText(/Your new video · Bean and Photo/)).toBeTruthy()
+ // The result is in the gallery under the swap's name.
+ expect(useCreateStore.getState().gallery.some((g) => g.label === 'Swap Character')).toBe(true)
+ })
+
+ it('a refusal starts and books no video and offers Uncensored', async () => {
+ cloud.state.refuse = true
+ render(<Panel />)
+ await flush()
+ fireEvent.click(createButton())
+ await flush()
+ expect(cloud.submits.map((s) => s.params.swap_step)).toEqual(['frame'])
+ expect(screen.getByText(/refused this image\. Nothing was charged, and the video was not started\./)).toBeTruthy()
+ expect(screen.getByText('Change character')).toBeTruthy()
+ cloud.state.refuse = false
+ fireEvent.click(screen.getByText('Turn on Uncensored and retry'))
+ await flush()
+ expect(cloud.submits[1].model).toBe('qwen-image-2.1-edit')
+ expect(useSwapOneClick.getState().openModels).toBe(true)
+ // Uncensored turns the check on: the open frame waits for Continue.
+ expect(document.querySelector('[data-swap-one-click=review]')).toBeTruthy()
+ expect(cloud.submits).toHaveLength(2)
+ })
+
+ it('with Uncensored the frame runs on the open editor, and the price follows', async () => {
+ useSwapOneClick.setState({ openModels: true })
+ render(<Panel />)
+ await flush()
+ fireEvent.click(createButton())
+ await flush()
+ expect(cloud.submits[0].model).toBe('qwen-image-2.1-edit')
+ expect(cloud.submits[0].params.swap_step).toBe('frame')
+ })
+
+ it('Check first frame stops after the frame; Continue starts the video', async () => {
+ render(<Panel />)
+ await flush()
+ fireEvent.click(screen.getByRole('switch', { name: 'Check first frame before video' }))
+ expect(useSwapOneClick.getState().check).toBe(true)
+ fireEvent.click(createButton())
+ await flush()
+ expect(document.querySelector('[data-swap-one-click=review]')).toBeTruthy()
+ expect(cloud.submits).toHaveLength(1)
+ fireEvent.click(screen.getByRole('button', { name: /^Continue/ }))
+ await flush()
+ expect(cloud.submits.map((s) => s.params.swap_step)).toEqual(['frame', 'video'])
+ })
+
+ it('turning Uncensored on turns the check on; after Uncensored the chain stops for the check', async () => {
+ render(<Panel />)
+ await flush()
+ const check = () => screen.getByRole('switch', { name: 'Check first frame before video' }).getAttribute('aria-checked')
+ fireEvent.click(screen.getByRole('switch', { name: 'Uncensored' }))
+ expect(check()).toBe('true')
+ fireEvent.click(screen.getByRole('switch', { name: 'Uncensored' }))
+ expect(check()).toBe('false')
+ fireEvent.click(screen.getByRole('switch', { name: 'Uncensored' }))
+ fireEvent.click(createButton())
+ await flush()
+ expect(cloud.submits.map((s) => s.model)).toEqual(['qwen-image-2.1-edit'])
+ expect(document.querySelector('[data-swap-one-click=review]')).toBeTruthy()
+ })
+
+ it('a check set by hand no longer follows Uncensored', async () => {
+ render(<Panel />)
+ await flush()
+ fireEvent.click(screen.getByRole('switch', { name: 'Uncensored' }))
+ fireEvent.click(screen.getByRole('switch', { name: 'Check first frame before video' }))
+ fireEvent.click(screen.getByRole('switch', { name: 'Uncensored' }))
+ fireEvent.click(screen.getByRole('switch', { name: 'Uncensored' }))
+ expect(screen.getByRole('switch', { name: 'Check first frame before video' }).getAttribute('aria-checked')).toBe('false')
+ })
+
+ it('both switches stand in the panel, both off', async () => {
+ render(<Panel />)
+ await flush()
+ const open = screen.getByRole('switch', { name: 'Uncensored' })
+ expect(open.getAttribute('aria-checked')).toBe('false')
+ expect(screen.getByText('Off: Nano Banana Pro + SCAIL-2. On: open-weight models, less strict.')).toBeTruthy()
+ expect(screen.getByRole('switch', { name: 'Check first frame before video' }).getAttribute('aria-checked')).toBe('false')
+ })
+})
+
+describe('the gates', () => {
+ it('without the consent the button stays off and nothing goes up', async () => {
+ useCreateStore.setState({ swapConsent: false })
+ render(<Panel />)
+ await flush()
+ expect(screen.getByText(SWAP_CONSENT_TEXT)).toBeTruthy()
+ expect(createButton().disabled).toBe(true)
+ fireEvent.click(createButton())
+ await flush()
+ expect(cloud.submits).toHaveLength(0)
+ expect(cloud.uploadInput).not.toHaveBeenCalled()
+ })
+
+ it('without a character for a mark the button stays off', async () => {
+ useCreateStore.setState({ swapFigures: [{ image: null, role: '', mark: { x: 0.5, y: 0.5 } }] })
+ render(<Panel />)
+ await flush()
+ expect(createButton().disabled).toBe(true)
+ })
+
+ it('four people: OpenJutsu in one step through the normal Create run, no chain', async () => {
+ const fig = { image: { filename: 'p', url: PIXEL, width: 1, height: 1 }, role: '', mark: { x: 0.5, y: 0.5 } }
+ useCreateStore.setState({ swapFigures: [fig, fig, fig, fig] })
+ render(<Panel />)
+ await flush()
+ expect(useCreateStore.getState().cloudOpModel).toBe('openjutsu-character-swap')
+ expect(screen.queryByRole('switch', { name: 'Uncensored' })).toBeNull()
+ fireEvent.click(createButton())
+ await flush()
+ expect(generate).toHaveBeenCalledTimes(1)
+ expect(cloud.submits).toHaveLength(0)
+ expect(swapChainStore.getState().chain).toBeNull()
+ })
+
+ it('the area shows it only with the account switch and on the cloud', () => {
+ expect(renderHook(() => useSwapOneClickShown()).result.current).toBe(true)
+ useCharacterHubReleaseStore.setState({ fromMe: false, fromCatalog: null })
+ expect(renderHook(() => useSwapOneClickShown()).result.current).toBe(false)
+ useCharacterHubReleaseStore.setState({ fromMe: true, fromCatalog: null })
+ useCreateStore.setState({ backend: 'local' })
+ expect(renderHook(() => useSwapOneClickShown()).result.current).toBe(false)
+ })
+
+ it('without the switch the panel says Coming soon and has no Create', async () => {
+ useCharacterHubReleaseStore.setState({ fromMe: false, fromCatalog: null })
+ render(<Panel />)
+ await flush()
+ expect(screen.getByText(/Coming soon to your LU Cloud/)).toBeTruthy()
+ expect(createButton().disabled).toBe(true)
+ })
+})
diff --git a/src/components/create/experimental/hub/CharacterHub.tsx b/src/components/create/experimental/hub/CharacterHub.tsx
index a2b57bf0..64729b88 100644
--- a/src/components/create/experimental/hub/CharacterHub.tsx
+++ b/src/components/create/experimental/hub/CharacterHub.tsx
@@ -34,7 +34,8 @@ import { Composer, LaneControls } from '../Composer'
import { SpecialControls, SpecialMore } from '../SpecialIntentControls'
import { Select, type SelectOption } from '../../ui/Select'
import { cn } from '../../ui/cn'
-import { HubAvatar, HubCharactersContext, MoreOptions } from './HubParts'
+import { HUB_COLUMN, HubAvatar, HubCharactersContext, MoreOptions } from './HubParts'
+import { SwapOneClick, useSwapOneClickShown } from './SwapOneClick'
import { openHubAction, useHubCharacters } from './hubCharacters'
type TeaserIntent = Extract<CloudTeaserTarget, { surface: 'intent' }>['intent']
@@ -56,11 +57,15 @@ interface Props {
}
/** The column every step shares: 660 px, centred. */
-const COLUMN = 'mx-auto w-full max-w-[660px] px-4'
+const COLUMN = HUB_COLUMN
export function CharacterHub({ stage, onOpenAdvanced, onOpenWorkflows, onOpenGallery }: Props) {
const step = useCreateStore((s) => s.hubStep)
const { list, loading } = useHubCharacters()
+ // Swap with the account switch on the cloud: the one click flow, with its
+ // own bar (hub/SwapOneClick.tsx). Without it the panel as before.
+ const oneClick = useSwapOneClickShown()
+ const setHubStep = useCreateStore((s) => s.setHubStep)
return (
<HubCharactersContext.Provider value={list}>
<section className="lu-hub flex min-w-0 flex-1 flex-col overflow-hidden" data-character-hub={step} aria-label="Character">
@@ -69,7 +74,10 @@ export function CharacterHub({ stage, onOpenAdvanced, onOpenWorkflows, onOpenGal
</div>
{step === 'who' && <Scroll><HubWho list={list} loading={loading} onOpenGallery={onOpenGallery} /></Scroll>}
{step === 'what' && <Scroll><HubWhat /></Scroll>}
- {step === 'panel' && (
+ {step === 'panel' && oneClick && (
+ <SwapOneClick onChangeCharacter={() => setHubStep('who')} onOpenAdvanced={onOpenAdvanced} />
+ )}
+ {step === 'panel' && !oneClick && (
<>
<Scroll>
<div className="empty:hidden pt-3"><Stage hub {...stage} /></div>
diff --git a/src/components/create/experimental/hub/HubParts.tsx b/src/components/create/experimental/hub/HubParts.tsx
index ce431bf9..37294a2e 100644
--- a/src/components/create/experimental/hub/HubParts.tsx
+++ b/src/components/create/experimental/hub/HubParts.tsx
@@ -156,3 +156,40 @@ export function UploadLine({ icon, label, accept, onFile, note }: {
</HubLine>
)
}
+
+/** The column every step of the area shares: 660 px, centred. */
+export const HUB_COLUMN = 'mx-auto w-full max-w-[660px] px-4'
+
+/** A switch as a row (one click swap, sketch c2): the name, a grey line what
+ * it does, the switch at the right. A hairline under it, no box. */
+export function HubSwitch({ title, line, on, onChange, disabled, testId }: {
+ title: string
+ line: string
+ on: boolean
+ onChange: (on: boolean) => void
+ disabled?: boolean
+ testId?: string
+}) {
+ return (
+ <div className="hub-line flex min-h-12 items-center gap-4 border-b py-1.5" data-hub-switch={testId}>
+ <span className="min-w-0 flex-1">
+ <span className="hub-text block hub-fs-14">{title}</span>
+ <span className="hub-dim block hub-fs-125">{line}</span>
+ </span>
+ <button
+ type="button"
+ role="switch"
+ aria-checked={on}
+ aria-label={title}
+ disabled={disabled}
+ onClick={() => onChange(!on)}
+ className={cn(
+ 'relative h-[18px] w-[30px] shrink-0 rounded-full transition-colors disabled:opacity-40',
+ on ? 'bg-[var(--hub-acc)]' : 'bg-[var(--hub-edge)]',
+ )}
+ >
+ <span className={cn('absolute top-[2px] h-[14px] w-[14px] rounded-full bg-white shadow transition-[left]', on ? 'left-[14px]' : 'left-[2px]')} />
+ </button>
+ </div>
+ )
+}
diff --git a/src/components/create/experimental/hub/SwapOneClick.tsx b/src/components/create/experimental/hub/SwapOneClick.tsx
new file mode 100644
index 00000000..528c7a8f
--- /dev/null
+++ b/src/components/create/experimental/hub/SwapOneClick.tsx
@@ -0,0 +1,526 @@
+// Swap with one click (14.11.2026, David's call, only with the account switch
+// features.characterHub; port of the web's hub/SwapOneClick.tsx, 4e121fc0 and
+// 4395e8d1). Sketches mockups-v2: c2 (ready), c3 (More options open), c4
+// (running), d2 (check, only with "Check first frame"), c5 (refused).
+// One button "Create · total" runs frame, video and sound one after the other
+// (lib/create/swap-chain.ts). The inputs are SwapControls as before; the one
+// framed part is the bar at the foot, built like the Composer's bar of the
+// area. In the desktop style: rows with hairlines, text choices, no boxes.
+
+import { useEffect, useMemo, useState, type ReactNode } from 'react'
+import { useStore } from 'zustand'
+import { ArrowRight, Check, Loader2, SlidersHorizontal, Sparkles, X } from 'lucide-react'
+import { useCreateStore, type SwapFigure } from '../../../../stores/createStore'
+import { useCreateExp } from '../CreateContext'
+import { useNarrow } from '../Composer'
+import { SwapControls, SpecialMore } from '../SpecialIntentControls'
+import { mediaSeconds, useStudioPrice } from '../useStudioPrice'
+import { Button } from '../../ui/Button'
+import { Select, type SelectOption } from '../../ui/Select'
+import { cn } from '../../ui/cn'
+import { HUB_COLUMN, HubSwitch, MoreOptions } from './HubParts'
+import { SwapLength, useSwapBar } from './SwapBarParts'
+import { adoptInput, cancelJob, pollJob, submitCloudJob, uploadInput, type CloudJob } from '../../../../api/cloud/jobs'
+import { galleryItemFromJob } from '../../../../lib/render/cloud-jobs'
+import { studioShownValue } from '../../../../lib/render/create-studio'
+import { describeSubmitError } from '../../../../lib/create/engine'
+import { signalCreditsExhausted } from '../../../../lib/credits-exhausted'
+import { buildSwapVideoSubmit } from '../../../../hooks/useCloudCreate'
+import { useCharacterHubReleased } from '../../../../lib/create/character-hub-release'
+import {
+ swapBilledPhotos, swapDefaultOptions, swapFrameMaxPeople, swapFrameModelFor, swapPricedSeconds, swapShortCredits,
+ swapWholeSeconds, SWAP_GALLERY_LABEL, SWAP_INTENT,
+} from '../../../../lib/render/swap'
+import { swapFrameCredits } from '../../../../lib/create/swap-frame'
+import { swapInputError } from '../../../../lib/create/swap-run'
+import {
+ approveSwapFrame, cancelSwapChain, clearSwapChain, resumeSwapChain, retrySwapFrame, retrySwapOpen,
+ startSwapChain, swapChainProblem, swapChainStore, swapChainTotal, SWAP_CHAIN_RUNNING, type SwapChainDeps, type SwapChainState,
+} from '../../../../lib/create/swap-chain'
+import {
+ swapFrameChoices, swapIsChain, swapModelName, swapOpenModelsLine, swapVideoBlocked, swapVideoModelFor,
+ useSwapOneClick, SWAP_VIDEO_CHOICES,
+} from '../../../../lib/create/swap-one-click'
+
+/** The ways of the chain, from the app. */
+export function swapChainDeps(refreshQuota: () => Promise<void> | void): SwapChainDeps {
+ return {
+ uploadInput: (file, role) => uploadInput(file, role),
+ adoptInput: (jobId, role) => adoptInput(jobId, role),
+ submitCloudJob, pollJob, cancelJob,
+ onQuota: () => { void refreshQuota() },
+ onResult: (job: CloudJob) => {
+ useCreateStore.getState().addToGallery({
+ ...galleryItemFromJob(job),
+ prompt: '',
+ label: SWAP_GALLERY_LABEL,
+ })
+ },
+ }
+}
+
+/** Who a person is: the character from the list, or a photo. */
+function figureName(f: SwapFigure): string {
+ return f.character ?? (f.image ? 'Photo' : '')
+}
+
+function joinNames(names: string[]): string {
+ const n = names.filter(Boolean)
+ if (n.length <= 1) return n[0] ?? ''
+ return `${n.slice(0, -1).join(', ')} and ${n[n.length - 1]}`
+}
+
+/** Does the area show the one click swap? Only with the account switch and on
+ * the cloud; otherwise the panel as before ("Coming soon", or the Cloud
+ * sheet in local mode). */
+export function useSwapOneClickShown(): boolean {
+ const intent = useCreateStore((s) => s.intent())
+ const backend = useCreateStore((s) => s.backend)
+ const released = useCharacterHubReleased()
+ return intent === SWAP_INTENT && released && backend === 'cloud'
+}
+
+export function SwapOneClick({ onChangeCharacter, onOpenAdvanced }: {
+ /** "Change character" after a refusal: step 1 opens. */
+ onChangeCharacter: () => void
+ onOpenAdvanced: () => void
+}) {
+ const { refreshQuota, quota, generate, cancel } = useCreateExp()
+ const deps = useMemo(() => swapChainDeps(refreshQuota), [refreshQuota])
+ const narrow = useNarrow()
+ const released = useCharacterHubReleased()
+
+ const videoInput = useCreateStore((s) => s.videoInput)
+ const frame = useCreateStore((s) => s.swapFrame)
+ const figures = useCreateStore((s) => s.swapFigures)
+ const swapSeconds = useCreateStore((s) => s.swapSeconds)
+ const consent = useCreateStore((s) => s.swapConsent)
+ const options = useCreateStore((s) => s.cloudStudioOptions)
+ const setOptions = useCreateStore((s) => s.setCloudStudioOptions)
+ const opModel = useCreateStore((s) => s.cloudOpModel)
+ const setOpModel = useCreateStore((s) => s.setCloudOpModel)
+ const setStudioCredits = useCreateStore((s) => s.setCloudStudioCredits)
+ const backend = useCreateStore((s) => s.backend)
+ const sound = useCreateStore((s) => s.sound)
+ const audioInput = useCreateStore((s) => s.audioInput)
+ const voiceFromJob = useCreateStore((s) => s.voiceFromJob)
+ const lipModel = useCreateStore((s) => s.lipsyncModel)
+ const lipCredits = useCreateStore((s) => (s.sound === 'lipsync' ? s.lipsyncCredits : null))
+ const isGenerating = useCreateStore((s) => s.isGenerating)
+ const progressText = useCreateStore((s) => s.progressText)
+
+ const prefs = useSwapOneClick()
+ const { chain, busy, note } = useStore(swapChainStore)
+ const [preparing, setPreparing] = useState<string | null>(null)
+ const [error, setError] = useState<string | null>(null)
+
+ // A chain that ran before a restart is followed on here.
+ useEffect(() => { void resumeSwapChain(deps) }, [deps])
+
+ const marked = figures.filter((f) => f.mark).length
+ const videoModel = swapVideoModelFor(figures.length, prefs.videoOverride || null)
+ const isChain = swapIsChain(videoModel)
+ const frameModel = swapFrameModelFor(prefs.openModels, prefs.frameOverride || null)
+
+ // The engine stands in the store, so price, run and gallery see the same.
+ useEffect(() => { if (opModel !== videoModel) setOpModel(videoModel) }, [opModel, videoModel, setOpModel])
+ useEffect(() => {
+ const preset = swapDefaultOptions(SWAP_INTENT, videoModel)
+ const missing = Object.entries(preset).filter(([k]) => options[k] === undefined)
+ if (missing.length) setOptions({ ...options, ...Object.fromEntries(missing) })
+ }, [videoModel, options, setOptions])
+
+ const [measured, setMeasured] = useState<{ url: string; seconds: number | undefined } | null>(null)
+ useEffect(() => {
+ let alive = true
+ if (!videoInput) return
+ void mediaSeconds(videoInput.url, 'video').then((v) => { if (alive) setMeasured({ url: videoInput.url, seconds: v }) })
+ return () => { alive = false }
+ }, [videoInput])
+ const videoSeconds = measured && videoInput && measured.url === videoInput.url ? measured.seconds : undefined
+
+ const priceSeconds = videoSeconds !== undefined ? swapPricedSeconds(videoModel, swapSeconds, videoSeconds) : undefined
+ const studioPrice = useStudioPrice(videoInput ? videoModel : undefined, options, '', priceSeconds, 0, swapBilledPhotos(videoModel, figures.length))
+ const bar = useSwapBar(videoSeconds)
+ // The server's quote; until it is there the catalogue's figure (as the bar).
+ const videoCredits = videoInput ? studioPrice?.credits ?? bar.videoCredits : null
+ // The ceiling of the video job is exactly this number (max_credits).
+ useEffect(() => { setStudioCredits(videoCredits) }, [videoCredits, setStudioCredits])
+ const frameCredits = isChain ? swapFrameCredits(frame?.width ?? 9, frame?.height ?? 16, figures.length, frameModel) : 0
+ const lipsyncOn = sound === 'lipsync'
+ const total = swapChainTotal({ frame: frameCredits, video: videoCredits, lipsync: lipsyncOn ? lipCredits ?? 0 : 0 })
+ const seconds = videoSeconds !== undefined ? (isChain ? swapWholeSeconds(videoModel, swapSeconds, videoSeconds) : Math.round(priceSeconds ?? 0)) : null
+ const resolution = String(studioShownValue(videoModel, options, 'resolution') ?? '')
+
+ const running = !!chain && SWAP_CHAIN_RUNNING.includes(chain.stage)
+ const plainRunning = !isChain && isGenerating
+ const creditsOk = total == null || quota == null || quota.remaining.credits >= total
+ const problem = !videoInput ? 'Add the original video first.'
+ : isChain ? swapChainProblem({ frame, figures: figures.map((f) => ({ image: f.image, role: f.role, mark: f.mark })), frameModel, consent })
+ : swapInputError(videoModel, { hasVideo: true, figures, consent })
+ const voiceMissing = lipsyncOn && !audioInput && !voiceFromJob
+ const ready = released && backend === 'cloud' && !problem && !voiceMissing && creditsOk && total != null
+ && !running && !plainRunning && !preparing && !busy
+
+ const names = joinNames(figures.map(figureName))
+
+ const create = async () => {
+ setError(null)
+ if (!ready) return
+ if (!isChain) { await generate(); return }
+ clearSwapChain()
+ setPreparing('Uploading your video…')
+ try {
+ const submit = await buildSwapVideoSubmit(videoModel, (t) => setPreparing(t))
+ setPreparing('Uploading photos…')
+ const lip = lipsyncOn && (audioInput || voiceFromJob)
+ ? {
+ model: lipModel, credits: lipCredits ?? 0,
+ audio: audioInput ? { type: 'blob' as const, blob: audioInput.blob } : { type: 'job' as const, jobId: voiceFromJob!.jobId },
+ }
+ : null
+ const started = startSwapChain({
+ frame, figures: figures.map((f) => ({ image: f.image, role: f.role, mark: f.mark ?? null })),
+ frameModel, check: prefs.check, consent, who: names,
+ videoSubmit: submit, videoCredits: videoCredits ?? 0, lipsync: lip,
+ }, deps)
+ // As soon as the chain stands, its own view takes over.
+ const unsub = swapChainStore.subscribe((st) => { if (st.chain) { setPreparing(null); unsub() } })
+ await started.catch((err: unknown) => {
+ unsub()
+ setPreparing(null)
+ const failure = describeSubmitError(err, signalCreditsExhausted)
+ if (failure.text) setError(failure.text)
+ })
+ } catch (err) {
+ setPreparing(null)
+ const failure = describeSubmitError(err, signalCreditsExhausted)
+ if (failure.text) setError(failure.text)
+ }
+ }
+
+ // ── running (c4) ──
+ if (preparing || running || plainRunning) {
+ return (
+ <SwapProgress
+ chain={chain}
+ preparing={preparing}
+ plain={plainRunning ? progressText || 'Rendering in the cloud…' : null}
+ originalUrl={frame?.url ?? null}
+ names={names}
+ note={note}
+ onCancel={() => { if (plainRunning) void cancel(); else void cancelSwapChain(deps) }}
+ cancelDisabled={!!preparing}
+ />
+ )
+ }
+
+ // ── check (d2) ──
+ if (chain?.stage === 'review') {
+ const summary = `${prefs.videoOverride ? '' : 'Auto · '}${swapModelName(videoModel)}${resolution ? ` · ${resolution}` : ''}${seconds ? ` · ${seconds} s` : ''}`
+ return <SwapReview chain={chain} originalUrl={frame?.url ?? null} deps={deps} summary={summary} narrow={narrow} />
+ }
+
+ // ── done ──
+ if (chain?.stage === 'done') {
+ return (
+ <Body>
+ <div className="pt-4" data-swap-one-click="done">
+ {chain.resultUrl && (
+ <video src={chain.resultUrl} controls playsInline className="max-h-[52vh] w-full rounded-lg bg-black object-contain" />
+ )}
+ <p className="hub-dim mt-2 hub-fs-125">Your new video{chain.who ? ` · ${chain.who}` : ''}. It is in your gallery.</p>
+ {chain.error && <p className="hub-text mt-2 hub-fs-13" role="alert">{chain.error}</p>}
+ <button type="button" onClick={() => clearSwapChain()} className="hub-muted mt-4 hub-fs-13 underline decoration-[var(--hub-edge)] underline-offset-[3px]">
+ Make another swap
+ </button>
+ </div>
+ </Body>
+ )
+ }
+
+ // ── inputs (c2 / c3 / c5) ──
+ const refused = chain?.stage === 'refused'
+ const failedText = chain?.stage === 'failed' ? chain.error : chain?.stage === 'canceled' ? 'Canceled. Nothing more was started.' : null
+ const summary = `${prefs.videoOverride ? '' : 'Auto · '}${swapModelName(videoModel)}${resolution ? ` · ${resolution}` : ''}`
+ const parts = [
+ isChain && frameCredits != null ? `frame ${swapShortCredits(frameCredits)}` : null,
+ videoCredits != null ? `video ${swapShortCredits(videoCredits)}` : null,
+ lipsyncOn && lipCredits ? `lip sync ${swapShortCredits(lipCredits)}` : null,
+ ].filter(Boolean).join(' + ')
+ const hint = problem ?? (voiceMissing ? 'Add the new voice first.' : !creditsOk ? 'Not enough credits for this swap.' : undefined)
+
+ return (
+ <>
+ <Body>
+ <div className="pt-3" data-swap-one-click="form" data-swap-marks={marked}>
+ <SwapControls
+ oneClick={{
+ model: videoModel,
+ switches: isChain && (
+ <div className="pt-1" data-swap-switches>
+ <HubSwitch testId="open-models" title="Uncensored" line={swapOpenModelsLine(videoModel)} on={prefs.openModels} onChange={prefs.setOpenModels} />
+ <HubSwitch testId="check" title="Check first frame before video" line="Pause after the first frame so you can retry it before paying for the video." on={prefs.check} onChange={prefs.setCheck} />
+ </div>
+ ),
+ }}
+ />
+ <MoreOptions testId="hub-more">
+ <SwapPicks videoModel={videoModel} frameModel={frameModel} people={figures.length} isChain={isChain} />
+ <SpecialMore intent={SWAP_INTENT} />
+ <button type="button" onClick={onOpenAdvanced} className="hub-muted hub-fs-125 underline decoration-[var(--hub-edge)] underline-offset-[3px]">
+ All settings of the model
+ </button>
+ </MoreOptions>
+
+ {refused && (
+ <div className="flex items-start gap-2.5 pt-4" role="alert" data-swap-refused>
+ <X size={14} className="hub-dim mt-[3px] shrink-0" />
+ <div className="hub-fs-13">
+ <p className="hub-text">{chain!.error}</p>
+ <p className="mt-1 flex flex-wrap items-center gap-x-2">
+ <button type="button" className="hub-acc" onClick={() => {
+ prefs.setOpenModels(true)
+ prefs.setFrameOverride('')
+ // With Uncensored the check is on by default (David, 14.11.).
+ void retrySwapOpen(deps, useSwapOneClick.getState().check)
+ }}>
+ Turn on Uncensored and retry
+ </button>
+ <span className="hub-dim" aria-hidden>·</span>
+ <button type="button" className="hub-acc" onClick={() => { clearSwapChain(); onChangeCharacter() }}>Change character</button>
+ </p>
+ </div>
+ </div>
+ )}
+ {(failedText || error) && (
+ <div className="flex items-start gap-2.5 pt-4" role="alert" data-swap-error>
+ <X size={14} className="hub-dim mt-[3px] shrink-0" />
+ <p className="hub-text flex-1 hub-fs-13">{failedText ?? error}</p>
+ <button type="button" className="hub-dim hub-fs-125" onClick={() => { setError(null); if (chain) clearSwapChain() }}>Dismiss</button>
+ </div>
+ )}
+ </div>
+ </Body>
+
+ <Foot>
+ <SwapBar
+ narrow={narrow}
+ summary={summary}
+ length={videoInput ? <SwapLength videoSeconds={videoSeconds} /> : null}
+ seconds={videoInput ? seconds : null}
+ total={total}
+ parts={parts}
+ ready={ready}
+ hint={hint}
+ onCreate={() => void create()}
+ />
+ </Foot>
+ </>
+ )
+}
+
+function Body({ children }: { children: ReactNode }) {
+ return (
+ <div className="min-h-0 flex-1 overflow-y-auto scrollbar-thin">
+ <div className={cn(HUB_COLUMN, 'pb-4')}>{children}</div>
+ </div>
+ )
+}
+
+function Foot({ children }: { children: ReactNode }) {
+ return <div className={cn(HUB_COLUMN, 'shrink-0 pb-3 pt-2')}>{children}</div>
+}
+
+/** "First frame ▾" and "Video ▾" under More options (c3). */
+function SwapPicks({ videoModel, frameModel, people, isChain }: { videoModel: string; frameModel: string; people: number; isChain: boolean }) {
+ const prefs = useSwapOneClick()
+ const frameItems: SelectOption[] = swapFrameChoices(prefs.openModels).map((c) => {
+ const tooMany = c.value !== '' && swapFrameMaxPeople(c.value) < Math.max(1, people)
+ return { ...c, disabled: tooMany, sublabel: tooMany ? `up to ${swapFrameMaxPeople(c.value)} ${swapFrameMaxPeople(c.value) === 1 ? 'person' : 'people'}` : undefined }
+ })
+ const videoItems: SelectOption[] = [
+ { value: '', label: `Auto (${swapModelName(swapVideoModelFor(people, null))})` },
+ ...SWAP_VIDEO_CHOICES.map((id) => ({ value: id, label: swapModelName(id), disabled: !!swapVideoBlocked(id, people), sublabel: swapVideoBlocked(id, people) ?? undefined })),
+ ]
+ return (
+ <div className="hub-fs-125" data-swap-picks>
+ {isChain && (
+ <div className="flex min-h-8 items-center gap-2.5" data-swap-pick="frame">
+ <span className="hub-muted w-[80px] shrink-0">First frame</span>
+ <Select variant="text" ariaLabel="First-frame model" textClassName="hub-fs-125" value={prefs.frameOverride}
+ options={frameItems} onChange={prefs.setFrameOverride} placeholder={swapModelName(frameModel)} />
+ </div>
+ )}
+ <div className="flex min-h-8 items-center gap-2.5" data-swap-pick="video">
+ <span className="hub-muted w-[80px] shrink-0">Video</span>
+ <Select variant="text" ariaLabel="Video model" textClassName="hub-fs-125" value={prefs.videoOverride}
+ options={videoItems} onChange={prefs.setVideoOverride} placeholder={swapModelName(videoModel)} />
+ </div>
+ </div>
+ )
+}
+
+/** The bar at the foot (c2): summary, length, total with its parts, Create.
+ * Narrow (phone width): the summary opens the length and the parts above
+ * the row, Create names the total (the Composer's narrow bar). */
+function SwapBar({ narrow, summary, length, seconds, total, parts, ready, hint, onCreate }: {
+ narrow: boolean; summary: string; length: ReactNode; seconds: number | null; total: number | null; parts: string
+ ready: boolean; hint: string | undefined; onCreate: () => void
+}) {
+ const [open, setOpen] = useState(false)
+ const price = total != null ? swapShortCredits(total) : null
+ const create = (
+ <span className="inline-flex" title={ready ? undefined : hint}>
+ <Button variant="primary" size="md" icon={Sparkles} disabled={!ready} onClick={onCreate}
+ className={narrow ? 'h-10 rounded-[20px] px-4' : undefined}>
+ {narrow && price
+ ? <>Create <span className="hub-fs-125 tabular-nums opacity-70">{price}</span></>
+ : price ? `Create · ${price}` : 'Create'}
+ </Button>
+ </span>
+ )
+ const priceText = total != null && (
+ <span className="flex items-baseline gap-1.5 whitespace-nowrap hub-fs-12" data-clip-price data-swap-total={total} title={`${total.toLocaleString('en-US')} credits`}>
+ <b className="hub-text hub-fs-13 font-medium tabular-nums">{swapShortCredits(total)}</b>
+ {parts && <span className="hub-dim" data-clip-split>{parts}</span>}
+ </span>
+ )
+ if (narrow) {
+ return (
+ <div className="hub-bar rounded-2xl" data-swap-bar="narrow">
+ {open && (
+ <div className="hub-line flex flex-wrap items-center gap-2 border-b px-2.5 py-2" data-hub-bar-options>
+ {length}
+ {priceText}
+ </div>
+ )}
+ <div className="flex min-h-[45px] items-center gap-1.5 py-1.5 pl-2.5 pr-1.5">
+ <button type="button" onClick={() => setOpen(!open)} aria-expanded={open}
+ className="hub-muted flex min-h-11 min-w-0 flex-1 items-center gap-1.5 text-left hub-fs-13" data-hub-bar-summary>
+ <SlidersHorizontal size={14} className="shrink-0" />
+ <span className="truncate">{summary}{seconds ? ` · ${seconds} s` : ''}</span>
+ </button>
+ {create}
+ </div>
+ </div>
+ )
+ }
+ return (
+ <div className="hub-bar" data-swap-bar="wide">
+ <div className="flex min-h-[45px] items-center gap-1.5 py-[5px] pl-2.5 pr-1.5">
+ <span className="hub-muted whitespace-nowrap hub-fs-13" data-swap-summary>{summary}</span>
+ {length}
+ <span className="flex-1" />
+ {priceText}
+ <span className="w-1" />
+ {create}
+ </div>
+ </div>
+ )
+}
+
+/** c4: "First frame ✓ → Video … → Sound", Cancel, you can leave. */
+function SwapProgress({ chain, preparing, plain, originalUrl, names, note, onCancel, cancelDisabled }: {
+ chain: SwapChainState | null; preparing: string | null; plain: string | null; originalUrl: string | null; names: string
+ note: string | null; onCancel: () => void; cancelDisabled: boolean
+}) {
+ const stage = preparing ? 'frame' : plain ? 'video' : chain?.stage ?? 'frame'
+ const frameUrl = chain?.frameUrl ?? null
+ const steps = [
+ ...(plain ? [] : [{ id: 'frame', label: 'First frame' }]),
+ { id: 'video', label: 'Video' },
+ // Sound and the length: without a new voice the worker does it in the
+ // video step, with a new voice it is a job of its own.
+ { id: 'sound', label: 'Sound' },
+ ]
+ const order = ['frame', 'video', 'sound']
+ const at = order.indexOf(stage)
+ return (
+ <Body>
+ <div className="pt-4" data-swap-one-click="running" data-swap-stage={stage}>
+ {(frameUrl || originalUrl) && (
+ <img src={frameUrl ?? originalUrl!} alt={frameUrl ? 'New first frame' : 'Original first frame'}
+ className={cn('max-h-[42vh] max-w-full rounded-lg object-cover sm:max-w-[420px]', !frameUrl && 'opacity-50')} />
+ )}
+ <p className="hub-dim mt-2 hub-fs-125">{frameUrl ? `New first frame${names ? ` · ${names}` : ''}` : preparing ?? 'Building the first frame…'}</p>
+ <div className="hub-line mt-3 flex min-h-12 flex-nowrap items-center gap-x-2.5 border-y py-1" data-swap-steps>
+ {steps.map((st, i) => {
+ const idx = order.indexOf(st.id)
+ const done = idx < at
+ const now = idx === at
+ return (
+ <span key={st.id} className="inline-flex shrink-0 items-center gap-2.5">
+ {i > 0 && <ArrowRight size={13} className="hub-dim" aria-hidden />}
+ <span className={cn('inline-flex items-center gap-1.5 hub-fs-14', done ? 'hub-text' : now ? 'hub-text font-medium' : 'hub-dim')}
+ data-swap-step={st.id} data-state={done ? 'done' : now ? 'now' : 'next'}>
+ {done && <Check size={14} className="hub-acc" />}
+ {now && <Loader2 size={14} className="hub-acc animate-spin" />}
+ {st.label}{now ? ' …' : ''}
+ </span>
+ </span>
+ )
+ })}
+ <span className="flex-1" />
+ <button type="button" onClick={onCancel} disabled={cancelDisabled} className="hub-muted min-h-11 shrink-0 hub-fs-14 disabled:opacity-40" data-swap-cancel>Cancel</button>
+ </div>
+ <p className="hub-dim mt-3 hub-fs-13">{note ?? (plain ? 'About 2 to 7 min. Keep LU open until it is done.' : 'About 2 to 7 min. You can leave this page.')}</p>
+ {plain && <p className="hub-dim mt-1 hub-fs-12">{plain}</p>}
+ </div>
+ </Body>
+ )
+}
+
+/** d2: "Does this look right?", below "What's wrong?", Try again and Continue. */
+function SwapReview({ chain, originalUrl, deps, summary, narrow }: {
+ chain: SwapChainState; originalUrl: string | null; deps: SwapChainDeps; summary: string; narrow: boolean
+}) {
+ const [extra, setExtra] = useState('')
+ const busy = useStore(swapChainStore, (s) => s.busy)
+ const next = chain.videoCredits + (chain.lipsync?.credits ?? 0)
+ return (
+ <>
+ <Body>
+ <div className="pt-4" data-swap-one-click="review">
+ <p className="flex flex-wrap items-baseline gap-x-3">
+ <b className="hub-text hub-fs-14 font-semibold">Does this look right?</b>
+ <span className="hub-dim hub-fs-125">The first frame of your new video. The rest follows the original motion.</span>
+ </p>
+ <div className="mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2">
+ {[{ src: originalUrl, label: 'Original' }, { src: chain.frameUrl, label: `New first frame${chain.who ? ` · ${chain.who}` : ''}` }].map((p) => (
+ <figure key={p.label}>
+ {p.src ? <img src={p.src} alt={p.label} className="max-h-[40vh] w-full rounded-lg bg-black object-cover" /> : <div className="aspect-video rounded-lg bg-[var(--hub-fill)]" />}
+ <figcaption className="hub-dim mt-1.5 hub-fs-125">{p.label}</figcaption>
+ </figure>
+ ))}
+ </div>
+ </div>
+ </Body>
+ <Foot>
+ <div className={cn('hub-bar', narrow && 'rounded-2xl')} data-swap-bar="review">
+ <input
+ type="text"
+ value={extra}
+ maxLength={500}
+ aria-label="What's wrong?"
+ placeholder="What's wrong? (optional)"
+ onChange={(e) => setExtra(e.target.value)}
+ className="hub-text hub-line h-11 w-full border-b bg-transparent px-3 hub-fs-14 outline-none"
+ />
+ <div className="flex min-h-[45px] items-center gap-2.5 py-[5px] pl-2.5 pr-1.5">
+ {!narrow && <span className="hub-muted whitespace-nowrap hub-fs-13">{summary}</span>}
+ <span className="flex-1" />
+ <button type="button" disabled={busy} onClick={() => { void retrySwapFrame(deps, { extra }); setExtra('') }}
+ className="hub-muted min-h-11 whitespace-nowrap hub-fs-13 disabled:opacity-40" data-swap-retry>
+ Try again · {swapShortCredits(chain.frameCredits)}
+ </button>
+ <Button variant="primary" size="md" icon={Sparkles} disabled={busy} onClick={() => void approveSwapFrame(deps)}
+ className={narrow ? 'h-10 rounded-[20px] px-4' : undefined}>
+ {`Continue · ${swapShortCredits(next)}`}
+ </Button>
+ </div>
+ </div>
+ </Foot>
+ </>
+ )
+}
diff --git a/src/hooks/__tests__/useCloudCreate-swap-one-click.test.ts b/src/hooks/__tests__/useCloudCreate-swap-one-click.test.ts
new file mode 100644
index 00000000..51a2f9cf
--- /dev/null
+++ b/src/hooks/__tests__/useCloudCreate-swap-one-click.test.ts
@@ -0,0 +1,186 @@
+/**
+ * One click swap (14.11.2026, port of the web's buildSwapVideoSubmit,
+ * 4395e8d1): the video job the chain sends after the frame step. Built from
+ * the store like a Create run of Swap Character, without its image, with
+ * swap_step 'video', the consent, the sound and the shown price as ceiling.
+ * The gate: without the account switch nothing is built and nothing goes up.
+ * Nothing is rendered or booked: upload, adopt, quote, submit are mocked.
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+vi.mock('react', async (orig) => {
+ const actual = (await orig()) as Record<string, unknown>
+ return { ...actual, useCallback: (fn: unknown) => fn }
+})
+
+const hoisted = vi.hoisted(() => {
+ class FakeCloudJobError extends Error {
+ status: number
+ code?: string
+ constructor(message: string, status: number, meta?: { code?: string }) {
+ super(message)
+ this.status = status
+ this.code = meta?.code
+ }
+ }
+ class FakeQuoteChangedError extends FakeCloudJobError {
+ credits: number
+ constructor(message: string, credits: number) {
+ super(message, 409, { code: 'quote_changed' })
+ this.credits = credits
+ }
+ }
+ const submitted: Array<{ kind: string; model: string; prompt: string; params: Record<string, unknown> }> = []
+ const steps: string[] = []
+ const lipOutcome = { status: 'succeeded' as 'succeeded' | 'failed', error: null as string | null }
+ return {
+ FakeCloudJobError,
+ FakeQuoteChangedError,
+ submitted,
+ steps,
+ lipOutcome,
+ uploadInput: vi.fn(async (_blob: unknown, slot: string) => {
+ steps.push(`upload ${slot}`)
+ return `user-1/staged-${slot}`
+ }),
+ getJob: vi.fn(async (id: string) => ({ id, result_url: `https://storage.example/${id}.mp3` })),
+ submitCloudJob: vi.fn(async (payload: (typeof submitted)[number]) => {
+ submitted.push(payload)
+ return { id: `job-${submitted.length}` }
+ }),
+ pollJob: vi.fn(async (id: string) => {
+ const lip = id === 'job-2'
+ return {
+ id, kind: 'video', model: lip ? 'latentsync' : 'scail-2',
+ status: lip ? lipOutcome.status : 'succeeded',
+ error: lip ? lipOutcome.error : null,
+ result_url: lip && lipOutcome.status !== 'succeeded' ? null : `https://storage.example/${id}.mp4`,
+ created_at: new Date().toISOString(),
+ }
+ }),
+ cancelJob: vi.fn(async () => ({ status: 'canceled' })),
+ adoptInput: vi.fn(async (jobId: string, role: string) => {
+ steps.push(`adopt ${jobId} ${role}`)
+ return `user-1/adopted-${jobId}-${role}`
+ }),
+ studioQuote: vi.fn(async () => ({ credits: 42 })),
+ }
+})
+const { submitted, steps, lipOutcome } = hoisted
+
+vi.mock('../useContentPolicy', () => ({
+ contentPolicySnapshot: () => 'off' as const,
+ loadContentPolicy: async () => 'off' as const,
+}))
+vi.mock('../../api/cloud/jobs', () => ({
+ uploadInput: hoisted.uploadInput,
+ getJob: hoisted.getJob,
+ submitCloudJob: hoisted.submitCloudJob,
+ pollJob: hoisted.pollJob,
+ cancelJob: hoisted.cancelJob,
+ adoptInput: hoisted.adoptInput,
+ CloudJobError: hoisted.FakeCloudJobError,
+ QuoteChangedError: hoisted.FakeQuoteChangedError,
+}))
+vi.mock('../../api/cloud/studio', () => ({
+ studioQuote: hoisted.studioQuote,
+ StudioQuoteChangedError: hoisted.FakeQuoteChangedError,
+}))
+// Clip 6.006 s, voice 9 s (no <video>/<audio> in node).
+vi.mock('../../components/create/experimental/useStudioPrice', async (orig) => ({
+ ...((await orig()) as Record<string, unknown>),
+ mediaSeconds: async (_url: string, kind: string) => (kind === 'audio' ? 9 : 6.006),
+}))
+
+import { buildSwapVideoSubmit } from '../useCloudCreate'
+import { useCreateStore } from '../../stores/createStore'
+import { useCloudCatalogStore } from '../../stores/cloudCatalogStore'
+import { useCharacterHubReleaseStore } from '../../lib/create/character-hub-release'
+import { neuerServer } from '../../lib/render/__tests__/fixtures/test-catalogs'
+
+const FOTO = { filename: 'face.png', url: 'data:image/png;base64,AA', width: 512, height: 768 }
+const CLIP = { name: 'dance.mp4', url: 'blob:dance', blob: new Blob(['x'], { type: 'video/mp4' }) }
+
+function katalog() {
+ return neuerServer().map((m) => (m.id === 'latentsync'
+ ? { ...m, credits: { base: 9000, length: { basis: 'audio' as const, block: 1, per_block: 3000, min: 3, max: 300, quote: 10 } } }
+ : m))
+}
+
+beforeEach(() => {
+ // An account the server released the Character area for (features.characterHub).
+ useCharacterHubReleaseStore.setState({ fromMe: true, fromCatalog: null })
+ submitted.length = 0
+ steps.length = 0
+ lipOutcome.status = 'succeeded'
+ lipOutcome.error = null
+ vi.stubGlobal('fetch', vi.fn(async () => ({ ok: true, blob: async () => new Blob(['x']) })))
+ useCreateStore.setState({
+ isGenerating: false, error: null, backend: 'cloud',
+ source: null, audioInput: null, videoInput: null, voiceFromJob: null,
+ extendSource: null, gallery: [], cloudStudioOptions: {}, cloudStudioCredits: null, cloudOpModel: '',
+ sound: 'original', lipsyncModel: 'latentsync', lipsyncCredits: null,
+ })
+ useCloudCatalogStore.setState({ models: katalog() })
+ useCreateStore.getState().setIntent('swap_character')
+ useCreateStore.setState({ swapFigures: [{ image: null, role: '' }], swapSeconds: null, swapConsent: false, swapBuilt: null, swapFrame: null })
+})
+
+const MARKED = [{ image: FOTO, role: '', mark: { x: 0.3, y: 0.4 } }, { image: FOTO, role: 'the man in grey', mark: { x: 0.7, y: 0.4 } }]
+
+function ready(model = 'scail-2', figures = MARKED) {
+ useCreateStore.getState().setCloudOpModel(model)
+ useCreateStore.setState({ videoInput: CLIP, swapConsent: true, swapFigures: figures, cloudStudioCredits: 48000 })
+}
+
+describe('the video job of the chain', () => {
+ it('SCAIL 2: swap_step video, the consent, the length, the sound, the shown price; no photos, no frame yet', async () => {
+ ready()
+ const submit = await buildSwapVideoSubmit('scail-2')
+ expect(submit.model).toBe('scail-2')
+ expect(submit.kind).toBe('video')
+ const p = submit.params as unknown as Record<string, unknown>
+ expect(p.op).toBe('studio')
+ expect(p.swap_step).toBe('video')
+ expect(p.swap_consent).toBe(true)
+ expect(p.sound).toBe('original')
+ expect(p.max_credits).toBe(48000)
+ expect(p.clip_seconds).toBe(6)
+ expect(p.video_path).toBe('user-1/staged-video')
+ expect(p.label).toBe('Swap Character')
+ expect(p.source_path).toBeUndefined()
+ expect(p.image_paths).toBeUndefined()
+ expect(p.studio_options).toMatchObject({ mode: 'replace', resolution: '720p' })
+ // Only the video went up; the photos go into the frame step.
+ expect(steps).toEqual(['upload video'])
+ expect(submitted).toHaveLength(0)
+ })
+
+ it('No sound goes with the job, Kling gets keep_original_sound false', async () => {
+ ready('kling-v3-pro-motion-control', [MARKED[0]])
+ useCreateStore.setState({ sound: 'none' })
+ const p = (await buildSwapVideoSubmit('kling-v3-pro-motion-control')).params as unknown as Record<string, unknown>
+ expect(p.sound).toBe('none')
+ expect(p.studio_options).toMatchObject({ keep_original_sound: false })
+ })
+
+ it('a new voice with two people is refused before anything goes up', async () => {
+ ready()
+ useCreateStore.setState({ sound: 'lipsync' })
+ await expect(buildSwapVideoSubmit('scail-2')).rejects.toThrow()
+ expect(steps).toEqual([])
+ })
+
+ it('without the account switch: Coming soon, nothing goes up', async () => {
+ useCharacterHubReleaseStore.setState({ fromMe: false, fromCatalog: null })
+ ready()
+ await expect(buildSwapVideoSubmit('scail-2')).rejects.toThrow('Swap Character is coming soon to your LU Cloud.')
+ expect(steps).toEqual([])
+ })
+
+ it('without the video nothing is built', async () => {
+ ready()
+ useCreateStore.setState({ videoInput: null })
+ await expect(buildSwapVideoSubmit('scail-2')).rejects.toThrow('Add the original video first.')
+ })
+})
diff --git a/src/hooks/useCloudCreate.ts b/src/hooks/useCloudCreate.ts
index 77c5ecf5..5d70fb8b 100644
--- a/src/hooks/useCloudCreate.ts
+++ b/src/hooks/useCloudCreate.ts
@@ -30,6 +30,7 @@ import {
QuoteChangedError,
type CloudJobParams,
type CloudJob,
+ type CloudJobSubmit,
} from '../api/cloud/jobs'
import { defaultCloudModel, editNeedsMask, modelForOp, utilityOpModel, resolveOpPick, cloudModelById, cloudMediaLive, resolveCharacterModel, lengthCredits, lengthPrice } from '../stores/cloudCatalogStore'
import { checkPromptSafety, blockMessageFor, type SafetyVerdict } from '../lib/render/safety'
@@ -1370,3 +1371,41 @@ export function useCloudCreate(opts: { onQuotaChange?: () => void } = {}) {
return { generate, cancel, enhanceVideo, makeVoice }
}
+
+/** One click swap (lib/create/swap-chain.ts, only with the account switch;
+ * port of the web's buildSwapVideoSubmit, 4395e8d1): the video job, built
+ * from the store like a Create run of Swap Character, only without its
+ * image. That comes from the frame step; the chain sets it as source_path.
+ * The video goes up here, so everything is on the server before the first
+ * job. The ceiling is the video price the bar shows (cloudStudioCredits).
+ * Throws with the text for the customer. */
+export async function buildSwapVideoSubmit(model: string, onStep?: (text: string) => void): Promise<CloudJobSubmit> {
+ const s = useCreateStore.getState()
+ if (!characterHubReleasedHere()) throw new Error('Swap Character is coming soon to your LU Cloud.')
+ if (!STUDIO_MODELS[model]) throw new Error('Swap Character needs a newer LU Cloud. Try again later.')
+ if (!s.videoInput) throw new Error('Add the original video first.')
+ const sound = s.sound
+ const invalid = soundInputError(sound, s.swapFigures.length, 'cloud', !!s.audioInput || !!s.voiceFromJob, s.lipsyncModel)
+ if (invalid) throw new Error(invalid)
+ const filtered = Object.fromEntries(
+ Object.entries(s.cloudStudioOptions).filter(([key]) => studioFields(model)[key] !== undefined),
+ )
+ const params: CloudJobParams = { op: 'studio', studio_options: filtered, client_request_id: crypto.randomUUID() }
+ onStep?.('Uploading your video…')
+ params.video_path = await uploadInput(s.videoInput.blob, 'video')
+ const videoSeconds = await mediaSeconds(s.videoInput.url, 'video').catch(() => undefined)
+ // No frame yet: swapRunParams sets swap_step 'video', the options, the
+ // length on whole seconds and the consent, and uploads nothing more.
+ Object.assign(params, await swapRunParams(
+ model,
+ { hasVideo: true, figures: s.swapFigures, consent: s.swapConsent, chosenSeconds: s.swapSeconds, videoSeconds, frameJobId: null },
+ filtered,
+ async () => { throw new Error('Swap: the people go into the first frame, not into the video job.') },
+ ))
+ params.sound = soundParam(sound)
+ const own = soundStudioOptions(model, sound)
+ if (Object.keys(own).length) params.studio_options = { ...(params.studio_options ?? filtered), ...own }
+ params.label = SWAP_GALLERY_LABEL
+ if (s.cloudStudioCredits != null) params.max_credits = s.cloudStudioCredits
+ return { kind: STUDIO_MODELS[model].kind, model, prompt: '', params }
+}
diff --git a/src/lib/create/__tests__/swap-chain.test.ts b/src/lib/create/__tests__/swap-chain.test.ts
new file mode 100644
index 00000000..b4e829f0
--- /dev/null
+++ b/src/lib/create/__tests__/swap-chain.test.ts
@@ -0,0 +1,355 @@
+// @vitest-environment jsdom
+/**
+ * One click swap (14.11.2026, only with the account switch; port of the web's
+ * swap-chain.test.ts, 4395e8d1): the chain of frame, video and sound. Every
+ * way to the server is a fake; counted is what is sent and what is not.
+ * Desktop difference: a character from the list is its picture as a photo
+ * (hubPortrait), so every person goes up as an upload, nothing is adopted
+ * except the own results of the chain.
+ */
+import { describe, it, expect, beforeEach } from 'vitest'
+import type { CloudJob, CloudJobSubmit } from '../../../api/cloud/jobs'
+import { CloudJobError } from '../../../api/cloud/client'
+import {
+ approveSwapFrame, cancelSwapChain, clearSwapChain, loadSwapChain, resumeSwapChain, retrySwapFrame, retrySwapOpen,
+ startSwapChain, swapChainProblem, swapChainStore, swapChainTotal, swapFrameRefused, SWAP_CHAIN_STORAGE_KEY,
+ SWAP_REFUSED_TEXT, type SwapChainDeps, type SwapChainStart,
+} from '../swap-chain'
+import { swapFrameCredits } from '../swap-frame'
+import {
+ swapFrameEditors, swapFrameFiltered, swapFrameMaxPeople, swapFrameModelFor, swapFrameOptionsFor,
+ SWAP_CONSENT_MISSING, SWAP_FRAME_MODEL, SWAP_FRAME_OPEN_MODEL,
+} from '../../render/swap'
+import {
+ swapFrameChoices, swapIsChain, swapModelName, swapOpenModelsLine, swapVideoBlocked, swapVideoModelFor, useSwapOneClick,
+} from '../swap-one-click'
+
+const PIXEL = 'data:image/jpeg;base64,/9j/4AAQ'
+
+type Outcome = Partial<CloudJob> & { status: CloudJob['status'] }
+
+function fakeDeps(outcomes: (submit: CloudJobSubmit, n: number) => Outcome) {
+ const submits: CloudJobSubmit[] = []
+ const adopted: unknown[] = []
+ const uploads: string[] = []
+ const canceled: string[] = []
+ const results: string[] = []
+ let quota = 0
+ const byId = new Map<string, Outcome>()
+ const deps: SwapChainDeps = {
+ uploadInput: async (_b, role) => { uploads.push(role); return `u/${uploads.length}-${role}` },
+ adoptInput: async (jobId, role) => { adopted.push([jobId, role]); return `a/${adopted.length}-${role}` },
+ submitCloudJob: async (submit) => {
+ submits.push(submit)
+ const id = `job-${submits.length}`
+ byId.set(id, outcomes(submit, submits.length))
+ return { id }
+ },
+ pollJob: async (id) => ({
+ id, kind: 'image', model: 'x', provider: 'p', result_url: null, attestation: null, cost_units: 0,
+ created_at: '', completed_at: '', error: null, ...byId.get(id)!,
+ } as CloudJob),
+ cancelJob: async (id) => { canceled.push(id) },
+ onResult: (job) => { results.push(job.id) },
+ onQuota: () => { quota++ },
+ }
+ return { deps, submits, adopted, uploads, canceled, results, quota: () => quota }
+}
+
+const ok = (url: string): Outcome => ({ status: 'succeeded', result_url: url })
+const params = (s: CloudJobSubmit) => s.params as unknown as Record<string, unknown>
+
+function start(over: Partial<SwapChainStart> = {}): SwapChainStart {
+ return {
+ frame: { url: PIXEL, width: 1280, height: 720 },
+ figures: [
+ { image: { url: PIXEL }, role: '', mark: { x: 0.4, y: 0.3 } },
+ { image: { url: PIXEL }, role: '', mark: { x: 0.7, y: 0.3 } },
+ ],
+ frameModel: SWAP_FRAME_MODEL,
+ check: false,
+ consent: true,
+ who: 'Bean and Photo',
+ videoSubmit: {
+ kind: 'video', model: 'scail-2', prompt: '',
+ params: { op: 'studio', video_path: 'u/video', swap_step: 'video', swap_consent: true, sound: 'original', max_credits: 48000 },
+ },
+ videoCredits: 48000,
+ lipsync: null,
+ ...over,
+ }
+}
+
+beforeEach(() => { clearSwapChain(); localStorage.clear() })
+
+describe('one click: frame, then video, then done', () => {
+ it('sends the frame step, then the video with the new frame as source_path', async () => {
+ const f = fakeDeps((s) => ok(s.kind === 'image' ? 'https://r/frame.jpg' : 'https://r/video.mp4'))
+ await startSwapChain(start(), f.deps)
+ expect(f.submits.map((s) => [s.model, params(s).swap_step])).toEqual([
+ ['nano-banana-pro-edit', 'frame'], ['scail-2', 'video'],
+ ])
+ // The video frame first, then one photo per person, all uploaded before
+ // the first job.
+ const frame = params(f.submits[0])
+ expect(frame.image_paths).toEqual(['u/1-source', 'u/2-source', 'u/3-source'])
+ expect(frame.swap_consent).toBe(true)
+ expect(frame.studio_options).toEqual({ aspect_ratio: '16:9', resolution: '2k', output_format: 'jpeg' })
+ expect(frame.max_credits).toBe(swapFrameCredits(1280, 720, 2))
+ // The video runs on the result of the frame step (adopt job-1).
+ expect(f.adopted).toEqual([['job-1', 'image']])
+ const video = params(f.submits[1])
+ expect(video.source_path).toBe('a/1-image')
+ expect(video.max_credits).toBe(48000)
+ expect(video.swap_consent).toBe(true)
+ expect(video.sound).toBe('original')
+ const chain = swapChainStore.getState().chain!
+ expect(chain.stage).toBe('done')
+ expect(chain.resultUrl).toBe('https://r/video.mp4')
+ expect(f.results).toEqual(['job-2'])
+ expect(f.quota()).toBeGreaterThan(0)
+ })
+
+ it('the new voice runs after the video as swap_step lipsync, on the own video', async () => {
+ const f = fakeDeps((s) => ok(`https://r/${s.kind}`))
+ await startSwapChain(start({
+ figures: [start().figures[0]],
+ lipsync: { model: 'latentsync', audio: { type: 'blob', blob: new Blob(['a']) }, credits: 900 },
+ }), f.deps)
+ expect(f.submits.map((s) => params(s).swap_step)).toEqual(['frame', 'video', 'lipsync'])
+ expect(f.uploads).toContain('audio')
+ const lip = params(f.submits[2])
+ expect(lip.swap_consent).toBe(true)
+ expect(lip.max_credits).toBe(900)
+ expect(f.adopted.at(-1)).toEqual(['job-2', 'video'])
+ expect(swapChainStore.getState().chain!.stage).toBe('done')
+ expect(f.results).toEqual(['job-2', 'job-3'])
+ })
+
+ it('a voice from an earlier job is adopted, not uploaded', async () => {
+ const f = fakeDeps((s) => ok(`https://r/${s.kind}`))
+ await startSwapChain(start({
+ figures: [start().figures[0]],
+ lipsync: { model: 'latentsync', audio: { type: 'job', jobId: 'voice-1' }, credits: 900 },
+ }), f.deps)
+ expect(f.adopted[0]).toEqual(['voice-1', 'audio'])
+ expect(f.uploads).not.toContain('audio')
+ })
+
+ it('a failed lip sync keeps the video and says so', async () => {
+ const f = fakeDeps((s, n) => (n === 3 ? { status: 'failed', error: 'Lip sync broke.' } : ok(`https://r/${s.kind}`)))
+ await startSwapChain(start({
+ figures: [start().figures[0]],
+ lipsync: { model: 'latentsync', audio: { type: 'blob', blob: new Blob(['a']) }, credits: 900 },
+ }), f.deps)
+ const chain = swapChainStore.getState().chain!
+ expect(chain.stage).toBe('done')
+ expect(chain.resultUrl).toBe('https://r/video')
+ expect(chain.error).toMatch(/lip sync failed: Lip sync broke\./)
+ })
+})
+
+describe('Check first frame before video', () => {
+ it('stops after the frame; the video starts only on Continue', async () => {
+ const f = fakeDeps((s) => ok(s.kind === 'image' ? 'https://r/frame.jpg' : 'https://r/video.mp4'))
+ await startSwapChain(start({ check: true }), f.deps)
+ expect(swapChainStore.getState().chain!.stage).toBe('review')
+ expect(swapChainStore.getState().chain!.frameUrl).toBe('https://r/frame.jpg')
+ expect(f.submits).toHaveLength(1)
+ await approveSwapFrame(f.deps)
+ expect(f.submits).toHaveLength(2)
+ expect(swapChainStore.getState().chain!.stage).toBe('done')
+ })
+
+ it('Try again runs only the frame step, with "What\'s wrong?" in the sentence', async () => {
+ const f = fakeDeps((s) => ok(s.kind === 'image' ? 'https://r/frame.jpg' : 'https://r/video.mp4'))
+ await startSwapChain(start({ check: true }), f.deps)
+ await retrySwapFrame(f.deps, { extra: 'Keep the glasses.' })
+ expect(f.submits.map((s) => s.kind)).toEqual(['image', 'image'])
+ expect(f.submits[1].prompt).toContain('Keep the glasses.')
+ expect(swapChainStore.getState().chain!.stage).toBe('review')
+ })
+})
+
+describe('Uncensored and own picks', () => {
+ it('with Uncensored Qwen Image 2.1 Edit builds the frame, at 1k', async () => {
+ expect(swapFrameModelFor(true)).toBe(SWAP_FRAME_OPEN_MODEL)
+ expect(swapFrameModelFor(false)).toBe(SWAP_FRAME_MODEL)
+ const f = fakeDeps((s) => ok(s.kind === 'image' ? 'https://r/frame.jpg' : 'https://r/video.mp4'))
+ await startSwapChain(start({ frameModel: swapFrameModelFor(true) }), f.deps)
+ expect(f.submits[0].model).toBe('qwen-image-2.1-edit')
+ expect(params(f.submits[0]).studio_options).toMatchObject({ resolution: '1k', aspect_ratio: '16:9' })
+ expect(params(f.submits[0]).swap_step).toBe('frame')
+ expect(swapFrameFiltered('qwen-image-2.1-edit')).toBe(false)
+ expect(swapFrameFiltered('nano-banana-pro-edit')).toBe(true)
+ })
+
+ it('every editor that reads two images can be picked, nothing else', () => {
+ const editors = swapFrameEditors()
+ expect(editors).toContain('nano-banana-pro-edit')
+ expect(editors).toContain('qwen-image-2.1-edit')
+ for (const id of editors) expect(swapFrameMaxPeople(id)).toBeGreaterThanOrEqual(1)
+ for (const id of editors) expect(typeof swapFrameOptionsFor(id, 720, 1280)).toBe('object')
+ const other = editors.find((id) => id !== SWAP_FRAME_MODEL && id !== SWAP_FRAME_OPEN_MODEL)
+ if (other) expect(swapFrameModelFor(false, other)).toBe(other)
+ expect(swapFrameModelFor(true, 'flux-schnell')).toBe(SWAP_FRAME_OPEN_MODEL)
+ expect(swapFrameChoices(false)[0]).toEqual({ value: '', label: 'Auto (Nano Banana Pro)' })
+ expect(swapFrameChoices(true)[0].label).toBe(`Auto (${swapModelName(SWAP_FRAME_OPEN_MODEL)})`)
+ })
+
+ it('video: 1 to 3 people SCAIL-2, 4 OpenJutsu, Kling only by hand and only for one', () => {
+ expect(swapVideoModelFor(1, null)).toBe('scail-2')
+ expect(swapVideoModelFor(3, null)).toBe('scail-2')
+ expect(swapVideoModelFor(4, null)).toBe('openjutsu-character-swap')
+ expect(swapVideoModelFor(1, 'kling-v3-pro-motion-control')).toBe('kling-v3-pro-motion-control')
+ expect(swapVideoModelFor(2, 'kling-v3-pro-motion-control')).toBe('scail-2')
+ expect(swapVideoModelFor(1, 'not-a-swap-model')).toBe('scail-2')
+ expect(swapVideoBlocked('kling-v3-pro-motion-control', 2)).toBe('one person only')
+ expect(swapVideoBlocked('scail-2', 4)).toBe('up to 3 people')
+ expect(swapIsChain('scail-2')).toBe(true)
+ expect(swapIsChain('kling-v3-pro-motion-control')).toBe(true)
+ expect(swapIsChain('openjutsu-character-swap')).toBe(false)
+ expect(swapOpenModelsLine('scail-2')).toBe('Off: Nano Banana Pro + SCAIL-2. On: open-weight models, less strict.')
+ })
+
+ it('Check first frame follows Uncensored (on with it, off without), until set by hand', () => {
+ useSwapOneClick.setState({ openModels: false, check: false, checkTouched: false })
+ const p = () => useSwapOneClick.getState()
+ p().setOpenModels(true)
+ expect(p().check).toBe(true)
+ p().setOpenModels(false)
+ expect(p().check).toBe(false)
+ p().setOpenModels(true)
+ // The customer turns it off by hand: it stays off from now on.
+ p().setCheck(false)
+ p().setOpenModels(false)
+ p().setOpenModels(true)
+ expect(p().check).toBe(false)
+ expect(p().checkTouched).toBe(true)
+ useSwapOneClick.setState({ openModels: false, check: false, checkTouched: false })
+ // Turned on by hand without Uncensored: stays on when Uncensored goes off again.
+ p().setCheck(true)
+ p().setOpenModels(true)
+ p().setOpenModels(false)
+ expect(p().check).toBe(true)
+ useSwapOneClick.setState({ openModels: false, check: false, checkTouched: false })
+ })
+
+ it('both switches start off', () => {
+ const p = useSwapOneClick.getState()
+ expect(p.openModels).toBe(false)
+ expect(p.check).toBe(false)
+ expect(p.frameOverride).toBe('')
+ expect(p.videoOverride).toBe('')
+ })
+})
+
+describe('the filtered editor refuses', () => {
+ it('no video, nothing booked; Turn on Uncensored and retry builds the frame on the open editor', async () => {
+ let refuse = true
+ const f = fakeDeps((s) => (s.kind === 'image' && refuse
+ ? { status: 'failed', error: 'Nano Banana Pro declined this prompt. No credits were charged.', fallback_model: 'qwen-image-2.1-edit' }
+ : ok(s.kind === 'image' ? 'https://r/frame.jpg' : 'https://r/video.mp4')))
+ await startSwapChain(start(), f.deps)
+ const chain = swapChainStore.getState().chain!
+ expect(chain.stage).toBe('refused')
+ expect(chain.error).toBe(SWAP_REFUSED_TEXT)
+ expect(f.submits.filter((s) => s.kind === 'video')).toHaveLength(0)
+ refuse = false
+ await retrySwapOpen(f.deps)
+ expect(f.submits[1].model).toBe('qwen-image-2.1-edit')
+ expect(params(f.submits[1]).max_credits).toBe(swapFrameCredits(1280, 720, 2, 'qwen-image-2.1-edit'))
+ expect(swapChainStore.getState().chain!.stage).toBe('done')
+ })
+
+ it('an open editor that fails is a failure, not a refusal', async () => {
+ const f = fakeDeps(() => ({ status: 'failed', error: 'This request could not be rendered.', fallback_model: null }))
+ await startSwapChain(start({ frameModel: SWAP_FRAME_OPEN_MODEL }), f.deps)
+ const chain = swapChainStore.getState().chain!
+ expect(chain.stage).toBe('failed')
+ expect(chain.error).toMatch(/^The first frame failed: .*The video was not started\.$/)
+ expect(f.submits).toHaveLength(1)
+ })
+
+ it('another error is no refusal', () => {
+ expect(swapFrameRefused({ status: 'failed', error: 'The render took too long and was stopped.', fallback_model: null })).toBe(false)
+ expect(swapFrameRefused({ status: 'failed', error: 'This request could not be rendered. No credits were charged.', fallback_model: null })).toBe(true)
+ expect(swapFrameRefused({ status: 'succeeded', error: null, fallback_model: null })).toBe(false)
+ })
+})
+
+describe('leaving and coming back', () => {
+ it('the state stands in localStorage; after a restart the running job is followed on, not sent again', async () => {
+ let frameDone = false
+ const f = fakeDeps(() => ({ status: 'running' }))
+ // The frame step still runs when the app closes.
+ f.deps.pollJob = async (id) => {
+ if (!frameDone) throw new CloudJobError('render timed out', 0)
+ return {
+ id, kind: id === 'job-1' ? 'image' : 'video', model: 'x', provider: 'p', status: 'succeeded',
+ result_url: `https://r/${id}`, attestation: null, cost_units: 0, created_at: '', completed_at: '', error: null,
+ } as CloudJob
+ }
+ await startSwapChain(start(), f.deps)
+ expect(JSON.parse(localStorage.getItem(SWAP_CHAIN_STORAGE_KEY)!).frameJobId).toBe('job-1')
+ expect(swapChainStore.getState().note).toMatch(/Still rendering/)
+ // Restart: the store is empty, localStorage is not.
+ swapChainStore.setState({ chain: null, busy: false, note: null })
+ frameDone = true
+ expect(loadSwapChain()!.stage).toBe('frame')
+ await resumeSwapChain(f.deps)
+ expect(f.submits.map((s) => s.kind)).toEqual(['image', 'video'])
+ expect(swapChainStore.getState().chain!.stage).toBe('done')
+ })
+
+ it('Cancel stops the running step', async () => {
+ const f = fakeDeps(() => ({ status: 'running' }))
+ f.deps.pollJob = async () => { throw new CloudJobError('render timed out', 0) }
+ await startSwapChain(start(), f.deps)
+ expect(await cancelSwapChain(f.deps)).toBe('canceled')
+ expect(f.canceled).toEqual(['job-1'])
+ expect(swapChainStore.getState().chain!.stage).toBe('canceled')
+ })
+
+ it('Cancel on a step a GPU already has: it finishes, nothing after it is sent', async () => {
+ const f = fakeDeps(() => ({ status: 'running' }))
+ f.deps.pollJob = async () => { throw new CloudJobError('render timed out', 0) }
+ f.deps.cancelJob = async () => { throw new CloudJobError('already running', 409) }
+ await startSwapChain(start(), f.deps)
+ expect(await cancelSwapChain(f.deps)).toBe('running')
+ const chain = swapChainStore.getState().chain!
+ expect(chain.check).toBe(true)
+ expect(swapChainStore.getState().note).toMatch(/cannot be stopped/)
+ })
+
+ it('a second start while one runs is refused', async () => {
+ const f = fakeDeps(() => ({ status: 'running' }))
+ f.deps.pollJob = async () => { throw new CloudJobError('render timed out', 0) }
+ await startSwapChain(start(), f.deps)
+ await expect(startSwapChain(start(), f.deps)).rejects.toThrow('A swap is already running.')
+ expect(f.submits).toHaveLength(1)
+ })
+})
+
+describe('total price and the check before the start', () => {
+ it('button = frame + video + lip sync', () => {
+ const frame = swapFrameCredits(1280, 720, 2)!
+ expect(frame).toBe(14000)
+ expect(swapChainTotal({ frame, video: 48000 })).toBe(62000)
+ expect(swapChainTotal({ frame, video: 48000, lipsync: 900 })).toBe(62900)
+ expect(swapChainTotal({ frame, video: null })).toBeNull()
+ })
+
+ it('without a character, a video or the consent nothing starts and nothing is uploaded', async () => {
+ const s = start()
+ expect(swapChainProblem({ ...s, frame: null })).toMatch(/video/)
+ expect(swapChainProblem({ ...s, figures: [{ image: null, role: '' }] })).toMatch(/character or a photo/)
+ expect(swapChainProblem({ ...s, consent: false })).toBe(SWAP_CONSENT_MISSING)
+ expect(swapChainProblem({ ...s, figures: [...s.figures, ...s.figures], frameModel: SWAP_FRAME_MODEL })).toBeNull()
+ expect(swapChainProblem(s)).toBeNull()
+ const f = fakeDeps(() => ok('x'))
+ await expect(startSwapChain({ ...s, consent: false }, f.deps)).rejects.toThrow(SWAP_CONSENT_MISSING)
+ expect(f.uploads).toHaveLength(0)
+ expect(f.submits).toHaveLength(0)
+ })
+})
diff --git a/src/lib/create/swap-chain.ts b/src/lib/create/swap-chain.ts
new file mode 100644
index 00000000..2b6eab6d
--- /dev/null
+++ b/src/lib/create/swap-chain.ts
@@ -0,0 +1,409 @@
+// Swap with one click (14.11.2026, David's call, only with the account switch
+// features.characterHub; port of the web's lib/create/swap-chain.ts,
+// 4395e8d1). One press on "Create · total" runs the whole chain: first the
+// first frame with the new people (frame step), then the video on that frame
+// (SCAIL 2 or Kling), then, when chosen, the new voice with the lips. With
+// "Check first frame before video" the chain stops after the frame (Try
+// again / Continue).
+//
+// The steps are the jobs that exist already (swap_step 'frame', 'video',
+// 'lipsync' with swap_consent). New is only the steering, and it runs in the
+// app. To survive a reload or a restart, every input is on the server before
+// the first job (video, photos, voice uploaded), and the state of the chain
+// stands in localStorage: which jobs run and what is sent next. Whoever opens
+// the panel again carries on at exactly that place (resumeSwapChain). While
+// the app is closed only the job that is due runs; the next one is sent by
+// the reopened panel, never twice.
+//
+// Without React and without the Create store, like swap-frame.ts: upload,
+// adopt, submit, poll and cancel are handed in.
+
+import { createStore } from 'zustand/vanilla'
+import { CloudJobError } from '../../api/cloud/client'
+import type { AdoptRole, CloudJob, CloudJobSubmit, UploadRole } from '../../api/cloud/jobs'
+import { dataUrlToBlob } from '../render/data-url'
+import { lipsyncSubmit } from '../render/sound'
+import {
+ swapFigureRoles, swapFrameFiltered, swapFrameMaxPeople, swapFrameOptionsFor, swapFramePrompt,
+ SWAP_CONSENT_MISSING, SWAP_FRAME_OPEN_MODEL, type SwapMark,
+} from '../render/swap'
+import { adoptResult, describeSubmitError, failedJobText, type RunDeps } from './engine'
+import { swapFrameCredits, swapFrameSubmit } from './swap-frame'
+import { lipsyncFailedText } from './lipsync-chain'
+
+export type SwapChainStage = 'frame' | 'review' | 'video' | 'sound' | 'done' | 'refused' | 'failed' | 'canceled'
+
+/** Stages in which a job runs or is about to be sent. */
+export const SWAP_CHAIN_RUNNING: readonly SwapChainStage[] = ['frame', 'video', 'sound']
+
+export interface SwapChainState {
+ v: 1
+ stage: SwapChainStage
+ startedAt: number
+ /** "Bean and Sam": who comes into the picture, for the caption. */
+ who: string
+ /** Frame step: editor, size of the video frame, people, roles. */
+ frameModel: string
+ frameSize: { width: number; height: number }
+ people: number
+ roles: string[]
+ frameSubmit: CloudJobSubmit
+ frameCredits: number
+ frameJobId: string | null
+ frameUrl: string | null
+ /** Stop after the frame ("Check first frame before video"). */
+ check: boolean
+ /** Video step, built except for the image (source_path), which only comes
+ * from the frame step. */
+ videoSubmit: CloudJobSubmit
+ videoCredits: number
+ videoJobId: string | null
+ /** New voice with lips: the voice is on the server already. */
+ lipsync: { model: string; audioPath: string; credits: number } | null
+ lipJobId: string | null
+ /** The job whose result stands at the end. */
+ resultJobId: string | null
+ resultUrl: string | null
+ error: string | null
+}
+
+export const SWAP_CHAIN_STORAGE_KEY = 'lu.swapChain.v1'
+
+function readStored(): SwapChainState | null {
+ try {
+ const raw = globalThis.localStorage?.getItem(SWAP_CHAIN_STORAGE_KEY)
+ if (!raw) return null
+ const s = JSON.parse(raw) as SwapChainState
+ return s && s.v === 1 && typeof s.stage === 'string' ? s : null
+ } catch { return null }
+}
+
+function writeStored(s: SwapChainState | null): void {
+ try {
+ if (s) globalThis.localStorage?.setItem(SWAP_CHAIN_STORAGE_KEY, JSON.stringify(s))
+ else globalThis.localStorage?.removeItem(SWAP_CHAIN_STORAGE_KEY)
+ } catch { /* storage refused: the chain still runs, only without resuming */ }
+}
+
+/** The state of the chain. `busy`: this window follows a job right now. */
+export const swapChainStore = createStore<{ chain: SwapChainState | null; busy: boolean; note: string | null }>(() => ({
+ chain: null, busy: false, note: null,
+}))
+
+/** Reads the stored state (once per start of the app). */
+export function loadSwapChain(): SwapChainState | null {
+ const stored = readStored()
+ if (stored && !swapChainStore.getState().chain) swapChainStore.setState({ chain: stored })
+ return swapChainStore.getState().chain
+}
+
+function patch(p: Partial<SwapChainState>): SwapChainState | null {
+ const cur = swapChainStore.getState().chain
+ if (!cur) return null
+ const next = { ...cur, ...p }
+ swapChainStore.setState({ chain: next })
+ writeStored(next)
+ return next
+}
+
+/** Clears the chain away (result seen, refused, start over). */
+export function clearSwapChain(): void {
+ abort?.abort()
+ abort = null
+ swapChainStore.setState({ chain: null, busy: false, note: null })
+ writeStored(null)
+}
+
+/** Did a filtered editor refuse the image? The server then names an open
+ * alternative (fallback_model) or the sentence of a refusal. */
+export function swapFrameRefused(job: Pick<CloudJob, 'status' | 'error' | 'fallback_model'>): boolean {
+ if (job.status !== 'failed') return false
+ return !!job.fallback_model || /declined|could not be rendered/i.test(job.error ?? '')
+}
+
+/** The sentence of a refusal. A failed run is refunded, so nothing is
+ * charged, not the image either. */
+export const SWAP_REFUSED_TEXT = 'The first-frame model refused this image. Nothing was charged, and the video was not started.'
+
+export interface SwapChainDeps extends RunDeps {
+ uploadInput: (file: Blob, role: UploadRole) => Promise<string>
+ adoptInput: (jobId: string, role: AdoptRole) => Promise<string>
+ /** A finished result (video, or video with the new voice) into the gallery. */
+ onResult?: (job: CloudJob) => void
+ /** Read the credits again (after submit, cancel, failure). */
+ onQuota?: () => void
+}
+
+/** A person as the chain reads it: a photo (data: URL). On the desktop a
+ * character from the list is its picture as a photo (hubPortrait). */
+export interface SwapChainFigure {
+ image: { url: string } | null
+ role: string
+ mark?: SwapMark | null
+}
+
+export interface SwapChainStart {
+ frame: { url: string; width: number; height: number } | null
+ figures: SwapChainFigure[]
+ frameModel: string
+ check: boolean
+ consent: boolean
+ who: string
+ /** The video job without its image, built like every Create run. */
+ videoSubmit: CloudJobSubmit
+ videoCredits: number
+ lipsync: { model: string; audio: { type: 'blob'; blob: Blob } | { type: 'job'; jobId: string }; credits: number } | null
+}
+
+/** What is missing before the chain can start, as a sentence for the customer. */
+export function swapChainProblem(start: Pick<SwapChainStart, 'frame' | 'figures' | 'frameModel' | 'consent'>): string | null {
+ if (!start.frame) return 'Add the original video first.'
+ const missing = start.figures.findIndex((f) => !f.image)
+ if (!start.figures.length || missing === 0) return 'Pick a character or a photo for the person you replace.'
+ if (missing > 0) return `Pick a character or a photo for person ${missing + 1}, or remove that mark.`
+ const max = swapFrameMaxPeople(start.frameModel)
+ if (start.figures.length > max) {
+ return `This first-frame model takes ${max} ${max === 1 ? 'person' : 'people'}. Pick another one under More options.`
+ }
+ if (start.figures.some((f) => f.role.length > 200)) return 'Keep each role under 200 characters.'
+ if (!start.consent) return SWAP_CONSENT_MISSING
+ return null
+}
+
+/** The price of the whole chain, as the button shows it. */
+export function swapChainTotal(parts: { frame: number | null; video: number | null; lipsync?: number | null }): number | null {
+ if (parts.frame == null || parts.video == null) return null
+ return parts.frame + parts.video + (parts.lipsync ?? 0)
+}
+
+let abort: AbortController | null = null
+let running: Promise<void> | null = null
+
+/** Uploads the inputs, lays the chain down and runs it. Throws with the text
+ * for the customer when something is missing; nothing is booked then. */
+export async function startSwapChain(start: SwapChainStart, deps: SwapChainDeps): Promise<void> {
+ const problem = swapChainProblem(start)
+ if (problem) throw new Error(problem)
+ const cur = swapChainStore.getState().chain
+ if (cur && SWAP_CHAIN_RUNNING.includes(cur.stage)) throw new Error('A swap is already running.')
+ swapChainStore.setState({ busy: true, note: 'Uploading…' })
+ try {
+ const framePath = await deps.uploadInput(dataUrlToBlob(start.frame!.url), 'source')
+ const figurePaths: string[] = []
+ for (const f of start.figures) figurePaths.push(await deps.uploadInput(dataUrlToBlob(f.image!.url), 'source'))
+ const lipsync = start.lipsync
+ ? {
+ model: start.lipsync.model,
+ credits: start.lipsync.credits,
+ audioPath: start.lipsync.audio.type === 'blob'
+ ? await deps.uploadInput(start.lipsync.audio.blob, 'audio')
+ : await adoptResult(deps.adoptInput, start.lipsync.audio.jobId, 'audio'),
+ }
+ : null
+ const { width, height } = start.frame!
+ const frameCredits = swapFrameCredits(width, height, start.figures.length, start.frameModel) ?? 0
+ const roles = swapFigureRoles(start.figures.map((f) => ({ role: f.role, mark: f.mark ?? null })))
+ const frameSubmit = swapFrameSubmit(framePath, figurePaths, {
+ frame: start.frame, figures: start.figures.map((f) => ({ imageUrl: f.image!.url, role: f.role, mark: f.mark ?? null })),
+ model: '', consent: start.consent, credits: frameCredits, frameModel: start.frameModel,
+ })
+ const chain: SwapChainState = {
+ v: 1, stage: 'frame', startedAt: Date.now(), who: start.who,
+ frameModel: start.frameModel, frameSize: { width, height }, people: start.figures.length, roles,
+ frameSubmit, frameCredits, frameJobId: null, frameUrl: null, check: start.check,
+ videoSubmit: start.videoSubmit, videoCredits: start.videoCredits, videoJobId: null,
+ lipsync, lipJobId: null, resultJobId: null, resultUrl: null, error: null,
+ }
+ swapChainStore.setState({ chain, note: null })
+ writeStored(chain)
+ } catch (err) {
+ swapChainStore.setState({ busy: false, note: null })
+ throw err
+ }
+ swapChainStore.setState({ busy: false })
+ await advanceSwapChain(deps)
+}
+
+/** Runs the chain on from the stored state until it stops (check, done,
+ * error) or this window no longer waits. Only once at a time. */
+export function advanceSwapChain(deps: SwapChainDeps): Promise<void> {
+ if (running) return running
+ running = (async () => {
+ const ac = new AbortController()
+ abort = ac
+ swapChainStore.setState({ busy: true })
+ try {
+ await drive(deps, ac.signal)
+ } finally {
+ if (abort === ac) abort = null
+ running = null
+ swapChainStore.setState({ busy: false })
+ }
+ })()
+ return running
+}
+
+/** On reopening: follow a running chain on. */
+export function resumeSwapChain(deps: SwapChainDeps): Promise<void> | null {
+ const chain = loadSwapChain()
+ if (!chain || !SWAP_CHAIN_RUNNING.includes(chain.stage)) return null
+ return advanceSwapChain(deps)
+}
+
+async function follow(id: string, deps: SwapChainDeps, signal: AbortSignal, timeoutMs: number): Promise<CloudJob | null> {
+ try {
+ return await deps.pollJob(id, { signal, timeoutMs })
+ } catch (err) {
+ if (err instanceof CloudJobError && err.message === 'polling aborted') return null
+ if (err instanceof CloudJobError && err.message === 'render timed out') {
+ // The job lives on; the chain carries on the next time the panel opens.
+ swapChainStore.setState({ note: 'Still rendering. This takes longer than usual; it continues when you come back.' })
+ return null
+ }
+ throw err
+ }
+}
+
+async function drive(deps: SwapChainDeps, signal: AbortSignal): Promise<void> {
+ for (;;) {
+ const s = swapChainStore.getState().chain
+ if (!s || !SWAP_CHAIN_RUNNING.includes(s.stage) || signal.aborted) return
+ try {
+ if (s.stage === 'frame') {
+ let id = s.frameJobId
+ if (!id) {
+ id = (await deps.submitCloudJob(s.frameSubmit)).id
+ patch({ frameJobId: id })
+ deps.onQuota?.()
+ }
+ const job = await follow(id, deps, signal, 10 * 60_000)
+ if (!job) return
+ if (job.status === 'succeeded' && job.result_url) {
+ patch({ frameUrl: job.result_url, stage: s.check ? 'review' : 'video' })
+ } else if (job.status === 'canceled') {
+ patch({ stage: 'canceled' })
+ } else {
+ // Refused or failed: the video does not start, nothing of it is
+ // booked (a failed run is refunded).
+ deps.onQuota?.()
+ patch(swapFrameFiltered(s.frameModel) && swapFrameRefused(job)
+ ? { stage: 'refused', error: SWAP_REFUSED_TEXT }
+ : { stage: 'failed', error: `The first frame failed: ${failedJobText(job)} The video was not started.` })
+ }
+ } else if (s.stage === 'video') {
+ let id = s.videoJobId
+ if (!id) {
+ const sourcePath = await adoptResult(deps.adoptInput, s.frameJobId!, 'image')
+ if (signal.aborted) return
+ id = (await deps.submitCloudJob({ ...s.videoSubmit, params: { ...s.videoSubmit.params, source_path: sourcePath } })).id
+ patch({ videoJobId: id })
+ deps.onQuota?.()
+ }
+ const job = await follow(id, deps, signal, 45 * 60_000)
+ if (!job) return
+ if (job.status === 'succeeded' && job.result_url) {
+ deps.onResult?.(job)
+ patch(s.lipsync
+ ? { stage: 'sound', resultJobId: job.id, resultUrl: job.result_url }
+ : { stage: 'done', resultJobId: job.id, resultUrl: job.result_url })
+ } else if (job.status === 'canceled') {
+ patch({ stage: 'canceled' })
+ } else {
+ deps.onQuota?.()
+ patch({ stage: 'failed', error: failedJobText(job) })
+ }
+ } else if (s.stage === 'sound' && s.lipsync) {
+ let id = s.lipJobId
+ if (!id) {
+ const videoPath = await adoptResult(deps.adoptInput, s.videoJobId!, 'video')
+ if (signal.aborted) return
+ id = (await deps.submitCloudJob(lipsyncSubmit(s.lipsync.model, videoPath, s.lipsync.audioPath, s.lipsync.credits, true))).id
+ patch({ lipJobId: id })
+ deps.onQuota?.()
+ }
+ const job = await follow(id, deps, signal, 30 * 60_000)
+ if (!job) return
+ if (job.status === 'succeeded' && job.result_url) {
+ deps.onResult?.(job)
+ patch({ stage: 'done', resultJobId: job.id, resultUrl: job.result_url })
+ } else {
+ // The video is there already; only the voice is missing.
+ deps.onQuota?.()
+ patch({ stage: 'done', error: job.status === 'canceled' ? null : lipsyncFailedText(job.error) })
+ }
+ } else {
+ return
+ }
+ } catch (err) {
+ if (signal.aborted) return
+ const failure = describeSubmitError(err)
+ deps.onQuota?.()
+ patch({ stage: s.stage === 'sound' ? 'done' : 'failed', error: s.stage === 'sound' ? lipsyncFailedText(failure.text) : failure.text })
+ return
+ }
+ }
+}
+
+/** Continue after the check: the video starts on this frame. */
+export function approveSwapFrame(deps: SwapChainDeps): Promise<void> {
+ const s = swapChainStore.getState().chain
+ if (!s || s.stage !== 'review') return Promise.resolve()
+ patch({ stage: 'video' })
+ return advanceSwapChain(deps)
+}
+
+/** Try again: only the frame step runs again, "What's wrong?" joins the
+ * sentence. With `model` (Turn on Uncensored and retry) on another editor;
+ * `check` sets anew whether the chain stops after the frame. */
+export function retrySwapFrame(deps: SwapChainDeps, opts: { extra?: string; model?: string; check?: boolean } = {}): Promise<void> {
+ const s = swapChainStore.getState().chain
+ if (!s || !['review', 'refused', 'failed'].includes(s.stage) || s.videoJobId) return Promise.resolve()
+ const model = opts.model ?? s.frameModel
+ const credits = swapFrameCredits(s.frameSize.width, s.frameSize.height, s.people, model) ?? s.frameCredits
+ const { max_credits: _old, ...params } = s.frameSubmit.params
+ patch({
+ stage: 'frame', frameModel: model, frameCredits: credits, frameJobId: null, frameUrl: null, error: null,
+ check: opts.check ?? s.check,
+ frameSubmit: {
+ ...s.frameSubmit,
+ model,
+ prompt: swapFramePrompt(s.roles, opts.extra),
+ params: {
+ ...params,
+ studio_options: swapFrameOptionsFor(model, s.frameSize.width, s.frameSize.height),
+ max_credits: credits,
+ },
+ },
+ })
+ return advanceSwapChain(deps)
+}
+
+/** Turn on Uncensored and retry: the same frame step on the open editor.
+ * `check`: the switch "Check first frame" as it stands after the turn. */
+export function retrySwapOpen(deps: SwapChainDeps, check?: boolean): Promise<void> {
+ return retrySwapFrame(deps, { model: SWAP_FRAME_OPEN_MODEL, check })
+}
+
+/** Cancel: stops the running job. When a GPU has it already (409), it runs to
+ * its end, and the chain says so and sends nothing after it. */
+export async function cancelSwapChain(deps: Pick<SwapChainDeps, 'cancelJob' | 'onQuota'>): Promise<'canceled' | 'running'> {
+ const s = swapChainStore.getState().chain
+ if (!s) return 'canceled'
+ const id = s.stage === 'frame' ? s.frameJobId : s.stage === 'video' ? s.videoJobId : s.stage === 'sound' ? s.lipJobId : null
+ if (id) {
+ try {
+ await deps.cancelJob(id)
+ } catch (err) {
+ if (err instanceof CloudJobError && err.status === 409) {
+ swapChainStore.setState({ note: 'This step is already rendering and cannot be stopped. It finishes, and the next step is not started.' })
+ // Nothing more after this step.
+ patch({ check: true, lipsync: s.stage === 'video' ? null : s.lipsync })
+ return 'running'
+ }
+ }
+ }
+ abort?.abort()
+ patch({ stage: 'canceled' })
+ deps.onQuota?.()
+ return 'canceled'
+}
diff --git a/src/lib/create/swap-frame.ts b/src/lib/create/swap-frame.ts
index 304b1bbb..a92b2d43 100644
--- a/src/lib/create/swap-frame.ts
+++ b/src/lib/create/swap-frame.ts
@@ -18,7 +18,7 @@ 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,
+ swapFigureRoles, swapFrameKey, swapFrameOptionsFor, swapFramePrompt, swapMaxPeople,
SWAP_CONSENT_MISSING, SWAP_FRAME_MODEL, type SwapMark,
} from '../render/swap'
@@ -37,11 +37,15 @@ export interface SwapFrameRequest {
extra?: string
/** The price the button shows: the ceiling of the booking. */
credits: number | null
+ /** One click swap (only with the account switch): the editor of the frame
+ * step. Without it Nano Banana Pro as before. */
+ frameModel?: string
}
-/** 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)
+/** The price of the frame step from the catalogue (Nano Banana Pro, 2k, or
+ * the editor picked). */
+export function swapFrameCredits(width: number, height: number, people: number, model: string = SWAP_FRAME_MODEL): number | null {
+ return studioPreviewCredits(model, swapFrameOptionsFor(model, width, height), undefined, people + 1)
}
/** What is missing before the frame step can start, as a sentence for the
@@ -66,14 +70,15 @@ export function swapFrameProblem(req: SwapFrameRequest): string | null {
* person, in the order of the people. */
export function swapFrameSubmit(framePath: string, figurePaths: string[], req: SwapFrameRequest): CloudJobSubmit {
const roles = swapFigureRoles(req.figures)
+ const model = req.frameModel ?? SWAP_FRAME_MODEL
return {
kind: 'image',
- model: SWAP_FRAME_MODEL,
+ model,
prompt: swapFramePrompt(roles, req.extra),
params: {
op: 'studio',
image_paths: [framePath, ...figurePaths],
- studio_options: swapFrameOptions(req.frame?.width ?? 0, req.frame?.height ?? 0),
+ studio_options: swapFrameOptionsFor(model, req.frame?.width ?? 0, req.frame?.height ?? 0),
swap_step: 'frame',
swap_consent: true,
...(req.credits != null ? { max_credits: req.credits } : {}),
diff --git a/src/lib/create/swap-one-click.ts b/src/lib/create/swap-one-click.ts
new file mode 100644
index 00000000..6856fa51
--- /dev/null
+++ b/src/lib/create/swap-one-click.ts
@@ -0,0 +1,101 @@
+// The picks of the one click swap (14.11.2026, only with the account switch;
+// port of the web's lib/create/swap-one-click.ts): which editor builds the
+// first frame and which engine makes the video. Without an own pick the
+// number of people and the switch "Uncensored" decide.
+// 1 person SCAIL 2 (Kling only when picked under More options)
+// 2 to 3 SCAIL 2
+// 4 OpenJutsu, one step as before
+// Without React; the panel (hub/SwapOneClick.tsx) only holds the state.
+
+import { create } from 'zustand'
+import { STUDIO_MODELS } from '../render/studio-contract'
+import {
+ swapAutoModel, swapFrameEditors, swapFrameModelFor, swapMaxPeople, swapUsesFrame,
+ SWAP_FRAME_MODEL, SWAP_FRAME_OPEN_MODEL, SWAP_INTENT, SWAP_KLING_MODEL, SWAP_LONG_MODEL, SWAP_MAIN_MODEL, SWAP_OPENJUTSU_MODEL,
+} from '../render/swap'
+
+/** The engines "Video ▾" offers. */
+export const SWAP_VIDEO_CHOICES: readonly string[] = [SWAP_MAIN_MODEL, SWAP_KLING_MODEL, SWAP_OPENJUTSU_MODEL, SWAP_LONG_MODEL]
+
+/** The engine of the video: the own pick while it can take this many people,
+ * else automatic by the number of people. */
+export function swapVideoModelFor(people: number, override: string | null): string {
+ const n = Math.max(1, people)
+ if (override && SWAP_VIDEO_CHOICES.includes(override) && swapMaxPeople(override) >= n) return override
+ return swapAutoModel(n)
+}
+
+/** Why an engine cannot take this many people, or null. */
+export function swapVideoBlocked(model: string, people: number): string | null {
+ const max = swapMaxPeople(model)
+ if (Math.max(1, people) <= max) return null
+ return max === 1 ? 'one person only' : `up to ${max} people`
+}
+
+/** Does the swap run on this engine as a chain (frame, then video)? */
+export function swapIsChain(videoModel: string): boolean {
+ return swapUsesFrame(SWAP_INTENT, videoModel)
+}
+
+/** The name of a model as the bar shows it ("SCAIL-2", "Nano Banana Pro"). */
+export function swapModelName(id: string): string {
+ if (id === SWAP_MAIN_MODEL) return 'SCAIL-2'
+ if (id === SWAP_KLING_MODEL) return 'Kling 3.0 Pro'
+ return STUDIO_MODELS[id]?.label ?? id
+}
+
+/** The grey line under "Uncensored": what runs with and without the switch. */
+export function swapOpenModelsLine(videoModel: string): string {
+ return `Off: ${swapModelName(SWAP_FRAME_MODEL)} + ${swapModelName(videoModel)}. On: open-weight models, less strict.`
+}
+
+/** The picks of "First frame ▾": Auto and every editor that reads two images. */
+export function swapFrameChoices(openModels: boolean): { value: string; label: string }[] {
+ const auto = swapFrameModelFor(openModels, null)
+ return [
+ { value: '', label: `Auto (${swapModelName(auto)})` },
+ ...swapFrameEditors().map((id) => ({ value: id, label: swapModelName(id) })),
+ ]
+}
+
+export interface SwapOneClickPrefs {
+ /** The switch "Uncensored" (on the web "Open models"). */
+ openModels: boolean
+ check: boolean
+ /** The customer set "Check first frame" by hand: from then on it no longer
+ * follows "Uncensored". */
+ checkTouched: boolean
+ /** Editor under More options, '' = Auto. */
+ frameOverride: string
+ /** Engine under More options, '' = Auto. */
+ videoOverride: string
+ setOpenModels: (v: boolean) => void
+ /** The customer's own pick of "Check first frame". */
+ setCheck: (v: boolean) => void
+ setFrameOverride: (v: string) => void
+ setVideoOverride: (v: string) => void
+}
+
+/** "Check first frame" by default: on with "Uncensored", off without it
+ * (David's call, 14.11.2026: the open editor is less sure, the customer
+ * sees its frame before paying for the video). */
+export function swapCheckDefault(openModels: boolean): boolean {
+ return openModels
+}
+
+/** Both switches start off (David's call). Turning "Uncensored" on or off
+ * takes "Check first frame" along to its default, unless the customer set
+ * that switch by hand. */
+export const useSwapOneClick = create<SwapOneClickPrefs>((set) => ({
+ openModels: false,
+ check: swapCheckDefault(false),
+ checkTouched: false,
+ frameOverride: '',
+ videoOverride: '',
+ setOpenModels: (openModels) => set((s) => (s.checkTouched ? { openModels } : { openModels, check: swapCheckDefault(openModels) })),
+ setCheck: (check) => set({ check, checkTouched: true }),
+ setFrameOverride: (frameOverride) => set({ frameOverride }),
+ setVideoOverride: (videoOverride) => set({ videoOverride }),
+}))
+
+export { SWAP_FRAME_MODEL, SWAP_FRAME_OPEN_MODEL }
diff --git a/src/lib/render/swap.ts b/src/lib/render/swap.ts
index 5c3bf89e..69487ba5 100644
--- a/src/lib/render/swap.ts
+++ b/src/lib/render/swap.ts
@@ -20,6 +20,7 @@
// one step.
import { STUDIO_MODELS, studioSchema } from './studio-contract'
+import { STUDIO_EDIT_MODELS } from './studio-roles'
export const SWAP_INTENT = 'swap_character' as const
export type SwapIntent = typeof SWAP_INTENT
@@ -285,6 +286,82 @@ export function swapFrameOptions(width: number, height: number): Record<string,
return { aspect_ratio: swapFrameAspect(width, height), resolution: '2k', output_format: 'jpeg' }
}
+// One click swap (14.11.2026, David's call, only with the account switch;
+// port of the web's 4395e8d1). The frame step no longer runs on one fixed
+// model. Filtered it is Nano Banana Pro (2k), with "Uncensored" Qwen Image
+// 2.1 Edit (1k): in the real test of 14.11. the only open editor that kept
+// both identities and ran cleanly with SCAIL 2 (Qwen 3 and FLUX.3 Klein were
+// poor). Under "More options" any editor that reads at least two images (the
+// video frame and a photo per person) can be picked.
+
+/** The open editor of the frame step with "Uncensored". */
+export const SWAP_FRAME_OPEN_MODEL = 'qwen-image-2.1-edit'
+
+/** How many images an editor reads at most (the provider's schema). 0 without
+ * an image list, 10 when the schema names no limit. */
+export function swapEditorMaxImages(model: string): number {
+ const m = STUDIO_MODELS[model]
+ if (!m) return 0
+ const field = Object.entries(m.inputs).find(([, param]) => param === 'image_paths')?.[0]
+ if (!field) return 0
+ const max = (studioSchema(model).properties?.[field] as { maxItems?: number } | undefined)?.maxItems
+ return typeof max === 'number' ? max : 10
+}
+
+/** The editors the frame step may take: every instruction editor without a
+ * mask (STUDIO_EDIT_MODELS) that reads at least two images, in the order of
+ * the picker. */
+export function swapFrameEditors(): string[] {
+ return STUDIO_EDIT_MODELS.filter((id) => !!STUDIO_MODELS[id] && swapEditorMaxImages(id) >= 2)
+}
+
+/** The editor of the frame step: the own pick when it is allowed, else by the
+ * switch "Uncensored". */
+export function swapFrameModelFor(openModels: boolean, override?: string | null): string {
+ if (override && swapFrameEditors().includes(override)) return override
+ return openModels ? SWAP_FRAME_OPEN_MODEL : SWAP_FRAME_MODEL
+}
+
+/** Does the editor have the provider's content filter (closed weights)? Only
+ * there a refusal is a case for "Turn on Uncensored". */
+export function swapFrameFiltered(model: string): boolean {
+ return STUDIO_MODELS[model]?.weights !== 'open'
+}
+
+/** How many people the frame step can set on this editor: one image is the
+ * video frame, the rest a photo per person. */
+export function swapFrameMaxPeople(model: string): number {
+ return Math.max(0, swapEditorMaxImages(model) - 1)
+}
+
+/** The options of the frame step on any editor, only with fields its schema
+ * knows. Nano Banana Pro stays exactly at the real test (2k, JPEG), Qwen
+ * Image 2.1 Edit runs at 1k. */
+export function swapFrameOptionsFor(model: string, width: number, height: number): Record<string, unknown> {
+ if (model === SWAP_FRAME_MODEL) return swapFrameOptions(width, height)
+ if (!STUDIO_MODELS[model]) return {}
+ const props = (studioSchema(model).properties ?? {}) as Record<string, { enum?: unknown[] }>
+ const out: Record<string, unknown> = {}
+ const aspects = props.aspect_ratio?.enum?.filter((a): a is string => typeof a === 'string' && /^\d+:\d+$/.test(a))
+ if (aspects?.length) out.aspect_ratio = nearestAspect(aspects, width, height)
+ const resolutions = props.resolution?.enum?.map(String)
+ if (resolutions?.length) out.resolution = resolutions.includes('1k') ? '1k' : resolutions[0]
+ if (props.output_format?.enum?.includes('jpeg')) out.output_format = 'jpeg'
+ return out
+}
+
+function nearestAspect(list: readonly string[], width: number, height: number): string {
+ if (!(width > 0) || !(height > 0)) return list.includes('9:16') ? '9:16' : list[0]
+ const want = Math.log(width / height)
+ let best = list[0], gap = Infinity
+ for (const a of list) {
+ 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
+}
+
const IMAGE_ORDINAL = ['second', 'third', 'fourth', 'fifth']
/** The sentence of the frame step (template from the real runs of