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): edit several images in one go, save a character from a video

purple07d8bd1812c9
diff --git a/e2e/create-batch-edit.spec.ts b/e2e/create-batch-edit.spec.ts
new file mode 100644
index 00000000..edbd21de
--- /dev/null
+++ b/e2e/create-batch-edit.spec.ts
@@ -0,0 +1,144 @@
+import { test, expect, type Page } from '@playwright/test'
+import { tauriMockInit, DEFAULT_ASSISTANT_REPLY, DEFAULT_MODEL_NAME } from './support/tauri-mock'
+import { routeCloud, seedOnboardingDone, signInViaGate, cloudSwitch } from './support/cloud-mock'
+
+/**
+ * Several source images, one edit (Discord, cazwhin): pick several images in
+ * Remove Background on the cloud, see the sum before the run, watch the queue,
+ * and get one result per image. One image fails on the server, the others
+ * still land and the failed file is named. Every image is its own upload and
+ * its own job, nothing real is rendered or charged.
+ */
+
+const PNG = Buffer.from(
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==',
+ 'base64',
+)
+const CORS = { 'access-control-allow-origin': '*', 'access-control-allow-headers': '*', 'access-control-allow-methods': 'GET,POST,OPTIONS' }
+const json = (status: number, body: unknown) => ({ status, headers: { ...CORS, 'content-type': 'application/json' }, body: JSON.stringify(body) })
+
+interface Sent { uploads: number; jobs: { id: string; op: string; source: string }[] }
+
+/** The job endpoints of a batch: every submit books its own job. `failNth`
+ * (1-based) fails on the server, `refuseFrom` answers "out of credits". */
+async function routeJobs(page: Page, opts: { failNth?: number; refuseFrom?: number } = {}): Promise<Sent> {
+ const sent: Sent = { uploads: 0, jobs: [] }
+ await page.route('https://lu-labs.ai/api/jobs/upload**', async (route) => {
+ if (route.request().method() === 'OPTIONS') return route.fulfill({ status: 204, headers: CORS })
+ sent.uploads++
+ return route.fulfill(json(200, { path: `e2e-user-1/source-${sent.uploads}.png` }))
+ })
+ await page.route('https://lu-labs.ai/api/jobs', async (route) => {
+ const req = route.request()
+ if (req.method() === 'OPTIONS') return route.fulfill({ status: 204, headers: CORS })
+ if (req.method() !== 'POST') return route.fallback()
+ const body = req.postDataJSON() as { params: { op: string; source_path: string } }
+ const n = sent.jobs.length + 1
+ if (opts.refuseFrom && n >= opts.refuseFrom) {
+ return route.fulfill(json(429, { error: 'credits exhausted', code: 'credits_exhausted' }))
+ }
+ const id = `job-batch-${n}`
+ sent.jobs.push({ id, op: body.params.op, source: body.params.source_path })
+ return route.fulfill(json(202, { id, status: 'queued', created_at: new Date().toISOString(), quota: { kind: 'image', cost: 300 } }))
+ })
+ await page.route('https://lu-labs.ai/api/jobs/job-batch-*', async (route) => {
+ if (route.request().method() === 'OPTIONS') return route.fulfill({ status: 204, headers: CORS })
+ const id = new URL(route.request().url()).pathname.split('/').pop()!
+ const failed = opts.failNth !== undefined && id === `job-batch-${opts.failNth}`
+ return route.fulfill(json(200, {
+ job: {
+ id, kind: 'image', model: 'flux-schnell', provider: 'wavespeed',
+ status: failed ? 'failed' : 'succeeded',
+ result_url: failed ? null : `https://lu-labs.ai/e2e/${id}.png`,
+ attestation: null, cost_units: 300, created_at: new Date().toISOString(), completed_at: new Date().toISOString(),
+ error: failed ? 'The provider could not process this image.' : null,
+ },
+ }))
+ })
+ await page.route('https://lu-labs.ai/e2e/job-batch-*.png', (route) =>
+ route.fulfill({ status: 200, headers: { ...CORS, 'content-type': 'image/png' }, body: PNG }))
+ return sent
+}
+
+async function bootIntoCutout(page: Page) {
+ await page.addInitScript(tauriMockInit, { assistantReply: DEFAULT_ASSISTANT_REPLY, modelName: DEFAULT_MODEL_NAME })
+ await seedOnboardingDone(page)
+ await routeCloud(page, { license: 'active', access: true, mediaLive: true })
+ await page.goto('/')
+ await expect(cloudSwitch(page)).toBeVisible({ timeout: 20_000 })
+ await signInViaGate(page)
+ await expect(cloudSwitch(page)).toBeChecked({ timeout: 20_000 })
+ await page.getByRole('button', { name: /^Create$/ }).click()
+ await page.getByRole('radio', { name: /Remove Background/i }).click()
+ await expect(page.getByText(/Drop an image to cut out/i)).toBeVisible({ timeout: 15_000 })
+}
+
+const files = (names: string[]) => names.map((name) => ({ name, mimeType: 'image/png', buffer: PNG }))
+
+test('four images, one run each: sum up front, queue, results, the failed file named', async ({ page }) => {
+ await bootIntoCutout(page)
+ const sent = await routeJobs(page, { failNth: 2 })
+
+ // The multi-pick sits at the source surface, never at the prompt.
+ await expect(page.getByText('Pick several to give them all the same run')).toBeVisible()
+ await page.getByTestId('batch-files-input').setInputFiles(files(['d.png', 'a.png', 'c.png', 'b.png']))
+
+ await expect(page.getByTestId('batch-count')).toContainText('4 images.')
+ // The price is the honest sum: one image times four.
+ const price = (await page.getByTestId('batch-price').textContent()) ?? ''
+ const m = price.match(/^([\d,]+) credits per image, ([\d,]+) credits for all 4\./)
+ expect(m, price).not.toBeNull()
+ expect(Number(m![2].replace(/,/g, ''))).toBe(Number(m![1].replace(/,/g, '')) * 4)
+ expect(price).not.toContain('Your credits cover')
+ expect(sent.jobs).toHaveLength(0)
+
+ await page.getByRole('button', { name: /^Create$/ }).last().click()
+
+ // Three results land, each from its own job. The second image failed alone.
+ await expect(page.getByText(/3 of 4 images are done\. 1 failed: b\.png\./)).toBeVisible({ timeout: 45_000 })
+ await expect(page.getByText(/The provider could not process this image\./)).toBeVisible()
+ expect(sent.jobs.map((j) => j.op)).toEqual(['removebg', 'removebg', 'removebg', 'removebg'])
+ expect(sent.uploads).toBe(4)
+ expect(new Set(sent.jobs.map((j) => j.source)).size).toBe(4)
+
+ // The failed image is the one left on the Stage, ready for another try.
+ await expect(page.getByTestId('batch-count')).toHaveCount(0)
+ await expect(page.getByRole('button', { name: /^Create$/ }).last()).toBeEnabled()
+
+ // The gallery holds the three results, each tied to its file.
+ await page.getByRole('button', { name: 'Open the gallery' }).click()
+ for (const name of ['a.png', 'c.png', 'd.png']) {
+ await expect(page.locator(`button[title="From ${name}"]`)).toHaveCount(1)
+ }
+ await expect(page.locator('button[title="From b.png"]')).toHaveCount(0)
+})
+
+test('credits run out in the middle: the rest is never sent and stays in the list', async ({ page }) => {
+ await bootIntoCutout(page)
+ const sent = await routeJobs(page, { refuseFrom: 3 })
+
+ await page.getByTestId('batch-files-input').setInputFiles(files(['a.png', 'b.png', 'c.png', 'd.png', 'e.png']))
+ await expect(page.getByTestId('batch-count')).toContainText('5 images.')
+ await page.getByRole('button', { name: /^Create$/ }).last().click()
+
+ await expect(page.getByText(/2 of 5 images are done\. There were not enough credits to go on\. The other 3 were not started and nothing was charged for them\./)).toBeVisible({ timeout: 45_000 })
+ // Two booked. The third was refused before any booking, four and five never left the app.
+ expect(sent.jobs).toHaveLength(2)
+ expect(sent.uploads).toBe(3)
+ await expect(page.getByTestId('batch-count')).toContainText('3 images.')
+})
+
+test('the limit is 50 images, and a mask tab takes one image', async ({ page }) => {
+ await bootIntoCutout(page)
+ await routeJobs(page)
+
+ const many = Array.from({ length: 52 }, (_, i) => `img-${String(i + 1).padStart(2, '0')}.png`)
+ await page.getByTestId('batch-files-input').setInputFiles(files(many))
+ await expect(page.getByTestId('batch-count')).toContainText('50 images.', { timeout: 20_000 })
+ await expect(page.getByText('You can edit up to 50 images at once. 50 were added, 2 were left out.')).toBeVisible()
+
+ // Erase Object paints a mask per image: no multi-pick there.
+ await page.getByRole('radio', { name: /Erase Object/i }).click()
+ await expect(page.getByTestId('batch-files-input')).toHaveCount(0)
+ await expect(page.getByTestId('batch-strip')).toHaveCount(0)
+})
diff --git a/e2e/create-save-character.spec.ts b/e2e/create-save-character.spec.ts
new file mode 100644
index 00000000..bd72eff4
--- /dev/null
+++ b/e2e/create-save-character.spec.ts
@@ -0,0 +1,112 @@
+import { test, expect, type Page } from '@playwright/test'
+import { tauriMockInit, DEFAULT_ASSISTANT_REPLY, DEFAULT_MODEL_NAME } from './support/tauri-mock'
+import { routeCloud, seedOnboardingDone, signInViaGate, cloudSwitch } from './support/cloud-mock'
+
+/**
+ * "Save character from this video" (Discord, applejames): frames picked from a
+ * generated video become a named character that is kept on this machine. The
+ * frames are real: Chromium decodes a small clip and the canvas reads them.
+ * The character survives a reload and starts a training set in Character
+ * Studio with one click.
+ */
+
+// One second of a 64x64 test pattern, VP8 in WebM (about 3 KB).
+const CLIP = Buffer.from('GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQJChYECGFOAZwEAAAAAAAw2EU2bdLpNu4tTq4QVSalmU6yBoU27i1OrhBZUrmtTrIHYTbuMU6uEElTDZ1OsggElTbuMU6uEHFO7a1Osggwg7AEAAAAAAABZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmsirXsYMPQkBNgI1MYXZmNjIuMTIuMTAyV0GNTGF2ZjYyLjEyLjEwMkSJiECPQAAAAAAAFlSua8iuAQAAAAAAAD/XgQFzxYjedgJYAgf9DZyBACK1nIN1bmSIgQCGhVZfVlA4g4EBI+ODhAvrwgDgkLCBQLqBQJqBAlWwhFW5gQESVMNn/HNzoGPAgGfImkWjh0VOQ09ERVJEh41MYXZmNjIuMTIuMTAyc3PWY8CLY8WI3nYCWAIH/Q1nyKFFo4dFTkNPREVSRIeUTGF2YzYyLjI4LjEwMiBsaWJ2cHhnyKFFo4hEVVJBVElPTkSHkzAwOjAwOjAxLjAwMDAwMDAwMAAfQ7Z1SnTngQCjRU+BAACAMCEAnQEqQABAAABHCIWFiIWEiAICAnW6JQs+gfhX+zX9y+Qmmvwf7O/pTyQ5aOjj5D+Fv+A///w5/0vSA/op/SfxS7QPmB/in8g/pP+A9+L0A+gD/Lv4DwAP7Aejd/2P738An6t/5j/IfAJ/JP5L8/HKA9gp/FfwX9mfbj8s/Dz9u+nC9Oc4b9YvrP48fkB7AO6Q/mf4q/kTmHv6b+Q38X1Xn8mtkB/qP9m+5L38v3T8lf7d7BfjP/OfkB9AX8N/kP9a/Jn+7//XlAf0g59LxhjDPalfxyY3nzsg/T/nm5hkhQQlsTwIdEGhmlJJNGu+z93xf8c3Vl6cQtGaFoAbmP5lDZejln7Gd9ye754PY0vlbAD+/i2aWAGo4sPQcs24i34Z3SnewokjsT81vPjJXd7oSsnCdjok86SS9Vx6LKOq/yCP50n8t3u8OY6MXoUjWnTJ7ZUzih8uggV2Lma/Gzhv8mF66lSQ2w/UD4uzYrV+842kK0I7NYT/8FC3YTDNbxkJ1J18LsCBedOTINFl/MZWsxgC3nE52/MQKRcWozIsBAEjRZ6xNEgfJyVtT6fQoaOzWCBq346pcYBsWVah2DCz/lnU2hcnZOfj9If/9ph80IlaUYq7+/RMKWixx+PoFXgoZyj7LLRvwN08BYDEotbd0wXsd2YXZbHoJcRC3gDxp3CE0uU3owSpf9ndH9KMpdPIF+qkM2go/iuAZNVukLxqM0AkaBMy6TEqEgaBn0HzgcYGvbypFNl17VIPp//8mVmTCNiPZaqZ6F3olnMiJUdaEeZixdszDw/f+ybYGro0vJfQjkjtOUCvjufsLIarrLE+FExH8Xr85tqssmUcKVUN8jRznh5hYQwlBLNkrR3Z0QNtjvv//8FxbJeCdhmBH1HudW+bQ5lzaB11sy1RtK/RjyDhAIABfAvgbg4OjFtpZ0hBrsRtyyAy3z8Cs53tLjtChKiU6t20vj0XquhEIlbIpYxZ12iXAAJ9QAAbygAA3lAABLeHu0q//mJiMSOiuuY4Y0hVen5mmNyTgABdVNisR3UgAAI30LxZWbPd0AAAAC5QAAgrE1mlZKAbHAABj8Sj+lXKtqAACW/XIbfKyEneY8V8X/2gju2rxEnyTfQcq+2pFp79/1tYASdmVAAAAC3Y2+VlxJAkkP6a3FK4TuF9xgeaf8z8V64/2ffPXbKnsjmuu33/DzlvmdULkKXHk40Fj4KU/p8BCsq6du+CiAnoN/1CbSaftd04iqAuesQwUqlJtm+VCJ/5JCdi/UC/LaJR+Z2wW3DbKEkPtr/17mQfzI5cMkcvtc+bC/DZO53TDgrW9QfxSMYUFTyTmtdR4osJSNO93ESbDf/Gt/NP8toy7mwPfbkl5fetoLhg1pi6p4//kgFv0rlXek6avpzvUzEEu3qsZOTfkAvalALXC6POFKqwKj/iV+AEeLBkbsnWjWRt/mWaHgRuptNTzejEj/xsoLGfpggsZ/+Mp+3JtszpTfwcjvm7Dkcu+Ip5Rb1lvq9FVmQ2kWciLKVuc/ZNoeJojzEQWGf6e7ckC0nlf8suDji+B3117mBVn6t9PIi84N0VE9sCHYX/kEG9qLXh10Upgxmnh4XJJ2p+oyVBodKLovVQxH6TNOblXFPPaIqJScyLKOo7yHVkbn14INvFNbnE2IBEIgMAbPHqaOhm+hyW8sA3pyKUs+E8f+zsO+dHWYzHpV+O4L/1ZVjqH1NBp9FNoeWJ+ALBVuK6KZlFbV9Fl+jqz+UUp7+fZn8fSJ9aqiGBVZ72jhz5xjkiIFhZzUyekN/zOzd+SACjQU6BAMgAsQYAABAQABgMYDcpce3+zDegHL/97/6wHn1eqL/6L3R9EkqbrAINPLAIN00PhzS7lzgwY+TxSwAPjgBAJlEaTFYBEjA4ZkqWgUz+BH2fILBpeAxxqzSleExIOIsft2tYci7JQDAFdn1Bpd+UNNgaAkBR//y88fRU5JbsNI9wGCFmCCDY6vADMKUXtlLQVL39V4hae+Je0t03kuZ/qYRN8VOvMDQEmRzvVFH/uqgp5SaOqA6iQMEu5sb3kR7lREaJCuzpAUUklaLay3JozmGi4l8nrB/j4puFonok7XUafVQwNTr7cGCXw6Us9EAAYasA0qFNARqhO8XZmaLy/bv00cChREQroHguKMZF9CbCIl3GcP+Oph0pZ8SKpu9QqwDC7pcFlgAS9j827see/zgusTTvEmAJWYCxEtDs03WrnamjDTKBouaEq4AAo0FHgQGQABEEAAAQEAAYBrTb28/BHX/DmNlwZq/PA1DsKE0XuuJUqHAAD44AU4yJ572ISoX0RFdGfpB5TQ8h3ujdkY0z6Q+BtemBlCrOBJ5MWYNDPp36Szre+3IxmTQemorUx6D9Q0tsARY8LVI8EY0/WjzJM7Z3Qq2kQEC9j6Q/SFirxkH+FHC81DN8BMYqgLKJgEIkBWePEIrFFuHkgXZ9hkog82kbDXgAK0wDyKJQEmStyESzLJntCAWA8lAvjgio7uHgJxa+L7A8HFlXqQyGUsuYFWAaJNdUHOoCLr1WlWfj8QcUo5dIAHq8NYfIbNLLzLkWK7hnGLtHFfq5klVCAEoaJ8acqtGjsHVCIPHsvLUTTN5oig0stKoIbecgIdaU/iAApN2P/QGXoVambrtLSneahfM4aTZVmrEcwr/IBI3dakLL+cAAo0FLgQJYABEFAAAQEAAYBnARgBvU9wAmJweg/E4+jU2oIVW/wIK3uwjHKSFzUs9KoAAPjgTBaYw+xBowcd7amMPQzg5iLKkXfDmFsQ0BMWgHND2MCiQ+7wFQdXsERfIIJWkjswxdyawM4u5X0ZkQC4QBkGXEC28ZQB2Uj4s/cElf5sgpJ6aOwd8QMqOLTPjh+daNQtTgUjPssGRokiKxbQAUwB73EHCrG2hJZFoQaOuQHcrjFDfycdq2rswvbbv1ixQ/4AzFbCW3c4kMaWSTOrQViIACq4ulxrZ4x7XT7lvry54/DkzHea2i7PLvcSkgz4cuYw1zBQom8jtJffw5L2Yfll/8R/HLzu/ea+waJtYZQd8MSOkbkM5t8ZoHyYGPEBCgsPxHWotENgAVIR8x1nl5vXJF/G6GVJT2e1KXueOCNwiAc9GxmDm1ftKAAKNBM4EDIABxAwAAEBAAGAK/ADWgQd/gFkFP74JakxX9410W5AAPjgTB9UzTgBqEAKJJpEgIHL2JyVgF+2JNsvQMaJ7Z+MK2dsAtCGHl4BT5jCS/8D+hEDW+sADU+ghu6JVcBKucG19rtce2EQ/YJ+22oU48KEUKGnWigTo+50A5WwWhtNTZGacW4lJNBwbEVaGlxGzL3FsAGIPGKHHPJnJh0CDy2SARIo3z1r+kL79EfJlic8CwEU8K35AojzgS85gxzP+IpCsnGQGGbIWbqyY+UZc0ZF+sVnsgAFvIFs6TQU77QaZqkhjMwIepJo3uJLUt9Apt8MYPQMrfrr5Da18lCGD80XVU7ZIB5xGGfMayFW2AAQkmMjmUyxc8kX8kT8+Ntb6L2J0XphewTXQAFj7DQRDHRAAcU7trkbuPs4EAt4r3gQHxggGm8IED', 'base64')
+const CORS = { 'access-control-allow-origin': '*', 'access-control-allow-headers': '*', 'access-control-allow-methods': 'GET,POST,OPTIONS' }
+
+const VIDEO_ITEM = {
+ id: 'job-video-1', type: 'video', filename: 'clip.webm', subfolder: '', prompt: 'a knight walks through fog',
+ negativePrompt: '', model: 'wan-2.2-720p', modelType: 'wan', seed: 7, steps: 20, cfgScale: 5, sampler: '', scheduler: '',
+ width: 64, height: 64, batchSize: 1, createdAt: 1_760_000_000_000,
+ remoteUrl: 'https://lu-labs.ai/e2e/clip.webm', jobId: 'job-video-1', intent: 'video',
+}
+
+async function boot(page: Page) {
+ await page.addInitScript(tauriMockInit, { assistantReply: DEFAULT_ASSISTANT_REPLY, modelName: DEFAULT_MODEL_NAME })
+ await seedOnboardingDone(page)
+ // A finished cloud video in the gallery, as a persisted session leaves it.
+ await page.addInitScript((item) => {
+ if (!window.localStorage.getItem('create-store')) {
+ window.localStorage.setItem('create-store', JSON.stringify({ state: { gallery: [item] }, version: 2 }))
+ }
+ }, VIDEO_ITEM)
+ await routeCloud(page, { license: 'active', access: true, mediaLive: true })
+ await page.route('https://lu-labs.ai/e2e/clip.webm', (route) =>
+ route.fulfill({ status: 200, headers: { ...CORS, 'content-type': 'video/webm' }, body: CLIP }))
+ await page.goto('/')
+ await expect(cloudSwitch(page)).toBeVisible({ timeout: 20_000 })
+}
+
+async function intoCloudCreate(page: Page) {
+ await signInViaGate(page)
+ await expect(cloudSwitch(page)).toBeChecked({ timeout: 20_000 })
+ await page.getByRole('button', { name: /^Create$/ }).click()
+}
+
+/** Open the gallery and show its video in the large view. */
+async function showVideo(page: Page) {
+ await page.getByRole('radio', { name: /^Video$/ }).click()
+ await page.getByRole('button', { name: 'Open the gallery' }).click()
+ await page.locator('aside button:has(video)').click()
+}
+
+test('frames of a video become a saved character that survives a reload', async ({ page }) => {
+ await boot(page)
+ await intoCloudCreate(page)
+
+ // The action sits on the video in the large view.
+ await showVideo(page)
+ await page.getByTitle('Save character from this video').click({ force: true })
+ const dialog = page.getByRole('dialog', { name: 'Save character from this video' })
+ await expect(dialog).toBeVisible()
+
+ // Two frames from two moments of the clip.
+ const video = dialog.locator('video')
+ await expect.poll(() => video.evaluate((v: HTMLVideoElement) => v.readyState), { timeout: 20_000 }).toBeGreaterThanOrEqual(2)
+ await dialog.getByRole('button', { name: 'Add this frame' }).click()
+ await expect(dialog.getByTestId('character-frames').locator('img')).toHaveCount(1)
+ await video.evaluate((v: HTMLVideoElement) => new Promise<void>((resolve) => {
+ v.addEventListener('seeked', () => resolve(), { once: true })
+ v.currentTime = 0.6
+ }))
+ await dialog.getByRole('button', { name: 'Add this frame' }).click()
+ await expect(dialog.getByTestId('character-frames').locator('img')).toHaveCount(2)
+ // A picked frame is a real picture of the video's size.
+ const size = await dialog.getByTestId('character-frames').locator('img').first().evaluate(
+ (img: HTMLImageElement) => img.decode().then(() => [img.naturalWidth, img.naturalHeight]),
+ )
+ expect(size).toEqual([64, 64])
+
+ await dialog.getByLabel('Character name').fill('Sir Aldous')
+ await dialog.getByRole('button', { name: 'Save character' }).click()
+ await expect(dialog.getByTestId('character-saved')).toContainText('Saved Sir Aldous with 2 photos. It is kept on this computer.')
+ await expect(dialog.getByText(/Training needs at least 4 photos/)).toBeVisible()
+
+ // Hand the photos to Character Studio: they start the training set.
+ await dialog.getByRole('button', { name: 'Train in Character Studio' }).click()
+ await expect(dialog).toHaveCount(0)
+ await expect(page.getByRole('radio', { name: /Character Studio/i })).toBeChecked()
+ await expect(page.getByText(/^2\/30 photos\./)).toBeVisible()
+
+ // After a reload the character is still there (the boot script puts the app
+ // back into local mode, and the character is local anyway). One click adds
+ // its photos to the local training set.
+ await page.reload()
+ await expect(cloudSwitch(page)).toBeVisible({ timeout: 20_000 })
+ await page.getByRole('button', { name: /^Create$/ }).click()
+ await page.getByRole('radio', { name: 'Character Studio', exact: true }).click()
+ const chip = page.getByTitle('Add the 2 photos of Sir Aldous')
+ await expect(chip).toBeVisible({ timeout: 15_000 })
+ await expect(page.getByText(/Drop 4 to 100 photos of your character here/)).toBeVisible()
+ await chip.click()
+ await expect(page.getByText(/^2\/100 photos\./)).toBeVisible()
+})
+
+test('the lightbox of a video offers the same action', async ({ page }) => {
+ await boot(page)
+ await intoCloudCreate(page)
+ await showVideo(page)
+ await page.getByTitle('Fullscreen').click({ force: true })
+ await page.getByRole('button', { name: 'Save character', exact: true }).click()
+ await expect(page.getByRole('dialog', { name: 'Save character from this video' })).toBeVisible()
+})
diff --git a/e2e/memory-sync.spec.ts b/e2e/memory-sync.spec.ts
index fdee0561..2c26c00f 100644
--- a/e2e/memory-sync.spec.ts
+++ b/e2e/memory-sync.spec.ts
@@ -17,11 +17,11 @@ async function accountFixture(page: Page) {
await page.getByRole('button', { name: 'Use account memories', exact: true }).click()
}
-test('foreground cancellation stops a held pull and leaving the collection cancels the next run', async ({ page }) => {
+test('foreground cancellation stops a held pull and leaving the collection cancels the next run', async ({ page, baseURL }) => {
let finish: (() => Promise<void>) | undefined
let hold = true
let reads = 0
- await page.route('**/*', route => new URL(route.request().url()).port === '5273' ? route.continue() : route.abort())
+ await page.route('**/*', route => new URL(route.request().url()).port === new URL(baseURL!).port ? route.continue() : route.abort())
await page.route('**/api/memory/sync**', async route => {
expect(route.request().method()).toBe('GET')
reads++
@@ -66,10 +66,10 @@ test('foreground cancellation stops a held pull and leaving the collection cance
await expect(page.getByRole('button', { name: 'Cancel synchronization', exact: true })).toHaveCount(0)
})
-test('explicit UI sync uploads, downloads, preserves conflicts and persists shared deletion', async ({ page }, testInfo) => {
+test('explicit UI sync uploads, downloads, preserves conflicts and persists shared deletion', async ({ page, baseURL }, testInfo) => {
let records: SyncedMemoryRecord[] = []
let writes = 0
- await page.route('**/*', route => new URL(route.request().url()).port === '5273' ? route.continue() : route.abort())
+ await page.route('**/*', route => new URL(route.request().url()).port === new URL(baseURL!).port ? route.continue() : route.abort())
await page.route('**/api/memory/sync**', async route => {
expect(route.request().headers().authorization).toBe('Bearer synthetic-proof-token')
if (route.request().method() === 'POST') {
@@ -183,11 +183,11 @@ test('explicit UI sync uploads, downloads, preserves conflicts and persists shar
})
for (const responseMode of ['lost', 'cancelled'] as const) {
-test(`a ${responseMode} first-upload response cannot revive a locally deleted memory after reload`, async ({ page }) => {
+test(`a ${responseMode} first-upload response cannot revive a locally deleted memory after reload`, async ({ page, baseURL }) => {
let records: SyncedMemoryRecord[] = []
let lostResponse = false
let finish: (() => Promise<void>) | undefined
- await page.route('**/*', route => new URL(route.request().url()).port === '5273' ? route.continue() : route.abort())
+ await page.route('**/*', route => new URL(route.request().url()).port === new URL(baseURL!).port ? route.continue() : route.abort())
await page.route('**/api/memory/sync**', async route => {
if (route.request().method() === 'GET') return route.fulfill({ json: { ownerId: 'owner-a', records, next: null } })
const body: unknown = route.request().postDataJSON()
diff --git a/e2e/memory-write-fence.spec.ts b/e2e/memory-write-fence.spec.ts
index e83f845f..a8d2b404 100644
--- a/e2e/memory-write-fence.spec.ts
+++ b/e2e/memory-write-fence.spec.ts
@@ -1,8 +1,8 @@
import { expect, test } from '@playwright/test'
import { DEFAULT_MODEL_NAME } from './support/tauri-mock'
-test('deleting through Memory Settings survives a late automatic extraction and reload', async ({ page }) => {
- await page.route('**/*', route => new URL(route.request().url()).port === '5273' ? route.continue() : route.abort())
+test('deleting through Memory Settings survives a late automatic extraction and reload', async ({ page, baseURL }) => {
+ await page.route('**/*', route => new URL(route.request().url()).port === new URL(baseURL!).port ? route.continue() : route.abort())
await page.goto('/e2e/memory-sensitive-proof.html')
await page.evaluate(async (modelName) => {
const memoryPath = '/src/stores/memoryStore.ts'
diff --git a/src/components/create/experimental/BatchStrip.tsx b/src/components/create/experimental/BatchStrip.tsx
new file mode 100644
index 00000000..b84a5110
--- /dev/null
+++ b/src/components/create/experimental/BatchStrip.tsx
@@ -0,0 +1,163 @@
+// Several source images, one edit (Discord, cazwhin): the list sits at the
+// source image, never at the prompt. Under the large image: the further images
+// as small tiles, "Add more images", "Add a folder", and in the cloud the price
+// of the whole list as one sum. While it runs, the same tiles are the queue.
+import { useRef, useState } from 'react'
+import { AlertTriangle, Check, FolderOpen, ImagePlus, X } from 'lucide-react'
+import { useCreateStore } from '../../../stores/createStore'
+import { MAX_BATCH_IMAGES, batchCoverage } from '../../../lib/batch-edit'
+import { addBatchFiles, clearBatch, removeBatchEntry, useBatchOffered } from './batchRun'
+import { useRunCredits } from './useRunCredits'
+import { topLevelFiles } from './batchFiles'
+import { useCreateExp } from './CreateContext'
+import { Button } from '../ui/Button'
+import { cn } from '../ui/cn'
+
+const num = (n: number) => n.toLocaleString('en-US')
+
+/** The two hidden pickers, shared by the empty slot and the strip. */
+export function useBatchPickers(onFiles: (files: File[]) => void) {
+ const filesRef = useRef<HTMLInputElement>(null)
+ const folderRef = useRef<HTMLInputElement>(null)
+ const inputs = (
+ <>
+ <input
+ ref={filesRef}
+ type="file"
+ accept="image/*"
+ multiple
+ className="hidden"
+ data-testid="batch-files-input"
+ onChange={(e) => {
+ const files = Array.from(e.target.files ?? [])
+ e.target.value = ''
+ if (files.length) onFiles(files)
+ }}
+ />
+ <input
+ ref={folderRef}
+ type="file"
+ multiple
+ className="hidden"
+ data-testid="batch-folder-input"
+ {...{ webkitdirectory: '' }}
+ onChange={(e) => {
+ const files = topLevelFiles(Array.from(e.target.files ?? []))
+ e.target.value = ''
+ if (files.length) onFiles(files)
+ }}
+ />
+ </>
+ )
+ return { inputs, pickFiles: () => filesRef.current?.click(), pickFolder: () => folderRef.current?.click() }
+}
+
+/** Under the source image: the list of further images and its price. */
+export function BatchStrip() {
+ const batch = useCreateStore((s) => s.batchSources)
+ const backend = useCreateStore((s) => s.backend)
+ const offered = useBatchOffered()
+ const { quota } = useCreateExp()
+ const run = useRunCredits()
+ const [loading, setLoading] = useState(false)
+ const add = (files: File[]) => {
+ setLoading(true)
+ void addBatchFiles(files).finally(() => setLoading(false))
+ }
+ const { inputs, pickFiles, pickFolder } = useBatchPickers(add)
+
+ if (!offered) {
+ // A model that needs a painted mask edits one image at a time. A list left
+ // over from another model says so instead of quietly running only one.
+ if (batch.length < 2) return null
+ return (
+ <div className="mt-3 flex flex-col items-center gap-1" data-testid="batch-strip">
+ <p className="t-body text-gray-500 text-center max-w-sm">
+ This model needs a painted mask for each image, so it edits one image at a time. Only the image above runs.
+ </p>
+ <button onClick={clearBatch} className="t-label text-gray-500 hover:text-gray-300 underline underline-offset-2">Remove the other {batch.length - 1}</button>
+ </div>
+ )
+ }
+
+ const on = batch.length > 1
+ const full = batch.length >= MAX_BATCH_IMAGES
+ const perImage = backend === 'cloud' && run && quota ? run.cost : null
+ const covered = perImage !== null && quota ? batchCoverage(quota.remaining.credits, perImage, batch.length) : batch.length
+
+ return (
+ <div className="mt-3 flex flex-col items-center gap-2 max-w-full" data-testid="batch-strip">
+ {inputs}
+ {on && (
+ <div className="flex gap-1.5 overflow-x-auto max-w-[min(100%,34rem)] p-1 scrollbar-thin">
+ {batch.map((img, i) => (
+ <div key={img.url} className="relative shrink-0 w-12 h-12">
+ <img src={img.url} alt={img.name} title={img.name} className="w-12 h-12 rounded-md object-cover border border-white/[0.06]" />
+ <span className="absolute bottom-0.5 left-0.5 t-micro text-gray-200 bg-black/60 px-1 rounded">{i + 1}</span>
+ <button
+ onClick={() => { void removeBatchEntry(i) }}
+ className="absolute top-0.5 right-0.5 w-4 h-4 flex items-center justify-center rounded bg-black/60 text-gray-300 hover:text-white"
+ title={`Remove ${img.name}`}
+ aria-label={`Remove ${img.name}`}
+ >
+ <X size={10} />
+ </button>
+ </div>
+ ))}
+ </div>
+ )}
+ <div className="flex items-center gap-2">
+ <Button variant="ghost" icon={ImagePlus} loading={loading} disabled={full} onClick={pickFiles}>Add more images</Button>
+ <Button variant="ghost" icon={FolderOpen} disabled={loading || full} onClick={pickFolder}>Add a folder</Button>
+ {on && <Button variant="ghost" icon={X} onClick={clearBatch}>Clear list</Button>}
+ </div>
+ {on && (
+ <p className="t-body text-gray-500 text-center max-w-sm" data-testid="batch-count">
+ {batch.length} images. Each one gets the same {run && run.imageCount > 1 ? `run, ${run.imageCount} results each` : 'run'}, one after the other.
+ {full ? ` That is the most one list takes.` : ''}
+ </p>
+ )}
+ {on && perImage !== null && (
+ <p className="t-body text-gray-400 text-center max-w-sm" data-testid="batch-price">
+ {num(perImage)} credits per image, {num(perImage * batch.length)} credits for all {batch.length}.
+ {covered < batch.length
+ ? ` Your credits cover ${covered} of them. The rest will not run and is not charged.`
+ : ''}
+ </p>
+ )}
+ </div>
+ )
+}
+
+/** While a batch runs: which image is on, and how the others stand. */
+export function BatchQueue() {
+ const run = useCreateStore((s) => s.batchRun)
+ if (!run) return null
+ const total = run.statuses.length
+ const done = run.statuses.filter((s) => s === 'done').length
+ const failed = run.statuses.filter((s) => s === 'failed').length
+ return (
+ <div className="flex flex-col items-center gap-2 max-w-full" data-testid="batch-queue">
+ <p className="t-body text-gray-200" data-testid="batch-progress">Image {Math.min(run.index + 1, total)} of {total}</p>
+ <p className="t-mono text-gray-500 truncate max-w-[18rem]">{run.names[run.index]}</p>
+ <div className="flex gap-1 overflow-x-auto max-w-[min(100%,24rem)] p-1 scrollbar-thin">
+ {run.statuses.map((status, i) => (
+ <div
+ key={i}
+ title={`${run.names[i]}: ${status}`}
+ className={cn(
+ 'relative shrink-0 w-8 h-8 rounded-md overflow-hidden border',
+ status === 'running' ? 'border-lu-accent' : status === 'failed' ? 'border-red-400/70' : 'border-white/[0.06]',
+ status === 'waiting' && 'opacity-40',
+ )}
+ >
+ <img src={run.thumbs[i]} alt="" className="w-full h-full object-cover" />
+ {status === 'done' && <span className="absolute inset-0 flex items-center justify-center bg-black/45 text-gray-100"><Check size={12} /></span>}
+ {status === 'failed' && <span className="absolute inset-0 flex items-center justify-center bg-black/55 text-red-300"><AlertTriangle size={12} /></span>}
+ </div>
+ ))}
+ </div>
+ <p className="t-body text-gray-500">{done} done{failed > 0 ? `, ${failed} failed` : ''}. Cancel stops the rest.</p>
+ </div>
+ )
+}
diff --git a/src/components/create/experimental/Composer.tsx b/src/components/create/experimental/Composer.tsx
index 1e57232c..33bb5dc9 100644
--- a/src/components/create/experimental/Composer.tsx
+++ b/src/components/create/experimental/Composer.tsx
@@ -53,7 +53,9 @@ export function Composer({ onOpenAdvanced, onOpenWorkflows }: Props) {
const toggleNegative = useCreateStore((s) => s.toggleNegative)
const source = useCreateStore((s) => s.source)
const mask = useCreateStore((s) => s.mask)
- const isGenerating = useCreateStore((s) => s.isGenerating)
+ // A batch over several source images counts as one run in flight, also in
+ // the short gap between two of its images: the button stays Cancel.
+ const isGenerating = useCreateStore((s) => s.isGenerating || s.batchRun !== null)
const backend = useCreateStore((s) => s.backend)
const targetResolution = useCreateStore((s) => s.targetResolution)
const setTargetResolution = useCreateStore((s) => s.setTargetResolution)
diff --git a/src/components/create/experimental/CreateContext.tsx b/src/components/create/experimental/CreateContext.tsx
index fc9b20a1..02ac83ae 100644
--- a/src/components/create/experimental/CreateContext.tsx
+++ b/src/components/create/experimental/CreateContext.tsx
@@ -12,6 +12,7 @@ import { installMlxStack } from '../../../api/mlx-install'
import { useDownloadStore } from '../../../stores/downloadStore'
import { downloadBundleFiles, waitOrAbort, waitForModelsVisible, InstallCancelled } from '../../../lib/bundle-install'
import { ensureLocalFilename } from './loadImage'
+import { batchReady, requestBatchStop, runBatchEdit } from './batchRun'
import { comfyStartupError, COMFY_INSTALLED_BUT_DEAD } from './comfyError'
import { restartComfyForNewNodes } from '../../../api/comfy-restart'
import type { CloudQuota } from '../../../lib/render/cloud-jobs'
@@ -560,13 +561,21 @@ export function CreateExpProvider({ children }: { children: ReactNode }) {
}
}, [ensureComfyRunning, fetchModels])
+ // Several source images (lib/batch-edit): Create runs the same single run
+ // once per image, on the backend the batch started on.
+ const runOne = backend === 'cloud' ? cloud.generate : generate
const value: CreateExpValue = {
- generate: backend === 'cloud' ? cloud.generate : generate,
+ generate: () => (batchReady() ? runBatchEdit(runOne) : runOne()),
// Cancel routes by the backend that STARTED the run, not the current axis:
// the header switch (or the license probe) can flip local/cloud mid-render,
// and routing by the live value would abort a null handle while the real
// run keeps going (a cloud job keeps billing; a local job keeps rendering).
- cancel: () => (hasActiveCloudRun() ? cloud.cancel() : cancel()),
+ // A batch stops first, so nothing further starts while the run in flight
+ // is cancelled.
+ cancel: () => {
+ requestBatchStop()
+ return hasActiveCloudRun() ? cloud.cancel() : cancel()
+ },
enhanceVideo: cloud.enhanceVideo,
makeVoice: cloud.makeVoice,
samplerList, schedulerList, loraList, vaeList, refreshModelLists,
diff --git a/src/components/create/experimental/CreateExperimental.tsx b/src/components/create/experimental/CreateExperimental.tsx
index ad7b3b63..af58e707 100644
--- a/src/components/create/experimental/CreateExperimental.tsx
+++ b/src/components/create/experimental/CreateExperimental.tsx
@@ -14,6 +14,7 @@ import { Stage } from './Stage'
import { Composer } from './Composer'
import { CreatePanel } from './CreatePanel'
import { Lightbox } from './Lightbox'
+import { SaveCharacterModal } from './SaveCharacterModal'
import { AdvancedDrawer } from './AdvancedDrawer'
import { WorkflowsModal } from '../WorkflowsModal'
import { Hinweis } from '../../ui/Hinweis'
@@ -101,6 +102,8 @@ function CreateExperimentalInner() {
const [advancedOpen, setAdvancedOpen] = useState(false)
const [maskOpen, setMaskOpen] = useState(false)
const [lightbox, setLightbox] = useState<GalleryItem | null>(null)
+ // The video whose frames are being saved as a character (SaveCharacterModal).
+ const [characterFrom, setCharacterFrom] = useState<GalleryItem | null>(null)
const [panelOpen, setPanelOpen] = useState(false)
const [workflowsOpen, setWorkflowsOpen] = useState(false)
@@ -431,6 +434,7 @@ function CreateExperimentalInner() {
onEditResult={editAvailable ? (it) => { void editResultWithMask(it) } : undefined}
onAnimateResult={animateAvailable ? (it) => { void animateResult(it) } : undefined}
onFullscreen={(it) => setLightbox(it)}
+ onSaveCharacter={setCharacterFrom}
comfyStarting={comfyStarting}
/>
<CreatePanel open={panelOpen} onOpenChange={setPanelOpen} activeId={shownId} onSelect={openGalleryItem} />
@@ -497,7 +501,8 @@ function CreateExperimentalInner() {
</Modal>
)}
- <Lightbox item={lightbox} onClose={() => setLightbox(null)} />
+ <Lightbox item={lightbox} onClose={() => setLightbox(null)} onSaveCharacter={setCharacterFrom} />
+ <SaveCharacterModal item={characterFrom} onClose={() => setCharacterFrom(null)} />
<VhsInstallModal />
<RenderFixupModal />
</div>
diff --git a/src/components/create/experimental/CreatePanel.tsx b/src/components/create/experimental/CreatePanel.tsx
index 7b949fcd..2679f31c 100644
--- a/src/components/create/experimental/CreatePanel.tsx
+++ b/src/components/create/experimental/CreatePanel.tsx
@@ -108,6 +108,7 @@ export function CreatePanel({ open, onOpenChange, activeId, onSelect }: Props) {
<div key={g.id} className="relative group">
<button
onClick={() => onSelect(g.id)}
+ title={g.sourceName ? `From ${g.sourceName}` : undefined}
draggable={g.type === 'image' && !g.unavailable}
onDragStart={(e) => {
e.dataTransfer.setData(GALLERY_DRAG_TYPE, g.id)
diff --git a/src/components/create/experimental/CreditsMeter.tsx b/src/components/create/experimental/CreditsMeter.tsx
index 433565a3..95a4993a 100644
--- a/src/components/create/experimental/CreditsMeter.tsx
+++ b/src/components/create/experimental/CreditsMeter.tsx
@@ -1,12 +1,6 @@
-import { useCreateStore } from '../../../stores/createStore'
import { useCreateExp } from './CreateContext'
-import { intentToJob } from '../../../lib/render/cloud-jobs'
-import { defaultCloudModel, modelForOp, resolveOpPick, runCredits } from '../../../stores/cloudCatalogStore'
-import { createStudioCost, intentRoles, isStudioModel, resolveIntentPick, startImageCount } from '../../../lib/render/create-studio'
-import { STUDIO_MODELS } from '../../../lib/render/studio-contract'
-import { resolveCharacterModel } from '../../../hooks/useCloudCreate'
+import { useRunCredits } from './useRunCredits'
import { meterState } from '../../../lib/render/credits-meter'
-import { runImageCount } from '../../../lib/render/image-count'
import { Tooltip } from '../ui/Tooltip'
import { openExternal } from '../../../api/backend'
import { CLOUD_BASE } from '../../../api/cloud/config'
@@ -24,82 +18,9 @@ import { HINWEIS_TEXT, PUNKT_FARBE } from '../../../lib/hinweis'
// keine Farbe am Balken, sondern der rote Knopf darunter.
export function CreditsMeter() {
const { quota } = useCreateExp()
- const intent = useCreateStore((s) => s.intent())
- const cloudImageModel = useCreateStore((s) => s.cloudImageModel)
- const cloudVideoModel = useCreateStore((s) => s.cloudVideoModel)
- const cloudOpModel = useCreateStore((s) => s.cloudOpModel)
- const characterTab = useCreateStore((s) => s.characterTab)
- const selectedCharacter = useCreateStore((s) => s.selectedCharacter)
- // Review A kleiner Punkt 1: this meter is cloud-only (Composer renders it
- // only for backend 'cloud'), so it must price the SAME length the cloud
- // Length control shows and useCloudCreate books, cloudFrames/cloudFps, not
- // the local track's frames/fps.
- const frames = useCreateStore((s) => s.cloudFrames)
- const fps = useCreateStore((s) => s.cloudFps)
- const musicDuration = useCreateStore((s) => s.musicDuration)
- const targetResolution = useCreateStore((s) => s.targetResolution)
- const cloudStudioOptions = useCreateStore((s) => s.cloudStudioOptions)
- const cloudStudioCredits = useCreateStore((s) => s.cloudStudioCredits)
- const prompt = useCreateStore((s) => s.prompt)
- const cloudImageCount = useCreateStore((s) => s.cloudImageCount)
- const references = useCreateStore((s) => s.references)
- if (!quota) return null
- // No character picked yet: there is no run to price (resolveCharacterModel
- // would fall onto the family's first model and show a number for a run
- // nobody asked for). uselu main 5be5dec3 fixed the same false reading.
- if (intent === 'character' && characterTab === 'use' && !selectedCharacter) return null
-
- let { kind, op } = intentToJob(intent)
- // Mirror Composer's creditsOk pick exactly — meter and gate must show the
- // same number: the character use-surface prices the family's real
- // generation endpoint (never a hardcoded single default), the role
- // intents (lipsync/music/extend/motion) run whichever Studio or classic
- // op-picker model is chosen, everything else prices the per-kind
- // picker's model.
- const characterUse = intent === 'character' && characterTab === 'use'
- if (characterUse) {
- kind = 'image'
- op = 'generate'
- }
- const special =
- op === 'lipsync' || op === 'extend' || op === 'motion' ||
- op === 'music' || op === 'tts' || op === 'lora-train'
- const roleIntent = !characterUse && intentRoles(intent).length > 0
- const rolePick = roleIntent ? resolveIntentPick(intent, cloudOpModel) : undefined
- const picked = characterUse
- ? (resolveCharacterModel(selectedCharacter?.family ?? '', cloudOpModel) ?? '')
- : roleIntent
- ? (rolePick ?? '')
- : special
- ? resolveOpPick(op, cloudOpModel)
- : (kind === 'video' ? cloudVideoModel : cloudImageModel) || defaultCloudModel(kind)?.id || ''
- // Dieselbe Aufloesung wie Composer und Start (modelForOp): eine Wahl, die die
- // Unterkategorie nicht fahren kann, rechnet hier als das Modell, das wirklich
- // laeuft. Rollen-Absichten und der Character-Weg behalten ihre Wahl.
- const model = roleIntent || characterUse ? picked : modelForOp(kind, op, picked)
- // Ein Studio-Modell rechnet nach seinem eigenen Schema, auch aus Image, Edit,
- // Video und Animate (seit 02.10.2026).
- const studioPick = !characterUse && isStudioModel(model) ? model : undefined
- if (studioPick) kind = STUDIO_MODELS[studioPick].kind
- const seconds =
- op === 'music'
- ? musicDuration
- : kind === 'video' && (op === 'generate' || op === 'animate') && fps > 0
- ? frames / fps
- : undefined
- // A Studio model prices from its own provider schema, never runCredits()
- // (P3's guard there returns the caller's fallback on purpose, Portplan
- // Abschnitt 7, Risiko 1). The Composer fetches the live number once
- // (useStudioPrice) and leaves it here; this chip never asks twice for the
- // same figure.
- const extraPhotos = intent === 'edit' || intent === 'animate' ? references.length : 0
- const unitCost = studioPick
- ? cloudStudioCredits ?? createStudioCost(studioPick, cloudStudioOptions, Array.from(prompt).length, undefined, startImageCount(studioPick, extraPhotos) ?? 1)
- : runCredits(kind, op, picked, seconds, quota.costs[kind === 'audio' ? 'image' : kind], targetResolution)
- // Mehrere Bilder: jedes ist ein eigener Auftrag zum vollen Preis, die Summe
- // ist, was der Lauf bindet. Der Zaehler "noch N Bilder" rechnet je Bild.
- const imageCount = runImageCount(intent, cloudImageCount, characterUse)
- const cost = unitCost * imageCount
+ const run = useRunCredits()
+ if (!quota || !run) return null
+ const { kind, op, unitCost, imageCount, cost } = run
const remaining = quota.remaining.credits
const limit = quota.limits.credits
const gate = meterState(quota, cost, kind, op)
diff --git a/src/components/create/experimental/Lightbox.tsx b/src/components/create/experimental/Lightbox.tsx
index d260de52..e5c3b015 100644
--- a/src/components/create/experimental/Lightbox.tsx
+++ b/src/components/create/experimental/Lightbox.tsx
@@ -1,7 +1,7 @@
import { itemHasAlpha } from '../../../lib/transparent-image'
import { useEffect } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
-import { X, Sparkles } from 'lucide-react'
+import { X, Sparkles, UserRoundPlus } from 'lucide-react'
import { useCreateStore, type GalleryItem } from '../../../stores/createStore'
import { runCredits } from '../../../stores/cloudCatalogStore'
import { useCreateExp } from './CreateContext'
@@ -9,7 +9,12 @@ import { useComfyMedia } from './useComfyMedia'
import { PromptDetails } from './PromptDetails'
import { cn } from '../ui/cn'
-export function Lightbox({ item, onClose }: { item: GalleryItem | null; onClose: () => void }) {
+export function Lightbox({ item, onClose, onSaveCharacter }: {
+ item: GalleryItem | null
+ onClose: () => void
+ /** Pick frames of this video and save them as a character. */
+ onSaveCharacter?: (item: GalleryItem) => void
+}) {
const backend = useCreateStore((s) => s.backend)
const isGenerating = useCreateStore((s) => s.isGenerating)
const { enhanceVideo, quota } = useCreateExp()
@@ -70,6 +75,22 @@ export function Lightbox({ item, onClose }: { item: GalleryItem | null; onClose:
<Sparkles size={13} /> Enhance
</button>
)}
+ {onSaveCharacter && item.type === 'video' && !item.unavailable && (
+ <button
+ onClick={(e) => {
+ e.stopPropagation()
+ onClose()
+ onSaveCharacter(item)
+ }}
+ title="Pick frames of this video and save them as a character"
+ className={cn(
+ 'absolute top-4 h-9 px-3 flex items-center gap-1.5 rounded-lg t-control bg-white/10 text-gray-200 hover:bg-white/20',
+ canEnhance ? 'right-[10.5rem]' : 'right-16',
+ )}
+ >
+ <UserRoundPlus size={13} /> Save character
+ </button>
+ )}
{item.type === 'audio' ? (
<motion.div
initial={{ scale: 0.95 }}
diff --git a/src/components/create/experimental/OutputView.tsx b/src/components/create/experimental/OutputView.tsx
index 7c2dbf63..45f0b162 100644
--- a/src/components/create/experimental/OutputView.tsx
+++ b/src/components/create/experimental/OutputView.tsx
@@ -1,7 +1,7 @@
import { itemHasAlpha } from '../../../lib/transparent-image'
import { useEffect, useState } from 'react'
import { motion } from 'framer-motion'
-import { Cpu, Sparkles, ImageDown, Maximize2, Download, Wand2, MonitorOff, AudioLines, Film, Trash2 } from 'lucide-react'
+import { Cpu, Sparkles, ImageDown, Maximize2, Download, Wand2, MonitorOff, AudioLines, Film, Trash2, UserRoundPlus } from 'lucide-react'
import { coldLoadHint } from '../../../lib/cold-load-notice'
import { useCreateStore, type GalleryItem, type ProgressPhase } from '../../../stores/createStore'
import { isMlxImageHost } from '../../../api/mlx-image'
@@ -11,6 +11,7 @@ import { markGalleryItemAvailable } from './galleryUrl'
import { downloadGalleryItem } from './galleryDownload'
import { galleryLabel } from '../../../lib/render/gallery-label'
import { useComfyMedia } from './useComfyMedia'
+import { BatchQueue } from './BatchStrip'
import { cn } from '../ui/cn'
// The icon in the waiting circle says which PHASE the render is in, never
@@ -101,6 +102,7 @@ export function GeneratingView() {
) : phaseIcon(progressPhase)}
</div>
</div>
+ <BatchQueue />
<p className="t-body text-gray-300 tracking-wide">{progressText || 'Generating…'}</p>
{isLoading && !isMlxImageHost() && <ColdLoadLine />}
{progress > 0 && (
@@ -123,6 +125,8 @@ interface ResultProps {
* run (see isIntentAvailable('animate', ...) in Stage's caller), same gating
* pattern as onSendToEditor above it. */
onAnimate?: () => void
+ /** Pick frames of this finished video and save them as a character. */
+ onSaveCharacter?: () => void
}
@@ -139,7 +143,7 @@ function reconcileDims(item: GalleryItem, w: number, h: number) {
}
}
-export function ResultView({ item, onFullscreen, onSendToEditor, onAnimate }: ResultProps) {
+export function ResultView({ item, onFullscreen, onSendToEditor, onAnimate, onSaveCharacter }: ResultProps) {
const { src: url, onError } = useComfyMedia(item)
const download = () => void downloadGalleryItem(item)
const isVideo = item.type === 'video'
@@ -191,6 +195,9 @@ export function ResultView({ item, onFullscreen, onSendToEditor, onAnimate }: Re
{onAnimate && item.type === 'image' && !item.unavailable && (
<IconBtn title="Animate this image" onClick={onAnimate}><Film size={14} /></IconBtn>
)}
+ {onSaveCharacter && isVideo && !item.unavailable && (
+ <IconBtn title="Save character from this video" onClick={onSaveCharacter}><UserRoundPlus size={14} /></IconBtn>
+ )}
<IconBtn
title={item.unavailable ? 'Download needs the local engine' : 'Download'}
disabled={item.unavailable}
@@ -220,6 +227,9 @@ export function ResultView({ item, onFullscreen, onSendToEditor, onAnimate }: Re
)}
<span className="truncate max-w-[280px]">{prettyModel(item.model)}</span>
</div>
+ {item.sourceName && (
+ <div className="mt-1 t-mono text-gray-500 truncate max-w-[420px]" data-testid="source-name">from {item.sourceName}</div>
+ )}
{item.runNote && (
<div className="mt-1 t-mono text-gray-500" data-testid="run-note">{item.runNote}</div>
)}
diff --git a/src/components/create/experimental/ReferenceStrip.tsx b/src/components/create/experimental/ReferenceStrip.tsx
index f95c9348..b8d302ad 100644
--- a/src/components/create/experimental/ReferenceStrip.tsx
+++ b/src/components/create/experimental/ReferenceStrip.tsx
@@ -10,9 +10,9 @@
import { useRef, useState } from 'react'
import { ImagePlus, Loader2, X } from 'lucide-react'
import { useCreateStore } from '../../../stores/createStore'
-import { classifyModel } from '../../../api/comfyui'
-import { extraReferenceSlots } from '../../../lib/edit-references'
-import { referenceModel, studioExtraPhotoSlots } from '../../../lib/render/create-studio'
+import { useReferenceSlots } from './referenceSlots'
+import { SavedCharacterChips } from './SavedCharacters'
+import { loadPhotosAsReferences } from './characterPhotos'
import { loadImageRef } from './loadImage'
import { GALLERY_DRAG_TYPE, fetchGalleryItemBlob } from './galleryUrl'
import { cn } from '../ui/cn'
@@ -27,22 +27,12 @@ export function ReferenceStrip() {
const gallery = useCreateStore((s) => s.gallery)
const backend = useCreateStore((s) => s.backend)
const intent = useCreateStore((s) => s.intent())
- const imageModel = useCreateStore((s) => s.imageModel)
- const listedType = useCreateStore((s) => s.imageModelList.find((m) => m.name === s.imageModel)?.type)
- const cloudImageModel = useCreateStore((s) => s.cloudImageModel)
- const cloudVideoModel = useCreateStore((s) => s.cloudVideoModel)
- const cloudOpModel = useCreateStore((s) => s.cloudOpModel)
const inputRef = useRef<HTMLInputElement>(null)
const [loading, setLoading] = useState(false)
const [drag, setDrag] = useState(false)
- // The type from the fetched list carries the header sniff; the name is the
- // fallback, exactly as useCreate decides the pipeline.
const cloud = backend === 'cloud'
- const cloudPick = cloud ? referenceModel(intent, { cloudImageModel, cloudVideoModel, cloudOpModel }) : undefined
- const slots = cloud
- ? (cloudPick ? studioExtraPhotoSlots(cloudPick) : 0)
- : intent === 'edit' ? extraReferenceSlots(listedType ?? classifyModel(imageModel), imageModel) : 0
+ const slots = useReferenceSlots()
if (slots === 0) return null
const shown = references.slice(0, slots)
const canAdd = shown.length < slots
@@ -131,6 +121,21 @@ export function ReferenceStrip() {
? `Add up to ${slots} more images, for example a person or an outfit to bring into this one.`
: `Name them in the prompt as ${shown.map((_, i) => `image ${i + 2}`).join(', ')}.`}
</p>
+ {/* A character saved from a video (lib/saved-characters) loads its photos
+ here with one click: the first becomes the source, the rest fill the
+ strip. */}
+ <SavedCharacterChips
+ label="Saved characters"
+ disabled={loading}
+ title={(c) => `Load the photos of ${c.name}`}
+ onPick={(c) => {
+ setLoading(true)
+ setError(null)
+ void loadPhotosAsReferences(c.name, c.photos)
+ .catch((err: unknown) => setError(`Could not load the photos: ${err instanceof Error ? err.message : String(err)}`))
+ .finally(() => setLoading(false))
+ }}
+ />
<input
ref={inputRef}
type="file"
diff --git a/src/components/create/experimental/SaveCharacterModal.tsx b/src/components/create/experimental/SaveCharacterModal.tsx
new file mode 100644
index 00000000..c9721632
--- /dev/null
+++ b/src/components/create/experimental/SaveCharacterModal.tsx
@@ -0,0 +1,206 @@
+// "Save character from this video" (Discord, applejames): pause the clip on a
+// clear view of the figure, add that frame, repeat for a few angles, name the
+// character. The frames are saved as photos on this machine
+// (lib/saved-characters) and can go straight on to the reference strip or to
+// Character Studio.
+import { useEffect, useRef, useState } from 'react'
+import { Camera, Loader2, UserRound, Images, X } from 'lucide-react'
+import { useCreateStore, type GalleryItem } from '../../../stores/createStore'
+import { isMlxImageHost } from '../../../api/mlx-image'
+import { MAX_CHARACTER_NAME, MAX_CHARACTER_PHOTOS, saveCharacter, type SaveResult } from '../../../lib/saved-characters'
+import { grabFrame } from '../../../lib/video-frames'
+import { MIN_TRAIN_IMAGES } from '../../../lib/train-image-cap'
+import { Modal } from '../../ui/Modal'
+import { Button } from '../ui/Button'
+import { fetchGalleryItemBlob, proxiedComfyBlobUrl } from './galleryUrl'
+import { isIntentAvailable } from './intents'
+import { loadPhotosAsReferences, sendPhotosToStudio } from './characterPhotos'
+
+interface Frame { url: string; blob: Blob }
+
+/** The clip as a blob: URL of the app's own origin, the only kind of video a
+ * canvas may read a frame back from. */
+async function playableUrl(item: GalleryItem): Promise<string> {
+ if (item.dataUrl?.startsWith('blob:')) {
+ // A local MLX clip is one already. Copy it, so closing this window never
+ // revokes the URL the gallery still plays.
+ return URL.createObjectURL(await (await fetch(item.dataUrl)).blob())
+ }
+ try {
+ return URL.createObjectURL(await fetchGalleryItemBlob(item))
+ } catch (err) {
+ // A ComfyUI that refuses the direct load still answers through the proxy.
+ const proxied = await proxiedComfyBlobUrl(item)
+ if (proxied) return proxied
+ throw err
+ }
+}
+
+export function SaveCharacterModal({ item, onClose }: { item: GalleryItem | null; onClose: () => void }) {
+ return (
+ <Modal open={!!item} onClose={onClose} title="Save character from this video" maxWidth="max-w-2xl">
+ {item && <SaveCharacterBody key={item.id} item={item} onClose={onClose} />}
+ </Modal>
+ )
+}
+
+function SaveCharacterBody({ item, onClose }: { item: GalleryItem; onClose: () => void }) {
+ const backend = useCreateStore((s) => s.backend)
+ const videoRef = useRef<HTMLVideoElement>(null)
+ const [src, setSrc] = useState<string | null>(null)
+ const [loadError, setLoadError] = useState<string | null>(null)
+ const [frames, setFrames] = useState<Frame[]>([])
+ const [name, setName] = useState('')
+ const [note, setNote] = useState<string | null>(null)
+ const [busy, setBusy] = useState(false)
+ const [saved, setSaved] = useState<SaveResult | null>(null)
+ // Every preview URL this window minted, given back when it closes.
+ const minted = useRef<string[]>([])
+
+ useEffect(() => {
+ let alive = true
+ const urls = minted.current
+ void playableUrl(item).then((url) => {
+ if (!alive) { URL.revokeObjectURL(url); return }
+ urls.push(url)
+ setSrc(url)
+ }).catch((err: unknown) => {
+ if (alive) setLoadError(`Could not load this video: ${err instanceof Error ? err.message : String(err)}`)
+ })
+ return () => {
+ alive = false
+ for (const u of urls) URL.revokeObjectURL(u)
+ urls.length = 0
+ }
+ }, [item])
+
+ const full = frames.length >= MAX_CHARACTER_PHOTOS
+ const addFrame = async () => {
+ const video = videoRef.current
+ if (!video || full) return
+ video.pause()
+ setNote(null)
+ try {
+ const blob = await grabFrame(video)
+ const url = URL.createObjectURL(blob)
+ minted.current.push(url)
+ setFrames((f) => [...f, { url, blob }])
+ setSaved(null)
+ } catch (err) {
+ setNote(err instanceof Error ? err.message : String(err))
+ }
+ }
+
+ const save = async () => {
+ setBusy(true)
+ setNote(null)
+ try {
+ setSaved(await saveCharacter(name, frames.map((f) => f.blob)))
+ setFrames([])
+ } catch (err) {
+ setNote(err instanceof Error ? err.message : String(err))
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ const mlx = isMlxImageHost()
+ const canReference = isIntentAvailable('edit', backend, mlx)
+ const canTrain = isIntentAvailable('character', backend, mlx)
+ const asReferences = async () => {
+ if (!saved) return
+ setBusy(true)
+ try {
+ await loadPhotosAsReferences(saved.character.name, saved.character.photos)
+ onClose()
+ } catch (err) {
+ setNote(`Could not load the photos: ${err instanceof Error ? err.message : String(err)}`)
+ } finally {
+ setBusy(false)
+ }
+ }
+ const toStudio = () => {
+ if (!saved) return
+ sendPhotosToStudio(saved.character.name, saved.character.photos)
+ onClose()
+ }
+
+ return (
+ <div className="flex flex-col gap-3" data-testid="save-character">
+ {loadError ? (
+ <p className="t-body text-red-300">{loadError}</p>
+ ) : !src ? (
+ <div className="h-48 flex items-center justify-center t-control text-gray-400 gap-2"><Loader2 size={14} className="animate-spin" /> Loading the video…</div>
+ ) : (
+ <video ref={videoRef} src={src} controls loop muted playsInline className="w-full max-h-[44vh] rounded-lg bg-black object-contain" />
+ )}
+
+ <div className="flex items-center gap-3">
+ <div className="shrink-0 whitespace-nowrap">
+ <Button variant="secondary" icon={Camera} disabled={!src || full || busy} onClick={() => { void addFrame() }}>Add this frame</Button>
+ </div>
+ <span className="t-body text-gray-500">
+ {full
+ ? `That is the most a character keeps (${MAX_CHARACTER_PHOTOS}).`
+ : 'Pause on a clear view of the figure and add it. A few different angles work best.'}
+ </span>
+ </div>
+
+ {frames.length > 0 && (
+ <div className="flex flex-wrap gap-2" data-testid="character-frames">
+ {frames.map((f, i) => (
+ <div key={f.url} className="relative w-16 h-16">
+ <img src={f.url} alt={`frame ${i + 1}`} className="w-16 h-16 rounded-lg object-cover border border-white/[0.06]" />
+ <button
+ onClick={() => setFrames((list) => list.filter((x) => x.url !== f.url))}
+ className="absolute top-1 right-1 w-5 h-5 flex items-center justify-center rounded-md bg-black/60 text-gray-300 hover:text-white"
+ title={`Remove frame ${i + 1}`}
+ aria-label={`Remove frame ${i + 1}`}
+ >
+ <X size={11} />
+ </button>
+ </div>
+ ))}
+ </div>
+ )}
+
+ <div className="flex items-center gap-2">
+ <input
+ value={name}
+ onChange={(e) => setName(e.target.value.slice(0, MAX_CHARACTER_NAME))}
+ placeholder="Character name"
+ aria-label="Character name"
+ className="flex-1 min-w-0 h-[var(--control-h-md)] px-2.5 rounded-[var(--radius-control)] bg-white/[0.04] border border-white/[0.08] focus:border-white/20 outline-none t-control text-gray-100"
+ />
+ <Button variant="primary" loading={busy} disabled={frames.length === 0 || name.trim().length === 0} onClick={() => { void save() }}>
+ Save character
+ </Button>
+ </div>
+
+ {note && <p className="t-body text-red-300" data-testid="save-character-note">{note}</p>}
+
+ {saved && (
+ <div className="flex flex-col gap-2 rounded-lg bg-white/[0.03] border border-white/[0.06] p-3" data-testid="character-saved">
+ <p className="t-body text-gray-200">
+ {saved.merged
+ ? `Added ${saved.added} ${saved.added === 1 ? 'photo' : 'photos'} to ${saved.character.name}, ${saved.character.photos.length} in all.`
+ : `Saved ${saved.character.name} with ${saved.added} ${saved.added === 1 ? 'photo' : 'photos'}.`}
+ {saved.dropped > 0 ? ` ${saved.dropped} did not fit, a character keeps up to ${MAX_CHARACTER_PHOTOS}.` : ''}
+ {' '}It is kept on this computer.
+ </p>
+ <div className="flex flex-wrap items-center gap-2">
+ {canReference && (
+ <Button variant="secondary" icon={Images} disabled={busy} onClick={() => { void asReferences() }}>Use as reference photos</Button>
+ )}
+ {canTrain && (
+ <Button variant="secondary" icon={UserRound} disabled={busy} onClick={toStudio}>Train in Character Studio</Button>
+ )}
+ </div>
+ {canTrain && saved.character.photos.length < MIN_TRAIN_IMAGES && (
+ <p className="t-body text-gray-500">Training needs at least {MIN_TRAIN_IMAGES} photos. Add more frames or more photos there.</p>
+ )}
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/src/components/create/experimental/SavedCharacters.tsx b/src/components/create/experimental/SavedCharacters.tsx
new file mode 100644
index 00000000..5f438b68
--- /dev/null
+++ b/src/components/create/experimental/SavedCharacters.tsx
@@ -0,0 +1,91 @@
+// The saved characters as a row of chips: one click loads a character's
+// photos. Shown at the reference strip and on the Character Studio board.
+import { useEffect, useState } from 'react'
+import { Trash2 } from 'lucide-react'
+import {
+ deleteSavedCharacter, listSavedCharacters, subscribeSavedCharacters, type SavedCharacter,
+} from '../../../lib/saved-characters'
+import { cn } from '../ui/cn'
+
+export interface SavedCharacterView extends SavedCharacter {
+ /** Preview of the first photo. */
+ thumb: string
+}
+
+/** The saved characters, kept current after every save and delete. */
+export function useSavedCharacters(): SavedCharacterView[] {
+ const [list, setList] = useState<SavedCharacterView[]>([])
+ useEffect(() => {
+ let alive = true
+ let urls: string[] = []
+ const load = () => {
+ void listSavedCharacters().then((rows) => {
+ if (!alive) return
+ const old = urls
+ const next = rows.filter((c) => c.photos.length > 0).map((c) => ({ ...c, thumb: URL.createObjectURL(c.photos[0]) }))
+ urls = next.map((n) => n.thumb)
+ setList(next)
+ for (const u of old) URL.revokeObjectURL(u)
+ }).catch(() => { /* no list is not an error worth a banner */ })
+ }
+ load()
+ const off = subscribeSavedCharacters(load)
+ return () => {
+ alive = false
+ off()
+ for (const u of urls) URL.revokeObjectURL(u)
+ }
+ }, [])
+ return list
+}
+
+export function SavedCharacterChips({ label, title, onPick, disabled }: {
+ label: string
+ /** Tooltip of a chip, given the character. */
+ title: (c: SavedCharacter) => string
+ onPick: (c: SavedCharacter) => void
+ disabled?: boolean
+}) {
+ const list = useSavedCharacters()
+ const [confirm, setConfirm] = useState<string | null>(null)
+ if (list.length === 0) return null
+ return (
+ <div className="flex flex-col items-center gap-1.5 max-w-full" data-testid="saved-characters">
+ <span className="t-label text-gray-600">{label}</span>
+ <div className="flex flex-wrap justify-center gap-1.5">
+ {list.map((c) => (
+ <div key={c.id} className="group relative flex items-center rounded-full bg-white/[0.04] border border-white/[0.06] hover:border-white/15 transition-colors">
+ <button
+ onClick={() => onPick(c)}
+ disabled={disabled}
+ title={title(c)}
+ className={cn('flex items-center gap-1.5 pl-1 pr-2 py-1 t-control text-gray-300 hover:text-white', disabled && 'opacity-50 cursor-not-allowed')}
+ >
+ <img src={c.thumb} alt="" className="w-6 h-6 rounded-full object-cover" />
+ <span className="truncate max-w-[9rem]">{c.name}</span>
+ <span className="t-micro text-gray-500">{c.photos.length}</span>
+ </button>
+ {confirm === c.id ? (
+ <button
+ onClick={() => { setConfirm(null); void deleteSavedCharacter(c.id) }}
+ onBlur={() => setConfirm(null)}
+ className="pr-2 t-control text-red-300 hover:text-red-200"
+ >
+ Delete?
+ </button>
+ ) : (
+ <button
+ onClick={() => setConfirm(c.id)}
+ title={`Delete ${c.name}`}
+ aria-label={`Delete ${c.name}`}
+ className="pr-2 text-gray-600 hover:text-gray-300 opacity-0 group-hover:opacity-100 focus:opacity-100 transition-opacity"
+ >
+ <Trash2 size={11} />
+ </button>
+ )}
+ </div>
+ ))}
+ </div>
+ </div>
+ )
+}
diff --git a/src/components/create/experimental/Stage.tsx b/src/components/create/experimental/Stage.tsx
index 9fb62ab3..ce85953d 100644
--- a/src/components/create/experimental/Stage.tsx
+++ b/src/components/create/experimental/Stage.tsx
@@ -22,6 +22,12 @@ import { isMlxImageHost } from '../../../api/mlx-image'
import { bundleForVideoIntent } from '../../../api/comfyui'
import { getVideoBundles } from '../../../api/discover'
import { ReferenceStrip } from './ReferenceStrip'
+import { BatchStrip, useBatchPickers } from './BatchStrip'
+import { addBatchFiles, useBatchOffered } from './batchRun'
+import { filesFromDrop } from './batchFiles'
+import { useReferenceSlots } from './referenceSlots'
+import { SavedCharacterChips } from './SavedCharacters'
+import { loadPhotosAsReferences, sendPhotosToStudio } from './characterPhotos'
import { MIN_TRAIN_IMAGES, maxTrainImages } from '../../../lib/train-image-cap'
interface Props {
@@ -37,14 +43,18 @@ interface Props {
* as onEditResult above. */
onAnimateResult?: (item: GalleryItem) => void
onFullscreen: (item: GalleryItem) => void
+ /** Pick frames of a finished video and save them as a character. */
+ onSaveCharacter?: (item: GalleryItem) => void
/** ComfyUI is coming up: no setup card in that window (./stageGate). */
comfyStarting?: boolean
}
-export function Stage({ displayed, onOpenMaskEditor, onEditResult, onAnimateResult, onFullscreen, comfyStarting }: Props) {
+export function Stage({ displayed, onOpenMaskEditor, onEditResult, onAnimateResult, onFullscreen, onSaveCharacter, comfyStarting }: Props) {
const intent = useCreateStore((s) => s.intent())
const meta = INTENT_MAP[intent]
- const isGenerating = useCreateStore((s) => s.isGenerating)
+ // A batch over several source images is one stretch of work: between two of
+ // its images nothing is rendering, and the Stage must not flash back.
+ const isGenerating = useCreateStore((s) => s.isGenerating || s.batchRun !== null)
const source = useCreateStore((s) => s.source)
const sourceSetAt = useCreateStore((s) => s.sourceSetAt)
const setPrompt = useCreateStore((s) => s.setPrompt)
@@ -129,6 +139,7 @@ export function Stage({ displayed, onOpenMaskEditor, onEditResult, onAnimateResu
onFullscreen={() => onFullscreen(displayed)}
onSendToEditor={displayed.type === 'image' && onEditResult ? () => onEditResult(displayed) : undefined}
onAnimate={displayed.type === 'image' && onAnimateResult ? () => onAnimateResult(displayed) : undefined}
+ onSaveCharacter={displayed.type === 'video' && onSaveCharacter ? () => onSaveCharacter(displayed) : undefined}
/>
)
} else {
@@ -208,6 +219,12 @@ function InputSlot() {
const inputRef = useRef<HTMLInputElement>(null)
const [drag, setDrag] = useState(false)
const [loading, setLoading] = useState(false)
+ // Edit, Remove Background and Enhance Image take several images at once
+ // where no mask is needed (lib/batch-edit).
+ const batchOffered = useBatchOffered()
+ // A model that reads several photos of a figure can start from a saved
+ // character (lib/saved-characters) instead of a file.
+ const referenceSlots = useReferenceSlots()
// David 2026-07-10: ops never auto-adopt a gallery image — instead the slot
// offers the recent gallery images as an EXPLICIT pick, next to drag&drop
@@ -248,6 +265,15 @@ function InputSlot() {
}
}
+ // More than one file: the list. One file: the plain single source.
+ const handleFiles = async (files: File[]) => {
+ if (files.length === 0) return
+ if (!batchOffered || files.length === 1) return handleFile(files[0])
+ setLoading(true)
+ try { await addBatchFiles(files) } finally { setLoading(false) }
+ }
+ const { inputs: batchInputs, pickFiles, pickFolder } = useBatchPickers((files) => { void handleFiles(files) })
+
return (
// Scroll-safe centering: `m-auto` centres the column when there's room and
// collapses to a scroll when the dropzone + gallery strip exceed a short
@@ -256,14 +282,13 @@ function InputSlot() {
<div className="flex-1 min-h-0 overflow-y-auto scrollbar-thin flex flex-col">
<div className="m-auto w-full max-w-sm flex flex-col items-center p-6">
<div
- onClick={() => inputRef.current?.click()}
+ onClick={() => (batchOffered ? pickFiles() : inputRef.current?.click())}
onDragOver={(e) => { e.preventDefault(); setDrag(true) }}
onDragLeave={() => setDrag(false)}
onDrop={(e) => {
e.preventDefault()
setDrag(false)
- const f = e.dataTransfer.files[0]
- if (f) { void handleFile(f); return }
+ if (e.dataTransfer.files.length) { void filesFromDrop(e.dataTransfer).then(handleFiles); return }
const item = gallery.find((g) => g.id === e.dataTransfer.getData(GALLERY_DRAG_TYPE))
if (item && !loading) void adoptFromGallery(item)
}}
@@ -284,9 +309,38 @@ function InputSlot() {
<div className="text-center">
<div className="t-title text-gray-300">{meta.id === 'removebg' ? 'Drop an image to cut out' : meta.id === 'animate' ? 'Drop an image to animate' : 'Drop an image to edit'}</div>
<div className="t-body text-gray-600">or click to browse · PNG, JPG, WebP</div>
+ {batchOffered && <div className="t-body text-gray-600">Pick several to give them all the same run</div>}
</div>
<input ref={inputRef} type="file" accept="image/*" className="hidden" onChange={(e) => { const f = e.target.files?.[0]; if (f) handleFile(f) }} />
</div>
+ {batchOffered && (
+ <>
+ {batchInputs}
+ <button
+ onClick={pickFolder}
+ disabled={loading}
+ className="mt-2 t-control text-gray-500 hover:text-gray-300 underline underline-offset-2 transition-colors"
+ >
+ or choose a folder of images
+ </button>
+ </>
+ )}
+ {referenceSlots > 0 && (
+ <div className="mt-4 w-full">
+ <SavedCharacterChips
+ label="or start from a saved character"
+ disabled={loading}
+ title={(c) => `Load the photos of ${c.name}`}
+ onPick={(c) => {
+ setLoading(true)
+ setError(null)
+ void loadPhotosAsReferences(c.name, c.photos)
+ .catch((err: unknown) => setError(`Could not load the photos: ${err instanceof Error ? err.message : String(err)}`))
+ .finally(() => setLoading(false))
+ }}
+ />
+ </div>
+ )}
{galleryImages.length > 0 && (
<div className="mt-4 w-full">
<div className="t-label text-gray-600 mb-2 text-center">or pick from your gallery</div>
@@ -318,14 +372,27 @@ function SourcePreview({ onOpenMaskEditor }: { onOpenMaskEditor: () => void }) {
const setMask = useCreateStore((s) => s.setMask)
const intent = useCreateStore((s) => s.intent())
const meta = INTENT_MAP[intent]
+ const batchCount = useCreateStore((s) => s.batchSources.length)
+ const batchOffered = useBatchOffered()
+ // The same run over several images: no mask (it belongs to one image), and
+ // the list below replaces "Change image".
+ const batchOn = batchOffered && batchCount > 1
// Zombie render: an intent switch drops the source in the same store update
// that swaps this component out, but the child subscription can fire first.
if (!source) return null
return (
- <div className="flex-1 min-h-0 overflow-y-auto scrollbar-thin flex flex-col">
- <div className="m-auto flex flex-col items-center p-6">
+ <div
+ className="flex-1 min-h-0 overflow-y-auto scrollbar-thin flex flex-col"
+ onDragOver={(e) => { if (batchOffered && e.dataTransfer.types.includes('Files')) e.preventDefault() }}
+ onDrop={(e) => {
+ if (!batchOffered || !e.dataTransfer.files.length) return
+ e.preventDefault()
+ void filesFromDrop(e.dataTransfer).then(addBatchFiles)
+ }}
+ >
+ <div className="m-auto flex flex-col items-center p-6 max-w-full">
<div className="relative">
<img src={source.url} alt="source" className={cn('max-h-[52vh] max-w-full object-contain rounded-[var(--radius-panel)] border border-white/[0.06]', intent === 'removebg' && 'lu-checker')} />
{mask && (
@@ -340,14 +407,21 @@ function SourcePreview({ onOpenMaskEditor }: { onOpenMaskEditor: () => void }) {
</button>
</div>
<ReferenceStrip />
- <div className="flex items-center gap-2 mt-4">
- {meta.allowsMask && (
- <Button variant="secondary" icon={Wand2} onClick={onOpenMaskEditor}>{mask ? 'Edit mask' : 'Paint mask'}</Button>
- )}
- <ChangeImageButton onChange={(r) => setSource(r)} />
- </div>
+ {!batchOn && (
+ <div className="flex items-center gap-2 mt-4">
+ {meta.allowsMask && (
+ <Button variant="secondary" icon={Wand2} onClick={onOpenMaskEditor}>{mask ? 'Edit mask' : 'Paint mask'}</Button>
+ )}
+ <ChangeImageButton onChange={(r) => setSource(r)} />
+ </div>
+ )}
+ <BatchStrip />
<p className="t-body text-gray-600 mt-3 text-center max-w-sm">
- {meta.id === 'removebg' ? 'Hit Create to cut out the subject and export a transparent PNG.'
+ {batchOn ? (
+ meta.id === 'removebg' ? `Hit Create to cut out all ${batchCount} images.`
+ : meta.id === 'upscale' ? `Hit Create to upscale all ${batchCount} images.`
+ : `Write your prompt below, then Create. All ${batchCount} images get the same edit.`
+ ) : meta.id === 'removebg' ? 'Hit Create to cut out the subject and export a transparent PNG.'
: meta.id === 'upscale' ? 'Hit Create to upscale the image.'
: meta.id === 'eraser' ? 'Paint a mask over the object to remove, then hit Create.'
: meta.allowsMask ? 'Leave the mask empty to restyle the whole image, or paint an area to change just that. Write your prompt below, then Create.'
@@ -653,7 +727,13 @@ function TrainSetBoard() {
One person or character, varied angles and lighting works best
</div>
</button>
- ) : (
+ ) : null}
+ <SavedCharacterChips
+ label={trainImages.length === 0 ? 'or start from a saved character' : 'Add the photos of a saved character'}
+ title={(c) => `Add the ${c.photos.length} photos of ${c.name}`}
+ onPick={(c) => sendPhotosToStudio(c.name, c.photos)}
+ />
+ {trainImages.length === 0 ? null : (
<>
<div className="flex-1 min-h-0 overflow-y-auto scrollbar-thin">
<div className="grid grid-cols-4 sm:grid-cols-6 gap-2">
diff --git a/src/components/create/experimental/__tests__/batch-surface.test.tsx b/src/components/create/experimental/__tests__/batch-surface.test.tsx
new file mode 100644
index 00000000..f3d194fc
--- /dev/null
+++ b/src/components/create/experimental/__tests__/batch-surface.test.tsx
@@ -0,0 +1,291 @@
+// @vitest-environment jsdom
+/**
+ * Several source images, one edit: what the source surface shows and what a
+ * local run does with the list. The cloud bookings are proven in
+ * hooks/__tests__/useCloudCreate-batch.test.ts.
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import { render, cleanup, screen, fireEvent, waitFor } from '@testing-library/react'
+
+const ctx = vi.hoisted(() => ({
+ quota: {
+ tier: 'hosted-max', period: '2026-10-01', renewsAt: '2026-11-01T00:00:00.000Z',
+ limits: { credits: 500000 }, costs: { image: 300, video: 10000 }, used: { credits_used: 0 }, remaining: { credits: 500000 },
+ topup: { credits: 0 }, video: { limit: 500000, used: 0, remaining: 500000 }, trainings: { limit: 3, used: 0, remaining: 3 },
+ },
+}))
+vi.mock('../CreateContext', () => ({
+ useCreateExp: () => ({
+ generate: vi.fn(), cancel: vi.fn(), makeVoice: vi.fn(), quota: ctx.quota,
+ samplerList: [], schedulerList: [], loraList: [], vaeList: [], refreshModelLists: vi.fn(),
+ connected: true, modelsLoaded: true, mlxMissing: false,
+ installCapability: vi.fn(), installModelBundle: vi.fn(),
+ }),
+}))
+vi.mock('../loadImage', () => ({
+ loadImageRef: vi.fn(async (f: File) => {
+ if (f.name.startsWith('broken')) throw new Error('the image could not be decoded, use PNG, JPG or WebP')
+ return { filename: `up_${f.name}`, url: `data:image/png;base64,${btoa(f.name)}`, width: 64, height: 64 }
+ }),
+}))
+vi.mock('../../../../api/mlx-image', () => ({ isMlxImageHost: () => false }))
+vi.mock('../../../../api/backend', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../../../../api/backend')>()),
+ openExternal: vi.fn(),
+}))
+vi.mock('../../../../hooks/useCloudCreate', () => ({
+ resolveCharacterModel: () => undefined,
+ takeCloudRunStop: () => null,
+ dataUrlToBlob: (url: string) => new Blob([url], { type: 'image/png' }),
+}))
+
+import { Stage } from '../Stage'
+import { BatchQueue, BatchStrip } from '../BatchStrip'
+import { ResultView } from '../OutputView'
+import { addBatchFiles, removeBatchEntry, requestBatchStop, runBatchEdit } from '../batchRun'
+import { topLevelFiles } from '../batchFiles'
+import { useCreateStore, type GalleryItem } from '../../../../stores/createStore'
+import { useCloudCatalogStore } from '../../../../stores/cloudCatalogStore'
+import { neuerServer } from '../../../../lib/render/__tests__/fixtures/test-catalogs'
+
+const png = (name: string) => new File([name], name, { type: 'image/png' })
+const names = () => useCreateStore.getState().batchSources.map((b) => b.name)
+let minted = 0
+
+function start(backend: 'local' | 'cloud', intent: 'edit' | 'removebg' | 'upscale' | 'eraser') {
+ useCreateStore.setState({ backend, caps: { rmbg: true, 'inpaint-nodes': true } as never })
+ useCreateStore.getState().setIntent(intent)
+}
+
+const item = (id: string): GalleryItem => ({
+ id, type: 'image', filename: `${id}.png`, subfolder: '', prompt: '', negativePrompt: '', model: 'm', modelType: 'sdxl',
+ seed: 1, steps: 1, cfgScale: 1, sampler: '', scheduler: '', width: 8, height: 8, batchSize: 1, createdAt: Date.now(),
+ dataUrl: 'data:image/png;base64,AA',
+})
+
+beforeEach(() => {
+ minted = 0
+ vi.stubGlobal('URL', Object.assign(URL, {
+ createObjectURL: vi.fn(() => `blob:test/${++minted}`),
+ revokeObjectURL: vi.fn(),
+ }))
+ ctx.quota.remaining.credits = 500000
+ useCloudCatalogStore.setState({ models: neuerServer() })
+ useCreateStore.setState({
+ backend: 'cloud', isGenerating: false, error: null, source: null, mask: null, references: [],
+ batchSources: [], batchRun: null, gallery: [], cloudStudioOptions: {}, cloudStudioCredits: null, cloudImageCount: 1,
+ imageModelList: [], videoModelList: [],
+ })
+})
+afterEach(() => { cleanup() })
+
+describe('picking several images at the source surface', () => {
+ it('several files in the picker become the list, the first one is the large image', async () => {
+ start('cloud', 'removebg')
+ render(<Stage onOpenMaskEditor={vi.fn()} onFullscreen={vi.fn()} />)
+ expect(screen.getByText('Pick several to give them all the same run')).toBeTruthy()
+ fireEvent.change(screen.getByTestId('batch-files-input'), { target: { files: [png('b.png'), png('a.png'), png('c.png')] } })
+ await screen.findByTestId('batch-strip')
+ await waitFor(() => expect(screen.getByTestId('batch-count').textContent).toContain('3 images.'))
+ expect(names()).toEqual(['a.png', 'b.png', 'c.png'])
+ expect(atob(useCreateStore.getState().source!.url.split(',')[1])).toBe('a.png')
+ expect(screen.getByText('Hit Create to cut out all 3 images.')).toBeTruthy()
+ // The list replaces "Change image", there is no mask to paint.
+ expect(screen.queryByText('Change image')).toBeNull()
+ expect(screen.queryByText('Paint mask')).toBeNull()
+ })
+
+ it('one file is the plain single source, as before', async () => {
+ start('cloud', 'removebg')
+ render(<Stage onOpenMaskEditor={vi.fn()} onFullscreen={vi.fn()} />)
+ fireEvent.change(screen.getByTestId('batch-files-input'), { target: { files: [png('only.png')] } })
+ await waitFor(() => expect(useCreateStore.getState().source).not.toBeNull())
+ expect(names()).toEqual([])
+ expect(screen.queryByTestId('batch-count')).toBeNull()
+ expect(screen.getByText('Add more images')).toBeTruthy()
+ })
+
+ it('"Add more images" on a single source keeps it as the first of the list', async () => {
+ start('cloud', 'removebg')
+ useCreateStore.getState().setSource({ filename: '', url: 'data:image/png;base64,AA', width: 8, height: 8 })
+ await addBatchFiles([png('x.png'), png('y.png')])
+ expect(names()).toEqual(['image 1.png', 'x.png', 'y.png'])
+ })
+
+ it('a folder picker gives the images of the folder, not of the folders below it', () => {
+ const inFolder = (name: string, rel: string) => Object.defineProperty(png(name), 'webkitRelativePath', { value: rel })
+ const files = [inFolder('a.png', 'shots/a.png'), inFolder('deep.png', 'shots/old/deep.png'), inFolder('b.png', 'shots/b.png')]
+ expect(topLevelFiles(files).map((f) => f.name)).toEqual(['a.png', 'b.png'])
+ })
+
+ it('the empty slot offers a folder where a list can run, and not for Erase Object', () => {
+ start('cloud', 'removebg')
+ const { unmount } = render(<Stage onOpenMaskEditor={vi.fn()} onFullscreen={vi.fn()} />)
+ expect(screen.getByText('or choose a folder of images')).toBeTruthy()
+ expect(screen.getByTestId('batch-folder-input').hasAttribute('webkitdirectory')).toBe(true)
+ unmount()
+ start('cloud', 'eraser')
+ render(<Stage onOpenMaskEditor={vi.fn()} onFullscreen={vi.fn()} />)
+ expect(screen.queryByText('or choose a folder of images')).toBeNull()
+ expect(screen.queryByTestId('batch-files-input')).toBeNull()
+ })
+
+ it('a cloud Edit model that needs a mask takes one image only', () => {
+ start('cloud', 'edit')
+ useCreateStore.getState().setCloudImageModel('flux-dev')
+ const { unmount } = render(<Stage onOpenMaskEditor={vi.fn()} onFullscreen={vi.fn()} />)
+ expect(screen.queryByTestId('batch-files-input')).toBeNull()
+ unmount()
+ useCreateStore.getState().setCloudImageModel('qwen-image-edit')
+ render(<Stage onOpenMaskEditor={vi.fn()} onFullscreen={vi.fn()} />)
+ expect(screen.getByTestId('batch-files-input')).toBeTruthy()
+ })
+})
+
+describe('the list under the source', () => {
+ it('names the price of one image and the sum for all, from the same number the meter uses', async () => {
+ start('cloud', 'removebg')
+ await addBatchFiles([png('a.png'), png('b.png'), png('c.png')])
+ render(<BatchStrip />)
+ const text = screen.getByTestId('batch-price').textContent!
+ const [, per, sum, n] = text.match(/^([\d,]+) credits per image, ([\d,]+) credits for all (\d+)\./)!
+ const perImage = Number(per.replace(/,/g, ''))
+ expect(perImage).toBeGreaterThan(0)
+ expect(Number(sum.replace(/,/g, ''))).toBe(perImage * 3)
+ expect(n).toBe('3')
+ expect(text).not.toContain('Your credits cover')
+ })
+
+ it('says how many images the credits cover when they do not cover all', async () => {
+ start('cloud', 'removebg')
+ await addBatchFiles([png('a.png'), png('b.png'), png('c.png'), png('d.png')])
+ const first = render(<BatchStrip />)
+ const perImage = Number(screen.getByTestId('batch-price').textContent!.match(/^([\d,]+)/)![1].replace(/,/g, ''))
+ first.unmount()
+ ctx.quota.remaining.credits = perImage * 2 + 1
+ render(<BatchStrip />)
+ expect(screen.getByTestId('batch-price').textContent).toContain('Your credits cover 2 of them. The rest will not run and is not charged.')
+ })
+
+ it('a local list shows no price', async () => {
+ start('local', 'removebg')
+ await addBatchFiles([png('a.png'), png('b.png')])
+ render(<BatchStrip />)
+ expect(screen.getByTestId('batch-count').textContent).toContain('2 images.')
+ expect(screen.queryByTestId('batch-price')).toBeNull()
+ })
+
+ it('removing images shrinks the list, and one image left is a single source again', async () => {
+ start('cloud', 'removebg')
+ await addBatchFiles([png('a.png'), png('b.png'), png('c.png')])
+ render(<BatchStrip />)
+ fireEvent.click(screen.getByLabelText('Remove a.png'))
+ await waitFor(() => expect(names()).toEqual(['b.png', 'c.png']))
+ await waitFor(() => expect(atob(useCreateStore.getState().source!.url.split(',')[1])).toBe('b.png'))
+ await removeBatchEntry(1)
+ expect(names()).toEqual([])
+ expect(useCreateStore.getState().source).not.toBeNull()
+ })
+
+ it('a list left over under a mask model says that only one image runs', async () => {
+ start('cloud', 'edit')
+ useCreateStore.getState().setCloudImageModel('qwen-image-edit')
+ await addBatchFiles([png('a.png'), png('b.png'), png('c.png')])
+ useCreateStore.getState().setCloudImageModel('flux-dev')
+ render(<BatchStrip />)
+ expect(screen.getByText(/needs a painted mask for each image/)).toBeTruthy()
+ expect(screen.queryByTestId('batch-price')).toBeNull()
+ fireEvent.click(screen.getByText('Remove the other 2'))
+ expect(names()).toEqual([])
+ })
+
+ it('removing the source image drops the whole list', async () => {
+ start('cloud', 'removebg')
+ await addBatchFiles([png('a.png'), png('b.png')])
+ useCreateStore.getState().setSource(null)
+ expect(names()).toEqual([])
+ })
+})
+
+describe('the queue while it runs', () => {
+ it('says which image is on and how the others stand', () => {
+ useCreateStore.setState({
+ batchRun: { index: 2, statuses: ['done', 'failed', 'running', 'waiting'], names: ['a.png', 'b.png', 'c.png', 'd.png'], thumbs: ['blob:1', 'blob:2', 'blob:3', 'blob:4'] },
+ })
+ render(<BatchQueue />)
+ expect(screen.getByTestId('batch-progress').textContent).toBe('Image 3 of 4')
+ expect(screen.getByText('c.png')).toBeTruthy()
+ expect(screen.getByText('1 done, 1 failed. Cancel stops the rest.')).toBeTruthy()
+ })
+
+ it('the Stage stays on the queue between two images of a batch', () => {
+ start('cloud', 'removebg')
+ useCreateStore.setState({
+ isGenerating: false,
+ batchRun: { index: 0, statuses: ['done', 'waiting'], names: ['a.png', 'b.png'], thumbs: ['blob:1', 'blob:2'] },
+ })
+ render(<Stage onOpenMaskEditor={vi.fn()} onFullscreen={vi.fn()} />)
+ expect(screen.getByTestId('batch-queue')).toBeTruthy()
+ })
+})
+
+describe('a local run over the list', () => {
+ // The local generate(), reduced to what the batch reads from it: a result in
+ // the gallery, or an error in the store.
+ const localRun = (fail: string[] = []) => vi.fn(async () => {
+ const s = useCreateStore.getState()
+ const name = atob(s.source!.url.split(',')[1])
+ if (fail.includes(name)) { s.setError(`Generation failed: ${name}`); return }
+ s.addToGallery(item(`r-${name}`))
+ })
+
+ it('runs every image with the same settings and ties each result to its file', async () => {
+ start('local', 'edit')
+ await addBatchFiles([png('a.png'), png('b.png'), png('c.png')])
+ useCreateStore.getState().setMask({ filename: 'm.png', url: 'data:image/png;base64,M', width: 8, height: 8 })
+ const run = localRun()
+ await runBatchEdit(run)
+ expect(run).toHaveBeenCalledTimes(3)
+ const s = useCreateStore.getState()
+ expect(s.gallery.map((g) => `${g.id}<${g.sourceName}`).sort()).toEqual(['r-a.png<a.png', 'r-b.png<b.png', 'r-c.png<c.png'])
+ expect(s.mask).toBeNull()
+ expect(s.batchSources).toEqual([])
+ expect(s.batchRun).toBeNull()
+ expect(s.error).toBeNull()
+ })
+
+ it('a failing image does not stop the others and stays in the list with an image that would not load', async () => {
+ start('local', 'removebg')
+ await addBatchFiles([png('a.png'), png('b.png'), png('c.png'), png('broken.png')])
+ const run = localRun(['b.png'])
+ await runBatchEdit(run)
+ expect(run).toHaveBeenCalledTimes(3)
+ const s = useCreateStore.getState()
+ expect(s.gallery).toHaveLength(2)
+ expect(names()).toEqual(['b.png', 'broken.png'])
+ expect(s.error).toBe(
+ '2 of 4 images are done. 2 failed: b.png, broken.png. First error: Generation failed: b.png. ' +
+ 'What is left stays ready, hit Create to run it.',
+ )
+ })
+
+ it('Cancel between two images starts nothing further', async () => {
+ start('local', 'removebg')
+ await addBatchFiles([png('a.png'), png('b.png'), png('c.png')])
+ const run = vi.fn(async () => {
+ useCreateStore.getState().addToGallery(item(`r-${run.mock.calls.length}`))
+ requestBatchStop()
+ })
+ await runBatchEdit(run)
+ expect(run).toHaveBeenCalledTimes(1)
+ expect(names()).toEqual(['b.png', 'c.png'])
+ expect(useCreateStore.getState().error).toContain('Stopped. The other 2 were not started.')
+ })
+})
+
+describe('a result made from a list', () => {
+ it('shows the file it came from', () => {
+ render(<ResultView item={{ ...item('r1'), sourceName: 'holiday 12.jpg' }} onFullscreen={vi.fn()} />)
+ expect(screen.getByTestId('source-name').textContent).toBe('from holiday 12.jpg')
+ })
+})
diff --git a/src/components/create/experimental/__tests__/save-character.test.tsx b/src/components/create/experimental/__tests__/save-character.test.tsx
new file mode 100644
index 00000000..8535bf01
--- /dev/null
+++ b/src/components/create/experimental/__tests__/save-character.test.tsx
@@ -0,0 +1,199 @@
+// @vitest-environment jsdom
+/**
+ * "Save character from this video" (Discord, applejames): frames picked from a
+ * video become a named character kept on this machine, and that character
+ * loads into the reference strip or starts a set in Character Studio.
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import { render, cleanup, screen, fireEvent, waitFor } from '@testing-library/react'
+
+const grab = vi.hoisted(() => ({ n: 0, fail: null as string | null }))
+vi.mock('../../../../lib/video-frames', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../../../../lib/video-frames')>()),
+ grabFrame: vi.fn(async () => {
+ if (grab.fail) throw new Error(grab.fail)
+ return new Blob([`frame-${++grab.n}`], { type: 'image/jpeg' })
+ }),
+}))
+vi.mock('../galleryUrl', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../galleryUrl')>()),
+ fetchGalleryItemBlob: vi.fn(async () => new Blob(['video'], { type: 'video/mp4' })),
+ proxiedComfyBlobUrl: vi.fn(async () => null),
+}))
+vi.mock('../loadImage', () => ({
+ loadImageRef: vi.fn(async (f: File) => ({ filename: `up_${f.name}`, url: `data:image/jpeg;base64,${btoa(f.name)}`, width: 64, height: 64 })),
+}))
+vi.mock('../../../../api/mlx-image', () => ({ isMlxImageHost: () => false }))
+vi.mock('../CreateContext', () => ({
+ useCreateExp: () => ({
+ generate: vi.fn(), cancel: vi.fn(), quota: null, enhanceVideo: vi.fn(),
+ connected: true, modelsLoaded: true, mlxMissing: false, installCapability: vi.fn(), installModelBundle: vi.fn(),
+ }),
+}))
+
+import { SaveCharacterModal } from '../SaveCharacterModal'
+import { ReferenceStrip } from '../ReferenceStrip'
+import { Stage } from '../Stage'
+import { Lightbox } from '../Lightbox'
+import { ResultView } from '../OutputView'
+import { useCreateStore, type GalleryItem } from '../../../../stores/createStore'
+import { __resetSavedCharacters, listSavedCharacters, saveCharacter } from '../../../../lib/saved-characters'
+
+const VIDEO: GalleryItem = {
+ id: 'v1', type: 'video', filename: 'clip.mp4', subfolder: '', prompt: 'a knight walks', negativePrompt: '', model: 'wan',
+ modelType: 'wan', seed: 1, steps: 1, cfgScale: 1, sampler: '', scheduler: '', width: 832, height: 480, batchSize: 1,
+ createdAt: 1, remoteUrl: 'https://storage.example/clip.mp4', jobId: 'job-1',
+}
+const photo = (t: string) => new Blob([t], { type: 'image/jpeg' })
+const QWEN21 = 'qwen_image_2.1_int8_convrot.safetensors'
+let minted = 0
+
+async function openAndAdd(frames: number) {
+ const onClose = vi.fn()
+ render(<SaveCharacterModal item={VIDEO} onClose={onClose} />)
+ const add = await screen.findByText('Add this frame')
+ await waitFor(() => expect((add.closest('button') as HTMLButtonElement).disabled).toBe(false))
+ for (let i = 0; i < frames; i++) {
+ fireEvent.click(add)
+ await waitFor(() => expect(screen.getByTestId('character-frames').querySelectorAll('img')).toHaveLength(i + 1))
+ }
+ return onClose
+}
+
+beforeEach(() => {
+ grab.n = 0; grab.fail = null; minted = 0
+ __resetSavedCharacters()
+ vi.stubGlobal('URL', Object.assign(URL, {
+ createObjectURL: vi.fn(() => `blob:test/${++minted}`),
+ revokeObjectURL: vi.fn(),
+ }))
+ // jsdom has no media playback.
+ window.HTMLMediaElement.prototype.pause = vi.fn()
+ useCreateStore.setState({
+ backend: 'local', isGenerating: false, error: null, source: null, mask: null, references: [],
+ batchSources: [], batchRun: null, trainImages: [], gallery: [],
+ imageModel: QWEN21, imageModelList: [{ name: QWEN21, type: 'qwenimage' }] as never,
+ caps: { rmbg: true, 'inpaint-nodes': true } as never,
+ })
+ useCreateStore.getState().setIntent('video')
+})
+afterEach(() => { cleanup() })
+
+describe('where the action sits', () => {
+ it('on a video in the large view and in the lightbox, not on an image', () => {
+ const onSave = vi.fn()
+ const first = render(<ResultView item={VIDEO} onFullscreen={vi.fn()} onSaveCharacter={onSave} />)
+ fireEvent.click(screen.getByTitle('Save character from this video'))
+ expect(onSave).toHaveBeenCalledTimes(1)
+ first.unmount()
+
+ const image = { ...VIDEO, id: 'i1', type: 'image' as const }
+ const second = render(<ResultView item={image} onFullscreen={vi.fn()} onSaveCharacter={onSave} />)
+ expect(screen.queryByTitle('Save character from this video')).toBeNull()
+ second.unmount()
+
+ const onClose = vi.fn()
+ render(<Lightbox item={VIDEO} onClose={onClose} onSaveCharacter={onSave} />)
+ fireEvent.click(screen.getByText('Save character'))
+ expect(onSave).toHaveBeenLastCalledWith(VIDEO)
+ expect(onClose).toHaveBeenCalled()
+ })
+})
+
+describe('picking frames and saving', () => {
+ it('saves the picked frames under the name, on this machine', async () => {
+ await openAndAdd(3)
+ fireEvent.click(screen.getByLabelText('Remove frame 2'))
+ await waitFor(() => expect(screen.getByTestId('character-frames').querySelectorAll('img')).toHaveLength(2))
+ const save = screen.getByText('Save character').closest('button') as HTMLButtonElement
+ expect(save.disabled).toBe(true)
+ fireEvent.change(screen.getByLabelText('Character name'), { target: { value: 'Mira' } })
+ expect(save.disabled).toBe(false)
+ fireEvent.click(save)
+ await screen.findByTestId('character-saved')
+ expect(screen.getByTestId('character-saved').textContent).toContain('Saved Mira with 2 photos. It is kept on this computer.')
+ const list = await listSavedCharacters()
+ expect(list.map((c) => c.name)).toEqual(['Mira'])
+ expect(await Promise.all(list[0].photos.map((p) => p.text()))).toEqual(['frame-1', 'frame-3'])
+ // Two photos are not a training set yet, and the window says so.
+ expect(screen.getByText(/Training needs at least 4 photos/)).toBeTruthy()
+ })
+
+ it('more frames under the same name grow the same character', async () => {
+ await saveCharacter('Mira', [photo('old')])
+ await openAndAdd(1)
+ fireEvent.change(screen.getByLabelText('Character name'), { target: { value: 'mira' } })
+ fireEvent.click(screen.getByText('Save character'))
+ await screen.findByTestId('character-saved')
+ expect(screen.getByTestId('character-saved').textContent).toContain('Added 1 photo to Mira, 2 in all.')
+ expect(await listSavedCharacters()).toHaveLength(1)
+ })
+
+ it('a frame that cannot be read says so and saves nothing', async () => {
+ grab.fail = 'Could not read this frame.'
+ render(<SaveCharacterModal item={VIDEO} onClose={vi.fn()} />)
+ const add = await screen.findByText('Add this frame')
+ await waitFor(() => expect((add.closest('button') as HTMLButtonElement).disabled).toBe(false))
+ fireEvent.click(add)
+ expect((await screen.findByTestId('save-character-note')).textContent).toBe('Could not read this frame.')
+ expect(screen.queryByTestId('character-frames')).toBeNull()
+ })
+})
+
+describe('what a saved character does next', () => {
+ it('"Use as reference photos": first photo is the source, the rest fill the strip, in Edit', async () => {
+ const onClose = await openAndAdd(3)
+ fireEvent.change(screen.getByLabelText('Character name'), { target: { value: 'Mira' } })
+ fireEvent.click(screen.getByText('Save character'))
+ fireEvent.click(await screen.findByText('Use as reference photos'))
+ await waitFor(() => expect(onClose).toHaveBeenCalled())
+ const s = useCreateStore.getState()
+ expect(s.intent()).toBe('edit')
+ expect(s.source?.filename).toBe('up_mira-01.jpg')
+ expect(s.references.map((r) => r.filename)).toEqual(['up_mira-02.jpg', 'up_mira-03.jpg'])
+ })
+
+ it('"Train in Character Studio": the photos start the training set, the minimum stays', async () => {
+ const onClose = await openAndAdd(2)
+ fireEvent.change(screen.getByLabelText('Character name'), { target: { value: 'Mira' } })
+ fireEvent.click(screen.getByText('Save character'))
+ fireEvent.click(await screen.findByText('Train in Character Studio'))
+ expect(onClose).toHaveBeenCalled()
+ const s = useCreateStore.getState()
+ expect(s.intent()).toBe('character')
+ expect(s.characterTab).toBe('train')
+ expect(s.trainImages.map((t) => t.name)).toEqual(['mira-01.jpg', 'mira-02.jpg'])
+ })
+
+ it('the reference strip loads a saved character with one click', async () => {
+ await saveCharacter('Mira', [photo('a'), photo('b'), photo('c'), photo('d'), photo('e'), photo('f')])
+ useCreateStore.getState().setIntent('edit')
+ useCreateStore.getState().setSource({ filename: 'scene.png', url: 'data:image/png;base64,AA', width: 8, height: 8 })
+ render(<ReferenceStrip />)
+ fireEvent.click(await screen.findByTitle('Load the photos of Mira'))
+ await waitFor(() => expect(useCreateStore.getState().source?.filename).toBe('up_mira-01.jpg'))
+ // The store keeps four further photos at most, a model shows what it reads.
+ expect(useCreateStore.getState().references).toHaveLength(4)
+ })
+
+ it('the Character Studio board adds the photos of a saved character', async () => {
+ await saveCharacter('Mira', [photo('a'), photo('b'), photo('c'), photo('d')])
+ useCreateStore.getState().setIntent('character')
+ useCreateStore.getState().setCharacterTab('train')
+ render(<Stage onOpenMaskEditor={vi.fn()} onFullscreen={vi.fn()} />)
+ fireEvent.click(await screen.findByTitle('Add the 4 photos of Mira'))
+ expect(useCreateStore.getState().trainImages).toHaveLength(4)
+ })
+
+ it('a saved character can be deleted, after a second click', async () => {
+ await saveCharacter('Mira', [photo('a')])
+ useCreateStore.getState().setIntent('edit')
+ useCreateStore.getState().setSource({ filename: 'scene.png', url: 'data:image/png;base64,AA', width: 8, height: 8 })
+ render(<ReferenceStrip />)
+ fireEvent.click(await screen.findByLabelText('Delete Mira'))
+ expect(await listSavedCharacters()).toHaveLength(1)
+ fireEvent.click(screen.getByText('Delete?'))
+ await waitFor(async () => expect(await listSavedCharacters()).toHaveLength(0))
+ await waitFor(() => expect(screen.queryByTestId('saved-characters')).toBeNull())
+ })
+})
diff --git a/src/components/create/experimental/batchFiles.ts b/src/components/create/experimental/batchFiles.ts
new file mode 100644
index 00000000..d6558244
--- /dev/null
+++ b/src/components/create/experimental/batchFiles.ts
@@ -0,0 +1,49 @@
+// Reading the files of a drop or of a picked folder, for the list of several
+// source images (lib/batch-edit).
+
+function readFolder(dir: FileSystemDirectoryEntry): Promise<File[]> {
+ const reader = dir.createReader()
+ const found: FileSystemEntry[] = []
+ return new Promise<File[]>((resolve) => {
+ // readEntries hands the folder out in chunks and ends with an empty one.
+ const next = () => reader.readEntries((chunk) => {
+ if (chunk.length === 0) {
+ void Promise.all(found.filter((e) => e.isFile).map(entryFile)).then((files) => resolve(files.flatMap((f) => (f ? [f] : []))))
+ return
+ }
+ found.push(...chunk)
+ next()
+ }, () => resolve([]))
+ next()
+ })
+}
+
+function entryFile(entry: FileSystemEntry): Promise<File | null> {
+ return new Promise((resolve) => (entry as FileSystemFileEntry).file(resolve, () => resolve(null)))
+}
+
+/**
+ * The files of a drop. A dropped folder gives its own images (not the ones in
+ * folders below it). Call it inside the drop handler: the browser only hands
+ * out the entries while the event is alive.
+ */
+export function filesFromDrop(dt: DataTransfer): Promise<File[]> {
+ const plain = Array.from(dt.files)
+ const entries = Array.from(dt.items ?? []).map((it) => (it.kind === 'file' && typeof it.webkitGetAsEntry === 'function' ? it.webkitGetAsEntry() : null))
+ if (!entries.some((e) => e?.isDirectory)) return Promise.resolve(plain)
+ return Promise.all(entries.map(async (e) => {
+ if (!e) return []
+ if (e.isDirectory) return readFolder(e as FileSystemDirectoryEntry)
+ const f = await entryFile(e)
+ return f ? [f] : []
+ })).then((lists) => lists.flat())
+}
+
+/** A folder picker hands out every file below the folder. The batch takes the
+ * folder's own images. */
+export function topLevelFiles(files: readonly File[]): File[] {
+ return files.filter((f) => {
+ const rel = (f as File & { webkitRelativePath?: string }).webkitRelativePath ?? ''
+ return rel.split('/').length <= 2
+ })
+}
diff --git a/src/components/create/experimental/batchRun.ts b/src/components/create/experimental/batchRun.ts
new file mode 100644
index 00000000..ac12106e
--- /dev/null
+++ b/src/components/create/experimental/batchRun.ts
@@ -0,0 +1,234 @@
+// Several source images, one edit: the wiring between the list on the Stage,
+// the store and the normal Create run. The rules live in lib/batch-edit.
+//
+// Each image goes through the very same generate() a single image uses, local
+// or cloud. So the uploads, the safety check, the confirmed price and the
+// booking are the ones that already exist, once per image, and an image that
+// never starts is never sent and never charged.
+import { useCreateStore, type ImageRef, type MediaRef } from '../../../stores/createStore'
+import { defaultCloudModel, editNeedsMask, modelForOp, useCloudCatalogStore } from '../../../stores/cloudCatalogStore'
+import { isStudioModel } from '../../../lib/render/create-studio'
+import { runImageCount } from '../../../lib/render/image-count'
+import { dataUrlToBlob, takeCloudRunStop } from '../../../hooks/useCloudCreate'
+import {
+ MAX_BATCH_IMAGES, batchOffered, batchPickNote, batchSummary, cloudRunsPerMinute, createPacer,
+ pickBatchFiles, runBatch, type RunOutcome,
+} from '../../../lib/batch-edit'
+import { needsMaskFor } from './maskGate'
+import { loadImageRef } from './loadImage'
+import { mediaRefFrom } from './mediaRef'
+
+type Snapshot = ReturnType<typeof useCreateStore.getState>
+
+/** The image model an Edit runs on in the cloud, as Composer and the start
+ * resolve it. */
+function cloudEditModel(s: Pick<Snapshot, 'cloudImageModel'>): string {
+ return modelForOp('image', 'edit', s.cloudImageModel || defaultCloudModel('image')?.id || '')
+}
+
+/** Does the tab on screen take several source images right now? */
+export function batchOfferedNow(s: Pick<Snapshot, 'intent' | 'backend' | 'cloudImageModel'>): boolean {
+ const intent = s.intent()
+ return batchOffered(intent, needsMaskFor(intent, s.backend, !editNeedsMask(cloudEditModel(s))))
+}
+
+/** The same answer for a component, redrawn when the model or the catalog changes. */
+export function useBatchOffered(): boolean {
+ useCloudCatalogStore((s) => s.models)
+ return useCreateStore((s) => batchOfferedNow(s))
+}
+
+/** True when Create starts a batch instead of one run. */
+export function batchReady(): boolean {
+ const s = useCreateStore.getState()
+ return s.batchSources.length > 1 && batchOfferedNow(s)
+}
+
+function fileOf(ref: MediaRef): File {
+ return ref.blob instanceof File ? ref.blob : new File([ref.blob], ref.name, { type: ref.blob.type || 'image/png' })
+}
+
+function sourceAsEntry(source: ImageRef): MediaRef {
+ const blob = dataUrlToBlob(source.url)
+ const ext = blob.type === 'image/jpeg' ? 'jpg' : blob.type === 'image/webp' ? 'webp' : 'png'
+ return mediaRefFrom(new File([blob], `image 1.${ext}`, { type: blob.type || 'image/png' }))
+}
+
+const sameFile = (a: MediaRef, b: MediaRef) => a.name === b.name && a.blob.size === b.blob.size
+
+async function showAsSource(ref: MediaRef): Promise<void> {
+ const st = useCreateStore.getState()
+ try {
+ st.setSource(await loadImageRef(fileOf(ref)))
+ } catch (err) {
+ st.setError(`Could not load ${ref.name}: ${err instanceof Error ? err.message : String(err)}`)
+ }
+}
+
+/**
+ * Picked or dropped files join the source surface. One image into an empty
+ * slot is the plain single source, as before. Anything more becomes the list,
+ * and the image already on the Stage stays its first entry.
+ */
+export async function addBatchFiles(files: readonly File[]): Promise<void> {
+ const st = useCreateStore.getState()
+ const existing = st.batchSources.length || (st.source ? 1 : 0)
+ const pick = pickBatchFiles(files, MAX_BATCH_IMAGES - existing)
+ const note = batchPickNote(pick)
+ st.setError(note)
+ if (pick.accepted.length === 0) return
+
+ if (existing === 0 && pick.accepted.length === 1) {
+ try {
+ st.setSource(await loadImageRef(pick.accepted[0]))
+ } catch (err) {
+ st.setError(`Could not load the image: ${err instanceof Error ? err.message : String(err)}`)
+ }
+ return
+ }
+
+ const list = st.batchSources.length ? st.batchSources : st.source ? [sourceAsEntry(st.source)] : []
+ const next = [...list]
+ for (const file of pick.accepted) {
+ const ref = mediaRefFrom(file)
+ if (next.some((have) => sameFile(have, ref))) URL.revokeObjectURL(ref.url)
+ else next.push(ref)
+ }
+ if (next.length < 2) {
+ // Only the image that is already there was picked again.
+ if (!st.batchSources.length) for (const r of next) URL.revokeObjectURL(r.url)
+ return
+ }
+ st.setBatchSources(next)
+ // A mask belongs to one image, a list has none.
+ st.setMask(null)
+ if (!st.source) await showAsSource(next[0])
+}
+
+/** Takes one image out of the list. A list of one is the plain single source again. */
+export async function removeBatchEntry(index: number): Promise<void> {
+ const st = useCreateStore.getState()
+ const next = st.batchSources.filter((_, i) => i !== index)
+ // The file outlives its preview URL, which the store gives back below.
+ const head = next[0] ? fileOf(next[0]) : null
+ st.setBatchSources(next.length < 2 ? [] : next)
+ if (index !== 0 || !head) return
+ try {
+ useCreateStore.getState().setSource(await loadImageRef(head))
+ } catch (err) {
+ st.setError(`Could not load ${head.name}: ${err instanceof Error ? err.message : String(err)}`)
+ }
+}
+
+/** Back to the one image on the Stage. */
+export function clearBatch(): void {
+ useCreateStore.getState().setBatchSources([])
+}
+
+// The stop flag lives at module scope like the cloud run's own handle: the
+// batch outlives the Create view, and Cancel has to reach it from a remount.
+let stopRequested = false
+
+/** Cancel: nothing further starts. The caller also cancels the run in flight. */
+export function requestBatchStop(): void {
+ stopRequested = true
+}
+
+export const batchRunning = (): boolean => useCreateStore.getState().batchRun !== null
+
+/**
+ * Runs the list: for each image, show it as the source and call the normal
+ * run. `runOne` is the generate() of the backend the batch started on.
+ */
+export async function runBatchEdit(
+ runOne: () => void | Promise<void>,
+ opts: { sleep?: (ms: number) => Promise<void> } = {},
+): Promise<void> {
+ const start = useCreateStore.getState()
+ if (start.batchRun || start.isGenerating) return
+ const entries = start.batchSources.slice(0, MAX_BATCH_IMAGES)
+ if (entries.length < 2) return
+ const intent = start.intent()
+ const backend = start.backend
+ stopRequested = false
+ start.setMask(null)
+ start.setError(null)
+ const names = entries.map((e) => e.name)
+ const thumbs = entries.map((e) => e.url)
+ start.setBatchRun({ index: 0, statuses: entries.map(() => 'waiting'), names, thumbs })
+
+ const pacer = backend === 'cloud'
+ ? createPacer({
+ limit: cloudRunsPerMinute({
+ count: runImageCount(intent, start.cloudImageCount),
+ extraPhotos: intent === 'edit' ? start.references.length : 0,
+ studio: intent === 'edit' && isStudioModel(cloudEditModel(start)),
+ }),
+ sleep: opts.sleep,
+ })
+ : null
+
+ const one = async (entry: MediaRef): Promise<RunOutcome> => {
+ let ref: ImageRef
+ try {
+ ref = await loadImageRef(fileOf(entry))
+ } catch (err) {
+ return { made: 0, error: `Could not load the image: ${err instanceof Error ? err.message : String(err)}` }
+ }
+ if (stopRequested) return { made: 0, error: null }
+ const s = useCreateStore.getState()
+ s.setSource(ref)
+ s.setError(null)
+ const before = new Set(s.gallery.map((g) => g.id))
+ takeCloudRunStop()
+ await runOne()
+ const after = useCreateStore.getState()
+ const made = after.gallery.filter((g) => !before.has(g.id))
+ for (const g of made) after.updateGalleryItem(g.id, { sourceName: entry.name })
+ const stop = takeCloudRunStop()
+ return { made: made.length, error: after.error, stop: stop?.reason, retryAfterMs: stop?.retryAfterMs }
+ }
+
+ let report: Awaited<ReturnType<typeof runBatch>> | null = null
+ try {
+ report = await runBatch(entries, {
+ runOne: one,
+ cancelled: () => stopRequested,
+ stillValid: () => {
+ const s = useCreateStore.getState()
+ return s.intent() === intent && s.backend === backend
+ },
+ pace: pacer ? async () => {
+ const waiting = pacer.wait()
+ // Only say so when the batch really has to wait.
+ const t = setTimeout(() => useCreateStore.getState().setProgress(0, 'Waiting a moment, the server takes a limited number of images per minute…'), 300)
+ try { await waiting } finally { clearTimeout(t) }
+ } : undefined,
+ sleep: opts.sleep,
+ onProgress: (statuses, index) => useCreateStore.getState().setBatchRun({ index, statuses, names, thumbs }),
+ })
+ } finally {
+ const st = useCreateStore.getState()
+ st.setBatchRun(null)
+ // What has no result stays in the list, so Create runs exactly the rest.
+ // Everything else leaves it, or a second Create would book it again.
+ const rest = report ? report.pending.map((i) => entries[i]) : []
+ const valid = st.intent() === intent
+ if (!valid) {
+ // setIntent already dropped the list with the source.
+ } else if (rest.length >= 2) {
+ st.setBatchSources(rest)
+ await showAsSource(rest[0])
+ } else {
+ const last = rest[0] ? fileOf(rest[0]) : null
+ st.setBatchSources([])
+ if (last) {
+ try { useCreateStore.getState().setSource(await loadImageRef(last)) }
+ catch { useCreateStore.getState().setSource(null) }
+ }
+ }
+ const summary = report ? batchSummary(report) : null
+ if (summary) useCreateStore.getState().setError(summary)
+ stopRequested = false
+ }
+}
diff --git a/src/components/create/experimental/characterPhotos.ts b/src/components/create/experimental/characterPhotos.ts
new file mode 100644
index 00000000..13485058
--- /dev/null
+++ b/src/components/create/experimental/characterPhotos.ts
@@ -0,0 +1,43 @@
+// What a set of character photos can do next: load into the reference strip,
+// or start a training set in Character Studio. Used by the frames picked from
+// a video and by a saved character (lib/saved-characters).
+import { useCreateStore } from '../../../stores/createStore'
+import { MAX_STORED_REFERENCES } from '../../../lib/edit-references'
+import { frameFileName } from '../../../lib/video-frames'
+import { loadImageRef } from './loadImage'
+import { mediaRefFrom } from './mediaRef'
+
+function asFiles(name: string, photos: readonly Blob[]): File[] {
+ return photos.map((blob, i) => new File([blob], frameFileName(name, i), { type: blob.type || 'image/jpeg' }))
+}
+
+/**
+ * The first photo becomes the source image, the next ones fill the reference
+ * strip under it. Edit and Animate Image keep their tab, every other tab
+ * switches to Edit. A model shows and sends only as many photos as it reads.
+ * Returns how many photos were loaded.
+ */
+export async function loadPhotosAsReferences(name: string, photos: readonly Blob[]): Promise<number> {
+ const files = asFiles(name, photos).slice(0, MAX_STORED_REFERENCES + 1)
+ if (files.length === 0) return 0
+ const st = useCreateStore.getState()
+ const intent = st.intent()
+ if (intent !== 'edit' && intent !== 'animate') st.setIntent('edit')
+ const refs = []
+ for (const file of files) refs.push(await loadImageRef(file))
+ const now = useCreateStore.getState()
+ now.setBatchSources([])
+ now.setMask(null)
+ now.setSource(refs[0])
+ now.setReferences(refs.slice(1))
+ return refs.length
+}
+
+/** The photos join the training set in Character Studio. The studio's own
+ * minimum and maximum stay as they are. */
+export function sendPhotosToStudio(name: string, photos: readonly Blob[]): void {
+ const st = useCreateStore.getState()
+ st.setIntent('character')
+ st.setCharacterTab('train')
+ st.addTrainImages(asFiles(name, photos).map(mediaRefFrom))
+}
diff --git a/src/components/create/experimental/referenceSlots.ts b/src/components/create/experimental/referenceSlots.ts
new file mode 100644
index 00000000..de7edc50
--- /dev/null
+++ b/src/components/create/experimental/referenceSlots.ts
@@ -0,0 +1,24 @@
+// How many further photos the model on screen reads besides the source image.
+// 0 hides the reference strip. One reader for the strip and for the saved
+// characters that load into it.
+import { useCreateStore } from '../../../stores/createStore'
+import { classifyModel } from '../../../api/comfyui'
+import { extraReferenceSlots } from '../../../lib/edit-references'
+import { referenceModel, studioExtraPhotoSlots } from '../../../lib/render/create-studio'
+
+export function useReferenceSlots(): number {
+ const backend = useCreateStore((s) => s.backend)
+ const intent = useCreateStore((s) => s.intent())
+ const imageModel = useCreateStore((s) => s.imageModel)
+ const listedType = useCreateStore((s) => s.imageModelList.find((m) => m.name === s.imageModel)?.type)
+ const cloudImageModel = useCreateStore((s) => s.cloudImageModel)
+ const cloudVideoModel = useCreateStore((s) => s.cloudVideoModel)
+ const cloudOpModel = useCreateStore((s) => s.cloudOpModel)
+ // The type from the fetched list carries the header sniff; the name is the
+ // fallback, exactly as useCreate decides the pipeline.
+ if (backend === 'cloud') {
+ const pick = referenceModel(intent, { cloudImageModel, cloudVideoModel, cloudOpModel })
+ return pick ? studioExtraPhotoSlots(pick) : 0
+ }
+ return intent === 'edit' ? extraReferenceSlots(listedType ?? classifyModel(imageModel), imageModel) : 0
+}
diff --git a/src/components/create/experimental/useRunCredits.ts b/src/components/create/experimental/useRunCredits.ts
new file mode 100644
index 00000000..ddf7b778
--- /dev/null
+++ b/src/components/create/experimental/useRunCredits.ts
@@ -0,0 +1,103 @@
+import { useCreateStore } from '../../../stores/createStore'
+import { useCreateExp } from './CreateContext'
+import { intentToJob, type RenderKind, type RenderOp } from '../../../lib/render/cloud-jobs'
+import { defaultCloudModel, modelForOp, resolveOpPick, runCredits } from '../../../stores/cloudCatalogStore'
+import { createStudioCost, intentRoles, isStudioModel, resolveIntentPick, startImageCount } from '../../../lib/render/create-studio'
+import { STUDIO_MODELS } from '../../../lib/render/studio-contract'
+import { resolveCharacterModel } from '../../../hooks/useCloudCreate'
+import { runImageCount } from '../../../lib/render/image-count'
+
+/** What the cloud run on screen costs. One reader for the meter chip and for
+ * the list of several source images, so both name the same number. */
+export interface RunCredits {
+ kind: RenderKind
+ op: RenderOp
+ /** One result. */
+ unitCost: number
+ /** Results per run (1 to 4 for Image and Edit). */
+ imageCount: number
+ /** One run: unitCost times imageCount. */
+ cost: number
+}
+
+/** Null while there is no quota yet, or no run to price. */
+export function useRunCredits(): RunCredits | null {
+ const { quota } = useCreateExp()
+ const intent = useCreateStore((s) => s.intent())
+ const cloudImageModel = useCreateStore((s) => s.cloudImageModel)
+ const cloudVideoModel = useCreateStore((s) => s.cloudVideoModel)
+ const cloudOpModel = useCreateStore((s) => s.cloudOpModel)
+ const characterTab = useCreateStore((s) => s.characterTab)
+ const selectedCharacter = useCreateStore((s) => s.selectedCharacter)
+ // Review A kleiner Punkt 1: this meter is cloud-only (Composer renders it
+ // only for backend 'cloud'), so it must price the SAME length the cloud
+ // Length control shows and useCloudCreate books, cloudFrames/cloudFps, not
+ // the local track's frames/fps.
+ const frames = useCreateStore((s) => s.cloudFrames)
+ const fps = useCreateStore((s) => s.cloudFps)
+ const musicDuration = useCreateStore((s) => s.musicDuration)
+ const targetResolution = useCreateStore((s) => s.targetResolution)
+ const cloudStudioOptions = useCreateStore((s) => s.cloudStudioOptions)
+ const cloudStudioCredits = useCreateStore((s) => s.cloudStudioCredits)
+ const prompt = useCreateStore((s) => s.prompt)
+ const cloudImageCount = useCreateStore((s) => s.cloudImageCount)
+ const references = useCreateStore((s) => s.references)
+ if (!quota) return null
+ // No character picked yet: there is no run to price (resolveCharacterModel
+ // would fall onto the family's first model and show a number for a run
+ // nobody asked for). uselu main 5be5dec3 fixed the same false reading.
+ if (intent === 'character' && characterTab === 'use' && !selectedCharacter) return null
+
+ let { kind, op } = intentToJob(intent)
+ // Mirror Composer's creditsOk pick exactly: meter and gate must show the
+ // same number: the character use-surface prices the family's real
+ // generation endpoint (never a hardcoded single default), the role
+ // intents (lipsync/music/extend/motion) run whichever Studio or classic
+ // op-picker model is chosen, everything else prices the per-kind
+ // picker's model.
+ const characterUse = intent === 'character' && characterTab === 'use'
+ if (characterUse) {
+ kind = 'image'
+ op = 'generate'
+ }
+ const special =
+ op === 'lipsync' || op === 'extend' || op === 'motion' ||
+ op === 'music' || op === 'tts' || op === 'lora-train'
+ const roleIntent = !characterUse && intentRoles(intent).length > 0
+ const rolePick = roleIntent ? resolveIntentPick(intent, cloudOpModel) : undefined
+ const picked = characterUse
+ ? (resolveCharacterModel(selectedCharacter?.family ?? '', cloudOpModel) ?? '')
+ : roleIntent
+ ? (rolePick ?? '')
+ : special
+ ? resolveOpPick(op, cloudOpModel)
+ : (kind === 'video' ? cloudVideoModel : cloudImageModel) || defaultCloudModel(kind)?.id || ''
+ // Dieselbe Aufloesung wie Composer und Start (modelForOp): eine Wahl, die die
+ // Unterkategorie nicht fahren kann, rechnet hier als das Modell, das wirklich
+ // laeuft. Rollen-Absichten und der Character-Weg behalten ihre Wahl.
+ const model = roleIntent || characterUse ? picked : modelForOp(kind, op, picked)
+ // Ein Studio-Modell rechnet nach seinem eigenen Schema, auch aus Image, Edit,
+ // Video und Animate (seit 02.10.2026).
+ const studioPick = !characterUse && isStudioModel(model) ? model : undefined
+ if (studioPick) kind = STUDIO_MODELS[studioPick].kind
+ const seconds =
+ op === 'music'
+ ? musicDuration
+ : kind === 'video' && (op === 'generate' || op === 'animate') && fps > 0
+ ? frames / fps
+ : undefined
+ // A Studio model prices from its own provider schema, never runCredits()
+ // (P3's guard there returns the caller's fallback on purpose, Portplan
+ // Abschnitt 7, Risiko 1). The Composer fetches the live number once
+ // (useStudioPrice) and leaves it here; this chip never asks twice for the
+ // same figure.
+ const extraPhotos = intent === 'edit' || intent === 'animate' ? references.length : 0
+ const unitCost = studioPick
+ ? cloudStudioCredits ?? createStudioCost(studioPick, cloudStudioOptions, Array.from(prompt).length, undefined, startImageCount(studioPick, extraPhotos) ?? 1)
+ : runCredits(kind, op, picked, seconds, quota.costs[kind === 'audio' ? 'image' : kind], targetResolution)
+ // Mehrere Bilder: jedes ist ein eigener Auftrag zum vollen Preis, die Summe
+ // ist, was der Lauf bindet. Der Zaehler "noch N Bilder" rechnet je Bild.
+ const imageCount = runImageCount(intent, cloudImageCount, characterUse)
+ const cost = unitCost * imageCount
+ return { kind, op, unitCost, imageCount, cost }
+}
diff --git a/src/hooks/__tests__/useCloudCreate-batch.test.ts b/src/hooks/__tests__/useCloudCreate-batch.test.ts
new file mode 100644
index 00000000..84bc8b21
--- /dev/null
+++ b/src/hooks/__tests__/useCloudCreate-batch.test.ts
@@ -0,0 +1,303 @@
+/**
+ * Several source images, one edit, in the cloud: what is sent and what is
+ * booked. The real generate() and the real batch run, with submit, upload,
+ * poll and cancel mocked. Nothing is rendered and nothing is charged.
+ *
+ * The rule under test: every image is its own run with its own booking, and an
+ * image that never starts is never uploaded and never submitted.
+ */
+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 }
+})
+
+type Payload = { kind: string; model: string; prompt: string; params: Record<string, unknown> }
+const hoisted = vi.hoisted(() => {
+ class FakeCloudJobError extends Error {
+ status: number
+ code?: string
+ retryAfterMs?: number
+ constructor(message: string, status: number, meta?: { code?: string; retryAfterMs?: number }) {
+ super(message)
+ this.status = status
+ this.code = meta?.code
+ this.retryAfterMs = meta?.retryAfterMs
+ }
+ }
+ class FakeQuoteChanged extends FakeCloudJobError {
+ credits: number
+ constructor(message: string, credits: number) {
+ super(message, 409, { code: 'quote_changed' })
+ this.credits = credits
+ }
+ }
+ return {
+ FakeCloudJobError,
+ FakeQuoteChanged,
+ plan: {
+ /** What the n-th submit does instead of booking (1-based). */
+ refuse: {} as Record<number, () => Error>,
+ /** Job ids whose render fails. */
+ failed: new Set<string>(),
+ /** Called when a job is polled, to act in the middle of a run. */
+ onPoll: null as null | ((id: string) => void | Promise<void>),
+ upload: 0,
+ },
+ submitted: [] as Payload[],
+ booked: [] as string[],
+ uploaded: [] as string[],
+ cancelled: [] as string[],
+ quote: vi.fn(async (..._a: unknown[]) => ({ credits: 5000 })),
+ }
+})
+const { submitted, booked, uploaded, cancelled, plan } = hoisted
+
+vi.mock('../useContentPolicy', () => ({
+ contentPolicySnapshot: () => 'off' as const,
+ loadContentPolicy: async () => 'off' as const,
+}))
+vi.mock('../../api/cloud/jobs', () => ({
+ uploadInput: vi.fn(async (_b: unknown, slot: string) => { const p = `user-1/staged-${slot}-${++plan.upload}.png`; uploaded.push(p); return p }),
+ getJob: vi.fn(),
+ cancelJob: vi.fn(async (id: string) => { cancelled.push(id); return { status: 'canceled' } }),
+ submitCloudJob: vi.fn(async (payload: Payload) => {
+ submitted.push(payload)
+ const refuse = plan.refuse[submitted.length]
+ if (refuse) throw refuse()
+ const asked = (payload.params.count as number | undefined) ?? 1
+ const ids = Array.from({ length: asked }, (_, i) => `job-${submitted.length}-${i}`)
+ booked.push(...ids)
+ if (asked === 1) return { id: ids[0], quota: { cost: 300 } }
+ return { id: ids[0], quota: { cost: 300 }, jobs: ids.map((id) => ({ id, status: 'queued', cost: 300 })), requested: asked }
+ }),
+ pollJob: vi.fn(async (id: string, opts: { signal?: AbortSignal }) => {
+ await plan.onPoll?.(id)
+ if (opts.signal?.aborted) throw new hoisted.FakeCloudJobError('polling aborted', 0)
+ const status = plan.failed.has(id) ? 'failed' : 'succeeded'
+ return {
+ id, kind: 'image', model: 'flux-schnell', status,
+ result_url: status === 'succeeded' ? `https://storage.example/${id}.png` : null,
+ error: status === 'failed' ? 'provider said no' : null,
+ created_at: new Date().toISOString(), params: {},
+ }
+ }),
+ CloudJobError: hoisted.FakeCloudJobError,
+ QuoteChangedError: hoisted.FakeQuoteChanged,
+}))
+vi.mock('../../api/cloud/studio', () => ({
+ studioQuote: hoisted.quote,
+ StudioQuoteChangedError: hoisted.FakeQuoteChanged,
+}))
+// No FileReader and no ComfyUI in this run: a file becomes a data URL that
+// carries its name, so the test can see which image was uploaded.
+vi.mock('../../components/create/experimental/loadImage', () => ({
+ loadImageRef: vi.fn(async (f: File) => ({ filename: '', url: `data:image/png;base64,${btoa(f.name)}`, width: 64, height: 64 })),
+}))
+
+import { useCloudCreate } from '../useCloudCreate'
+import { useCreateStore } from '../../stores/createStore'
+import { useCloudCatalogStore } from '../../stores/cloudCatalogStore'
+import { neuerServer } from '../../lib/render/__tests__/fixtures/test-catalogs'
+import {
+ addBatchFiles, batchReady, requestBatchStop, runBatchEdit,
+} from '../../components/create/experimental/batchRun'
+
+const png = (name: string) => new File([name], name, { type: 'image/png' })
+const noSleep = { sleep: async () => {} }
+const names = () => useCreateStore.getState().batchSources.map((b) => b.name)
+
+async function stage(intent: 'edit' | 'removebg' | 'upscale', files: string[]) {
+ useCreateStore.getState().setIntent(intent)
+ await addBatchFiles(files.map(png))
+}
+
+beforeEach(() => {
+ submitted.length = 0; booked.length = 0; uploaded.length = 0; cancelled.length = 0
+ plan.refuse = {}; plan.failed.clear(); plan.onPoll = null; plan.upload = 0
+ hoisted.quote.mockClear()
+ useCreateStore.setState({
+ isGenerating: false, error: null, backend: 'cloud', source: null, mask: null, references: [],
+ batchSources: [], batchRun: null,
+ gallery: [], cloudStudioOptions: {}, cloudStudioCredits: null, cloudImageCount: 1,
+ })
+ useCreateStore.getState().setPrompt('a neutral placeholder line')
+ useCloudCatalogStore.setState({ models: neuerServer() })
+})
+
+describe('each image is its own run and its own booking', () => {
+ it('three images: three uploads, three submits, three results tied to their file', async () => {
+ await stage('removebg', ['c.png', 'a.png', 'b.png'])
+ expect(names()).toEqual(['a.png', 'b.png', 'c.png'])
+ expect(batchReady()).toBe(true)
+
+ await runBatchEdit(useCloudCreate().generate, noSleep)
+
+ expect(submitted).toHaveLength(3)
+ expect(submitted.every((p) => p.params.op === 'removebg' && p.params.count === undefined)).toBe(true)
+ // Its own request id and its own staged source per image.
+ expect(new Set(submitted.map((p) => p.params.client_request_id)).size).toBe(3)
+ expect(submitted.map((p) => p.params.source_path)).toEqual(uploaded)
+ expect(new Set(uploaded).size).toBe(3)
+ expect(booked).toHaveLength(3)
+
+ const s = useCreateStore.getState()
+ expect(s.gallery.map((g) => g.sourceName).sort()).toEqual(['a.png', 'b.png', 'c.png'])
+ expect(s.batchSources).toEqual([])
+ expect(s.batchRun).toBeNull()
+ expect(s.error).toBeNull()
+ expect(s.isGenerating).toBe(false)
+ })
+
+ it('Edit with two results per image: every image asks for its own two', async () => {
+ useCreateStore.getState().setCloudImageModel('qwen-image-edit')
+ await stage('edit', ['a.png', 'b.png'])
+ useCreateStore.getState().setCloudImageCount(2)
+
+ await runBatchEdit(useCloudCreate().generate, noSleep)
+
+ expect(submitted).toHaveLength(2)
+ expect(submitted.map((p) => p.params.count)).toEqual([2, 2])
+ expect(submitted.every((p) => p.params.mask_path === undefined)).toBe(true)
+ expect(booked).toHaveLength(4)
+ const made = useCreateStore.getState().gallery
+ expect(made.filter((g) => g.sourceName === 'a.png')).toHaveLength(2)
+ expect(made.filter((g) => g.sourceName === 'b.png')).toHaveLength(2)
+ })
+})
+
+describe('credits cover only a part', () => {
+ it('the refused image and everything behind it is never booked, never sent', async () => {
+ await stage('removebg', ['a.png', 'b.png', 'c.png', 'd.png'])
+ plan.refuse[3] = () => new hoisted.FakeCloudJobError('credits exhausted', 429, { code: 'credits_exhausted' })
+
+ await runBatchEdit(useCloudCreate().generate, noSleep)
+
+ // Two booked, the third asked and refused, the fourth never left the app.
+ expect(booked).toHaveLength(2)
+ expect(submitted).toHaveLength(3)
+ expect(uploaded).toHaveLength(3)
+ const s = useCreateStore.getState()
+ expect(s.gallery).toHaveLength(2)
+ expect(names()).toEqual(['c.png', 'd.png'])
+ expect(s.error).toBe(
+ '2 of 4 images are done. There were not enough credits to go on. The other 2 were not started and nothing was charged for them. ' +
+ 'What is left stays ready, hit Create to run it.',
+ )
+ })
+
+ it('a second Create runs exactly what is left, nothing twice', async () => {
+ await stage('removebg', ['a.png', 'b.png', 'c.png', 'd.png'])
+ plan.refuse[3] = () => new hoisted.FakeCloudJobError('credits exhausted', 429, { code: 'credits_exhausted' })
+ await runBatchEdit(useCloudCreate().generate, noSleep)
+ plan.refuse = {}
+ expect(booked).toHaveLength(2)
+
+ await runBatchEdit(useCloudCreate().generate, noSleep)
+
+ // Two more bookings, for c.png and d.png only.
+ expect(booked).toHaveLength(4)
+ expect(submitted).toHaveLength(5)
+ expect(useCreateStore.getState().gallery.map((g) => g.sourceName).sort()).toEqual(['a.png', 'b.png', 'c.png', 'd.png'])
+ expect(useCreateStore.getState().batchSources).toEqual([])
+ })
+})
+
+describe('one image fails', () => {
+ it('the others still run, and the failed file is named at the end', async () => {
+ await stage('removebg', ['a.png', 'b.png', 'c.png'])
+ plan.failed.add('job-2-0')
+
+ await runBatchEdit(useCloudCreate().generate, noSleep)
+
+ expect(submitted).toHaveLength(3)
+ const s = useCreateStore.getState()
+ expect(s.gallery.map((g) => g.sourceName).sort()).toEqual(['a.png', 'c.png'])
+ expect(s.error).toBe('2 of 3 images are done. 1 failed: b.png. Error: provider said no. What is left stays ready, hit Create to run it.')
+ // One image left is the plain single source again.
+ expect(s.batchSources).toEqual([])
+ expect(atob(s.source!.url.split(',')[1])).toBe('b.png')
+ })
+})
+
+describe('Cancel', () => {
+ it('stops the run in flight and nothing behind it starts', async () => {
+ await stage('removebg', ['a.png', 'b.png', 'c.png', 'd.png'])
+ const cloud = useCloudCreate()
+ plan.onPoll = async (id) => {
+ if (id !== 'job-2-0') return
+ requestBatchStop()
+ await cloud.cancel()
+ }
+
+ await runBatchEdit(cloud.generate, noSleep)
+
+ expect(submitted).toHaveLength(2)
+ expect(uploaded).toHaveLength(2)
+ expect(cancelled).toEqual(['job-2-0'])
+ const s = useCreateStore.getState()
+ expect(s.gallery).toHaveLength(1)
+ expect(names()).toEqual(['b.png', 'c.png', 'd.png'])
+ expect(s.error).toBe('1 of 4 images are done. Stopped. The other 3 were not started. What is left stays ready, hit Create to run it.')
+ })
+})
+
+describe('the send limit', () => {
+ it('"too fast" waits as the server asked and sends the same image again, booked once', async () => {
+ await stage('removebg', ['a.png', 'b.png'])
+ plan.refuse[1] = () => new hoisted.FakeCloudJobError('too many submissions', 429, { retryAfterMs: 20_000 })
+ const slept: number[] = []
+
+ await runBatchEdit(useCloudCreate().generate, { sleep: async (ms) => { slept.push(ms) } })
+
+ expect(slept).toEqual([20_000])
+ expect(submitted).toHaveLength(3)
+ expect(booked).toHaveLength(2)
+ expect(useCreateStore.getState().gallery.map((g) => g.sourceName).sort()).toEqual(['a.png', 'b.png'])
+ expect(useCreateStore.getState().error).toBeNull()
+ })
+})
+
+describe('a model that needs a mask', () => {
+ it('never runs as a batch, the list waits for a model without a mask', async () => {
+ useCreateStore.getState().setCloudImageModel('qwen-image-edit')
+ await stage('edit', ['a.png', 'b.png'])
+ expect(batchReady()).toBe(true)
+ useCreateStore.getState().setCloudImageModel('flux-dev')
+ expect(batchReady()).toBe(false)
+ })
+
+ it('Erase Object takes one image, and adding files there makes no list', async () => {
+ useCreateStore.getState().setIntent('eraser')
+ expect(batchReady()).toBe(false)
+ })
+})
+
+describe('the list itself', () => {
+ it('takes 50 images at most and says so', async () => {
+ useCreateStore.getState().setIntent('removebg')
+ await addBatchFiles(Array.from({ length: 53 }, (_, i) => png(`f${String(i).padStart(2, '0')}.png`)))
+ const s = useCreateStore.getState()
+ expect(s.batchSources).toHaveLength(50)
+ expect(s.error).toBe('You can edit up to 50 images at once. 50 were added, 3 were left out.')
+ await addBatchFiles([png('late.png')])
+ expect(useCreateStore.getState().batchSources).toHaveLength(50)
+ expect(useCreateStore.getState().error).toBe('The list is full. You can edit up to 50 images at once.')
+ })
+
+ it('leaving the tab drops the list, so nothing runs later by surprise', async () => {
+ await stage('removebg', ['a.png', 'b.png'])
+ useCreateStore.getState().setIntent('image')
+ expect(useCreateStore.getState().batchSources).toEqual([])
+ expect(batchReady()).toBe(false)
+ })
+
+ it('a changed tab in the middle of a run ends it before the next image', async () => {
+ await stage('removebg', ['a.png', 'b.png', 'c.png'])
+ plan.onPoll = (id) => { if (id === 'job-1-0') useCreateStore.getState().setIntent('image') }
+ await runBatchEdit(useCloudCreate().generate, noSleep)
+ expect(submitted).toHaveLength(1)
+ expect(booked).toHaveLength(1)
+ })
+})
diff --git a/src/hooks/useCloudCreate.ts b/src/hooks/useCloudCreate.ts
index 4057ef64..b9e80b52 100644
--- a/src/hooks/useCloudCreate.ts
+++ b/src/hooks/useCloudCreate.ts
@@ -214,12 +214,25 @@ let activeAbort: AbortController | null = null
* mid-render, and a mis-routed cancel strands a billing cloud job. */
export const hasActiveCloudRun = (): boolean => activeAbort !== null
+/** Why the last generate() was refused, when the reason holds for the next run
+ * too. A batch over several source images (lib/batch-edit) reads it after each
+ * image to decide whether going on makes sense. A code, never the message. */
+export interface CloudRunStop { reason: 'credits' | 'price' | 'auth' | 'throttle'; retryAfterMs?: number }
+let lastRunStop: CloudRunStop | null = null
+/** Reads the reason once and clears it. */
+export function takeCloudRunStop(): CloudRunStop | null {
+ const stop = lastRunStop
+ lastRunStop = null
+ return stop
+}
+
export function useCloudCreate(opts: { onQuotaChange?: () => void } = {}) {
const { onQuotaChange } = opts
const generate = useCallback(async () => {
const s = useCreateStore.getState()
if (s.isGenerating) return
+ lastRunStop = null
const intent = s.intent()
let { kind, op } = intentToJob(intent)
// Character-Studio 'use' surface: a plain image generate with the trained
@@ -708,7 +721,10 @@ export function useCloudCreate(opts: { onQuotaChange?: () => void } = {}) {
if (ids.length > 1) {
// Jedes Bild landet in der Galerie, sobald es fertig ist. Ein Auftrag,
// der scheitert, stoppt die anderen nicht und gibt nur seinen Preis zurueck.
- if (submitted.stopped === 'credits_exhausted') signalCreditsExhausted('credits')
+ if (submitted.stopped === 'credits_exhausted') {
+ signalCreditsExhausted('credits')
+ lastRunStop = { reason: 'credits' }
+ }
const finished = new Set<string>()
const outcomes = await Promise.allSettled(ids.map(async (jid, index) => {
const job = await pollJob(jid, {
@@ -813,10 +829,16 @@ export function useCloudCreate(opts: { onQuotaChange?: () => void } = {}) {
// new quote against the number this message just showed, and books.
st.setCloudStudioCredits(err.credits)
st.setError(`The price changed to ${err.credits.toLocaleString('en-US')} credits. Review it, then hit Create again.`)
+ lastRunStop = { reason: 'price' }
} else if (err instanceof CloudJobError && err.status === 429) {
st.setError(throttleMessage(err))
+ // The three money codes end a batch, a plain "too fast" only pauses it.
+ lastRunStop = err.code === 'credits_exhausted' || err.code === 'video_budget_exhausted' || err.code === 'trainings_exhausted'
+ ? { reason: 'credits' }
+ : { reason: 'throttle', retryAfterMs: err.retryAfterMs }
} else if (err instanceof CloudJobError && err.status === 401) {
st.setError('Sign in to your LU Cloud account to render in the cloud.')
+ lastRunStop = { reason: 'auth' }
} else if (err instanceof CloudJobError && err.message === 'render timed out') {
// The desktop app has no jobs-history view — point at the account
// page instead of promising an in-app surface that doesn't exist.
diff --git a/src/lib/__tests__/batch-edit.test.ts b/src/lib/__tests__/batch-edit.test.ts
new file mode 100644
index 00000000..947dacf3
--- /dev/null
+++ b/src/lib/__tests__/batch-edit.test.ts
@@ -0,0 +1,239 @@
+/**
+ * Several source images, one edit (lib/batch-edit): which files join, how fast
+ * a cloud batch sends, and when it stops. Nothing here renders or books.
+ */
+import { describe, it, expect, vi } from 'vitest'
+import {
+ MAX_BATCH_IMAGES, batchCoverage, batchOffered, batchPickNote, batchSummary, cloudRunsPerMinute,
+ createPacer, pickBatchFiles, runBatch, type RunOutcome,
+} from '../batch-edit'
+
+const file = (name: string, type = 'image/png') => new File(['x'], name, { type })
+const ok: RunOutcome = { made: 1, error: null }
+const entries = (n: number) => Array.from({ length: n }, (_, i) => ({ name: `img-${i + 1}.png` }))
+const noWait = { sleep: async () => {} }
+
+describe('where a batch is offered', () => {
+ it('Edit, Remove Background and Enhance Image, and only without a mask', () => {
+ expect(batchOffered('edit', false)).toBe(true)
+ expect(batchOffered('removebg', false)).toBe(true)
+ expect(batchOffered('upscale', false)).toBe(true)
+ expect(batchOffered('edit', true)).toBe(false)
+ expect(batchOffered('eraser', true)).toBe(false)
+ expect(batchOffered('image', false)).toBe(false)
+ expect(batchOffered('animate', false)).toBe(false)
+ })
+})
+
+describe('picking files', () => {
+ it('takes images in name order and skips everything else', () => {
+ const pick = pickBatchFiles([file('b10.png'), file('notes.txt', 'text/plain'), file('b2.png'), file('a.jpg', 'image/jpeg')], 50)
+ expect(pick.accepted.map((f) => f.name)).toEqual(['a.jpg', 'b2.png', 'b10.png'])
+ expect(pick.skipped).toBe(1)
+ expect(pick.over).toBe(0)
+ })
+
+ it('a file from a dropped folder without a type counts by its name', () => {
+ const pick = pickBatchFiles([file('shot.JPG', ''), file('readme', '')], 50)
+ expect(pick.accepted).toHaveLength(1)
+ expect(pick.accepted[0].type).toBe('image/jpeg')
+ expect(pick.skipped).toBe(1)
+ })
+
+ it('stops at the limit and says how many were left out', () => {
+ const many = Array.from({ length: 57 }, (_, i) => file(`f${i}.png`))
+ const pick = pickBatchFiles(many, MAX_BATCH_IMAGES)
+ expect(pick.accepted).toHaveLength(50)
+ expect(pick.over).toBe(7)
+ expect(batchPickNote(pick)).toBe('You can edit up to 50 images at once. 50 were added, 7 were left out.')
+ })
+
+ it('no room left: nothing is added and the note says so', () => {
+ const pick = pickBatchFiles([file('a.png')], 0)
+ expect(pick.accepted).toHaveLength(0)
+ expect(batchPickNote(pick)).toBe('The list is full. You can edit up to 50 images at once.')
+ })
+
+ it('only wrong files: the same sentence a single wrong file gets', () => {
+ expect(batchPickNote(pickBatchFiles([file('a.pdf', 'application/pdf')], 50))).toBe('That file type is not supported. Use PNG, JPG or WebP.')
+ })
+
+ it('a clean pick says nothing', () => {
+ expect(batchPickNote(pickBatchFiles([file('a.png'), file('b.png')], 50))).toBeNull()
+ })
+})
+
+describe('credits and pace', () => {
+ it('coverage counts whole images', () => {
+ expect(batchCoverage(700, 300, 12)).toBe(2)
+ expect(batchCoverage(100, 300, 12)).toBe(0)
+ expect(batchCoverage(99999, 300, 12)).toBe(12)
+ expect(batchCoverage(0, 0, 5)).toBe(5)
+ })
+
+ it('stays under 30 submits, 60 uploads and 20 quotes a minute', () => {
+ expect(cloudRunsPerMinute({ count: 1, extraPhotos: 0, studio: false })).toBe(24)
+ expect(cloudRunsPerMinute({ count: 4, extraPhotos: 0, studio: false })).toBe(6)
+ expect(cloudRunsPerMinute({ count: 1, extraPhotos: 4, studio: false })).toBe(9)
+ expect(cloudRunsPerMinute({ count: 1, extraPhotos: 0, studio: true })).toBe(10)
+ for (const count of [1, 2, 3, 4]) {
+ for (const extraPhotos of [0, 1, 2, 3, 4]) {
+ const runs = cloudRunsPerMinute({ count, extraPhotos, studio: true })
+ expect(runs * count).toBeLessThanOrEqual(30)
+ expect(runs * (1 + extraPhotos)).toBeLessThanOrEqual(60)
+ expect(runs).toBeLessThanOrEqual(20)
+ }
+ }
+ })
+
+ it('the pacer lets the limit through and makes the next start wait for the window', async () => {
+ let now = 0
+ const slept: number[] = []
+ const pacer = createPacer({ limit: 2, windowMs: 60_000, now: () => now, sleep: async (ms) => { slept.push(ms); now += ms } })
+ expect(await pacer.wait()).toBe(0)
+ now = 10_000
+ expect(await pacer.wait()).toBe(0)
+ now = 15_000
+ expect(await pacer.wait()).toBe(45_000)
+ expect(slept).toEqual([45_000])
+ expect(now).toBe(60_000)
+ })
+})
+
+describe('running the list', () => {
+ it('one failing image does not stop the others and is named at the end', async () => {
+ const runOne = vi.fn(async (e: { name: string }): Promise<RunOutcome> =>
+ e.name === 'img-2.png' ? { made: 0, error: 'provider said no' } : ok)
+ const r = await runBatch(entries(4), { runOne, cancelled: () => false, ...noWait })
+ expect(runOne).toHaveBeenCalledTimes(4)
+ expect(r.done).toBe(3)
+ expect(r.failed).toEqual([{ name: 'img-2.png', error: 'provider said no' }])
+ expect(r.pending).toEqual([1])
+ expect(r.stop).toBeNull()
+ expect(batchSummary(r)).toBe('3 of 4 images are done. 1 failed: img-2.png. Error: provider said no. What is left stays ready, hit Create to run it.')
+ })
+
+ it('all done: nothing to say', async () => {
+ const r = await runBatch(entries(3), { runOne: async () => ok, cancelled: () => false, ...noWait })
+ expect(r.done).toBe(3)
+ expect(r.pending).toEqual([])
+ expect(batchSummary(r)).toBeNull()
+ })
+
+ it('Cancel stops the rest, and the image that was cancelled is not a failure', async () => {
+ let stop = false
+ const runOne = vi.fn(async (_e: unknown, i: number): Promise<RunOutcome> => {
+ if (i === 1) { stop = true; return { made: 0, error: null } }
+ return ok
+ })
+ const r = await runBatch(entries(5), { runOne, cancelled: () => stop, ...noWait })
+ expect(runOne).toHaveBeenCalledTimes(2)
+ expect(r.done).toBe(1)
+ expect(r.failed).toEqual([])
+ expect(r.stop).toBe('cancelled')
+ expect(r.left).toBe(4)
+ expect(r.pending).toEqual([1, 2, 3, 4])
+ expect(batchSummary(r)).toBe('1 of 5 images are done. Stopped. The other 4 were not started. What is left stays ready, hit Create to run it.')
+ })
+
+ it('a run that could not be stopped still counts when its result lands', async () => {
+ let stop = false
+ const runOne = vi.fn(async (): Promise<RunOutcome> => { stop = true; return { made: 1, error: 'This render already started.' } })
+ const r = await runBatch(entries(3), { runOne, cancelled: () => stop, ...noWait })
+ expect(runOne).toHaveBeenCalledTimes(1)
+ expect(r.done).toBe(1)
+ expect(r.stop).toBe('cancelled')
+ expect(r.pending).toEqual([1, 2])
+ })
+
+ it('credits run out: the rest never starts', async () => {
+ const runOne = vi.fn(async (_e: unknown, i: number): Promise<RunOutcome> =>
+ i < 2 ? ok : { made: 0, error: "You're out of credits.", stop: 'credits' })
+ const r = await runBatch(entries(6), { runOne, cancelled: () => false, ...noWait })
+ expect(runOne).toHaveBeenCalledTimes(3)
+ expect(r.done).toBe(2)
+ expect(r.failed).toEqual([])
+ expect(r.stop).toBe('credits')
+ expect(r.left).toBe(4)
+ expect(batchSummary(r)).toBe('2 of 6 images are done. There were not enough credits to go on. The other 4 were not started and nothing was charged for them. What is left stays ready, hit Create to run it.')
+ })
+
+ it('credits run out inside a run with several results: what landed counts, the rest stops', async () => {
+ const runOne = vi.fn(async (): Promise<RunOutcome> => ({ made: 2, error: 'Started 2 of 4 images.', stop: 'credits' }))
+ const r = await runBatch(entries(3), { runOne, cancelled: () => false, ...noWait })
+ expect(runOne).toHaveBeenCalledTimes(1)
+ expect(r.done).toBe(1)
+ expect(r.notes).toEqual([{ name: 'img-1.png', error: 'Started 2 of 4 images.' }])
+ expect(r.stop).toBe('credits')
+ expect(r.pending).toEqual([1, 2])
+ })
+
+ it('a changed price stops the batch and shows the new price', async () => {
+ const msg = 'The price changed to 5,000 credits. Review it, then hit Create again.'
+ const r = await runBatch(entries(3), { runOne: async () => ({ made: 0, error: msg, stop: 'price' }), cancelled: () => false, ...noWait })
+ expect(r.stop).toBe('price')
+ expect(r.done).toBe(0)
+ expect(batchSummary(r)).toBe(`0 of 3 images are done. ${msg} The other 3 were not started. What is left stays ready, hit Create to run it.`)
+ })
+
+ it('"too fast" waits as long as the server asked and sends the same image again', async () => {
+ const slept: number[] = []
+ let calls = 0
+ const runOne = vi.fn(async (): Promise<RunOutcome> => (++calls === 1 ? { made: 0, error: 'Too many requests at once.', stop: 'throttle', retryAfterMs: 12_000 } : ok))
+ const r = await runBatch(entries(2), { runOne, cancelled: () => false, sleep: async (ms) => { slept.push(ms) } })
+ expect(slept).toEqual([12_000])
+ expect(runOne).toHaveBeenCalledTimes(3)
+ expect(r.done).toBe(2)
+ expect(r.stop).toBeNull()
+ })
+
+ it('a server that keeps saying "too fast" ends the batch after two more tries', async () => {
+ const runOne = vi.fn(async (): Promise<RunOutcome> => ({ made: 0, error: 'Too many requests at once.', stop: 'throttle' }))
+ const r = await runBatch(entries(4), { runOne, cancelled: () => false, ...noWait })
+ expect(runOne).toHaveBeenCalledTimes(3)
+ expect(r.stop).toBe('throttle')
+ expect(r.failed).toEqual([])
+ expect(r.left).toBe(4)
+ })
+
+ it('the same error three times in a row stops the rest', async () => {
+ const runOne = vi.fn(async (): Promise<RunOutcome> => ({ made: 0, error: 'ComfyUI is not running.' }))
+ const r = await runBatch(entries(8), { runOne, cancelled: () => false, ...noWait })
+ expect(runOne).toHaveBeenCalledTimes(3)
+ expect(r.stop).toBe('repeated')
+ expect(r.failed).toHaveLength(3)
+ expect(r.left).toBe(5)
+ expect(batchSummary(r)).toBe('0 of 8 images are done. 3 failed: img-1.png, img-2.png, img-3.png. The same error came back 3 times, so the other 5 were not started. Error: ComfyUI is not running. What is left stays ready, hit Create to run it.')
+ })
+
+ it('different errors do not count as the same one', async () => {
+ const runOne = vi.fn(async (_e: unknown, i: number): Promise<RunOutcome> => ({ made: 0, error: `error ${i}` }))
+ const r = await runBatch(entries(5), { runOne, cancelled: () => false, ...noWait })
+ expect(runOne).toHaveBeenCalledTimes(5)
+ expect(r.stop).toBeNull()
+ })
+
+ it('a changed tab ends the batch before the next image', async () => {
+ let valid = true
+ const runOne = vi.fn(async (): Promise<RunOutcome> => { valid = false; return ok })
+ const r = await runBatch(entries(3), { runOne, cancelled: () => false, stillValid: () => valid, ...noWait })
+ expect(runOne).toHaveBeenCalledTimes(1)
+ expect(r.stop).toBe('changed')
+ })
+
+ it('waits for the pace before every start and reports the queue', async () => {
+ const pace = vi.fn(async () => {})
+ const seen: string[] = []
+ await runBatch(entries(2), {
+ runOne: async () => ok, cancelled: () => false, pace, ...noWait,
+ onProgress: (statuses, index) => seen.push(`${index}:${statuses.join(',')}`),
+ })
+ expect(pace).toHaveBeenCalledTimes(2)
+ expect(seen).toEqual(['0:running,waiting', '0:done,waiting', '1:done,running', '1:done,done'])
+ })
+
+ it('names at most five failed files', async () => {
+ const r = await runBatch(entries(7), { runOne: async (_e, i) => ({ made: 0, error: `e${i}` }), cancelled: () => false, ...noWait })
+ expect(batchSummary(r)).toContain('7 failed: img-1.png, img-2.png, img-3.png, img-4.png, img-5.png and 2 more.')
+ })
+})
diff --git a/src/lib/__tests__/saved-characters.test.ts b/src/lib/__tests__/saved-characters.test.ts
new file mode 100644
index 00000000..0cb93424
--- /dev/null
+++ b/src/lib/__tests__/saved-characters.test.ts
@@ -0,0 +1,72 @@
+/**
+ * A character saved as photos (lib/saved-characters). The test run has no
+ * IndexedDB, so this exercises the session store behind the same functions.
+ */
+import { describe, it, expect, beforeEach, vi } from 'vitest'
+import {
+ MAX_CHARACTER_PHOTOS, __resetSavedCharacters, deleteSavedCharacter, listSavedCharacters,
+ saveCharacter, subscribeSavedCharacters,
+} from '../saved-characters'
+
+const photo = (text: string) => new Blob([text], { type: 'image/jpeg' })
+
+beforeEach(() => __resetSavedCharacters())
+
+describe('saving', () => {
+ it('keeps the photos under the name and gives them back as images', async () => {
+ const r = await saveCharacter(' Mira Vale ', [photo('one'), photo('two')])
+ expect(r.character.name).toBe('Mira Vale')
+ expect(r.added).toBe(2)
+ expect(r.merged).toBe(false)
+ const list = await listSavedCharacters()
+ expect(list).toHaveLength(1)
+ expect(list[0].photos).toHaveLength(2)
+ expect(list[0].photos[0].type).toBe('image/jpeg')
+ expect(await list[0].photos[1].text()).toBe('two')
+ })
+
+ it('the same name again adds to the same character, whatever the case', async () => {
+ await saveCharacter('Mira', [photo('one')])
+ const r = await saveCharacter('mira', [photo('two'), photo('three')])
+ expect(r.merged).toBe(true)
+ expect(r.character.photos).toHaveLength(3)
+ expect(await listSavedCharacters()).toHaveLength(1)
+ })
+
+ it('needs a name and at least one frame', async () => {
+ await expect(saveCharacter(' ', [photo('one')])).rejects.toThrow('Give the character a name.')
+ await expect(saveCharacter('Mira', [])).rejects.toThrow('Add at least one frame first.')
+ expect(await listSavedCharacters()).toEqual([])
+ })
+
+ it('keeps 30 photos at most and says how many did not fit', async () => {
+ const many = Array.from({ length: 34 }, (_, i) => photo(`p${i}`))
+ const r = await saveCharacter('Mira', many)
+ expect(r.added).toBe(MAX_CHARACTER_PHOTOS)
+ expect(r.dropped).toBe(4)
+ await expect(saveCharacter('Mira', [photo('more')])).rejects.toThrow('Mira already has 30 photos, the most a character keeps.')
+ })
+
+ it('lists the newest first', async () => {
+ vi.spyOn(Date, 'now').mockReturnValueOnce(1_000).mockReturnValueOnce(2_000)
+ await saveCharacter('First', [photo('a')])
+ await saveCharacter('Second', [photo('b')])
+ expect((await listSavedCharacters()).map((c) => c.name)).toEqual(['Second', 'First'])
+ vi.restoreAllMocks()
+ })
+})
+
+describe('deleting and listening', () => {
+ it('a delete removes the character and tells the listeners', async () => {
+ const heard = vi.fn()
+ const off = subscribeSavedCharacters(heard)
+ const { character } = await saveCharacter('Mira', [photo('one')])
+ expect(heard).toHaveBeenCalledTimes(1)
+ await deleteSavedCharacter(character.id)
+ expect(heard).toHaveBeenCalledTimes(2)
+ expect(await listSavedCharacters()).toEqual([])
+ off()
+ await saveCharacter('Mira', [photo('one')])
+ expect(heard).toHaveBeenCalledTimes(2)
+ })
+})
diff --git a/src/lib/__tests__/video-frames.test.ts b/src/lib/__tests__/video-frames.test.ts
new file mode 100644
index 00000000..3de1c330
--- /dev/null
+++ b/src/lib/__tests__/video-frames.test.ts
@@ -0,0 +1,49 @@
+// @vitest-environment jsdom
+/**
+ * A still out of a video (lib/video-frames): the frame is drawn at the video's
+ * own size and comes back as a JPEG, and a video without a picture says so.
+ */
+import { describe, it, expect, vi, afterEach } from 'vitest'
+import { frameFileName, grabFrame } from '../video-frames'
+
+afterEach(() => vi.restoreAllMocks())
+
+function fakeCanvas(toBlob: (cb: (b: Blob | null) => void, type: string, q: number) => void, draw = vi.fn()) {
+ const canvas = { width: 0, height: 0, getContext: () => ({ drawImage: draw }), toBlob }
+ const real = document.createElement.bind(document)
+ vi.spyOn(document, 'createElement').mockImplementation(((tag: string) => (tag === 'canvas' ? canvas : real(tag))) as typeof document.createElement)
+ return { canvas, draw }
+}
+
+describe('grabFrame', () => {
+ it('draws the frame at the size of the video and returns a JPEG', async () => {
+ const seen: { type: string; q: number }[] = []
+ const { canvas, draw } = fakeCanvas((cb, type, q) => { seen.push({ type, q }); cb(new Blob(['jpg'], { type })) })
+ const video = { videoWidth: 1280, videoHeight: 720 } as HTMLVideoElement
+ const blob = await grabFrame(video)
+ expect(canvas.width).toBe(1280)
+ expect(canvas.height).toBe(720)
+ expect(draw).toHaveBeenCalledWith(video, 0, 0, 1280, 720)
+ expect(seen).toEqual([{ type: 'image/jpeg', q: 0.92 }])
+ expect(blob.type).toBe('image/jpeg')
+ })
+
+ it('a video that has not loaded says so', async () => {
+ await expect(grabFrame({ videoWidth: 0, videoHeight: 0 } as HTMLVideoElement)).rejects.toThrow('The video has no picture yet. Let it load, then try again.')
+ })
+
+ it('a frame the browser will not hand out is an error, not a broken photo', async () => {
+ fakeCanvas((cb) => cb(null))
+ await expect(grabFrame({ videoWidth: 64, videoHeight: 64 } as HTMLVideoElement)).rejects.toThrow('Could not read this frame.')
+ fakeCanvas(() => { throw new Error('SecurityError') })
+ await expect(grabFrame({ videoWidth: 64, videoHeight: 64 } as HTMLVideoElement)).rejects.toThrow('Could not read this frame.')
+ })
+})
+
+describe('frameFileName', () => {
+ it('numbers the frames under the character name', () => {
+ expect(frameFileName('Mira Vale', 0)).toBe('mira-vale-01.jpg')
+ expect(frameFileName('Zoë / 2', 11)).toBe('zoë-2-12.jpg')
+ expect(frameFileName(' ', 0)).toBe('character-01.jpg')
+ })
+})
diff --git a/src/lib/batch-edit.ts b/src/lib/batch-edit.ts
new file mode 100644
index 00000000..a41a3dc2
--- /dev/null
+++ b/src/lib/batch-edit.ts
@@ -0,0 +1,317 @@
+// Several source images, one edit (Discord, cazwhin, 2026-10: "I have a folder
+// of images and need them all edited the same"). The same prompt and settings
+// run over every image, one after the other. Each image is its own run with its
+// own booking, exactly like a single Create, so nothing here knows about money:
+// it only decides which image is next and when to stop.
+//
+// Pure on purpose (no store, no network): the wiring lives in
+// components/create/experimental/batchRun.ts, the web twin in apps/web.
+
+/** The most source images one batch takes. */
+export const MAX_BATCH_IMAGES = 50
+
+/** The tabs that take several source images: Edit, Remove Background and
+ * Enhance Image. Erase Object paints a mask per image and stays single. */
+export const BATCH_INTENTS: ReadonlySet<string> = new Set(['edit', 'removebg', 'upscale'])
+
+/** A batch is only offered where a run needs no painted mask, because a mask
+ * belongs to one image. */
+export function batchOffered(intent: string, needsMask: boolean): boolean {
+ return BATCH_INTENTS.has(intent) && !needsMask
+}
+
+const IMAGE_EXT = /\.(png|jpe?g|webp|gif|bmp|avif|heic|heif)$/i
+const EXT_MIME: Record<string, string> = {
+ png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', webp: 'image/webp', gif: 'image/gif',
+ bmp: 'image/bmp', avif: 'image/avif', heic: 'image/heic', heif: 'image/heif',
+}
+
+/** A file read out of a dropped folder can arrive without a type. The name
+ * decides then, and the file gets the type the rest of Create checks. */
+function asImageFile(file: File): File | null {
+ if (file.type.startsWith('image/')) return file
+ if (file.type || !IMAGE_EXT.test(file.name)) return null
+ const ext = file.name.split('.').pop()!.toLowerCase()
+ return new File([file], file.name, { type: EXT_MIME[ext] ?? 'image/png' })
+}
+
+export interface BatchPick {
+ /** Images that fit, in name order. */
+ accepted: File[]
+ /** Files that are not images. */
+ skipped: number
+ /** Images past the limit. */
+ over: number
+}
+
+/** Which of the picked files join the batch: images only, sorted by name the
+ * way a folder shows them, and no more than there is room for. */
+export function pickBatchFiles(files: readonly File[], room: number): BatchPick {
+ const images: File[] = []
+ let skipped = 0
+ for (const f of files) {
+ const img = asImageFile(f)
+ if (img) images.push(img)
+ else skipped++
+ }
+ images.sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: 'base' }))
+ const accepted = images.slice(0, Math.max(0, room))
+ return { accepted, skipped, over: images.length - accepted.length }
+}
+
+/** What to say about a pick that did not take everything. Null when it did. */
+export function batchPickNote(pick: BatchPick): string | null {
+ const parts: string[] = []
+ if (pick.over > 0 && pick.accepted.length === 0) {
+ parts.push(`The list is full. You can edit up to ${MAX_BATCH_IMAGES} images at once.`)
+ } else if (pick.over > 0) {
+ parts.push(
+ `You can edit up to ${MAX_BATCH_IMAGES} images at once. ` +
+ `${pick.accepted.length} ${pick.accepted.length === 1 ? 'was' : 'were'} added, ${pick.over} ${pick.over === 1 ? 'was' : 'were'} left out.`,
+ )
+ }
+ if (pick.skipped > 0) {
+ parts.push(
+ pick.accepted.length === 0 && pick.over === 0
+ ? 'That file type is not supported. Use PNG, JPG or WebP.'
+ : `${pick.skipped} ${pick.skipped === 1 ? 'file is not an image and was' : 'files are not images and were'} skipped.`,
+ )
+ }
+ return parts.length ? parts.join(' ') : null
+}
+
+/** How many of `n` images the credits cover, when one image costs `cost`. */
+export function batchCoverage(remaining: number, cost: number, n: number): number {
+ if (cost <= 0) return n
+ return Math.max(0, Math.min(n, Math.floor(remaining / cost)))
+}
+
+/**
+ * How many runs per minute a cloud batch starts. The server takes 30 job
+ * submits, 60 uploads and 20 Studio quotes per minute and user. A run sends
+ * `count` submits, one upload for the source plus one per reference photo, and
+ * a Studio run asks one quote. Stays below each limit so a batch is never
+ * refused for sending too fast.
+ */
+export function cloudRunsPerMinute(opts: { count: number; extraPhotos: number; studio: boolean }): number {
+ const bySubmit = Math.floor(24 / Math.max(1, opts.count))
+ const byUpload = Math.floor(48 / (1 + Math.max(0, opts.extraPhotos)))
+ const byQuote = opts.studio ? 10 : Infinity
+ return Math.max(1, Math.min(bySubmit, byUpload, byQuote))
+}
+
+/** Lets `limit` starts through per window and makes the next one wait. */
+export function createPacer(opts: {
+ limit: number
+ windowMs?: number
+ now?: () => number
+ sleep?: (ms: number) => Promise<void>
+}): { wait: () => Promise<number> } {
+ const windowMs = opts.windowMs ?? 60_000
+ const now = opts.now ?? (() => Date.now())
+ const sleep = opts.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)))
+ const starts: number[] = []
+ return {
+ /** Resolves when the next start is allowed. Returns how long it waited. */
+ async wait() {
+ let waited = 0
+ for (;;) {
+ const t = now()
+ while (starts.length && t - starts[0] >= windowMs) starts.shift()
+ if (starts.length < opts.limit) {
+ starts.push(t)
+ return waited
+ }
+ const ms = windowMs - (t - starts[0])
+ waited += ms
+ await sleep(ms)
+ }
+ },
+ }
+}
+
+export type BatchStatus = 'waiting' | 'running' | 'done' | 'failed'
+
+/** What the queue shows while a batch runs. */
+export interface BatchRunState {
+ /** The image that is running now. */
+ index: number
+ statuses: BatchStatus[]
+ names: string[]
+ thumbs: string[]
+}
+
+/** Why a batch ended before its last image. */
+export type BatchStop =
+ | 'cancelled' // the user hit Cancel
+ | 'credits' // the wallet ran dry
+ | 'price' // the confirmed price was higher than the one shown
+ | 'auth' // signed out
+ | 'throttle' // the server kept saying "too fast"
+ | 'changed' // the tab or the mode changed under the run
+ | 'repeated' // the same error three times in a row
+
+/** One image's run, as the batch sees it. */
+export interface RunOutcome {
+ /** Results that landed in the gallery. */
+ made: number
+ /** What the run said went wrong, if anything. */
+ error: string | null
+ /** The run was refused for a reason that holds for every further image. */
+ stop?: 'credits' | 'price' | 'auth' | 'throttle'
+ /** With `throttle`: how long the server asked to wait. */
+ retryAfterMs?: number
+}
+
+export interface BatchReport {
+ total: number
+ done: number
+ failed: { name: string; error: string }[]
+ /** Images that made a result and also reported a problem (one of several
+ * results failed). */
+ notes: { name: string; error: string }[]
+ /** Indexes that have no result: failed ones and ones that never started. */
+ pending: number[]
+ /** Images that never started. */
+ left: number
+ stop: BatchStop | null
+ stopDetail: string | null
+}
+
+const SAME_ERROR_LIMIT = 3
+const THROTTLE_RETRIES = 2
+
+/**
+ * Runs the images one after the other.
+ *
+ * One image failing does not stop the others. The batch stops early only when
+ * going on makes no sense: Cancel, an empty wallet, a changed price, a sign
+ * out, a server that keeps refusing the pace, a changed tab, or the same error
+ * three times in a row (an engine that is down fails every image the same way).
+ * Whatever did not start is never booked, because it is never sent.
+ */
+export async function runBatch<T extends { name: string }>(
+ entries: readonly T[],
+ deps: {
+ runOne: (entry: T, index: number) => Promise<RunOutcome>
+ cancelled: () => boolean
+ /** False once the tab or mode the batch started in is gone. */
+ stillValid?: () => boolean
+ /** Resolves when the next start is allowed (the send limit). */
+ pace?: () => Promise<unknown>
+ sleep?: (ms: number) => Promise<void>
+ onProgress?: (statuses: BatchStatus[], index: number) => void
+ },
+): Promise<BatchReport> {
+ const sleep = deps.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)))
+ const statuses: BatchStatus[] = entries.map(() => 'waiting')
+ const failed: BatchReport['failed'] = []
+ const notes: BatchReport['notes'] = []
+ let done = 0
+ let stop: BatchStop | null = null
+ let stopDetail: string | null = null
+ let lastError: string | null = null
+ let sameError = 0
+
+ for (let i = 0; i < entries.length; i++) {
+ if (deps.cancelled()) { stop = 'cancelled'; break }
+ if (deps.stillValid && !deps.stillValid()) { stop = 'changed'; break }
+ await deps.pace?.()
+ if (deps.cancelled()) { stop = 'cancelled'; break }
+
+ statuses[i] = 'running'
+ deps.onProgress?.([...statuses], i)
+ let out = await deps.runOne(entries[i], i)
+ // "Too fast" is about the pace, not about this image: wait as long as the
+ // server asked and send the same image again.
+ for (let retry = 0; out.stop === 'throttle' && out.made === 0 && retry < THROTTLE_RETRIES && !deps.cancelled(); retry++) {
+ await sleep(Math.min(60_000, Math.max(1_000, out.retryAfterMs ?? 5_000)))
+ if (deps.cancelled()) break
+ out = await deps.runOne(entries[i], i)
+ }
+
+ if (out.made > 0) {
+ statuses[i] = 'done'
+ done++
+ sameError = 0
+ lastError = null
+ if (out.error) notes.push({ name: entries[i].name, error: out.error })
+ } else if (deps.cancelled()) {
+ // A run the user stopped is not a failed image. It stays in the list.
+ statuses[i] = 'waiting'
+ stop = 'cancelled'
+ } else if (out.stop) {
+ // Refused before anything was booked, for a reason that is not about
+ // this image. It stays in the list like the ones behind it.
+ statuses[i] = 'waiting'
+ } else {
+ const error = out.error ?? 'No result came back.'
+ statuses[i] = 'failed'
+ failed.push({ name: entries[i].name, error })
+ sameError = error === lastError ? sameError + 1 : 1
+ lastError = error
+ }
+ deps.onProgress?.([...statuses], i)
+
+ if (stop) break
+ if (out.stop) { stop = out.stop; stopDetail = out.error; break }
+ if (sameError >= SAME_ERROR_LIMIT && i < entries.length - 1) { stop = 'repeated'; stopDetail = lastError; break }
+ }
+
+ const pending = statuses.flatMap((s, i) => (s === 'done' ? [] : [i]))
+ return {
+ total: entries.length,
+ done,
+ failed,
+ notes,
+ pending,
+ left: statuses.filter((s) => s === 'waiting').length,
+ stop,
+ stopDetail,
+ }
+}
+
+/** An error text as a closed sentence, so the next one does not run into it. */
+function sentence(text: string): string {
+ const t = text.trim()
+ return /[.!?…]$/.test(t) ? t : `${t}.`
+}
+
+function nameList(names: string[]): string {
+ const shown = names.slice(0, 5).join(', ')
+ return names.length > 5 ? `${shown} and ${names.length - 5} more` : shown
+}
+
+/** What to tell the user once a batch ends. Null when every image is done. */
+export function batchSummary(r: BatchReport): string | null {
+ if (!r.stop && r.failed.length === 0 && r.notes.length === 0) return null
+ const parts: string[] = [`${r.done} of ${r.total} images are done.`]
+ if (r.failed.length) {
+ parts.push(`${r.failed.length} failed: ${nameList(r.failed.map((f) => f.name))}.`)
+ if (r.stop !== 'repeated') parts.push(`${r.failed.length === 1 ? 'Error' : 'First error'}: ${sentence(r.failed[0].error)}`)
+ }
+ if (r.notes.length) parts.push(`${r.notes[0].name}: ${sentence(r.notes[0].error)}`)
+ const rest = r.left === 1 ? 'The last image was' : `The other ${r.left} were`
+ switch (r.stop) {
+ case 'cancelled':
+ parts.push(r.left > 0 ? `Stopped. ${rest} not started.` : 'Stopped.')
+ break
+ case 'credits':
+ parts.push(`There were not enough credits to go on. ${rest} not started and nothing was charged for them.`)
+ break
+ case 'price':
+ case 'auth':
+ case 'throttle':
+ if (r.stopDetail) parts.push(sentence(r.stopDetail))
+ parts.push(`${rest} not started.`)
+ break
+ case 'changed':
+ parts.push(`Stopped because the tab or the mode changed. ${rest} not started.`)
+ break
+ case 'repeated':
+ parts.push(`The same error came back ${SAME_ERROR_LIMIT} times, so ${rest.replace(/^The/, 'the')} not started. Error: ${sentence(r.stopDetail ?? 'unknown')}`)
+ break
+ }
+ if (r.pending.length > 0) parts.push('What is left stays ready, hit Create to run it.')
+ return parts.join(' ')
+}
diff --git a/src/lib/saved-characters.ts b/src/lib/saved-characters.ts
new file mode 100644
index 00000000..bfbca104
--- /dev/null
+++ b/src/lib/saved-characters.ts
@@ -0,0 +1,152 @@
+// A character saved as photos (Discord, applejames, 2026-10: "If I like the
+// look of a character who appeared in a video I generated, is there a way to
+// simply save that character?").
+//
+// A character in LU was only ever a trained LoRA. This is the short way in
+// front of that: a name plus a handful of photos, kept on this machine. The
+// photos load back into the reference strip with one click (models that read
+// several photos of a figure need no training at all), or go to Character
+// Studio as the start of a training set.
+//
+// The bytes live in IndexedDB, never in localStorage: thirty frames are a few
+// megabytes, and the create store's own quota is five.
+
+/** The most photos one saved character keeps. Cloud training takes 30. */
+export const MAX_CHARACTER_PHOTOS = 30
+export const MAX_CHARACTER_NAME = 40
+
+export interface SavedCharacter {
+ id: string
+ name: string
+ createdAt: number
+ photos: Blob[]
+}
+
+/** What is written to disk. Bytes plus type instead of a Blob: WebKit has
+ * lost Blobs stored in IndexedDB before, an ArrayBuffer always comes back. */
+interface StoredCharacter {
+ id: string
+ name: string
+ createdAt: number
+ photos: { type: string; bytes: ArrayBuffer }[]
+}
+
+const DB_NAME = 'lu-saved-characters'
+const STORE = 'characters'
+
+const hasIDB = (): boolean => {
+ try { return typeof indexedDB !== 'undefined' && indexedDB !== null } catch { return false }
+}
+
+// Without IndexedDB (a test run, a degraded webview) the characters live for
+// the session only. Saving still works, it just does not survive a restart.
+const memory = new Map<string, StoredCharacter>()
+
+let db: Promise<IDBDatabase> | null = null
+function open(): Promise<IDBDatabase> {
+ if (db) return db
+ const opening = new Promise<IDBDatabase>((resolve, reject) => {
+ const req = indexedDB.open(DB_NAME, 1)
+ req.onupgradeneeded = () => {
+ if (!req.result.objectStoreNames.contains(STORE)) req.result.createObjectStore(STORE, { keyPath: 'id' })
+ }
+ req.onsuccess = () => resolve(req.result)
+ req.onerror = () => reject(req.error)
+ req.onblocked = () => reject(new Error('indexedDB open blocked'))
+ })
+ db = opening
+ // A failed open must not stay cached, or one busy moment breaks the session.
+ opening.catch(() => { if (db === opening) db = null })
+ return opening
+}
+
+function request<T>(mode: IDBTransactionMode, run: (store: IDBObjectStore) => IDBRequest<T>): Promise<T> {
+ return open().then((database) => new Promise<T>((resolve, reject) => {
+ const tx = database.transaction(STORE, mode)
+ const req = run(tx.objectStore(STORE))
+ tx.oncomplete = () => resolve(req.result)
+ tx.onerror = () => reject(tx.error)
+ tx.onabort = () => reject(tx.error)
+ }))
+}
+
+async function readAll(): Promise<StoredCharacter[]> {
+ if (!hasIDB()) return [...memory.values()]
+ return request<StoredCharacter[]>('readonly', (s) => s.getAll())
+}
+
+async function write(row: StoredCharacter): Promise<void> {
+ if (!hasIDB()) { memory.set(row.id, row); return }
+ await request('readwrite', (s) => s.put(row))
+}
+
+const listeners = new Set<() => void>()
+/** Fires after every save and delete. */
+export function subscribeSavedCharacters(fn: () => void): () => void {
+ listeners.add(fn)
+ return () => { listeners.delete(fn) }
+}
+function changed(): void {
+ for (const fn of listeners) fn()
+}
+
+function revive(row: StoredCharacter): SavedCharacter {
+ return {
+ id: row.id,
+ name: row.name,
+ createdAt: row.createdAt,
+ photos: row.photos.map((p) => new Blob([p.bytes], { type: p.type || 'image/jpeg' })),
+ }
+}
+
+/** Every saved character, newest first. */
+export async function listSavedCharacters(): Promise<SavedCharacter[]> {
+ const rows = await readAll()
+ return rows.sort((a, b) => b.createdAt - a.createdAt).map(revive)
+}
+
+export interface SaveResult {
+ character: SavedCharacter
+ /** Photos that were added by this save. */
+ added: number
+ /** Photos that did not fit under the limit. */
+ dropped: number
+ /** True when the name already existed and the photos joined it. */
+ merged: boolean
+}
+
+/**
+ * Saves photos under a name. A name that exists already (upper and lower case
+ * count as the same) gets the photos added, so a second video of the same
+ * figure grows the same character.
+ */
+export async function saveCharacter(name: string, photos: readonly Blob[]): Promise<SaveResult> {
+ const clean = name.trim().replace(/\s+/g, ' ').slice(0, MAX_CHARACTER_NAME)
+ if (!clean) throw new Error('Give the character a name.')
+ if (photos.length === 0) throw new Error('Add at least one frame first.')
+ const rows = await readAll()
+ const existing = rows.find((r) => r.name.toLowerCase() === clean.toLowerCase())
+ const room = MAX_CHARACTER_PHOTOS - (existing?.photos.length ?? 0)
+ const take = photos.slice(0, Math.max(0, room))
+ if (take.length === 0) {
+ throw new Error(`${existing?.name ?? clean} already has ${MAX_CHARACTER_PHOTOS} photos, the most a character keeps.`)
+ }
+ const fresh = await Promise.all(take.map(async (p) => ({ type: p.type || 'image/jpeg', bytes: await p.arrayBuffer() })))
+ const row: StoredCharacter = existing
+ ? { ...existing, photos: [...existing.photos, ...fresh] }
+ : { id: crypto.randomUUID(), name: clean, createdAt: Date.now(), photos: fresh }
+ await write(row)
+ changed()
+ return { character: revive(row), added: take.length, dropped: photos.length - take.length, merged: !!existing }
+}
+
+export async function deleteSavedCharacter(id: string): Promise<void> {
+ if (!hasIDB()) memory.delete(id)
+ else await request('readwrite', (s) => s.delete(id))
+ changed()
+}
+
+/** Test seam: forget the in-memory characters. */
+export function __resetSavedCharacters(): void {
+ memory.clear()
+}
diff --git a/src/lib/video-frames.ts b/src/lib/video-frames.ts
new file mode 100644
index 00000000..3b84e731
--- /dev/null
+++ b/src/lib/video-frames.ts
@@ -0,0 +1,29 @@
+// A still out of a playing video: the frame on screen, drawn onto a canvas.
+// No decoder, no dependency. The video has to come from a blob: URL (or the
+// app's own origin), a frame of a foreign URL cannot be read back.
+
+/** The frame the video shows right now, as a JPEG. */
+export function grabFrame(video: HTMLVideoElement, quality = 0.92): Promise<Blob> {
+ const width = video.videoWidth
+ const height = video.videoHeight
+ if (!width || !height) return Promise.reject(new Error('The video has no picture yet. Let it load, then try again.'))
+ const canvas = document.createElement('canvas')
+ canvas.width = width
+ canvas.height = height
+ const ctx = canvas.getContext('2d')
+ if (!ctx) return Promise.reject(new Error('Could not read this frame.'))
+ return new Promise<Blob>((resolve, reject) => {
+ try {
+ ctx.drawImage(video, 0, 0, width, height)
+ canvas.toBlob((blob) => (blob ? resolve(blob) : reject(new Error('Could not read this frame.'))), 'image/jpeg', quality)
+ } catch {
+ reject(new Error('Could not read this frame.'))
+ }
+ })
+}
+
+/** The file name of the n-th frame of a character. */
+export function frameFileName(name: string, index: number): string {
+ const base = name.trim().replace(/[^\p{L}\p{N}]+/gu, '-').replace(/^-+|-+$/g, '').toLowerCase() || 'character'
+ return `${base}-${String(index + 1).padStart(2, '0')}.jpg`
+}
diff --git a/src/stores/createStore.ts b/src/stores/createStore.ts
index f7615a4c..754aea1a 100644
--- a/src/stores/createStore.ts
+++ b/src/stores/createStore.ts
@@ -2,6 +2,7 @@ import { create } from 'zustand'
import { maxTrainImages } from '../lib/train-image-cap'
import { MAX_STORED_REFERENCES } from '../lib/edit-references'
import { clampImageCount } from '../lib/render/image-count'
+import { BATCH_INTENTS, type BatchRunState } from '../lib/batch-edit'
import type { FixupPrompt } from '../lib/render-fixups'
import { persist } from 'zustand/middleware'
import { safeJSONStorage } from '../lib/storage-quota'
@@ -15,6 +16,8 @@ import { isRecord } from '../types/json-guards'
*/
const RUNTIME_ONLY_KEYS: readonly string[] = [
'backend', 'source', 'mask', 'references', 'caps', 'isGenerating', 'comfyCorsBlocked',
+ // A queue of source images from yesterday must never start a run today.
+ 'batchSources', 'batchRun',
// Ein gespeicherter Preis von gestern ist eine Luege (siehe partialize
// unten): auch wenn ein fremder/aelterer Blob ihn doch mitbringt, darf er
// nie zurueckkommen.
@@ -236,6 +239,8 @@ export interface GalleryItem {
jobId?: string
/** Which redesign intent produced this item (gallery tagging). */
intent?: CreateIntent
+ /** Several source images, one edit: the file this result was made from. */
+ sourceName?: string
/** Kurze Ueberschrift, wenn der Prompt nicht sagt, was dabei herauskam: der
* Titel des Presets, die Beschreibung des Schrittes. Siehe gallery-label.ts. */
label?: string
@@ -358,6 +363,12 @@ interface CreateState {
/** Edit: further reference images after the source, for a model that takes
* them (lib/edit-references). Runtime-only like `source`; cleared with it. */
references: ImageRef[]
+ /** Several source images, one edit (lib/batch-edit): the files that get the
+ * same run, one after the other. Empty for a single image, else two or more,
+ * and `source` shows the first. Runtime-only like `source`. */
+ batchSources: MediaRef[]
+ /** The queue of a running batch, null when none runs. */
+ batchRun: BatchRunState | null
sourceSetAt: number
mask: ImageRef | null
/** Runtime-only: local (Bridge) vs cloud (/api/jobs), derived from session. */
@@ -511,6 +522,8 @@ interface CreateState {
addReference: (img: ImageRef) => void
removeReference: (index: number) => void
setReferences: (refs: ImageRef[]) => void
+ setBatchSources: (list: MediaRef[]) => void
+ setBatchRun: (run: BatchRunState | null) => void
setMask: (img: ImageRef | null) => void
setBackend: (backend: CreateBackend) => void
setCloudImageModel: (id: string) => void
@@ -703,6 +716,8 @@ export const useCreateStore = create<CreateState>()(
growMaskBy: 6,
source: null as ImageRef | null,
references: [] as ImageRef[],
+ batchSources: [] as MediaRef[],
+ batchRun: null as BatchRunState | null,
sourceSetAt: 0,
mask: null as ImageRef | null,
backend: 'local' as CreateBackend,
@@ -900,6 +915,8 @@ export const useCreateStore = create<CreateState>()(
}
})
if (changed) set({ cloudStudioOptions: {} })
+ // The list of further source images stays only where it can run.
+ if (get().batchSources.length && (!get().source || !BATCH_INTENTS.has(intent))) get().setBatchSources([])
},
toggleNegative: () => set((s) => ({ showNegative: !s.showNegative })),
toggleLora: (name) => set((s) => ({ selectedLoras: s.selectedLoras.some((l) => l.name === name) ? s.selectedLoras.filter((l) => l.name !== name) : [...s.selectedLoras, { name, strength: 0.8 }] })),
@@ -1000,12 +1017,21 @@ export const useCreateStore = create<CreateState>()(
setMusicDuration: (s2) => set({ musicDuration: Math.max(5, Math.min(240, Math.floor(s2))) }),
setMusicLyrics: (musicLyrics) => set({ musicLyrics: musicLyrics.slice(0, 2000) }),
setMusicHowtoSeen: (musicHowtoSeen) => set({ musicHowtoSeen }),
- setSource: (source) => set({ source, sourceSetAt: source ? Date.now() : 0, ...(source ? {} : { mask: null, references: [] }) }),
+ setSource: (source) => {
+ // The list of further source images goes with the image it belongs to.
+ if (!source) get().setBatchSources([])
+ set({ source, sourceSetAt: source ? Date.now() : 0, ...(source ? {} : { mask: null, references: [] }) })
+ },
// Capped at the most any model takes, local or cloud (lib/edit-references);
// the UI offers fewer for a model with fewer slots and the builder slices.
addReference: (img) => set((s) => ({ references: [...s.references, img].slice(0, MAX_STORED_REFERENCES) })),
removeReference: (index) => set((s) => ({ references: s.references.filter((_, i) => i !== index) })),
setReferences: (references) => set({ references }),
+ setBatchSources: (batchSources) => {
+ releaseDroppedMediaRefs(get().batchSources, batchSources)
+ set({ batchSources })
+ },
+ setBatchRun: (batchRun) => set({ batchRun }),
setMask: (mask) => set({ mask }),
// Flipping to local clears the intents that have no local lane
// (upscale/eraser plus character training — all hosted-only) so the