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(character): the stage (variant B), a first page, New character, LoRA drop, Rename

purpleb505efb950ec
diff --git a/e2e/character-hub.spec.ts b/e2e/character-hub.spec.ts
index 4aa977d0..989a98d6 100644
--- a/e2e/character-hub.spec.ts
+++ b/e2e/character-hub.spec.ts
@@ -1,13 +1,15 @@
import { test, expect, type Page } from '@playwright/test'
import { tauriMockInit, DEFAULT_ASSISTANT_REPLY, DEFAULT_MODEL_NAME, type TauriMockOptions } from './support/tauri-mock'
import { routeCloud, seedOnboardingDone, signInViaGate, cloudSwitch } from './support/cloud-mock'
-import { characterPill, openCharacterHub } from './support/character-hub'
+import { characterPill, openCharacterHub, openCharacterTraining } from './support/character-hub'
/**
- * The Character area of Create (3.1.0 part B, David's sketches v2): one pill
- * "Character" instead of Character, Motion, Lipsync and Swap. Step 1 Who?
- * (every character), step 2 What? (Image, Swap, Motion, Talk with their
- * price), step 3 the panel. The head line switches character and action.
+ * The Character area of Create (3.1.0 part B, the stage David chose on
+ * 16.11.2026): one pill "Character" instead of Character, Motion, Lipsync
+ * and Swap. The characters are tabs, the picked one stands on the left with
+ * its photos beside it, and the bar at the foot switches between Image,
+ * Swap, Motion and Talk. Without a character the area shows its three steps
+ * and "Create a character"; "New character" is a page of its own.
* Swap, the sound choice and the lip sync step need the account switch of
* the server (features.characterHub); without it Swap says "Coming soon".
*
@@ -128,7 +130,7 @@ async function shoot(page: Page, name: string, focus?: string) {
const dir = process.env.LU_HUB_SHOTS_DIR
if (!dir) return
// The area from its top, as the sketches show it.
- await page.locator('[data-character-hub] .overflow-y-auto').first().evaluate((el) => { el.scrollTop = 0 }).catch(() => undefined)
+ await page.evaluate(() => { for (const el of document.querySelectorAll('[data-character-hub] .hub-body, [data-character-hub] .hub-new, [data-character-hub] .overflow-y-auto')) el.scrollTop = 0 })
if (focus) await page.locator(focus).first().evaluate((el) => el.scrollIntoView({ block: 'end' }))
for (const theme of ['dark', 'light'] as const) {
await page.evaluate((t) => {
@@ -144,15 +146,21 @@ async function shoot(page: Page, name: string, focus?: string) {
})
}
-/** Two saved photo characters, made the way a customer makes them. */
+/** A saved photo character, made the way a customer makes one: the page
+ * "New character", photos, a name, Save. */
async function savePhotoCharacter(page: Page, name: string, file: string, copies: number) {
const photo = await media(file, 'image/png')
- await page.locator('input[aria-label="Upload photos or a LoRA file"]').setInputFiles(
+ await page.locator('[data-hub-new]').click()
+ await expect(page.locator('[data-character-hub]')).toHaveAttribute('data-character-hub', 'new')
+ // Nothing stands there before the user's own photos.
+ await expect(page.locator('[data-hub-photos]')).toHaveCount(0)
+ await page.locator('input[aria-label="Photos or a LoRA file"]').setInputFiles(
Array.from({ length: copies }, (_, i) => ({ ...photo, name: `${name}-${i + 1}.png` })),
)
- await page.getByRole('textbox', { name: 'Name of the new character' }).fill(name)
- await page.getByRole('button', { name: 'Save', exact: true }).click()
- await expect(page.locator(`[data-hub-character^="saved:"]`, { hasText: name })).toBeVisible()
+ await expect(page.locator('[data-hub-photos]')).toHaveAttribute('data-hub-photos', String(copies))
+ await page.locator('[data-hub-new-name]').fill(name)
+ await page.getByRole('button', { name: `Save ${name}`, exact: true }).click()
+ await expect(page.locator(`[data-hub-character^="saved:"]`, { hasText: name })).toHaveAttribute('aria-selected', 'true')
}
/** A tap on the first frame at a share of its width and height. */
@@ -163,7 +171,7 @@ async function tapFrame(page: Page, x: number, y: number) {
await frame.click({ position: { x: box.width * x, y: box.height * y } })
}
-test('one pill, three steps: who, what, the panel, and the head line switches both', async ({ page }) => {
+test('one pill: the characters as tabs, the stage, and the bar switches the action', async ({ page }) => {
const seen = await boot(page, { hub: true })
// The four old pills are one now, marked new.
@@ -173,30 +181,34 @@ test('one pill, three steps: who, what, the panel, and the head line switches bo
await expect(page.getByRole('radio', { name: old, exact: true })).toHaveCount(0)
}
- // Step 1: every source in one list, rows with their meta.
+ // Every source is a tab; the first character takes the stage by itself.
await openCharacterHub(page)
const hub = page.locator('[data-character-hub]')
- await expect(hub).toHaveAttribute('data-character-hub', 'who')
- await expect(page.locator('[data-hub-character="cloud:11111111-1111-4111-8111-111111111111"]')).toContainText('Trained · Flux')
- await expect(page.locator('[data-hub-character="cloud:22222222-2222-4222-8222-222222222222"]')).toContainText('Trained · Qwen')
+ await expect(hub).toHaveAttribute('data-character-hub', 'what')
+ const bean = page.locator('[data-hub-character="cloud:11111111-1111-4111-8111-111111111111"]')
+ await expect(bean).toHaveAttribute('aria-selected', 'true')
+ await expect(page.locator('[data-hub-card]')).toContainText('Trained · Flux')
+ await page.locator('[data-hub-character="cloud:22222222-2222-4222-8222-222222222222"]').click()
+ await expect(page.locator('[data-hub-card]')).toContainText('Trained · Qwen')
await savePhotoCharacter(page, 'Sam', 'sam-altman.png', 12)
+ await expect(page.locator('[data-hub-card]')).toContainText('Photos · 12')
+ // Only the character's own photos stand on the stage.
+ await expect(page.getByRole('list', { name: 'Photos of Sam' }).locator('img')).toHaveCount(12)
await savePhotoCharacter(page, 'Oma', 'oma.png', 8)
- await expect(page.locator('[data-hub-character^="saved:"]', { hasText: 'Sam' })).toContainText('Photos · 12')
- await expect(page.locator('[data-hub-new]')).toHaveText(/Train from photos\s*·\s*Upload photos or LoRA\s*·\s*From my gallery/)
- await expect(page.getByRole('button', { name: 'Just use a photo' })).toBeVisible()
+ await expect(page.locator('[data-hub-photo-only]')).toBeVisible()
await shoot(page, 'a-wer')
- // Step 2: what Bean should do, with the catalogue's prices.
- await page.locator('[data-hub-character^="cloud:1111"]').click()
+ // What Bean should do: the bar asks, nothing is picked yet.
+ await bean.click()
await expect(hub).toHaveAttribute('data-character-hub', 'what')
- await expect(page.getByText('What should Bean do?')).toBeVisible()
- await expect(page.locator('[data-hub-action="swap"] [data-hub-action-meta]')).toHaveText('8k / s')
- await expect(page.locator('[data-hub-action="image"] [data-hub-action-meta]')).toContainText('from 3k')
+ await expect(page.locator('[data-hub-action-line]')).toHaveText('What should Bean do?')
+ for (const a of ['image', 'swap', 'motion', 'talk']) await expect(page.locator(`[data-hub-action="${a}"]`)).toHaveAttribute('aria-checked', 'false')
await shoot(page, 'b-was')
- // Step 3: Swap, Bean on person 1.
+ // Swap, Bean on person 1, with the catalogue's price.
await page.getByRole('radio', { name: 'Swap Character', exact: true }).click()
await expect(hub).toHaveAttribute('data-character-hub', 'panel')
+ await expect(page.locator('[data-hub-action-meta]')).toHaveText('8k / s')
await expect(page.locator('[data-swap-controls]')).toBeVisible()
await expect(page.getByRole('button', { name: 'Character for person 1' })).toContainText('Bean')
await page.locator('[data-swap-controls] input[type=file][accept^="video"]').setInputFiles(await clip(page, 'clip.webm', 'clip.mp4'))
@@ -215,35 +227,36 @@ test('one pill, three steps: who, what, the panel, and the head line switches bo
await expect(page.getByRole('radio', { name: 'New voice, lips in sync' })).toBeDisabled()
await page.getByRole('checkbox').check()
// The bar: model, length, price with its parts.
- await expect(page.getByRole('button', { name: 'Length' })).toContainText('6 s')
- await expect(page.locator('[data-clip-price]')).toContainText('62k')
- await expect(page.locator('[data-clip-split]')).toContainText('frame 14k + video 48k')
+ // (6 s and 62k with the real clip of LU_HUB_MEDIA_DIR; the clip recorded
+ // in the page is shorter.)
+ await expect(page.getByRole('button', { name: 'Length' })).toContainText(/\d+ s/)
+ await expect(page.locator('[data-clip-price]')).toContainText(/\d+k/)
+ await expect(page.locator('[data-clip-split]')).toContainText(/frame 14k \+ video \d+k/)
await shoot(page, 'c-swap')
- // The head line: another action keeps the character.
- await page.getByRole('button', { name: 'Action' }).click()
- await page.getByRole('option', { name: /^Motion/ }).click()
+ // Another action keeps the character.
+ await page.getByRole('radio', { name: 'Motion Control', exact: true }).click()
await expect(page.locator('[data-motion-controls]')).toBeVisible()
await expect(page.locator('[data-portrait-line]')).toContainText('Bean', { timeout: 15_000 })
- // The video of Swap came along; the head line's X takes it away.
+ // The video of Swap came along; the X in the bar takes it away.
await expect(page.locator('[data-hub-clip]')).toContainText('clip.mp4')
await page.getByRole('button', { name: 'Remove the video' }).click()
await page.locator('[data-motion-controls] input[type=file][accept^="video"]').setInputFiles(await clip(page, 'podcast.webm', 'podcast.mp4'))
await expect(page.locator('[data-hub-clip]')).toContainText('podcast.mp4')
await expect(page.locator('[data-sound-controls=motion]')).toBeVisible()
- // Another character from the head line takes the portrait's place.
- await page.getByRole('button', { name: 'Character', exact: true }).click()
- await page.getByRole('option', { name: /^Sam/ }).click()
+ // Another character's tab takes the portrait's place.
+ await page.locator('[data-hub-character^="saved:"]', { hasText: 'Sam' }).click()
await expect(page.locator('[data-portrait-line]')).toContainText('Sam', { timeout: 15_000 })
await shoot(page, 'e-motion')
- // Talk, then back to the list.
- await page.getByRole('button', { name: 'Action' }).click()
- await page.getByRole('option', { name: /^Talk/ }).click()
+ // Talk, then Image with its price.
+ await page.getByRole('radio', { name: 'Talking Character', exact: true }).click()
+ await expect(page.locator('[data-talk-controls]')).toBeVisible()
+ await bean.click()
+ await page.getByRole('radio', { name: 'Character Studio', exact: true }).click()
+ await expect(page.locator('[data-hub-action-meta]')).toContainText('from 3k')
+ await page.getByRole('radio', { name: 'Talking Character', exact: true }).click()
await expect(page.locator('[data-talk-controls]')).toBeVisible()
- await page.getByRole('button', { name: 'Character', exact: true }).click()
- await page.getByRole('option', { name: 'All characters…' }).click()
- await expect(hub).toHaveAttribute('data-character-hub', 'who')
// The pill goes back to the action that was open.
await page.getByRole('radio', { name: /^Image$/ }).click()
@@ -264,23 +277,26 @@ test('Image runs on the character, More options keeps its file actions', async (
// The prompt sits in the bar, like the chat's composer.
await expect(page.getByPlaceholder('Describe the scene for your character…')).toBeVisible()
await page.getByRole('button', { name: 'More options' }).click()
- await expect(page.locator('[data-character-file-actions]')).toBeVisible()
- await expect(page.getByTestId('character-download')).toBeVisible()
+ const more = page.getByTestId('hub-more')
+ await expect(more.locator('[data-character-file-actions]')).toBeVisible()
+ await expect(more.getByTestId('character-download')).toBeVisible()
+ // The same file actions stand at the character on the stage.
+ await expect(page.locator('[data-hub-card] [data-character-file-actions]')).toBeVisible()
})
test('without the account switch: Swap says coming soon, Motion has no sound choice', async ({ page }) => {
const seen = await boot(page, { hub: false })
await openCharacterHub(page)
- await page.getByRole('button', { name: 'Just use a photo' }).click()
- await expect(page.locator('[data-hub-action="swap"] [data-hub-action-meta]')).toHaveText('Coming soon to your LU Cloud')
+ await page.locator('[data-hub-photo-only]').click()
+ await expect(page.locator('[data-hub-card="photo"]')).toContainText('Just use a photo')
await shoot(page, 'ohne-schalter-b')
await page.getByRole('radio', { name: 'Swap Character', exact: true }).click()
+ await expect(page.locator('[data-hub-action-meta]')).toHaveText('Coming soon to your LU Cloud')
await expect(page.locator('[data-swap-unavailable="soon"]')).toHaveText('Coming soon to your LU Cloud')
await expect(page.locator('[data-swap-controls]')).toHaveCount(0)
await expect(page.getByRole('button', { name: /^Create/ }).last()).toBeDisabled()
await shoot(page, 'ohne-schalter-swap')
- await page.getByRole('button', { name: 'Action' }).click()
- await page.getByRole('option', { name: /^Motion/ }).click()
+ await page.getByRole('radio', { name: 'Motion Control', exact: true }).click()
await expect(page.locator('[data-motion-controls]')).toBeVisible()
await expect(page.locator('[data-sound-controls]')).toHaveCount(0)
expect(seen.submits).toHaveLength(0)
@@ -328,10 +344,11 @@ test('with the switch: Swap is one click, the check stops after the frame', asyn
test('local mode: Swap is locked to the cloud, the local lanes are there', async ({ page }) => {
await boot(page, { hub: true, local: true, mock: { platform: 'mac', mlx: { ltx2EngineInstalled: true, installedVideos: ['ltx-2.3-q4', 'ltx-2.3-motion-control'], loras: [{ name: 'char_opa_zimage.safetensors' }] } } })
await openCharacterHub(page)
- await expect(page.locator('[data-hub-character="mlx:char_opa_zimage.safetensors"]')).toContainText('Local LoRA', { timeout: 15_000 })
- await page.locator('[data-hub-character="mlx:char_opa_zimage.safetensors"]').click()
+ await expect(page.locator('[data-hub-character="mlx:char_opa_zimage.safetensors"]')).toHaveAttribute('aria-selected', 'true', { timeout: 15_000 })
+ await expect(page.locator('[data-hub-card]')).toContainText('Local LoRA')
+ // A local LoRA has no picture and no photos here: a line says so, nothing stands in.
+ await expect(page.locator('[data-hub-no-photos]')).toBeVisible()
await expect(page.getByRole('radio', { name: 'Swap Character, runs on LU Cloud' })).toBeVisible()
- await expect(page.locator('[data-hub-action="motion"] [data-hub-action-meta]')).toContainText('Local')
await shoot(page, 'lokal-b')
await page.getByRole('radio', { name: 'Swap Character, runs on LU Cloud' }).click()
await expect(page.getByRole('dialog')).toBeVisible()
@@ -340,24 +357,25 @@ test('local mode: Swap is locked to the cloud, the local lanes are there', async
// Motion runs on this Mac: the LTX-2.3 pack, no sound choice.
await page.getByRole('radio', { name: 'Motion Control', exact: true }).click()
await expect(page.locator('[data-motion-controls]')).toBeVisible()
+ await expect(page.locator('[data-hub-action-meta]')).toContainText('Local')
await expect(page.locator('[data-sound-controls]')).toHaveCount(0)
await shoot(page, 'lokal-e-motion')
})
-test('reuse: a training handed over from the gallery opens the area on Train', async ({ page }) => {
+test('the training is a page of the area, with the way back to the stage', async ({ page }) => {
await boot(page, { hub: true })
// The way of SaveCharacterModal and the chat: setIntent('character') with
- // the training tab. Here through the area's own link.
- await openCharacterHub(page)
- await page.getByRole('button', { name: 'Train from photos' }).click()
+ // the training tab. Here through the area's own page.
+ await openCharacterTraining(page)
const hub = page.locator('[data-character-hub]')
await expect(hub).toHaveAttribute('data-character-hub', 'panel')
- await expect(page.locator('[data-hub-head]')).toContainText('New character')
- await expect(page.locator('[data-hub-head]')).toContainText('Train')
+ await expect(page.locator('[data-hub-training]')).toContainText('Train a model')
+ await page.locator('[data-hub-back]').click()
+ await expect(page.locator('[data-hub-stage]')).toBeVisible()
await expect(characterPill(page)).toHaveAttribute('aria-checked', 'true')
})
-test('phone width: the same steps, the bar in its short form', async ({ page }) => {
+test('phone width: the same stage without the left column, the bar in its short form', async ({ page }) => {
await boot(page, { hub: true, width: 375, height: 812 })
await openCharacterHub(page)
await shoot(page, 'handy-a-wer')
@@ -369,13 +387,45 @@ test('phone width: the same steps, the bar in its short form', async ({ page })
await tapFrame(page, 0.45, 0.33)
await tapFrame(page, 0.66, 0.36)
await page.getByRole('checkbox').check()
- await expect(page.locator('[data-hub-bar-summary]')).toContainText('Auto · SCAIL-2 · 720p · 6 s')
+ await expect(page.locator('[data-hub-bar-summary]')).toContainText(/Auto · SCAIL-2 · 720p · \d+ s/)
await shoot(page, 'handy-c-swap')
await page.locator('[data-hub-bar-summary]').click()
await expect(page.locator('[data-hub-bar-options]')).toBeVisible()
await page.locator('[data-hub-bar-summary]').click()
- await page.getByRole('button', { name: 'Action' }).click()
- await page.getByRole('option', { name: /^Motion/ }).click()
+ await page.getByRole('radio', { name: 'Motion Control', exact: true }).click()
await expect(page.locator('[data-motion-controls]')).toBeVisible()
await shoot(page, 'handy-e-motion')
})
+
+test('no character yet: the three steps, one button, four examples and nothing else', async ({ page }) => {
+ await boot(page, { hub: true, mock: {} })
+ await page.route('https://lu-labs.ai/api/loras', (route) => route.fulfill({ status: 200, headers: { ...CORS, 'content-type': 'application/json' }, body: JSON.stringify({ loras: [] }) }))
+ await openCharacterHub(page)
+ const hub = page.locator('[data-character-hub]')
+ await expect(hub).toHaveAttribute('data-character-hub', 'who')
+ await expect(page.locator('[data-hub-empty] ol > li')).toHaveCount(3)
+ await expect(page.locator('[data-hub-example]')).toHaveCount(4)
+ await expect(page.locator('[data-hub-empty] h1, [data-hub-empty] h2')).toHaveCount(0)
+ await shoot(page, 'leer')
+ await page.locator('[data-hub-create] button').click()
+ await expect(hub).toHaveAttribute('data-character-hub', 'new')
+ // The page starts with the drop field alone.
+ await expect(page.locator('[data-hub-drop]')).toBeVisible()
+ await expect(page.locator('[data-hub-photos]')).toHaveCount(0)
+ await expect(page.getByRole('button', { name: 'Save', exact: true })).toBeDisabled()
+ await shoot(page, 'neu-leer')
+ const photo = await media('oma.png', 'image/png')
+ await page.locator('input[aria-label="Photos or a LoRA file"]').setInputFiles(Array.from({ length: 5 }, (_, i) => ({ ...photo, name: `oma-${i + 1}.png` })))
+ await page.locator('[data-hub-new-name]').fill('Oma')
+ await expect(page.locator('[data-hub-save-summary]')).toHaveText('5 photos · kept on this computer · free')
+ await shoot(page, 'neu-mit-fotos')
+ await page.getByRole('button', { name: 'Save Oma', exact: true }).click()
+ await expect(hub).toHaveAttribute('data-character-hub', 'what')
+ await expect(page.locator('[data-hub-card-name]')).toHaveText('Oma')
+ // Rename on the desktop.
+ await page.locator('[data-hub-rename]').click()
+ await page.getByRole('textbox', { name: 'New name for Oma' }).fill('Greta')
+ await page.locator('[data-hub-rename-save]').click()
+ await expect(page.locator('[data-hub-card-name]')).toHaveText('Greta')
+ await expect(page.locator('[data-hub-character^="saved:"]')).toContainText('Greta')
+})
diff --git a/e2e/support/character-hub.ts b/e2e/support/character-hub.ts
index 3e63bb6f..4d54ebb1 100644
--- a/e2e/support/character-hub.ts
+++ b/e2e/support/character-hub.ts
@@ -12,52 +12,68 @@ export function characterPill(page: Page) {
return page.getByRole('radiogroup', { name: 'Create mode' }).getByRole('radio', { name: 'Character', exact: true })
}
-/** Opens the area (step 1 on a fresh session). */
+/** Opens the area: its first page without a character, else the stage. */
export async function openCharacterHub(page: Page, timeout = 15_000): Promise<void> {
await characterPill(page).click({ timeout })
await expect(page.locator('[data-character-hub]')).toBeVisible({ timeout })
}
-/** Step 2 without a character ("Just use a photo"), then the action row
- * named like the old pill: 'Character Studio', 'Swap Character',
- * 'Motion Control', 'Talking Character' (a locked one reads
- * "…, runs on LU Cloud"). */
-export async function openCharacterAction(page: Page, name: string, timeout = 15_000): Promise<void> {
- await openCharacterHub(page, timeout)
+const ACTION_OF: Record<string, string> = {
+ 'Character Studio': 'image', 'Swap Character': 'swap', 'Motion Control': 'motion', 'Talking Character': 'talk',
+}
+
+/** The stage without a character ("Just use a photo"), from wherever the
+ * area stands. With no character at all there is no stage: the area shows
+ * its first page, and this answers false. */
+async function photoOnlyStage(page: Page, timeout: number): Promise<boolean> {
const hub = page.locator('[data-character-hub]')
- if ((await hub.getAttribute('data-character-hub')) === 'who') {
- await page.getByRole('button', { name: 'Just use a photo' }).click()
+ // A character of the account takes the stage by itself.
+ await expect(hub).not.toHaveAttribute('data-character-hub', 'who', { timeout: 1_500 }).catch(() => undefined)
+ const step = await hub.getAttribute('data-character-hub')
+ if (step === 'who') return false
+ // A page of the area (New character, the training): back to the characters.
+ const back = page.locator('[data-hub-back]')
+ if (await back.count()) {
+ await back.click()
+ if ((await hub.getAttribute('data-character-hub')) === 'who') return false
}
- if ((await hub.getAttribute('data-character-hub')) !== 'panel') {
+ await page.locator('[data-hub-photo-only]').click({ timeout })
+ return true
+}
+
+/** An action without a character, named like the old pill:
+ * 'Character Studio', 'Swap Character', 'Motion Control', 'Talking
+ * Character' (a locked one reads "…, runs on LU Cloud"). */
+export async function openCharacterAction(page: Page, name: string, timeout = 15_000): Promise<void> {
+ await openCharacterHub(page, timeout)
+ if (await photoOnlyStage(page, timeout)) {
await page.getByRole('radio', { name, exact: true }).click({ timeout })
- } else {
- // Already on a panel: switch the action in the head line.
- await page.getByRole('button', { name: 'Action' }).click()
- const label = { 'Character Studio': 'Image', 'Swap Character': 'Swap', 'Motion Control': 'Motion', 'Talking Character': 'Talk' }[name] ?? name
- await page.getByRole('option', { name: new RegExp(`^${label}`) }).click()
+ return
}
+ // No character yet: the examples of the first page open an action.
+ const action = ACTION_OF[name.replace(/, runs on LU Cloud$/, '')]
+ await page.locator(`[data-hub-example="${action}"]`).click({ timeout })
}
-/** "Train from photos": Character Studio's training. */
+/** The training: "New character", "Train a model", on to the training. */
export async function openCharacterTraining(page: Page, timeout = 15_000): Promise<void> {
await openCharacterHub(page, timeout)
const hub = page.locator('[data-character-hub]')
- if ((await hub.getAttribute('data-character-hub')) !== 'who') {
- await page.getByRole('button', { name: 'Character', exact: true }).click()
- await page.getByRole('option', { name: /^New character/ }).click()
- return
- }
- await page.getByRole('button', { name: 'Train from photos' }).click()
+ await expect(hub).not.toHaveAttribute('data-character-hub', 'who', { timeout: 1_500 }).catch(() => undefined)
+ if (await page.locator('[data-hub-training]').count()) return
+ const back = page.locator('[data-hub-back]')
+ if (await back.count()) await back.click()
+ if ((await hub.getAttribute('data-character-hub')) === 'who') await page.locator('[data-hub-create] button').click({ timeout })
+ else await page.locator('[data-hub-new]').click({ timeout })
+ await page.locator('[data-hub-way="train"]').click()
+ await page.getByRole('button', { name: 'Continue to training' }).click()
+ await expect(page.locator('[data-hub-training]')).toBeVisible({ timeout })
}
-/** Step 2 without a character, where the actions and their locks show. */
+/** The stage without a character, where the actions and their locks show. */
export async function openCharacterWhat(page: Page, timeout = 15_000): Promise<void> {
await openCharacterHub(page, timeout)
- const hub = page.locator('[data-character-hub]')
- if ((await hub.getAttribute('data-character-hub')) === 'panel') {
- await page.getByRole('button', { name: 'Character', exact: true }).click()
- await page.getByRole('option', { name: 'All characters…' }).click()
- }
- await page.getByRole('button', { name: 'Just use a photo' }).click()
- await expect(hub).toHaveAttribute('data-character-hub', 'what')
+ // No character yet: Image (it runs everywhere) opens the stage.
+ if (!(await photoOnlyStage(page, timeout))) await page.locator('[data-hub-example="image"]').click({ timeout })
+ await expect(page.locator('[data-hub-stage]')).toBeVisible({ timeout })
}
diff --git a/src-tauri/src/commands/character_files.rs b/src-tauri/src/commands/character_files.rs
index 8adf58be..25a7430d 100644
--- a/src-tauri/src/commands/character_files.rs
+++ b/src-tauri/src/commands/character_files.rs
@@ -426,6 +426,187 @@ pub async fn import_cloud_character(
})
}
+// ── a LoRA file the user brings ─────────────────────────────────────────────
+//
+// 3.1.0, "New character": a `.safetensors` dropped on the page becomes a
+// character of this machine. The window cannot hand over a path (the WebView
+// gives a dropped file as bytes), so the file comes in pieces and is put
+// together next to its place. It only gets its name, `char_<name>_zimage
+// .safetensors`, once its header reads as a LoRA.
+
+/// The most one piece carries, decoded.
+const MAX_PIECE_BYTES: usize = 16 * 1024 * 1024;
+/// The largest LoRA file taken at all.
+const MAX_LORA_BYTES: u64 = 4 * 1024 * 1024 * 1024;
+
+/// What a piece left behind.
+#[derive(Debug, PartialEq)]
+pub(crate) enum Piece {
+ /// Written; `received` bytes are there now.
+ More { received: u64 },
+ /// The last piece: the file stands under its name.
+ Saved { file: String, path: PathBuf, bytes: u64, format: KeyFormat },
+ /// A character of that name is there already. Nothing was replaced.
+ Exists { file: String },
+}
+
+fn staging_of(dest: &Path) -> PathBuf {
+ let mut name = dest.file_name().map(|n| n.to_os_string()).unwrap_or_default();
+ name.push(".upload");
+ dest.with_file_name(name)
+}
+
+/// Adds one piece of a brought LoRA file. `offset` is where the piece
+/// starts: 0 starts over, anything else must be exactly what is there.
+pub(crate) fn take_piece(loras: &Path, name: &str, offset: u64, bytes: &[u8], last: bool) -> Result<Piece, String> {
+ use std::io::Write;
+ let Some(file) = local_character_file(name, name) else {
+ return Err("Give the character a name with letters or digits.".to_string());
+ };
+ if bytes.len() > MAX_PIECE_BYTES {
+ return Err("This piece of the file is too large.".to_string());
+ }
+ let dest = loras.join(&file);
+ let staging = staging_of(&dest);
+ if dest.exists() {
+ let _ = fs::remove_file(&staging);
+ return Ok(Piece::Exists { file });
+ }
+ fs::create_dir_all(loras).map_err(|e| format!("The LoRA folder could not be made: {}", os_error::english(&e)))?;
+ let have = if offset == 0 { 0 } else { fs::metadata(&staging).map(|m| m.len()).unwrap_or(0) };
+ if have != offset {
+ let _ = fs::remove_file(&staging);
+ return Err("The file arrived out of order. Nothing was added, drop it again.".to_string());
+ }
+ if offset.saturating_add(bytes.len() as u64) > MAX_LORA_BYTES {
+ let _ = fs::remove_file(&staging);
+ return Err("This file is larger than a LoRA gets (4 GB). Nothing was added.".to_string());
+ }
+ let mut out = fs::OpenOptions::new()
+ .create(true)
+ .write(true)
+ .append(offset != 0)
+ .truncate(offset == 0)
+ .open(&staging)
+ .map_err(|e| format!("The file could not be written: {}", os_error::english(&e)))?;
+ if let Err(e) = out.write_all(bytes).and_then(|()| out.flush()) {
+ drop(out);
+ let _ = fs::remove_file(&staging);
+ return Err(format!("The file could not be written: {}", os_error::english(&e)));
+ }
+ drop(out);
+ let received = offset + bytes.len() as u64;
+ if !last {
+ return Ok(Piece::More { received });
+ }
+ let Some(names) = tensor_names(&staging) else {
+ let _ = fs::remove_file(&staging);
+ return Err("This file is not a LoRA LU can read. Nothing was added.".to_string());
+ };
+ let format = key_format(names.iter().map(String::as_str));
+ if dest.exists() {
+ let _ = fs::remove_file(&staging);
+ return Ok(Piece::Exists { file });
+ }
+ if let Err(e) = fs::rename(&staging, &dest) {
+ let _ = fs::remove_file(&staging);
+ return Err(format!("The file could not be saved: {}", os_error::english(&e)));
+ }
+ Ok(Piece::Saved { file, path: dest, bytes: received, format })
+}
+
+/// `character_lora_folder`: where a character file lives on this machine,
+/// `{status: "ok", path}`, or `{status: "no_comfy"}` when there is no LoRA
+/// folder (no ComfyUI found).
+#[tauri::command]
+pub fn character_lora_folder(state: tauri::State<'_, AppState>) -> serde_json::Value {
+ match local_loras_dir(state.inner()) {
+ Some(dir) => serde_json::json!({ "status": "ok", "path": dir.to_string_lossy() }),
+ None => serde_json::json!({ "status": "no_comfy" }),
+ }
+}
+
+/// `character_lora_folder_open`: that folder in the file manager. It is made
+/// first, so a machine without a LoRA yet opens an empty folder.
+#[cfg(desktop)]
+#[tauri::command]
+pub fn character_lora_folder_open(state: tauri::State<'_, AppState>) -> Result<serde_json::Value, String> {
+ let Some(dir) = local_loras_dir(state.inner()) else {
+ return Ok(serde_json::json!({ "status": "no_comfy" }));
+ };
+ fs::create_dir_all(&dir).map_err(|e| format!("The LoRA folder could not be made: {}", os_error::english(&e)))?;
+ #[cfg(target_os = "macos")]
+ let mut cmd = {
+ let mut c = std::process::Command::new("open");
+ c.arg(&dir);
+ c
+ };
+ #[cfg(target_os = "windows")]
+ let mut cmd = {
+ let mut c = std::process::Command::new("explorer");
+ c.arg(&dir);
+ c
+ };
+ #[cfg(all(unix, not(target_os = "macos")))]
+ let mut cmd = {
+ let mut c = crate::process_util::foreign_system_command("xdg-open");
+ c.arg(&dir);
+ c
+ };
+ crate::process_util::suppress_window(&mut cmd);
+ // explorer.exe answers 1 even when it worked, so only a failed spawn counts.
+ cmd.spawn().map_err(|e| format!("Could not open the folder: {}", os_error::english(&e)))?;
+ Ok(serde_json::json!({ "status": "ok", "path": dir.to_string_lossy() }))
+}
+
+/// `character_lora_import`: one piece of a LoRA file the user dropped on
+/// "New character" (`take_piece`). Answers `{status: "more", received}`,
+/// `{status: "saved", file, path, bytes, keyFormat}`, `{status: "exists",
+/// file}` or `{status: "no_comfy"}`.
+#[cfg(desktop)]
+#[tauri::command]
+#[allow(non_snake_case)]
+pub async fn character_lora_import(
+ app: tauri::AppHandle,
+ state: tauri::State<'_, AppState>,
+ name: String,
+ offset: u64,
+ dataB64: String,
+ last: bool,
+) -> Result<serde_json::Value, String> {
+ let Some(loras) = local_loras_dir(state.inner()) else {
+ return Ok(serde_json::json!({ "status": "no_comfy" }));
+ };
+ let train = crate::commands::trainer::trainer_root(&app).join("train");
+ tauri::async_runtime::spawn_blocking(move || {
+ let bytes = base64::engine::general_purpose::STANDARD
+ .decode(dataB64.as_bytes())
+ .map_err(|_| "The file did not arrive whole. Nothing was added, drop it again.".to_string())?;
+ Ok(match take_piece(&loras, &name, offset, &bytes, last)? {
+ Piece::More { received } => serde_json::json!({ "status": "more", "received": received }),
+ Piece::Exists { file } => serde_json::json!({ "status": "exists", "file": file }),
+ Piece::Saved { file, path, bytes, format } => {
+ // Training photos of an earlier character of this name are
+ // not this file's.
+ if let Some(trigger) = trigger_of(&file) {
+ disown_training_set(&train.join(crate::commands::trainer::sanitize_component(&trigger)));
+ }
+ serde_json::json!({ "status": "saved", "file": file, "path": path.to_string_lossy(), "bytes": bytes, "keyFormat": format })
+ }
+ })
+ })
+ .await
+ .map_err(|e| format!("The file could not be saved: {e}"))?
+}
+
+/// `character_lora_import_cancel`: the pieces of an import that was given up.
+#[cfg(desktop)]
+#[tauri::command]
+pub fn character_lora_import_cancel(state: tauri::State<'_, AppState>, name: String) {
+ let (Some(loras), Some(file)) = (local_loras_dir(state.inner()), local_character_file(&name, &name)) else { return };
+ let _ = fs::remove_file(staging_of(&loras.join(file)));
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -507,6 +688,62 @@ mod tests {
assert!(tensor_names(&dir.join("not.safetensors")).is_none());
}
+ fn lora_bytes(names: &[&str]) -> Vec<u8> {
+ let dir = test_dir("character-lora-bytes");
+ let path = dir.join("x.safetensors");
+ safetensors(&path, names);
+ fs::read(path).unwrap()
+ }
+
+ #[test]
+ fn a_brought_lora_comes_in_pieces_and_gets_its_name_at_the_end() {
+ let dir = test_dir("character-lora-pieces");
+ let loras = dir.join("loras");
+ let bytes = lora_bytes(&["diffusion_model.layers.0.attention.to_q.lora_A.weight"]);
+ let (a, b) = bytes.split_at(bytes.len() / 2);
+ assert_eq!(take_piece(&loras, "Mira", 0, a, false).unwrap(), Piece::More { received: a.len() as u64 });
+ assert!(!loras.join("char_Mira_zimage.safetensors").exists(), "no name before the header was read");
+ let done = take_piece(&loras, "Mira", a.len() as u64, b, true).unwrap();
+ let dest = loras.join("char_Mira_zimage.safetensors");
+ assert_eq!(done, Piece::Saved { file: "char_Mira_zimage.safetensors".into(), path: dest.clone(), bytes: bytes.len() as u64, format: KeyFormat::Same });
+ assert_eq!(fs::read(&dest).unwrap(), bytes);
+ assert!(!staging_of(&dest).exists());
+ }
+
+ #[test]
+ fn a_piece_out_of_order_or_a_file_that_is_no_lora_adds_nothing() {
+ let dir = test_dir("character-lora-refused");
+ let loras = dir.join("loras");
+ let dest = loras.join("char_a_zimage.safetensors");
+ assert!(take_piece(&loras, "a", 0, b"abc", false).is_ok());
+ assert!(take_piece(&loras, "a", 99, b"def", false).unwrap_err().contains("out of order"));
+ assert!(!staging_of(&dest).exists());
+ let err = take_piece(&loras, "a", 0, b"<html>not a lora</html>", true).unwrap_err();
+ assert!(err.contains("not a LoRA"), "{err}");
+ assert!(!dest.exists() && !staging_of(&dest).exists());
+ assert!(take_piece(&loras, "€€", 0, b"x", true).unwrap_err().contains("name"));
+ }
+
+ #[test]
+ fn a_character_of_that_name_is_never_replaced() {
+ let dir = test_dir("character-lora-exists");
+ let loras = dir.join("loras");
+ fs::create_dir_all(&loras).unwrap();
+ fs::write(loras.join("char_a_zimage.safetensors"), b"mine").unwrap();
+ let bytes = lora_bytes(&["diffusion_model.layers.0.attention.to_q.lora_A.weight"]);
+ assert_eq!(take_piece(&loras, "a", 0, &bytes, true).unwrap(), Piece::Exists { file: "char_a_zimage.safetensors".into() });
+ assert_eq!(fs::read(loras.join("char_a_zimage.safetensors")).unwrap(), b"mine");
+ }
+
+ #[test]
+ fn a_lora_for_another_model_is_taken_and_named_as_unknown() {
+ let dir = test_dir("character-lora-other");
+ let loras = dir.join("loras");
+ let bytes = lora_bytes(&["transformer.single_transformer_blocks.0.attn.to_q.lora_A.weight"]);
+ let Piece::Saved { format, .. } = take_piece(&loras, "b", 0, &bytes, true).unwrap() else { panic!("not saved") };
+ assert_eq!(format, KeyFormat::Unknown);
+ }
+
fn photo(path: &Path, w: u32, h: u32) {
image::RgbImage::from_pixel(w, h, image::Rgb([200, 100, 50])).save(path).unwrap();
}
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index e8af94f9..293ddf18 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -943,6 +943,13 @@ pub fn run() {
#[cfg(desktop)]
commands::character_files::import_cloud_character,
commands::character_files::character_photos,
+ commands::character_files::character_lora_folder,
+ #[cfg(desktop)]
+ commands::character_files::character_lora_folder_open,
+ #[cfg(desktop)]
+ commands::character_files::character_lora_import,
+ #[cfg(desktop)]
+ commands::character_files::character_lora_import_cancel,
commands::chat_attachments::export_chats_dialog,
commands::chat_attachments::import_chats_dialog,
commands::model_sniff::sniff_model_files,
diff --git a/src/components/create/experimental/CharacterUseLocally.tsx b/src/components/create/experimental/CharacterUseLocally.tsx
index 0b54db2c..ffc322dd 100644
--- a/src/components/create/experimental/CharacterUseLocally.tsx
+++ b/src/components/create/experimental/CharacterUseLocally.tsx
@@ -14,7 +14,7 @@ import { cn } from '../ui/cn'
/** After a file landed: ComfyUI rereads its folders, then every shelf asks
* again. The Mac lists its own folder and needs no rescan. */
-async function refreshLocalShelves(): Promise<void> {
+export async function refreshLocalShelves(): Promise<void> {
const { isMlxImageHost } = await import('../../../api/mlx-image')
if (!isMlxImageHost()) {
const [{ refreshComfyModels }, { clearNodeCache }] = await Promise.all([
diff --git a/src/components/create/experimental/Composer.tsx b/src/components/create/experimental/Composer.tsx
index d61ea006..df34baf3 100644
--- a/src/components/create/experimental/Composer.tsx
+++ b/src/components/create/experimental/Composer.tsx
@@ -20,6 +20,7 @@ import { swapBilledPhotos, swapPricedSeconds, swapShortCredits } from '../../../
import { swapReady } from '../../../lib/create/swap-run'
import { modelLabel } from '../../../lib/render/preset-models'
import { SwapLength, SwapPrice, useSwapBar } from './hub/SwapBarParts'
+import { HubBarTop } from './hub/HubParts'
import { useLocalPick } from './localPick'
import { swapConfirmedFrame } from '../../../lib/create/swap-frame'
import { soundApplies, soundInputError } from '../../../lib/render/sound'
@@ -483,7 +484,9 @@ export function Composer({ onOpenAdvanced, onOpenWorkflows, hub = false }: Props
vor der Umstellung hatte. Siehe --lu-measure in index.css; dass die
Zahl hier doppelt steht statt den Token zu lesen, ist ein eigener
Befund und hier nicht behoben. */}
- <div className="mx-auto w-full max-w-[660px] space-y-2.5">
+ {/* In the Character area the place decides the width: the stage's foot
+ spans it, the training page is its own 660 column. */}
+ <div className={cn('mx-auto w-full space-y-2.5', !hub && 'max-w-[660px]')}>
{special && !hub && <SpecialControls intent={intent} />}
{intent === '3d' && <ThreeDControls {...threeDControlFacts(backend, studioPick)} studioId={studioPick} pictureFirst={backend === 'local' || isPictureFirstRun(threeDWay, studioPick)} />}
{/* Swap Character's options are its own panel above (SpecialControls). */}
@@ -501,6 +504,7 @@ export function Composer({ onOpenAdvanced, onOpenWorkflows, hub = false }: Props
<div className={hub
? cn('hub-bar transition-colors', narrow && 'rounded-2xl')
: 'rounded-[var(--radius-panel)] bg-white/[0.03] border border-white/[0.06] focus-within:border-white/15 transition-colors'}>
+ {hub && <HubBarTop />}
{needPrompt && (
// The prompt assistant (B43) sits in the field's corner, not in the
// action bar: there every pixel is the model chip's, whose whole
diff --git a/src/components/create/experimental/SpecialIntentControls.tsx b/src/components/create/experimental/SpecialIntentControls.tsx
index e3d8d200..eddc39ed 100644
--- a/src/components/create/experimental/SpecialIntentControls.tsx
+++ b/src/components/create/experimental/SpecialIntentControls.tsx
@@ -2025,8 +2025,10 @@ function SwapMore() {
)
}
-/** Image: what can be done with the picked character's file. */
-function CharacterMore() {
+/** What can be done with the picked character's file: under More options
+ * of Image, and `bare` (without the name, on any tab) at the character on
+ * the stage. */
+export function CharacterMore({ bare = false }: { bare?: boolean } = {}) {
const backend = useCreateStore((s) => s.backend)
const characterTab = useCreateStore((s) => s.characterTab)
const hubCharacter = useCreateStore((s) => s.hubCharacter)
@@ -2034,11 +2036,11 @@ function CharacterMore() {
const setHubCharacter = useCreateStore((s) => s.setHubCharacter)
const lora = hubCharacter?.lora
const localFile = characterLoraFile(hubCharacter?.ref)
- if (characterTab !== 'use' || !hubCharacter) return null
+ if ((!bare && characterTab !== 'use') || !hubCharacter) return null
if (localFile && hubCharacter.ref) {
return (
<div className="flex items-center gap-1 hub-fs-125" data-character-file-actions>
- <span className="hub-muted mr-2">{hubCharacter.name}</span>
+ {!bare && <span className="hub-muted mr-2">{hubCharacter.name}</span>}
<LocalCharacterDelete file={localFile} trigger={hubCharacter.ref.triggerWord} />
</div>
)
@@ -2046,7 +2048,7 @@ function CharacterMore() {
if (backend !== 'cloud' || !lora) return null
return (
<div className="flex items-center gap-1 hub-fs-125" data-character-file-actions>
- <span className="hub-muted mr-2">{hubCharacter.name}</span>
+ {!bare && <span className="hub-muted mr-2">{hubCharacter.name}</span>}
<CharacterDownload lora={lora} />
<CharacterUseLocally lora={lora} />
<button
diff --git a/src/components/create/experimental/__tests__/character-stage.test.tsx b/src/components/create/experimental/__tests__/character-stage.test.tsx
new file mode 100644
index 00000000..320660cd
--- /dev/null
+++ b/src/components/create/experimental/__tests__/character-stage.test.tsx
@@ -0,0 +1,199 @@
+// @vitest-environment jsdom
+/**
+ * The Character area as David chose it on 16.11.2026 (variant B):
+ * - no character yet: three steps, one button, four examples, no headline;
+ * - "New character" starts with the drop field alone and shows only the
+ * photos the user put there;
+ * - the stage shows only real things: a character without photos gets a
+ * line, never a stand-in picture;
+ * - Rename works on the desktop;
+ * - nothing of the area moves by itself except the four examples.
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import { render, cleanup, screen, fireEvent, waitFor } from '@testing-library/react'
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+
+const io = vi.hoisted(() => ({ folder: { status: 'ok', path: '/Users/dave/Library/Application Support/lu-labs/loras' } as { status: string; path?: string } | null, opened: 0, imported: [] as string[] }))
+vi.mock('../../../../api/backend', async (orig) => ({ ...(await orig<typeof import('../../../../api/backend')>()), isTauri: () => true }))
+vi.mock('../../../../lib/create/character-lora', async (orig) => ({
+ ...(await orig<typeof import('../../../../lib/create/character-lora')>()),
+ characterLoraFolder: vi.fn(async () => io.folder),
+ openCharacterLoraFolder: vi.fn(async () => { io.opened++ }),
+ importCharacterLora: vi.fn(async (_f: Blob, name: string) => { io.imported.push(name); return { status: 'saved', file: `char_${name}_zimage.safetensors`, path: '/x', keyFormat: 'same' } }),
+}))
+vi.mock('../CharacterUseLocally', () => ({ refreshLocalShelves: vi.fn(async () => undefined), CharacterUseLocally: () => null }))
+vi.mock('../SpecialIntentControls', () => ({ CharacterMore: () => <span data-testid="file-actions" /> }))
+
+import { HubEmpty } from '../hub/HubEmpty'
+import { HubNewCharacter } from '../hub/HubNewCharacter'
+import { HubCard, HubPhotos } from '../hub/HubStage'
+import { useCreateStore } from '../../../../stores/createStore'
+import { useCharacterNames } from '../../../../lib/create/character-names'
+import { __resetSavedCharacters, listSavedCharacters, saveCharacter } from '../../../../lib/saved-characters'
+import { hubFromSaved, type HubCharacter } from '../../../../lib/create/character-hub'
+
+const png = (name: string) => new File([`png-${name}`], name, { type: 'image/png' })
+const hub = (ui: React.ReactElement) => render(<div className="lu-hub">{ui}</div>)
+
+beforeEach(() => {
+ __resetSavedCharacters()
+ useCharacterNames.setState({ names: {} })
+ io.folder = { status: 'ok', path: '/Users/dave/Library/Application Support/lu-labs/loras' }
+ io.opened = 0
+ io.imported = []
+ let n = 0
+ vi.stubGlobal('URL', Object.assign(URL, { createObjectURL: () => `blob:test-${++n}`, revokeObjectURL: () => undefined }))
+})
+afterEach(() => { cleanup(); vi.unstubAllGlobals() })
+
+describe('no character yet', () => {
+ it('shows the three steps, one button and four examples, and no headline', () => {
+ const onCreate = vi.fn()
+ const onTry = vi.fn()
+ const { container } = hub(<HubEmpty onCreate={onCreate} onTry={onTry} />)
+ expect(container.querySelectorAll('ol > li')).toHaveLength(3)
+ expect(container.querySelectorAll('[data-hub-example]')).toHaveLength(4)
+ expect(container.querySelectorAll('h1, h2, h3')).toHaveLength(0)
+ expect(screen.getAllByRole('button').filter((b) => b.textContent === 'Create a character')).toHaveLength(1)
+ fireEvent.click(screen.getByRole('button', { name: 'Create a character' }))
+ expect(onCreate).toHaveBeenCalledTimes(1)
+ fireEvent.click(container.querySelector('[data-hub-example="swap"]')!)
+ expect(onTry).toHaveBeenCalledWith('swap')
+ })
+
+ it('draws the examples with the LU mark, not with a photo', () => {
+ const { container } = hub(<HubEmpty onCreate={() => {}} onTry={() => {}} />)
+ expect(container.querySelectorAll('img')).toHaveLength(0)
+ const marks = [...container.querySelectorAll('image')].map((i) => i.getAttribute('href'))
+ expect(marks.length).toBeGreaterThanOrEqual(4)
+ expect(new Set(marks)).toEqual(new Set(['/LU-monogram.svg']))
+ })
+})
+
+describe('New character', () => {
+ const page = (over: Partial<React.ComponentProps<typeof HubNewCharacter>> = {}) =>
+ hub(<HubNewCharacter onBack={() => {}} onSaved={() => {}} onOpenGallery={() => {}} {...over} />)
+
+ it('starts with the drop field alone: no picture stands there before the user adds one', async () => {
+ const { container } = page()
+ expect(container.querySelector('[data-hub-drop]')).toBeTruthy()
+ expect(container.querySelectorAll('img')).toHaveLength(0)
+ expect(container.querySelector('[data-hub-photos]')).toBeNull()
+ expect((screen.getByRole('button', { name: 'Save' }) as HTMLButtonElement).disabled).toBe(true)
+ await waitFor(() => expect(container.querySelector('[data-hub-lora-path]')).toBeTruthy())
+ })
+
+ it('shows exactly the photos that were added, and saves them under the name', async () => {
+ const onSaved = vi.fn()
+ const { container } = page({ onSaved })
+ fireEvent.change(screen.getByLabelText('Photos or a LoRA file'), { target: { files: [png('a.png'), png('b.png'), png('c.png')] } })
+ await waitFor(() => expect(container.querySelectorAll('ul[data-hub-photos] img')).toHaveLength(3))
+ fireEvent.click(screen.getByRole('button', { name: 'Remove photo 2' }))
+ await waitFor(() => expect(container.querySelectorAll('ul[data-hub-photos] img')).toHaveLength(2))
+ fireEvent.change(container.querySelector('[data-hub-new-name]')!, { target: { value: 'Greta' } })
+ expect(container.querySelector('[data-hub-save-summary]')!.textContent).toBe('2 photos · kept on this computer · free')
+ fireEvent.click(screen.getByRole('button', { name: 'Save Greta' }))
+ await waitFor(() => expect(onSaved).toHaveBeenCalledTimes(1))
+ const saved = await listSavedCharacters()
+ expect(saved.map((c) => [c.name, c.photos.length])).toEqual([['Greta', 2]])
+ expect((onSaved.mock.calls[0][0] as HubCharacter).key).toBe(`saved:${saved[0].id}`)
+ })
+
+ it('"Train a model" leads on to the training, with or without photos', async () => {
+ page()
+ fireEvent.click(screen.getByRole('radio', { name: /Train a model/ }))
+ const go = screen.getByRole('button', { name: 'Continue to training' }) as HTMLButtonElement
+ expect(go.disabled).toBe(false)
+ fireEvent.click(go)
+ await waitFor(() => expect(useCreateStore.getState().hubStep).toBe('panel'))
+ expect(useCreateStore.getState().intent()).toBe('character')
+ expect(useCreateStore.getState().characterTab).toBe('train')
+ })
+
+ it('names the real LoRA folder and opens it', async () => {
+ const { container } = page()
+ const path = await waitFor(() => { const el = container.querySelector('[data-hub-lora-path]'); if (!el) throw new Error('no path yet'); return el })
+ expect(path.textContent).toBe('~/Library/Application Support/lu-labs/loras')
+ expect(path.getAttribute('title')).toBe('/Users/dave/Library/Application Support/lu-labs/loras')
+ fireEvent.click(screen.getByRole('button', { name: 'Open LoRA folder' }))
+ await waitFor(() => expect(io.opened).toBe(1))
+ })
+
+ it('without a LoRA folder the page says so and offers no button for it', async () => {
+ io.folder = { status: 'no_comfy' }
+ const { container } = page()
+ await waitFor(() => expect(container.querySelector('[data-hub-lora-folder="no_comfy"]')).toBeTruthy())
+ expect(screen.queryByRole('button', { name: 'Open LoRA folder' })).toBeNull()
+ })
+
+ it('a dropped LoRA file becomes a character under the name it suggests', async () => {
+ const onSaved = vi.fn()
+ const { container } = page({ onSaved })
+ const lora = new File(['weights'], 'char_mira_zimage.safetensors')
+ fireEvent.drop(container.querySelector('[data-hub-drop]')!, { dataTransfer: { files: [lora] } })
+ await waitFor(() => expect(container.querySelector('[data-hub-lora-file]')).toBeTruthy())
+ expect((container.querySelector('[data-hub-new-name]') as HTMLInputElement).value).toBe('mira')
+ await waitFor(() => expect(container.querySelector('[data-hub-lora-path]')).toBeTruthy())
+ fireEvent.click(screen.getByRole('button', { name: 'Add mira' }))
+ await waitFor(() => expect(onSaved).toHaveBeenCalledTimes(1))
+ expect(io.imported).toEqual(['mira'])
+ // The new character takes the stage, by the id the list gives it.
+ expect(onSaved.mock.calls[0][0]).toMatchObject({ kind: 'local', key: 'local:char_mira_zimage.safetensors', name: 'mira' })
+ })
+})
+
+describe('the stage', () => {
+ it('a character without a picture shows its initial, without photos a line, never a stand-in', () => {
+ const c: HubCharacter = { key: 'local:char_opa_zimage.safetensors', kind: 'local', name: 'opa', meta: 'Local LoRA', image: null, ref: { id: 'local:char_opa_zimage.safetensors', name: 'opa', triggerWord: 'opa', family: 'zimage' } }
+ const { container } = hub(<><HubCard c={c} photo={null} /><HubPhotos c={c} photos={[]} loading={false} /></>)
+ expect(container.querySelectorAll('img, image')).toHaveLength(0)
+ expect(container.querySelector('.hub-initial')!.textContent).toBe('O')
+ expect(container.querySelector('[data-hub-no-photos]')!.textContent).toBe('The photos opa was trained on are not on this computer.')
+ })
+
+ it('shows the photos it is given, and only those', () => {
+ const c: HubCharacter = { key: 'saved:1', kind: 'saved', name: 'Oma', meta: 'Photos · 2', image: 'blob:a', photos: [new Blob(['a']), new Blob(['b'])] }
+ const { container } = hub(<HubPhotos c={c} photos={['blob:a', 'blob:b']} loading={false} />)
+ expect([...container.querySelectorAll('img')].map((i) => i.getAttribute('src'))).toEqual(['blob:a', 'blob:b'])
+ })
+
+ it('Rename gives a photo character another name where it is stored', async () => {
+ const { character } = await saveCharacter('Oma', [new Blob(['a'], { type: 'image/png' })])
+ const { container } = hub(<HubCard c={hubFromSaved(character, null)} photo={null} />)
+ fireEvent.click(container.querySelector('[data-hub-rename]')!)
+ fireEvent.change(screen.getByLabelText('New name for Oma'), { target: { value: 'Greta' } })
+ fireEvent.click(container.querySelector('[data-hub-rename-save]')!)
+ await waitFor(async () => expect((await listSavedCharacters())[0].name).toBe('Greta'))
+ expect(useCharacterNames.getState().names).toEqual({})
+ })
+
+ it('Rename gives a LoRA character a label on this computer, and its trigger word stays', async () => {
+ const c: HubCharacter = { key: 'cloud:7', kind: 'cloud', name: 'char seven', meta: 'Trained · Flux', image: null, ref: { id: '7', name: 'char seven', triggerWord: 'sevenchar', family: 'flux' } }
+ const { container } = hub(<HubCard c={c} photo={null} />)
+ fireEvent.click(container.querySelector('[data-hub-rename]')!)
+ expect(container.textContent).toContain('The trigger word stays.')
+ fireEvent.change(screen.getByLabelText('New name for char seven'), { target: { value: 'Greta' } })
+ fireEvent.keyDown(screen.getByLabelText('New name for char seven'), { key: 'Enter' })
+ await waitFor(() => expect(useCharacterNames.getState().names).toEqual({ 'cloud:7': 'Greta' }))
+ expect(container.textContent).toContain('Trigger word: sevenchar')
+ })
+})
+
+describe('nothing moves by itself', () => {
+ it('only the four examples of the first page are animated, and they stand still with reduced motion', () => {
+ const css = readFileSync(resolve(__dirname, '../../../../index.css'), 'utf8')
+ const from = css.indexOf('/* The stage (variant B')
+ const to = css.indexOf('/* The NEW mark on the Character pill')
+ expect(from).toBeGreaterThan(0)
+ expect(to).toBeGreaterThan(from)
+ const block = css.slice(from, to)
+ const animated = [...block.matchAll(/([^{}]+)\{[^{}]*\banimation:(?!\s*none)[^;]+;[^{}]*\}/g)].map((m) => m[1].trim())
+ expect(animated.length).toBe(4)
+ for (const sel of animated) expect(sel).toMatch(/^\.lu-hub \.hub-ex-(a|b|tilt|bar)$/)
+ expect(block).not.toMatch(/\btransition\b/)
+ const reduced = block.slice(block.indexOf('@media (prefers-reduced-motion: reduce)'))
+ for (const cls of ['hub-ex-a', 'hub-ex-b', 'hub-ex-tilt', 'hub-ex-bar']) expect(reduced).toContain(`.lu-hub .${cls}`)
+ expect(reduced).toMatch(/animation: none/)
+ })
+})
diff --git a/src/components/create/experimental/__tests__/eine-kante-und-ein-feld.test.ts b/src/components/create/experimental/__tests__/eine-kante-und-ein-feld.test.ts
index 978c63bd..9db432e2 100644
--- a/src/components/create/experimental/__tests__/eine-kante-und-ein-feld.test.ts
+++ b/src/components/create/experimental/__tests__/eine-kante-und-ein-feld.test.ts
@@ -70,7 +70,10 @@ describe('D-S32: die Reglerzeile steht mittig ueber der Promptbox', () => {
// Promptpanel liegen in DERSELBEN Spalte (`mx-auto w-full max-w-[…]`),
// sind damit gleich breit und haben dieselbe Mitte. Faende das hier nicht
// mehr statt, waere die Zentrierung eine Zusage ohne Deckung.
- const spalte = code.match(/className="mx-auto w-full max-w-\[(\d+)px\] space-y-[\d.]+"/)
+ // Since the stage of the Character area (3.1.0, variant B) the width of
+ // that column is the place's in `hub` (the stage's foot spans it), and
+ // the 660 px stand as the other branch of the same class.
+ const spalte = code.match(/className=\{cn\('mx-auto w-full space-y-[\d.]+', !hub && 'max-w-\[(\d+)px\]'\)\}/)
expect(spalte, 'die gemeinsame Spalte von Reglerzeile und Promptpanel fehlt').toBeTruthy()
// Since 3.1.0 part B the panel has a second face, the bar of the
// Character area (`hub`): the class stands as the string of the other
diff --git a/src/components/create/experimental/__tests__/lora-names-have-a-full-tooltip.test.tsx b/src/components/create/experimental/__tests__/lora-names-have-a-full-tooltip.test.tsx
index d76e73b9..9f690211 100644
--- a/src/components/create/experimental/__tests__/lora-names-have-a-full-tooltip.test.tsx
+++ b/src/components/create/experimental/__tests__/lora-names-have-a-full-tooltip.test.tsx
@@ -24,7 +24,7 @@ vi.mock('../../../../api/cloud/loras', () => ({
}))
import { SchemaControl } from '../SchemaControl'
-import { HubWho } from '../hub/CharacterHub'
+import { HubTabs } from '../hub/HubStage'
import { hubFromCloud } from '../../../../lib/create/character-hub'
import { listLoras } from '../../../../api/cloud/loras'
@@ -38,11 +38,11 @@ describe('LoRA names that keep one line', () => {
})
it('a character row names the character in full as its tooltip, next to the trigger word', async () => {
- // Since 3.1.0 part B the characters are the rows of step 1 of the
+ // Since 3.1.0 part B the characters are the tabs of the stage of the
// Character area; a long name is cut there as it was on the chip.
const list = (await listLoras()).map(hubFromCloud)
- render(<HubWho list={list} loading={false} onOpenGallery={() => {}} />)
- const row = await screen.findByRole('button', { name: /Grace in the red coat/ })
+ render(<div className="lu-hub"><HubTabs list={list} loading={false} current={null} photoOnly={false} onPick={() => {}} onPhotoOnly={() => {}} onNew={() => {}} /></div>)
+ const row = await screen.findByRole('tab', { name: /Grace in the red coat/ })
expect(row.getAttribute('title')).toBe('Grace in the red coat, studio set, second training run, trigger word: gracechar')
})
})
diff --git a/src/components/create/experimental/__tests__/mac-character-shelf.test.tsx b/src/components/create/experimental/__tests__/mac-character-shelf.test.tsx
index e3cbed20..28f4607a 100644
--- a/src/components/create/experimental/__tests__/mac-character-shelf.test.tsx
+++ b/src/components/create/experimental/__tests__/mac-character-shelf.test.tsx
@@ -29,13 +29,19 @@ vi.mock('../../../../api/comfyui', async (orig) => ({ ...(await orig<typeof impo
vi.mock('../../../../api/in-tauri', () => ({ isTauri: () => true }))
import { SpecialControls } from '../SpecialIntentControls'
-import { HubWho } from '../hub/CharacterHub'
+import { HubTabs } from '../hub/HubStage'
import { openHubAction, useHubCharacters } from '../hub/hubCharacters'
-/** Step 1 of the Character area as the app shows it: every source in one list. */
+/** The tabs of the Character area as the app shows them: every source in one list. */
function Who() {
const { list, loading } = useHubCharacters()
- return <HubWho list={list} loading={loading} onOpenGallery={() => {}} />
+ const current = useCreateStore((s) => s.hubCharacter)
+ return (
+ <div className="lu-hub">
+ <HubTabs list={list} loading={loading} current={current?.key ?? null} photoOnly={false}
+ onPick={(c) => useCreateStore.getState().setHubCharacter(c)} onPhotoOnly={() => {}} onNew={() => {}} />
+ </div>
+ )
}
import { useCreateStore } from '../../../../stores/createStore'
import type { ClassifiedModel } from '../../../../api/comfyui'
@@ -61,16 +67,16 @@ afterEach(() => cleanup())
describe('Character Studio on the Mac', () => {
it('lists the characters of the Mac LoRA folder, and a pick brings its Z-Image model', async () => {
arrange('use')
- // Step 1 lists the folder's characters (since 3.1.0 part B the rows of
- // the Character area), Image is the action that runs one.
+ // The tabs list the folder's characters (since 3.1.0 part B the stage
+ // of the Character area), Image is the action that runs one.
render(<Who />)
const row = await screen.findByTitle('davechar, trigger word: davechar')
- expect(row.textContent).toContain('Local LoRA')
- expect(screen.queryByRole('button', { name: /other-style/ })).toBeNull()
+ expect(screen.queryByRole('tab', { name: /other-style/ })).toBeNull()
expect(io.comfy).not.toHaveBeenCalled()
fireEvent.click(row)
const picked = useCreateStore.getState().hubCharacter
expect(picked?.key).toBe(`mlx:${CHAR}`)
+ expect(picked?.meta).toBe('Local LoRA')
await act(async () => { await openHubAction('image', picked) })
cleanup()
render(<SpecialControls intent="character" />)
diff --git a/src/components/create/experimental/hub/CharacterHub.tsx b/src/components/create/experimental/hub/CharacterHub.tsx
index 64729b88..7f7e3619 100644
--- a/src/components/create/experimental/hub/CharacterHub.tsx
+++ b/src/components/create/experimental/hub/CharacterHub.tsx
@@ -1,142 +1,88 @@
-// The Character area of Create (3.1.0 part B), built after David's sketches
-// v2 (uebergabe-310/SWAP-HUB-bilder/mockups-v2): one column of 660 px
-// (760 rendered, the chat's measure), a head line `Character ▾ → Action ▾`
-// as text, rows with hairlines, and at the foot the one framed part, the bar
-// (Composer, hub).
+// The Character area of Create (3.1.0 part B). The stage David chose on
+// 16.11.2026 (uebergabe-310/character-design, variant B) in place of the one
+// narrow column of the first build:
//
-// step 1 Who? every character in one list, "+ New character" with three
-// ways, "Just use a photo"
-// step 2 What? Image, Swap, Motion, Talk with their price
-// step 3 the panel of the action: the stage (a run, a result), the
-// inputs (SpecialControls), the lane's own controls, More options,
-// the bar.
+// no character the three steps and "Create a character", beside them
+// what a character can do (HubEmpty)
+// new the page that makes one from photos or a LoRA file
+// (HubNewCharacter)
+// the stage the characters as tabs, the picked one on the left, its
+// photos or the panel of an action on the right, and the
+// bar across the foot with Image, Swap, Motion and Talk
+// training a page of its own, the panel as it was
+//
+// The inner intent ids and the panels of the actions are untouched
+// (lib/create/character-hub.ts): an action is still a name for an intent.
-import { useRef, useState, type ReactNode } from 'react'
-import { ArrowRight, Film, Image as ImageIcon, Mic, PersonStanding, Plus, Replace, X } from 'lucide-react'
+import { useEffect, type ReactNode } from 'react'
+import { ChevronLeft, Film, X } from 'lucide-react'
import { useCreateStore, type CreateIntent } from '../../../../stores/createStore'
import { useUIStore, type CloudTeaserTarget } from '../../../../stores/uiStore'
import { useSettingsStore } from '../../../../stores/settingsStore'
import { useCloudCatalogStore } from '../../../../stores/cloudCatalogStore'
import { useCharacterHubReleased } from '../../../../lib/create/character-hub-release'
import {
- ACTION_LABEL, ACTION_LINE, HUB_ACTIONS, HUB_JUST_PHOTO, HUB_JUST_PHOTO_LINE, HUB_LOCAL_LINE, HUB_SWAP_SOON,
- actionCloudPrice, actionMeta, actionOfIntent, intentOfAction, whatHeading,
+ HUB_ACTIONS, HUB_SWAP_SOON, actionCloudPrice, actionMeta, actionOfIntent, intentOfAction,
type HubAction, type HubCharacter,
} from '../../../../lib/create/character-hub'
-import { saveCharacter } from '../../../../lib/saved-characters'
import { isMlxImageHost } from '../../../../api/mlx-image'
-import { openMlxLoraFolder } from '../../../../api/mlx-loras'
import { mlxFollowsMotion, mlxTalking } from '../../../../api/mlx-video'
import { INTENT_MAP } from '../intents'
import { useIntentLanes } from '../IntentBar'
import { Stage } from '../Stage'
import { Composer, LaneControls } from '../Composer'
import { SpecialControls, SpecialMore } from '../SpecialIntentControls'
-import { Select, type SelectOption } from '../../ui/Select'
import { cn } from '../../ui/cn'
-import { HUB_COLUMN, HubAvatar, HubCharactersContext, MoreOptions } from './HubParts'
+import { HUB_COLUMN, HubBarTopContext, HubCharactersContext, MoreOptions } from './HubParts'
+import { HubEmpty } from './HubEmpty'
+import { HubNewCharacter } from './HubNewCharacter'
+import { HubActions, HubCard, HubPhotos, HubTabs, type HubActionState } from './HubStage'
import { SwapOneClick, useSwapOneClickShown } from './SwapOneClick'
-import { openHubAction, useHubCharacters } from './hubCharacters'
+import { openHubAction, useCharacterPhotos, useHubCharacters } from './hubCharacters'
type TeaserIntent = Extract<CloudTeaserTarget, { surface: 'intent' }>['intent']
-const ACTION_ICON: Record<HubAction, ReactNode> = {
- image: <ImageIcon size={15} />,
- swap: <Replace size={15} />,
- motion: <PersonStanding size={15} />,
- talk: <Mic size={15} />,
-}
-
interface Props {
/** The props the Stage takes, as CreateExperimental hands them to it. */
stage: Omit<React.ComponentProps<typeof Stage>, 'hub'>
onOpenAdvanced: () => void
onOpenWorkflows: () => void
- /** "From my gallery": the gallery opens, a clip there saves its frames. */
+ /** "Frames from a gallery video": the gallery opens, a clip there saves its frames. */
onOpenGallery: () => void
}
-/** The column every step shares: 660 px, centred. */
-const COLUMN = HUB_COLUMN
-
export function CharacterHub({ stage, onOpenAdvanced, onOpenWorkflows, onOpenGallery }: Props) {
- const step = useCreateStore((s) => s.hubStep)
- const { list, loading } = useHubCharacters()
- // Swap with the account switch on the cloud: the one click flow, with its
- // own bar (hub/SwapOneClick.tsx). Without it the panel as before.
- const oneClick = useSwapOneClickShown()
- const setHubStep = useCreateStore((s) => s.setHubStep)
- return (
- <HubCharactersContext.Provider value={list}>
- <section className="lu-hub flex min-w-0 flex-1 flex-col overflow-hidden" data-character-hub={step} aria-label="Character">
- <div className={cn(COLUMN, 'shrink-0')}>
- <HubHead list={list} />
- </div>
- {step === 'who' && <Scroll><HubWho list={list} loading={loading} onOpenGallery={onOpenGallery} /></Scroll>}
- {step === 'what' && <Scroll><HubWhat /></Scroll>}
- {step === 'panel' && oneClick && (
- <SwapOneClick onChangeCharacter={() => setHubStep('who')} onOpenAdvanced={onOpenAdvanced} />
- )}
- {step === 'panel' && !oneClick && (
- <>
- <Scroll>
- <div className="empty:hidden pt-3"><Stage hub {...stage} /></div>
- <HubPanel onOpenAdvanced={onOpenAdvanced} />
- </Scroll>
- <div className={cn(COLUMN, 'shrink-0')}>
- <Composer hub onOpenAdvanced={onOpenAdvanced} onOpenWorkflows={onOpenWorkflows} />
- </div>
- </>
- )}
- </section>
- </HubCharactersContext.Provider>
- )
-}
-
-function Scroll({ children }: { children: ReactNode }) {
- return (
- <div className="min-h-0 flex-1 overflow-y-auto scrollbar-thin">
- <div className={cn(COLUMN, 'pb-4')}>{children}</div>
- </div>
- )
-}
-
-// ── head line ───────────────────────────────────────────────────────────────
-
-const CHOOSE = '__choose'
-const PHOTO = '__photo'
-const NEW = '__new'
-
-function HubHead({ list }: { list: HubCharacter[] }) {
const step = useCreateStore((s) => s.hubStep)
const intent = useCreateStore((s) => s.intent())
const characterTab = useCreateStore((s) => s.characterTab)
- const hubCharacter = useCreateStore((s) => s.hubCharacter)
+ const picked = useCreateStore((s) => s.hubCharacter)
const setHubCharacter = useCreateStore((s) => s.setHubCharacter)
const setHubStep = useCreateStore((s) => s.setHubStep)
- const videoInput = useCreateStore((s) => s.videoInput)
- const setVideoInput = useCreateStore((s) => s.setVideoInput)
const setError = useCreateStore((s) => s.setError)
+ const { list, loading } = useHubCharacters()
+ // Swap with the account switch on the cloud: the one click flow, with its
+ // own bar (hub/SwapOneClick.tsx). Without it the panel as before.
+ const oneClick = useSwapOneClickShown()
const pickAction = usePickAction()
+
+ // The character as the list has it now (a new name, a new picture), for as
+ // long as it is in the list.
+ const current = (picked && list.find((c) => c.key === picked.key)) || picked
const training = step === 'panel' && intent === 'character' && characterTab === 'train'
- const action = step === 'panel' ? actionOfIntent(intent) : null
+ const action = step === 'panel' && !training ? actionOfIntent(intent) : null
+ const { photos, loading: photosLoading } = useCharacterPhotos(step === 'what' || step === 'panel' ? current : null)
- const who: SelectOption[] = [
- ...list.map((c) => ({ value: c.key, label: c.name, sublabel: c.meta, lead: <HubAvatar name={c.name} image={c.image} size={18} /> })),
- { value: PHOTO, label: HUB_JUST_PHOTO },
- { value: NEW, label: 'New character', lead: <Plus size={14} className="hub-dim" /> },
- { value: CHOOSE, label: 'All characters…' },
- ]
- const whoValue = training ? NEW : hubCharacter?.key ?? (step === 'who' ? '' : PHOTO)
- const whoOptions = whoValue === PHOTO || whoValue === NEW || !whoValue || list.some((c) => c.key === whoValue)
- ? who
- : [{ value: whoValue, label: hubCharacter?.name ?? '', lead: <HubAvatar name={hubCharacter?.name ?? ''} image={hubCharacter?.image} size={20} /> }, ...who]
- const withLead = whoOptions.map((o) => (o.value === hubCharacter?.key ? { ...o, lead: <HubAvatar name={o.label} image={hubCharacter?.image} size={20} /> } : o))
+ // Nobody picked yet, and there are characters: the first one takes the
+ // stage, so the area opens on something of the user's own.
+ const first = list[0]
+ useEffect(() => {
+ if (step === 'who' && first) {
+ setHubCharacter(first)
+ setHubStep('what')
+ }
+ }, [step, first, setHubCharacter, setHubStep])
- const onWho = (v: string) => {
- if (v === CHOOSE) { setHubStep('who'); return }
- if (v === NEW) { startTraining(); return }
- const c = v === PHOTO ? null : list.find((x) => x.key === v) ?? null
+ const pick = (c: HubCharacter | null) => {
setHubCharacter(c)
if (step === 'panel' && action) {
void openHubAction(action, c, true).then((err) => { if (err) setError(err) })
@@ -145,56 +91,89 @@ function HubHead({ list }: { list: HubCharacter[] }) {
}
}
- const actions: SelectOption[] = HUB_ACTIONS.map((a) => ({ value: a, label: ACTION_LABEL[a], sublabel: ACTION_LINE[a] }))
-
- return (
- <div className="hub-line flex h-[35px] items-center gap-2 border-b hub-fs-13" data-hub-head>
- <Select
- variant="text"
- ariaLabel="Character"
- placeholder="Character"
- textClassName={step === 'who' ? 'hub-acc' : undefined}
- value={whoValue}
- options={withLead}
- onChange={onWho}
+ let body: ReactNode
+ if (step === 'new') {
+ body = (
+ <HubNewCharacter
+ onBack={() => setHubStep(picked ? 'what' : 'who')}
+ onSaved={(c) => { setHubCharacter(c); setHubStep(c ? 'what' : 'who') }}
+ onOpenGallery={onOpenGallery}
/>
- <ArrowRight size={12} className="hub-dim shrink-0" aria-hidden />
- <Select
- variant="text"
- ariaLabel="Action"
- // A new character's training stands where the action stands; the
- // list leads on to the actions once it is trained.
- placeholder={training ? 'Train' : 'Action'}
- textClassName={training ? undefined : step === 'what' ? 'hub-acc' : step === 'who' ? 'hub-dim' : undefined}
- value={training ? '' : action ?? ''}
- options={actions}
- onChange={(v) => pickAction(v as HubAction)}
- />
- <span className="flex-1" />
- {step === 'panel' && videoInput && (intent === 'swap_character' || intent === 'motion' || intent === 'lipsync') && (
- <span className="hub-muted flex min-w-0 items-center gap-1.5 hub-fs-12" data-hub-clip>
- <Film size={13} className="hub-dim shrink-0" />
- <span className="truncate">{videoInput.name}</span>
- <button type="button" onClick={() => setVideoInput(null)} className="hub-dim p-0.5" title="Remove the video" aria-label="Remove the video">
- <X size={12} />
+ )
+ } else if (training) {
+ body = (
+ <div className="hub-page" data-hub-training>
+ <div className="hub-line flex h-[35px] shrink-0 items-center gap-2 border-b hub-fs-13">
+ <button type="button" onClick={() => setHubStep(picked ? 'what' : 'who')} className="hub-muted flex items-center gap-1" data-hub-back>
+ <ChevronLeft size={13} />Characters
</button>
- </span>
- )}
- </div>
- )
-}
+ <span className="hub-dim" aria-hidden>/</span>
+ <span className="hub-text font-medium">Train a model</span>
+ </div>
+ <div className="min-h-0 flex-1 overflow-y-auto scrollbar-thin">
+ <div className={cn(HUB_COLUMN, 'pb-4')}>
+ <div className="pt-3 empty:hidden"><Stage hub {...stage} /></div>
+ <HubPanel onOpenAdvanced={onOpenAdvanced} />
+ </div>
+ </div>
+ <div className={cn(HUB_COLUMN, 'shrink-0')}>
+ <Composer hub onOpenAdvanced={onOpenAdvanced} onOpenWorkflows={onOpenWorkflows} />
+ </div>
+ </div>
+ )
+ } else if (step === 'who') {
+ body = loading
+ ? <p className="hub-dim py-6 hub-fs-13" data-hub-step="who">Loading your characters…</p>
+ : <HubEmpty onCreate={() => setHubStep('new')} onTry={(a) => { setHubCharacter(null); pickAction(a) }} />
+ } else {
+ body = (
+ <HubBarTopContext.Provider value={<StageActions active={action} name={current?.name ?? null} family={current?.ref?.family} onPick={pickAction} />}>
+ <div className="hub-stage" data-hub-stage>
+ <HubTabs
+ list={list}
+ loading={loading}
+ current={current?.key ?? null}
+ photoOnly={!current}
+ onPick={pick}
+ onPhotoOnly={() => pick(null)}
+ onNew={() => setHubStep('new')}
+ />
+ <HubCard c={current} photo={photos[0] ?? null} />
+ {step === 'what' && (
+ <>
+ <div className="hub-body scrollbar-thin pb-4 pt-4"><HubPhotos c={current} photos={photos} loading={photosLoading} /></div>
+ <div className="hub-foot"><div className="hub-bar" data-hub-bar="what"><StageActions active={null} name={current?.name ?? null} family={current?.ref?.family} onPick={pickAction} /></div></div>
+ </>
+ )}
+ {step === 'panel' && oneClick && (
+ <SwapOneClick onChangeCharacter={() => setHubStep('what')} onOpenAdvanced={onOpenAdvanced} />
+ )}
+ {step === 'panel' && !oneClick && (
+ <>
+ <div className="hub-body scrollbar-thin pb-4">
+ <div className="pt-3 empty:hidden"><Stage hub {...stage} /></div>
+ <HubPanel onOpenAdvanced={onOpenAdvanced} />
+ </div>
+ <div className="hub-foot"><Composer hub onOpenAdvanced={onOpenAdvanced} onOpenWorkflows={onOpenWorkflows} /></div>
+ </>
+ )}
+ </div>
+ </HubBarTopContext.Provider>
+ )
+ }
-/** "Train from photos": Character Studio's training, as it was. */
-function startTraining() {
- const st = useCreateStore.getState()
- st.setHubCharacter(null)
- st.setIntent('character')
- st.setCharacterTab('train')
+ return (
+ <HubCharactersContext.Provider value={list}>
+ <section className="lu-hub flex min-w-0 flex-1 flex-col overflow-hidden px-6" data-character-hub={step} aria-label="Character">
+ {body}
+ </section>
+ </HubCharactersContext.Provider>
+ )
}
-/** Step 2 and the head line pick an action the same way. A tab that cannot
- * run here (Swap in local mode, a Mac lane without its model) opens the
- * Cloud sheet, as its pill did. */
+/** The switch picks an action. A tab that cannot run here (Swap in local
+ * mode, a Mac lane without its model) opens the Cloud sheet, as its pill
+ * did. */
function usePickAction() {
const { intents, lockedOf } = useIntentLanes()
const setCloudTeaser = useUIStore((s) => s.setCloudTeaser)
@@ -204,196 +183,53 @@ function usePickAction() {
const meta = intents.find((m) => m.id === intent) ?? INTENT_MAP[intent]
if (lockedOf(meta)) { setCloudTeaser({ surface: 'intent', intent: intent as TeaserIntent }); return }
const { hubCharacter: c, hubStep } = useCreateStore.getState()
- // From step 2 the character's picture fills the inputs; switching the
- // action in the head line keeps what the panel already holds.
+ // From the stage the character's picture fills the inputs; switching
+ // the action keeps what the panel already holds.
void openHubAction(a, c, hubStep !== 'panel').then((err) => { if (err) setError(err) })
}
}
-// ── step 1: who? ────────────────────────────────────────────────────────────
-
-export function HubWho({ list, loading, onOpenGallery }: { list: HubCharacter[]; loading: boolean; onOpenGallery: () => void }) {
- const setHubCharacter = useCreateStore((s) => s.setHubCharacter)
- const setHubStep = useCreateStore((s) => s.setHubStep)
- const [upload, setUpload] = useState<File[] | null>(null)
- const [note, setNote] = useState<ReactNode>(null)
- const file = useRef<HTMLInputElement>(null)
-
- const pick = (c: HubCharacter | null) => { setHubCharacter(c); setHubStep('what') }
-
- return (
- <div data-hub-step="who">
- <h2 className="hub-dim mt-5 mb-1.5 hub-fs-10">My characters</h2>
- <div aria-label="My characters">
- {list.map((c) => (
- <button
- key={c.key}
- type="button"
- onClick={() => pick(c)}
- // The whole name, and the trigger word of a LoRA character, where
- // the row cuts a long name (GitHub discussion #150).
- title={c.ref ? `${c.name}, trigger word: ${c.ref.triggerWord}` : c.name}
- className="hub-line hub-hover -mx-2 flex h-10 w-[calc(100%+16px)] items-center gap-2.5 rounded-sm border-b px-2 text-left"
- data-hub-character={c.key}
- >
- <HubAvatar name={c.name} image={c.image} size={26} />
- <span className="hub-text min-w-0 flex-1 truncate hub-fs-14 font-medium">{c.name}</span>
- <span className="hub-dim hub-fs-125 tabular-nums">{c.meta}</span>
- </button>
- ))}
- {list.length === 0 && (
- <p className="hub-dim hub-line border-b py-3 hub-fs-13">{loading ? 'Loading your characters…' : 'No characters yet. Make your first one below.'}</p>
- )}
- </div>
-
- <div className="hub-line border-b pb-2.5">
- <div className="flex h-10 items-center gap-2.5">
- <span className="hub-muted grid w-[26px] place-items-center"><Plus size={15} /></span>
- <span className="hub-text hub-fs-14 font-medium">New character</span>
- </div>
- <div className="flex flex-wrap items-center gap-x-2 gap-y-1 pl-9 hub-fs-13" data-hub-new>
- <button type="button" className="hub-acc hover:underline" onClick={startTraining}>Train from photos</button>
- <span className="hub-dim" aria-hidden>·</span>
- <button type="button" className="hub-acc hover:underline" onClick={() => file.current?.click()}>Upload photos or LoRA</button>
- <span className="hub-dim" aria-hidden>·</span>
- <button
- type="button"
- className="hub-acc hover:underline"
- onClick={() => { onOpenGallery(); setNote('Open a video in the gallery and choose Save as character. Its frames become a character.') }}
- >
- From my gallery
- </button>
- <input
- ref={file}
- type="file"
- multiple
- accept="image/*,.safetensors"
- className="hidden"
- aria-label="Upload photos or a LoRA file"
- onChange={(e) => {
- const files = Array.from(e.target.files ?? [])
- e.target.value = ''
- if (files.some((f) => f.name.toLowerCase().endsWith('.safetensors'))) {
- setUpload(null)
- setNote(<LoraFileNote />)
- return
- }
- if (files.length) { setUpload(files); setNote(null) }
- }}
- />
- </div>
- {upload && <SavePhotos files={upload} onDone={() => setUpload(null)} />}
- {note && <p className="hub-dim pl-9 pt-2 hub-fs-125" role="status">{note}</p>}
- </div>
-
- <div className="flex flex-wrap items-baseline gap-3 pt-3.5 hub-fs-125">
- <button type="button" onClick={() => pick(null)} className="hub-muted underline decoration-[var(--hub-edge)] underline-offset-[3px]">
- {HUB_JUST_PHOTO}
- </button>
- <span className="hub-dim">{HUB_JUST_PHOTO_LINE}</span>
- </div>
- </div>
- )
-}
-
-/** A LoRA file is not uploaded from here: it goes into the LoRA folder of
- * this machine, under the name the list reads. */
-function LoraFileNote() {
- return (
- <>
- A LoRA file goes into your LoRA folder, named {'char_<name>_zimage.safetensors'}. It shows here after that.
- {isMlxImageHost() && (
- <> <button type="button" className="underline" onClick={() => { void openMlxLoraFolder().catch(() => undefined) }}>Open the LoRA folder</button></>
- )}
- </>
- )
-}
-
-/** Photos picked by "Upload photos or LoRA": one name, then they are a
- * character on this machine (lib/saved-characters), ready for every action. */
-function SavePhotos({ files, onDone }: { files: File[]; onDone: () => void }) {
- const [name, setName] = useState('')
- const [error, setError] = useState<string | null>(null)
- const save = async () => {
- try {
- await saveCharacter(name, files)
- onDone()
- } catch (err) {
- setError(err instanceof Error ? err.message : String(err))
- }
- }
- return (
- <div className="flex flex-wrap items-center gap-2.5 pl-9 pt-2 hub-fs-13" data-hub-save-photos>
- <span className="hub-muted">{files.length} {files.length === 1 ? 'photo' : 'photos'}</span>
- <input
- autoFocus
- value={name}
- maxLength={40}
- aria-label="Name of the new character"
- placeholder="Name"
- onChange={(e) => setName(e.target.value)}
- onKeyDown={(e) => { if (e.key === 'Enter') void save() }}
- className="hub-text hub-line w-40 border-b bg-transparent py-1 outline-none"
- />
- <button type="button" className="hub-acc disabled:opacity-40" disabled={!name.trim()} onClick={() => void save()}>Save</button>
- <button type="button" className="hub-dim" onClick={onDone}>Cancel</button>
- {error && <span role="alert" className="text-red-400">{error}</span>}
- </div>
- )
-}
-
-// ── step 2: what? ───────────────────────────────────────────────────────────
-
-function HubWhat() {
- const hubCharacter = useCreateStore((s) => s.hubCharacter)
+/** The switch with what each action costs or where it runs. */
+function StageActions({ active, name, family, onPick }: { active: HubAction | null; name: string | null; family: string | undefined; onPick: (a: HubAction) => void }) {
const backend = useCreateStore((s) => s.backend)
const cloudFeatures = useSettingsStore((s) => s.settings.cloudTeasersEnabled)
const released = useCharacterHubReleased()
useCloudCatalogStore((s) => s.fetchedAt)
const { intents, lockedOf } = useIntentLanes()
- const pickAction = usePickAction()
const showCloud = backend === 'cloud' || cloudFeatures
- const family = hubCharacter?.ref?.family
+ const actions: HubActionState[] = HUB_ACTIONS.flatMap((a) => {
+ const intent: CreateIntent = intentOfAction(a)
+ const meta = intents.find((m) => m.id === intent)
+ // Left out where the tab is left out (Cloud features off, or a Mac
+ // without the lane), as in the old pill bar.
+ if (!meta) return []
+ const locked = lockedOf(meta)
+ // Local: the action has a lane on this machine. In cloud mode that is
+ // asked of the local backend.
+ const local = !lockedOfLocal(intents, intent, backend, lockedOf)
+ const soon = a === 'swap' && !locked && !released
+ const price = actionCloudPrice(a, a === 'image' ? family : undefined)
+ const line = soon ? HUB_SWAP_SOON : locked ? 'Runs on LU Cloud' : actionMeta({ local, cloudPrice: price, showCloud: backend === 'cloud' || (showCloud && !local) })
+ return [{ action: a, label: meta.label, locked, meta: line }]
+ })
+ return <HubActions actions={actions} active={active} name={name} onPick={onPick} right={active ? <StageClip /> : null} />
+}
+/** The clip a panel holds, by its name, with the way to take it out. Swap
+ * hands it on to Motion and Talk, so it stands where all three see it. */
+function StageClip() {
+ const intent = useCreateStore((s) => s.intent())
+ const videoInput = useCreateStore((s) => s.videoInput)
+ const setVideoInput = useCreateStore((s) => s.setVideoInput)
+ if (!videoInput || !(intent === 'swap_character' || intent === 'motion' || intent === 'lipsync')) return null
return (
- <div data-hub-step="what">
- <h2 className="hub-dim mt-5 mb-1.5 hub-fs-10">{whatHeading(hubCharacter)}</h2>
- <div role="radiogroup" aria-label="Character action" className="hub-line border-t">
- {HUB_ACTIONS.map((a) => {
- const intent: CreateIntent = intentOfAction(a)
- const meta = intents.find((m) => m.id === intent)
- // Left out where the tab is left out (Cloud features off, or a Mac
- // without the lane), as in the old pill bar.
- if (!meta) return null
- const locked = lockedOf(meta)
- // Local: the action has a lane on this machine. In cloud mode that
- // is asked of the local backend.
- const local = !lockedOfLocal(intents, intent, backend, lockedOf)
- const soon = a === 'swap' && !locked && !released
- const price = actionCloudPrice(a, a === 'image' ? family : undefined)
- const line = soon ? HUB_SWAP_SOON : locked ? 'Runs on LU Cloud' : actionMeta({ local, cloudPrice: price, showCloud: backend === 'cloud' || (showCloud && !local) })
- return (
- <button
- key={a}
- type="button"
- role="radio"
- aria-checked={false}
- aria-label={locked ? `${meta.label}, runs on LU Cloud` : meta.label}
- title={locked ? `${meta.label}, runs on LU Cloud` : meta.label}
- onClick={() => pickAction(a)}
- className={cn('hub-line hub-hover -mx-2 flex h-[38px] w-[calc(100%+16px)] items-center gap-2.5 rounded-sm border-b px-2 text-left hub-fs-14', locked && 'opacity-60')}
- data-hub-action={a}
- >
- <span className="hub-muted shrink-0">{ACTION_ICON[a]}</span>
- <span className="hub-text w-[111px] shrink-0 font-medium">{ACTION_LABEL[a]}</span>
- <span className="hub-muted min-w-0 flex-1 truncate hub-fs-13 max-[520px]:hidden">{ACTION_LINE[a]}</span>
- <span className="hub-dim ml-auto whitespace-nowrap hub-fs-125 tabular-nums" data-hub-action-meta>{line}</span>
- </button>
- )
- })}
- </div>
- <p className="hub-dim pt-3 hub-fs-125">{HUB_LOCAL_LINE}</p>
- </div>
+ <span className="hub-muted flex min-w-0 shrink items-center gap-1.5 hub-fs-12" data-hub-clip>
+ <Film size={13} className="hub-dim shrink-0" />
+ <span className="max-w-[180px] truncate">{videoInput.name}</span>
+ <button type="button" onClick={() => setVideoInput(null)} className="hub-dim p-0.5" title="Remove the video" aria-label="Remove the video">
+ <X size={12} />
+ </button>
+ </span>
)
}
@@ -417,7 +253,7 @@ function lockedOfLocal(
return !meta.hasLocalLane
}
-// ── step 3: the panel ───────────────────────────────────────────────────────
+// ── the panel of an action ──────────────────────────────────────────────────
function HubPanel({ onOpenAdvanced }: { onOpenAdvanced: () => void }) {
const intent = useCreateStore((s) => s.intent())
@@ -441,4 +277,3 @@ function HubPanel({ onOpenAdvanced }: { onOpenAdvanced: () => void }) {
</div>
)
}
-
diff --git a/src/components/create/experimental/hub/HubEmpty.tsx b/src/components/create/experimental/hub/HubEmpty.tsx
new file mode 100644
index 00000000..6e30862b
--- /dev/null
+++ b/src/components/create/experimental/hub/HubEmpty.tsx
@@ -0,0 +1,151 @@
+// The Character area with no character yet (3.1.0, David 16.11.2026): the
+// three steps and one button on the left, on the right what a character can
+// do, as four small drawings with the LU mark as the figure. These four are
+// the only moving pictures of the area (index.css, .hub-ex-*); with reduced
+// motion they stand still.
+
+import type { ReactNode } from 'react'
+import { Image as ImageIcon, Mic, PersonStanding, Plus, Replace } from 'lucide-react'
+import { ACTION_LABEL, type HubAction } from '../../../../lib/create/character-hub'
+import { MONOGRAM } from '../../../layout/brand'
+import { Button } from '../../ui/Button'
+
+const STEPS = [
+ { title: 'Add photos of one face', line: '4 to 30 photos, or frames from a video in your gallery.' },
+ { title: 'Give it a name', line: 'Saved right away. Train it later for the best likeness.' },
+ { title: 'Use it', line: 'Image, Swap, Motion and Talk. In Chat too.' },
+]
+
+/** The LU mark as a figure: the monogram is the head, the shoulders are
+ * drawn in the same line. */
+function LuFigure({ x, y, k = 1, className }: { x: number; y: number; k?: number; className?: string }) {
+ return (
+ <g className={className} transform={`translate(${x} ${y}) scale(${k})`}>
+ <image href={MONOGRAM} x="-15" y="-34" width="30" height="30" className="hub-ex-mark" />
+ <path d="M-20 22v-8a12 12 0 0 1 12-12h16a12 12 0 0 1 12 12v8" fill="none" stroke="currentColor" strokeWidth="2.3" strokeLinecap="round" className="hub-text" />
+ </g>
+ )
+}
+
+/** Anybody: the same build in grey, with an empty head. */
+function GreyFigure({ x, y, k = 1, className }: { x: number; y: number; k?: number; className?: string }) {
+ return (
+ <g className={className} transform={`translate(${x} ${y}) scale(${k})`}>
+ <g fill="none" stroke="currentColor" strokeWidth="2.3" strokeLinecap="round" className="hub-dim">
+ <rect x="-11" y="-31" width="22" height="24" rx="8" />
+ <path d="M-20 22v-8a12 12 0 0 1 12-12h16a12 12 0 0 1 12 12v8" />
+ </g>
+ </g>
+ )
+}
+
+/** Image: the figure stays, the picture around it becomes another one
+ * (mountains by day, a town by night). */
+function ArtImage() {
+ return (
+ <>
+ <defs><clipPath id="hub-ex-picture"><rect x="14" y="8" width="92" height="64" rx="5" /></clipPath></defs>
+ <g clipPath="url(#hub-ex-picture)">
+ <g className="hub-ex-a hub-dim" fill="currentColor">
+ <circle cx="88" cy="22" r="7" opacity=".7" />
+ <path d="M14 72 44 30l18 24 12-14 32 32z" opacity=".45" />
+ </g>
+ <g className="hub-ex-b hub-dim" fill="currentColor">
+ <path d="M82 14a8 8 0 1 0 8 10 6.4 6.4 0 0 1-8-10z" opacity=".7" />
+ {[[18, 44, 13], [34, 30, 11], [48, 50, 15], [70, 38, 12], [86, 48, 16]].map(([x, y, w]) => (
+ <rect key={x} x={x} y={y} width={w} height={72 - y} opacity=".4" />
+ ))}
+ </g>
+ <LuFigure x={60} y={56} k={0.82} />
+ </g>
+ <rect x="14" y="8" width="92" height="64" rx="5" fill="none" stroke="currentColor" strokeWidth="1.2" className="hub-dim" />
+ </>
+ )
+}
+
+/** Swap: one of two people becomes the character. */
+function ArtSwap() {
+ return (
+ <>
+ <GreyFigure x={38} y={48} k={0.95} className="hub-ex-a" />
+ <LuFigure x={38} y={48} k={0.95} className="hub-ex-b" />
+ <GreyFigure x={84} y={48} k={0.95} />
+ </>
+ )
+}
+
+/** Motion: somebody moves, the character moves the same way. */
+function ArtMotion() {
+ return (
+ <>
+ <g className="hub-ex-tilt" style={{ transformOrigin: '30px 68px' }}><GreyFigure x={30} y={48} k={0.85} /></g>
+ <path d="M55 42h10m-4-4 4 4-4 4" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" className="hub-dim" />
+ <g className="hub-ex-tilt" style={{ transformOrigin: '90px 68px' }}><LuFigure x={90} y={48} k={0.95} /></g>
+ </>
+ )
+}
+
+/** Talk: the character and its voice. */
+function ArtTalk() {
+ return (
+ <>
+ <LuFigure x={36} y={48} />
+ {[12, 24, 16, 30, 20, 10].map((h, i) => (
+ <rect key={i} className="hub-ex-bar hub-acc" fill="currentColor" x={70 + i * 7} y={40 - h / 2} width="3.4" height={h} rx="1.7"
+ style={{ animationDelay: `${-i * 0.23}s`, transformOrigin: '0 40px' }} />
+ ))}
+ </>
+ )
+}
+
+const EXAMPLES: { action: HubAction; icon: ReactNode; line: string; art: () => ReactNode }[] = [
+ { action: 'image', icon: <ImageIcon size={14} />, line: 'Your character in any place you describe.', art: ArtImage },
+ { action: 'swap', icon: <Replace size={14} />, line: 'Your character takes the place of a person in a clip.', art: ArtSwap },
+ { action: 'motion', icon: <PersonStanding size={14} />, line: 'Your character copies a dance or a move.', art: ArtMotion },
+ { action: 'talk', icon: <Mic size={14} />, line: 'Your character says your text.', art: ArtTalk },
+]
+
+export function HubEmpty({ onCreate, onTry }: { onCreate: () => void; onTry: (action: HubAction) => void }) {
+ return (
+ <div className="hub-empty" data-hub-step="who" data-hub-empty>
+ <div className="min-w-0 flex-1">
+ <ol className="hub-line border-t">
+ {STEPS.map((s, i) => (
+ <li key={s.title} className="hub-line flex gap-4 border-b py-3">
+ <span className="hub-dim w-3 shrink-0 pt-px hub-fs-13 tabular-nums">{i + 1}</span>
+ <span className="min-w-0">
+ <span className="hub-text block hub-fs-14 font-medium">{s.title}</span>
+ <span className="hub-dim mt-0.5 block hub-fs-13">{s.line}</span>
+ </span>
+ </li>
+ ))}
+ </ol>
+ <div className="pt-6">
+ <span data-hub-create><Button variant="primary" size="lg" icon={Plus} onClick={onCreate}>Create a character</Button></span>
+ </div>
+ </div>
+ <ul className="hub-line min-w-0 flex-1 border-t" aria-label="What a character can do">
+ {EXAMPLES.map((e) => {
+ const Art = e.art
+ return (
+ <li key={e.action} className="hub-line border-b">
+ <button
+ type="button"
+ onClick={() => onTry(e.action)}
+ title={`Try ${ACTION_LABEL[e.action]} with one photo`}
+ className="hub-hover -mx-2 flex w-[calc(100%+16px)] items-center gap-4 rounded-sm px-2 py-3 text-left"
+ data-hub-example={e.action}
+ >
+ <svg viewBox="0 0 120 80" className="hub-ex shrink-0" aria-hidden><Art /></svg>
+ <span className="min-w-0">
+ <span className="hub-text flex items-center gap-1.5 hub-fs-14 font-medium"><span className="hub-muted">{e.icon}</span>{ACTION_LABEL[e.action]}</span>
+ <span className="hub-dim mt-0.5 block hub-fs-13">{e.line}</span>
+ </span>
+ </button>
+ </li>
+ )
+ })}
+ </ul>
+ </div>
+ )
+}
diff --git a/src/components/create/experimental/hub/HubNewCharacter.tsx b/src/components/create/experimental/hub/HubNewCharacter.tsx
new file mode 100644
index 00000000..9cf4ed97
--- /dev/null
+++ b/src/components/create/experimental/hub/HubNewCharacter.tsx
@@ -0,0 +1,371 @@
+// "New character" (3.1.0, David 16.11.2026): one page with one decision.
+// Left the photos (only the ones the user put there, nothing before that),
+// right the name and how LU remembers the face: keep the photos (a character
+// at once, lib/saved-characters) or train a model (the photos go on to the
+// training, as "Train from photos" did). A LoRA file dropped here becomes a
+// character of this machine instead (lib/create/character-lora); the page
+// says where that folder is and opens it.
+
+import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
+import { Check, ChevronLeft, FolderOpen, Upload, X } from 'lucide-react'
+import { useCreateStore } from '../../../../stores/createStore'
+import { isTauri } from '../../../../api/backend'
+import { MAX_CHARACTER_NAME, MAX_CHARACTER_PHOTOS, saveCharacter } from '../../../../lib/saved-characters'
+import { MIN_TRAIN_IMAGES, maxTrainImages } from '../../../../lib/train-image-cap'
+import { hubFromLocal, hubFromSaved, type HubCharacter } from '../../../../lib/create/character-hub'
+import { characterFromLora, localCharacterPrefix } from '../../../../lib/characters'
+import {
+ characterLoraFolder, importCharacterLora, isLoraFile, nameFromLoraFile, openCharacterLoraFolder, shortFolder,
+ type LoraFolder,
+} from '../../../../lib/create/character-lora'
+import { keyFormatNote } from '../../../../api/character-import'
+import { errorText } from '../../../../types/json-guards'
+import { Button } from '../../ui/Button'
+import { cn } from '../../ui/cn'
+import { sendPhotosToStudio } from '../characterPhotos'
+import { refreshLocalShelves } from '../CharacterUseLocally'
+import { ACTION_ICON } from './HubStage'
+import { ACTION_LABEL, HUB_ACTIONS } from '../../../../lib/create/character-hub'
+
+type Way = 'keep' | 'train'
+
+const GOOD = ['One person, face clearly visible', 'Different angles, light and clothes', 'Close-ups and half body mixed']
+const AVOID = ['Sunglasses, masks, heavy filters', 'Other people in the picture', 'Ten copies of the same selfie']
+
+function megabytes(bytes: number): string {
+ return `${Math.max(1, Math.round(bytes / (1024 * 1024)))} MB`
+}
+
+/** The addresses of the photos on the page, given back when they leave it. */
+function usePhotoUrls(files: File[]): string[] {
+ const urls = useMemo(() => files.map((f) => URL.createObjectURL(f)), [files])
+ useEffect(() => () => { for (const u of urls) URL.revokeObjectURL(u) }, [urls])
+ return urls
+}
+
+interface Props {
+ /** Back to the characters. */
+ onBack: () => void
+ /** A character was made: the stage shows it. */
+ onSaved: (c: HubCharacter | null) => void
+ /** "Frames from a gallery video": the gallery opens. */
+ onOpenGallery: () => void
+}
+
+export function HubNewCharacter({ onBack, onSaved, onOpenGallery }: Props) {
+ const [photos, setPhotos] = useState<File[]>([])
+ const [lora, setLora] = useState<File | null>(null)
+ const [name, setName] = useState('')
+ const [way, setWay] = useState<Way>('keep')
+ const [over, setOver] = useState(false)
+ const [busy, setBusy] = useState(false)
+ const [progress, setProgress] = useState<number | null>(null)
+ const [error, setError] = useState<string | null>(null)
+ const [note, setNote] = useState<ReactNode>(null)
+ // A LoRA that is in its folder, with something to say about it before the
+ // page is left.
+ const [added, setAdded] = useState<{ note: string; character: HubCharacter | null } | null>(null)
+ const [folder, setFolder] = useState<LoraFolder | null>(null)
+ const input = useRef<HTMLInputElement>(null)
+ const urls = usePhotoUrls(photos)
+ const desktop = isTauri()
+ const backend = useCreateStore((s) => s.backend)
+ // A character keeps 30 photos; a training set takes what the trainer takes.
+ const most = way === 'train' ? maxTrainImages(backend) : MAX_CHARACTER_PHOTOS
+
+ useEffect(() => {
+ let live = true
+ void characterLoraFolder().then((f) => { if (live) setFolder(f) })
+ return () => { live = false }
+ }, [])
+
+ const take = (list: File[]) => {
+ setError(null)
+ setNote(null)
+ const file = list.find(isLoraFile)
+ if (file) {
+ if (!desktop) { setError('A LoRA file can be added in the desktop app.'); return }
+ setLora(file)
+ setPhotos([])
+ if (!name.trim()) setName(nameFromLoraFile(file.name))
+ return
+ }
+ const images = list.filter((f) => f.type.startsWith('image/'))
+ if (images.length === 0) { if (list.length) setError('Add photos (JPG, PNG, WebP) or a .safetensors file.'); return }
+ setLora(null)
+ setPhotos((before) => {
+ const next = [...before, ...images].slice(0, most)
+ if (before.length + images.length > most) setNote(`${way === 'train' ? 'A training set takes' : 'A character keeps'} ${most} photos. The rest was left out.`)
+ return next
+ })
+ }
+
+ const clean = name.trim()
+ // The training has its own page, with its own photos and checks: the way
+ // there is always open, and takes along what is here already.
+ const toTraining = !lora && way === 'train'
+ const ready = !busy && (toTraining || (!!clean && (lora ? folder?.status === 'ok' : photos.length > 0)))
+ const hint = toTraining
+ ? null
+ : !lora && photos.length === 0
+ ? 'Add photos first'
+ : !clean
+ ? 'Give the character a name'
+ : lora && folder?.status !== 'ok'
+ ? 'There is no LoRA folder on this computer'
+ : null
+
+ const save = async () => {
+ if (!ready) return
+ setBusy(true)
+ setError(null)
+ try {
+ if (lora) {
+ setProgress(0)
+ const r = await importCharacterLora(lora, clean, (got, total) => setProgress(total > 0 ? got / total : 0))
+ if (r.status === 'exists') throw new Error(`There is already a character called ${clean} on this computer. Pick another name.`)
+ if (r.status === 'no_comfy') throw new Error('LU found no ComfyUI on this computer, so there is no LoRA folder to put the file in.')
+ await refreshLocalShelves()
+ const warn = keyFormatNote(r.keyFormat)
+ // The new character takes the stage, by the id the list gives it.
+ const ref = characterFromLora(r.file, await localCharacterPrefix())
+ const made = ref ? hubFromLocal(ref) : null
+ if (warn) { setAdded({ note: warn, character: made }); return }
+ onSaved(made)
+ return
+ }
+ if (way === 'train') {
+ if (clean) useCreateStore.getState().setTriggerWord(clean)
+ sendPhotosToStudio(clean || 'photo', photos)
+ // The training is a panel of the area (intent character, tab train).
+ useCreateStore.getState().setHubStep('panel')
+ return
+ }
+ const { character } = await saveCharacter(clean, photos)
+ onSaved(hubFromSaved(character, null))
+ } catch (err) {
+ setError(errorText(err))
+ } finally {
+ setBusy(false)
+ setProgress(null)
+ }
+ }
+
+ const summary = lora
+ ? `LoRA file · ${megabytes(lora.size)} · goes into your LoRA folder`
+ : way === 'train'
+ ? photos.length === 0
+ ? 'The training is set up on the next page'
+ : `${photos.length} ${photos.length === 1 ? 'photo' : 'photos'} go along · the training is set up on the next page`
+ : photos.length === 0
+ ? 'No photos yet'
+ : `${Math.min(photos.length, MAX_CHARACTER_PHOTOS)} ${photos.length === 1 ? 'photo' : 'photos'} · kept on this computer · free`
+ const button = added ? 'Done' : lora ? (clean ? `Add ${clean}` : 'Add') : way === 'train' ? 'Continue to training' : clean ? `Save ${clean}` : 'Save'
+
+ return (
+ <div className="hub-page" data-hub-step="new">
+ <div className="hub-line flex h-[35px] shrink-0 items-center gap-2 border-b hub-fs-13">
+ <button type="button" onClick={onBack} className="hub-muted flex items-center gap-1" data-hub-back>
+ <ChevronLeft size={13} />Characters
+ </button>
+ <span className="hub-dim" aria-hidden>/</span>
+ <span className="hub-text font-medium">New character</span>
+ </div>
+
+ <div className="hub-new scrollbar-thin">
+ <div className="min-w-0">
+ <div className="mb-2 flex items-baseline justify-between">
+ <h2 className="hub-dim hub-fs-10">{lora ? 'LoRA file' : 'Photos of the face'}</h2>
+ {!lora && photos.length > 0 && <span className="hub-dim hub-fs-12 tabular-nums" data-hub-photo-count>{photos.length} of {most}</span>}
+ </div>
+ <div
+ role="button"
+ tabIndex={0}
+ aria-label={desktop ? 'Drop photos or a LoRA file here, or choose files' : 'Drop photos here, or choose files'}
+ onClick={() => input.current?.click()}
+ onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); input.current?.click() } }}
+ onDragOver={(e) => { e.preventDefault(); setOver(true) }}
+ onDragLeave={() => setOver(false)}
+ onDrop={(e) => { e.preventDefault(); setOver(false); take(Array.from(e.dataTransfer.files ?? [])) }}
+ className={cn('hub-drop flex min-h-16 cursor-pointer items-center gap-3 px-4 hub-fs-14', over && 'hub-drop--over')}
+ data-hub-drop
+ >
+ <Upload size={17} className="hub-dim shrink-0" />
+ <span className="hub-muted min-w-0 flex-1">
+ <span className="hub-text font-medium">{desktop ? 'Drop photos or a LoRA file here' : 'Drop photos here'}</span>, or choose files
+ </span>
+ <button
+ type="button"
+ onClick={(e) => { e.stopPropagation(); onOpenGallery(); setNote('Open a video in the gallery and choose Save as character. Its frames become a character.') }}
+ className="hub-muted shrink-0 underline decoration-[var(--hub-edge)] underline-offset-[3px] hub-fs-125"
+ >
+ Frames from a gallery video
+ </button>
+ <input
+ ref={input}
+ type="file"
+ multiple
+ accept={desktop ? 'image/*,.safetensors' : 'image/*'}
+ className="hidden"
+ aria-label="Photos or a LoRA file"
+ onClick={(e) => e.stopPropagation()}
+ onChange={(e) => { take(Array.from(e.target.files ?? [])); e.target.value = '' }}
+ />
+ </div>
+
+ {photos.length > 0 && (
+ <ul className="mt-3.5 flex flex-wrap gap-2" aria-label="Photos of the new character" data-hub-photos={photos.length}>
+ {photos.map((f, i) => (
+ <li key={`${f.name}-${i}`} className="relative">
+ {urls[i] && <img src={urls[i]} alt="" className="hub-thumb" />}
+ <button
+ type="button"
+ onClick={() => setPhotos(photos.filter((_, k) => k !== i))}
+ className="absolute right-1 top-1 grid h-4 w-4 place-items-center rounded-full bg-black/55 text-white"
+ title="Remove this photo"
+ aria-label={`Remove photo ${i + 1}`}
+ >
+ <X size={10} strokeWidth={2.4} />
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+
+ {lora && (
+ <div className="hub-line mt-3.5 flex min-h-10 items-center gap-2.5 border-y hub-fs-14" data-hub-lora-file>
+ <span className="hub-text min-w-0 flex-1 truncate" title={lora.name}>{lora.name}</span>
+ <span className="hub-dim hub-fs-125 tabular-nums">{megabytes(lora.size)}</span>
+ {!busy && !added && (
+ <button type="button" onClick={() => setLora(null)} className="hub-dim p-1" title="Remove the file" aria-label="Remove the LoRA file"><X size={13} /></button>
+ )}
+ </div>
+ )}
+
+ {!lora && (
+ <div className="hub-line mt-5 grid grid-cols-2 gap-6 border-t pt-3.5 hub-fs-13">
+ <ul className="hub-muted space-y-1">
+ <li className="hub-text mb-1.5 flex items-center gap-1.5 font-medium"><Check size={13} strokeWidth={2.2} className="text-emerald-500 dark:text-emerald-300" />Good</li>
+ {GOOD.map((t) => <li key={t}>{t}</li>)}
+ </ul>
+ <ul className="hub-muted space-y-1">
+ <li className="hub-text mb-1.5 flex items-center gap-1.5 font-medium"><X size={13} strokeWidth={2.2} className="text-red-500 dark:text-red-300" />Avoid</li>
+ {AVOID.map((t) => <li key={t}>{t}</li>)}
+ </ul>
+ </div>
+ )}
+
+ {desktop && folder && (
+ <div className="hub-line mt-4 border-t pt-3.5 hub-fs-13" data-hub-lora-folder={folder.status}>
+ {folder.status === 'ok' ? (
+ <>
+ <p className="hub-muted flex items-start gap-2">
+ <FolderOpen size={14} className="hub-dim mt-0.5 shrink-0" />
+ <span><span className="hub-text font-medium">Already have a LoRA?</span> Drop the .safetensors above. LU copies it into its LoRA folder under the character's name:</span>
+ </p>
+ <p className="mt-1.5 flex flex-wrap items-center gap-x-4 gap-y-1 pl-[22px]">
+ <code className="hub-text hub-path min-w-0 break-all" title={folder.path} data-hub-lora-path>{shortFolder(folder.path)}</code>
+ <button
+ type="button"
+ onClick={() => { void openCharacterLoraFolder().catch((err) => setError(errorText(err))) }}
+ className="hub-muted underline decoration-[var(--hub-edge)] underline-offset-[3px]"
+ data-hub-lora-open
+ >
+ Open LoRA folder
+ </button>
+ </p>
+ </>
+ ) : (
+ <p className="hub-dim flex items-start gap-2">
+ <FolderOpen size={14} className="mt-0.5 shrink-0" />
+ <span>A LoRA file needs ComfyUI, and LU found none on this computer. Photos work without it.</span>
+ </p>
+ )}
+ </div>
+ )}
+
+ {note && <p className="hub-dim pt-3 hub-fs-125" role="status">{note}</p>}
+ </div>
+
+ <div className="min-w-0">
+ <label className="hub-dim mb-2 block hub-fs-10" htmlFor="hub-new-name">Name</label>
+ <input
+ id="hub-new-name"
+ value={name}
+ maxLength={MAX_CHARACTER_NAME}
+ placeholder="Name"
+ onChange={(e) => setName(e.target.value)}
+ onKeyDown={(e) => { if (e.key === 'Enter') void save() }}
+ className="hub-text hub-name-field w-full border-b bg-transparent pb-2 pt-1 outline-none"
+ data-hub-new-name
+ />
+
+ {lora ? (
+ <p className="hub-dim pt-5 hub-fs-13">
+ A LoRA is a small model that already knows a face. On this computer LU runs it with Z-Image. It shows in your characters as soon as it is in the folder.
+ </p>
+ ) : (
+ <>
+ <h2 className="hub-dim mb-1 mt-6 hub-fs-10">How should LU remember this face?</h2>
+ <div role="radiogroup" aria-label="How LU remembers the face" className="hub-line border-t">
+ <WayRow
+ on={way === 'keep'} onPick={() => setWay('keep')} id="keep" title="Keep the photos"
+ line="Ready now and free. Enough for Swap, Motion and Talk. New pictures use the photos as a reference."
+ />
+ <WayRow
+ on={way === 'train'} onPick={() => setWay('train')} id="train" title="Train a model"
+ line={`Best likeness in new pictures. Needs at least ${MIN_TRAIN_IMAGES} photos, 10 or more work better. It takes a while, on this computer or for credits on LU Cloud. The next page sets it up.`}
+ />
+ </div>
+ <h2 className="hub-dim mb-1 mt-6 hub-fs-10">After saving</h2>
+ <div className="hub-line flex min-h-10 flex-wrap items-center gap-x-4 gap-y-1 border-y hub-fs-13">
+ {HUB_ACTIONS.map((a) => (
+ <span key={a} className="hub-text inline-flex items-center gap-1.5"><span className="hub-muted">{ACTION_ICON[a]}</span>{ACTION_LABEL[a]}</span>
+ ))}
+ <span className="hub-dim ml-auto hub-fs-125">{way === 'train' ? 'ready after the training' : 'ready right away'}</span>
+ </div>
+ </>
+ )}
+ </div>
+ </div>
+
+ <div className="shrink-0 pb-3 pt-2">
+ {(error || added) && (
+ <p role={error ? 'alert' : 'status'} className={cn('pb-2 hub-fs-125', error ? 'text-red-500 dark:text-red-400' : 'hub-muted')} data-hub-new-message>
+ {error ?? `${clean} is in your LoRA folder. ${added?.note}`}
+ </p>
+ )}
+ <div className="hub-bar flex min-h-[52px] items-center gap-3 py-1.5 pl-3.5 pr-2" data-hub-save-bar>
+ {urls[0] && !lora && <img src={urls[0]} alt="" className="h-7 w-7 shrink-0 rounded-full object-cover" />}
+ {clean && <span className="hub-text shrink-0 hub-fs-14 font-medium">{clean}</span>}
+ <span className="hub-dim min-w-0 flex-1 truncate hub-fs-125" data-hub-save-summary>
+ {progress !== null ? `Copying… ${Math.round(progress * 100)} %` : summary}
+ </span>
+ {!lora && way === 'keep' && photos.length > 0 && <span className="hub-dim hub-fs-125 max-[820px]:hidden">You can still train later.</span>}
+ <span className="inline-flex" title={ready || added ? undefined : hint ?? undefined} data-hub-save>
+ <Button variant="primary" size="md" disabled={added ? false : !ready} onClick={() => { if (added) onSaved(added.character); else void save() }}>{button}</Button>
+ </span>
+ </div>
+ </div>
+ </div>
+ )
+}
+
+function WayRow({ on, onPick, id, title, line }: { on: boolean; onPick: () => void; id: string; title: string; line: string }) {
+ return (
+ <button
+ type="button"
+ role="radio"
+ aria-checked={on}
+ onClick={onPick}
+ className="hub-line flex w-full items-start gap-3 border-b py-3 text-left"
+ data-hub-way={id}
+ >
+ <span className={cn('hub-radio mt-0.5 shrink-0', on && 'hub-radio--on')} aria-hidden />
+ <span className="min-w-0">
+ <span className="hub-text block hub-fs-14 font-medium">{title}</span>
+ <span className="hub-dim mt-0.5 block hub-fs-13">{line}</span>
+ </span>
+ </button>
+ )
+}
diff --git a/src/components/create/experimental/hub/HubParts.tsx b/src/components/create/experimental/hub/HubParts.tsx
index 37294a2e..19a5841b 100644
--- a/src/components/create/experimental/hub/HubParts.tsx
+++ b/src/components/create/experimental/hub/HubParts.tsx
@@ -157,9 +157,19 @@ export function UploadLine({ icon, label, accept, onFile, note }: {
)
}
-/** The column every step of the area shares: 660 px, centred. */
+/** A page of the area that is one column (the training): 660 px, centred. */
export const HUB_COLUMN = 'mx-auto w-full max-w-[660px] px-4'
+/** What stands at the top of the bar at the foot: on the stage the switch
+ * between Image, Swap, Motion and Talk. Every bar of the area shows it
+ * (the Composer's, the one click swap's); outside the stage there is none. */
+export const HubBarTopContext = createContext<ReactNode>(null)
+
+export function HubBarTop() {
+ const top = useContext(HubBarTopContext)
+ return top ? <div className="hub-line border-b" data-hub-bar-top>{top}</div> : null
+}
+
/** A switch as a row (one click swap, sketch c2): the name, a grey line what
* it does, the switch at the right. A hairline under it, no box. */
export function HubSwitch({ title, line, on, onChange, disabled, testId }: {
diff --git a/src/components/create/experimental/hub/HubStage.tsx b/src/components/create/experimental/hub/HubStage.tsx
new file mode 100644
index 00000000..f9f24697
--- /dev/null
+++ b/src/components/create/experimental/hub/HubStage.tsx
@@ -0,0 +1,291 @@
+// The stage of the Character area (3.1.0, variant B, David 16.11.2026): the
+// characters as text tabs across the top, the picked one on the left with
+// its name and what can be done with it, its photos on the right, and at the
+// foot the bar with the switch between Image, Swap, Motion and Talk. Only
+// real things stand here: the user's characters and their own pictures. A
+// character without a picture shows its initial, one without photos a line
+// that says so.
+
+import { useEffect, useRef, useState, type ReactNode } from 'react'
+import { Image as ImageIcon, ImagePlus, Mic, PersonStanding, Plus, Replace } from 'lucide-react'
+import { useCreateStore } from '../../../../stores/createStore'
+import {
+ ACTION_LABEL, ACTION_LINE, HUB_JUST_PHOTO, HUB_JUST_PHOTO_LINE, hubInitial,
+ type HubAction, type HubCharacter,
+} from '../../../../lib/create/character-hub'
+import { useCharacterNames, cleanCharacterName, MAX_CHARACTER_LABEL } from '../../../../lib/create/character-names'
+import { deleteSavedCharacter, renameSavedCharacter } from '../../../../lib/saved-characters'
+import { errorText } from '../../../../types/json-guards'
+import { cn } from '../../ui/cn'
+import { sendPhotosToStudio } from '../characterPhotos'
+import { CharacterMore } from '../SpecialIntentControls'
+import { HubAvatar } from './HubParts'
+
+export const ACTION_ICON: Record<HubAction, ReactNode> = {
+ image: <ImageIcon size={14} />,
+ swap: <Replace size={14} />,
+ motion: <PersonStanding size={14} />,
+ talk: <Mic size={14} />,
+}
+
+// ── the tabs ────────────────────────────────────────────────────────────────
+
+export function HubTabs({ list, loading, current, photoOnly, onPick, onPhotoOnly, onNew }: {
+ list: HubCharacter[]
+ loading: boolean
+ /** The key of the character on the stage. */
+ current: string | null
+ /** "Just use a photo" is on the stage. */
+ photoOnly: boolean
+ onPick: (c: HubCharacter) => void
+ onPhotoOnly: () => void
+ onNew: () => void
+}) {
+ return (
+ <div className="hub-tabs hub-line border-b hub-fs-14" data-hub-tabs>
+ <div role="tablist" aria-label="My characters" className="hub-tablist scrollbar-none">
+ {list.map((c) => {
+ const on = c.key === current
+ return (
+ <button
+ key={c.key}
+ type="button"
+ role="tab"
+ aria-selected={on}
+ onClick={() => onPick(c)}
+ // The whole name, and the trigger word of a LoRA character,
+ // where the tab cuts a long name (GitHub discussion #150).
+ title={c.ref ? `${c.name}, trigger word: ${c.ref.triggerWord}` : c.name}
+ className={cn('hub-tab', on ? 'hub-tab--on hub-text font-medium' : 'hub-muted')}
+ data-hub-character={c.key}
+ >
+ <HubAvatar name={c.name} image={c.image} size={20} />
+ <span className="max-w-[140px] truncate">{c.name}</span>
+ </button>
+ )
+ })}
+ {loading && list.length === 0 && <span className="hub-dim self-center hub-fs-13">Loading your characters…</span>}
+ <button
+ type="button"
+ role="tab"
+ aria-selected={photoOnly}
+ onClick={onPhotoOnly}
+ title={HUB_JUST_PHOTO_LINE}
+ className={cn('hub-tab hub-fs-13', photoOnly ? 'hub-tab--on hub-text' : 'hub-dim')}
+ data-hub-photo-only
+ >
+ {HUB_JUST_PHOTO}
+ </button>
+ </div>
+ <button type="button" onClick={onNew} className="hub-acc flex shrink-0 items-center gap-1 hub-fs-13" data-hub-new>
+ <Plus size={14} />New character
+ </button>
+ </div>
+ )
+}
+
+// ── the character on the left ───────────────────────────────────────────────
+
+function Portrait({ c, photo }: { c: HubCharacter | null; photo: string | null }) {
+ const image = c?.image ?? photo
+ if (image) {
+ return <span className="hub-portrait" style={{ backgroundImage: `url("${image}")` }} role="img" aria-label={`Picture of ${c?.name ?? 'the character'}`} />
+ }
+ return (
+ <span className="hub-portrait hub-portrait--none hub-dim" aria-hidden>
+ {c ? <span className="hub-initial">{hubInitial(c.name)}</span> : <ImagePlus size={30} strokeWidth={1.4} />}
+ </span>
+ )
+}
+
+export function HubCard({ c, photo }: { c: HubCharacter | null; photo: string | null }) {
+ // Another character on the stage: an open rename or question is gone.
+ return <Card key={c?.key ?? ''} c={c} photo={photo} />
+}
+
+function Card({ c, photo }: { c: HubCharacter | null; photo: string | null }) {
+ const [renaming, setRenaming] = useState(false)
+ const [asking, setAsking] = useState(false)
+ const [error, setError] = useState<string | null>(null)
+
+ if (!c) {
+ return (
+ <aside className="hub-card" data-hub-card="photo">
+ <Portrait c={null} photo={null} />
+ <h2 className="hub-text hub-fs-20 font-semibold">{HUB_JUST_PHOTO}</h2>
+ <p className="hub-muted mt-1 hub-fs-13">{HUB_JUST_PHOTO_LINE}</p>
+ </aside>
+ )
+ }
+
+ const saved = c.kind === 'saved' ? c.key.slice('saved:'.length) : null
+ const remove = async () => {
+ if (!saved) return
+ try {
+ await deleteSavedCharacter(saved)
+ const st = useCreateStore.getState()
+ st.setHubCharacter(null)
+ st.setHubStep('who')
+ } catch (err) {
+ setError(errorText(err))
+ }
+ }
+
+ return (
+ <aside className="hub-card" data-hub-card={c.key}>
+ <Portrait c={c} photo={photo} />
+ {renaming ? (
+ <RenameField c={c} onDone={() => setRenaming(false)} />
+ ) : (
+ <h2 className="hub-text hub-fs-20 truncate font-semibold" title={c.name} data-hub-card-name>{c.name}</h2>
+ )}
+ <p className="hub-muted mt-1 hub-fs-13">{c.meta}</p>
+ {c.ref && <p className="hub-dim mt-0.5 hub-fs-125">Trigger word: {c.ref.triggerWord}</p>}
+
+ <div className="mt-2.5 flex flex-wrap items-center gap-x-3.5 gap-y-1 hub-fs-125" data-hub-card-links>
+ {!renaming && <button type="button" className="hub-muted hover:underline" onClick={() => { setError(null); setRenaming(true) }} data-hub-rename>Rename</button>}
+ {saved && c.photos && (
+ <button type="button" className="hub-muted hover:underline" onClick={() => { sendPhotosToStudio(c.name, c.photos ?? []); useCreateStore.getState().setHubStep('panel') }} data-hub-train>Train a model</button>
+ )}
+ {saved && !asking && <button type="button" className="hub-dim ml-auto hover:underline" onClick={() => setAsking(true)} data-hub-delete>Delete</button>}
+ {saved && asking && (
+ <span className="hub-muted ml-auto flex items-center gap-2.5" data-hub-delete-ask>
+ Delete {c.name}?
+ <button type="button" className="text-red-500 dark:text-red-400" onClick={() => void remove()} data-hub-delete-yes>Delete</button>
+ <button type="button" className="hub-dim" onClick={() => setAsking(false)}>Keep</button>
+ </span>
+ )}
+ </div>
+ {/* The file of a LoRA character: download, use on this computer, delete. */}
+ {!saved && <div className="-ml-1 mt-1.5"><CharacterMore bare /></div>}
+ {error && <p role="alert" className="mt-1.5 text-red-500 hub-fs-125 dark:text-red-400">{error}</p>}
+ {c.kind === 'local' && (
+ <p className="hub-dim hub-line mt-4 border-t pt-3 hub-fs-125">In Chat, name it: “a picture of {c.ref?.name ?? c.name} at the beach”.</p>
+ )}
+ </aside>
+ )
+}
+
+function RenameField({ c, onDone }: { c: HubCharacter; onDone: () => void }) {
+ const [name, setName] = useState(c.name)
+ const [error, setError] = useState<string | null>(null)
+ const field = useRef<HTMLInputElement>(null)
+ useEffect(() => { field.current?.select() }, [])
+ const save = async () => {
+ const clean = cleanCharacterName(name)
+ if (!clean) { setError('Give the character a name.'); return }
+ try {
+ if (c.kind === 'saved') await renameSavedCharacter(c.key.slice('saved:'.length), clean)
+ else useCharacterNames.getState().rename(c.key, clean)
+ onDone()
+ } catch (err) {
+ setError(errorText(err))
+ }
+ }
+ return (
+ <div data-hub-rename-field>
+ <input
+ ref={field}
+ autoFocus
+ value={name}
+ maxLength={MAX_CHARACTER_LABEL}
+ aria-label={`New name for ${c.name}`}
+ onChange={(e) => setName(e.target.value)}
+ onKeyDown={(e) => { if (e.key === 'Enter') void save(); if (e.key === 'Escape') onDone() }}
+ className="hub-text hub-fs-20 hub-name-field w-full border-b bg-transparent font-semibold outline-none"
+ />
+ <div className="mt-1.5 flex items-center gap-3 hub-fs-125">
+ <button type="button" className="hub-acc" onClick={() => void save()} data-hub-rename-save>Save</button>
+ <button type="button" className="hub-dim" onClick={onDone}>Cancel</button>
+ {c.ref && <span className="hub-dim">The trigger word stays.</span>}
+ </div>
+ {error && <p role="alert" className="mt-1 text-red-500 hub-fs-125 dark:text-red-400">{error}</p>}
+ </div>
+ )
+}
+
+// ── the photos on the right ─────────────────────────────────────────────────
+
+/** The character's own photos. "Made with …" (its results) comes with 3.1.1;
+ * until then this is what there is to see of it. */
+export function HubPhotos({ c, photos, loading }: { c: HubCharacter | null; photos: string[]; loading: boolean }) {
+ if (!c) {
+ return (
+ <div data-hub-step="what" data-hub-photos-of="">
+ <p className="hub-dim hub-line border-b py-3 hub-fs-13">Pick Swap or Motion below and add the photo there.</p>
+ </div>
+ )
+ }
+ const none = c.kind === 'cloud'
+ ? `${c.name} has no picture yet.`
+ : c.kind === 'local'
+ ? `The photos ${c.name} was trained on are not on this computer.`
+ : `${c.name} has no photos.`
+ return (
+ <div data-hub-step="what" data-hub-photos-of={c.key}>
+ <div className="mb-2 flex items-baseline justify-between">
+ <h2 className="hub-dim hub-fs-10">Photos of {c.name}</h2>
+ {photos.length > 1 && <span className="hub-dim hub-fs-12 tabular-nums">{photos.length}</span>}
+ </div>
+ {photos.length > 0 ? (
+ <ul className="hub-photos" aria-label={`Photos of ${c.name}`}>
+ {photos.map((src, i) => <li key={i}><img src={src} alt="" loading="lazy" /></li>)}
+ </ul>
+ ) : (
+ <p className="hub-dim hub-line border-y py-3 hub-fs-13" data-hub-no-photos>{loading ? 'Loading the photos…' : none}</p>
+ )}
+ </div>
+ )
+}
+
+// ── the switch in the bar ───────────────────────────────────────────────────
+
+export interface HubActionState {
+ action: HubAction
+ /** The name of the tab the action stands for ("Swap Character"), read out
+ * as it was on the old pill. */
+ label: string
+ /** Opens the Cloud sheet instead of the action. */
+ locked: boolean
+ /** The grey words on the right while this action is picked. */
+ meta: string
+}
+
+/** Image, Swap, Motion, Talk: the top line of the bar at the foot. */
+export function HubActions({ actions, active, name, onPick, right }: {
+ actions: HubActionState[]
+ active: HubAction | null
+ name: string | null
+ onPick: (a: HubAction) => void
+ /** What stands before the price on the right: the clip of the panel. */
+ right?: ReactNode
+}) {
+ const on = actions.find((a) => a.action === active) ?? null
+ const line = on
+ ? ACTION_LINE[on.action].replace('your character', name ?? 'your character').replace('Your character', name ?? 'Your character')
+ : name ? `What should ${name} do?` : 'What should your character do?'
+ return (
+ <div className="flex min-h-[42px] items-center gap-3 py-1 pl-1.5 pr-3" data-hub-actions>
+ <div role="radiogroup" aria-label="Character action" className="hub-act">
+ {actions.map((a) => (
+ <button
+ key={a.action}
+ type="button"
+ role="radio"
+ aria-checked={a.action === active}
+ aria-label={a.locked ? `${a.label}, runs on LU Cloud` : a.label}
+ title={a.locked ? `${a.label}, runs on LU Cloud` : ACTION_LINE[a.action]}
+ onClick={() => onPick(a.action)}
+ className={cn('hub-act-item hub-fs-13', a.action === active && 'hub-act-item--on', a.locked && 'opacity-60')}
+ data-hub-action={a.action}
+ >
+ {ACTION_ICON[a.action]}{ACTION_LABEL[a.action]}
+ </button>
+ ))}
+ </div>
+ <span className="hub-dim min-w-0 flex-1 truncate hub-fs-125 max-[640px]:hidden" data-hub-action-line>{line}</span>
+ {right}
+ {on?.meta && <span className="hub-dim shrink-0 whitespace-nowrap hub-fs-125 tabular-nums max-[520px]:hidden" data-hub-action-meta>{on.meta}</span>}
+ </div>
+ )
+}
diff --git a/src/components/create/experimental/hub/SwapOneClick.tsx b/src/components/create/experimental/hub/SwapOneClick.tsx
index 528c7a8f..68419024 100644
--- a/src/components/create/experimental/hub/SwapOneClick.tsx
+++ b/src/components/create/experimental/hub/SwapOneClick.tsx
@@ -18,7 +18,7 @@ import { mediaSeconds, useStudioPrice } from '../useStudioPrice'
import { Button } from '../../ui/Button'
import { Select, type SelectOption } from '../../ui/Select'
import { cn } from '../../ui/cn'
-import { HUB_COLUMN, HubSwitch, MoreOptions } from './HubParts'
+import { HubBarTop, HubSwitch, MoreOptions } from './HubParts'
import { SwapLength, useSwapBar } from './SwapBarParts'
import { adoptInput, cancelJob, pollJob, submitCloudJob, uploadInput, type CloudJob } from '../../../../api/cloud/jobs'
import { galleryItemFromJob } from '../../../../lib/render/cloud-jobs'
@@ -320,16 +320,14 @@ export function SwapOneClick({ onChangeCharacter, onOpenAdvanced }: {
)
}
+// The two parts the stage places (index.css, .hub-stage): the body beside
+// the character, the bar across the foot.
function Body({ children }: { children: ReactNode }) {
- return (
- <div className="min-h-0 flex-1 overflow-y-auto scrollbar-thin">
- <div className={cn(HUB_COLUMN, 'pb-4')}>{children}</div>
- </div>
- )
+ return <div className="hub-body scrollbar-thin pb-4">{children}</div>
}
function Foot({ children }: { children: ReactNode }) {
- return <div className={cn(HUB_COLUMN, 'shrink-0 pb-3 pt-2')}>{children}</div>
+ return <div className="hub-foot">{children}</div>
}
/** "First frame ▾" and "Video ▾" under More options (c3). */
@@ -389,6 +387,7 @@ function SwapBar({ narrow, summary, length, seconds, total, parts, ready, hint,
if (narrow) {
return (
<div className="hub-bar rounded-2xl" data-swap-bar="narrow">
+ <HubBarTop />
{open && (
<div className="hub-line flex flex-wrap items-center gap-2 border-b px-2.5 py-2" data-hub-bar-options>
{length}
@@ -408,6 +407,7 @@ function SwapBar({ narrow, summary, length, seconds, total, parts, ready, hint,
}
return (
<div className="hub-bar" data-swap-bar="wide">
+ <HubBarTop />
<div className="flex min-h-[45px] items-center gap-1.5 py-[5px] pl-2.5 pr-1.5">
<span className="hub-muted whitespace-nowrap hub-fs-13" data-swap-summary>{summary}</span>
{length}
@@ -498,6 +498,7 @@ function SwapReview({ chain, originalUrl, deps, summary, narrow }: {
</Body>
<Foot>
<div className={cn('hub-bar', narrow && 'rounded-2xl')} data-swap-bar="review">
+ <HubBarTop />
<input
type="text"
value={extra}
diff --git a/src/components/create/experimental/hub/hubCharacters.ts b/src/components/create/experimental/hub/hubCharacters.ts
index 5efa3a63..e7ac0491 100644
--- a/src/components/create/experimental/hub/hubCharacters.ts
+++ b/src/components/create/experimental/hub/hubCharacters.ts
@@ -9,7 +9,7 @@
// LoRA, Swap puts its picture on person 1, Motion and Talk start from its
// picture. Nothing here books or renders anything.
-import { useEffect, useState } from 'react'
+import { useEffect, useMemo, useState } from 'react'
import { useCreateStore } from '../../../../stores/createStore'
import { listLoras } from '../../../../api/cloud/loras'
import { listLocalCharacters, characterLoraFile } from '../../../../lib/characters'
@@ -21,6 +21,8 @@ import {
type HubAction, type HubCharacter,
} from '../../../../lib/create/character-hub'
import type { ImageRef } from '../../../../lib/image-ref'
+import { useCharacterNames, withCharacterNames } from '../../../../lib/create/character-names'
+import { trainingPhotos } from '../../../../lib/character-photos'
import { useSavedCharacters } from '../SavedCharacters'
import { loadImageRef } from '../loadImage'
import { loadPhotosAsReferences } from '../characterPhotos'
@@ -60,12 +62,48 @@ export function useHubCharacters(): HubCharacterList {
return () => { live = false }
}, [tauri, version])
+ const names = useCharacterNames((s) => s.names)
// A source that is not asked here (cloud off, no Tauri) is an empty list;
- // one that is asked shows its last answer until the new one is in.
- const cloud = backend !== 'cloud' ? [] : cloudRows?.list ?? null
- const local = !tauri ? [] : localRows?.list ?? null
- const photoSets = saved.map((c) => hubFromSaved(c, c.thumb))
- return { list: mergeHubCharacters(cloud ?? [], local ?? [], photoSets), loading: cloud === null || local === null }
+ // one that is asked shows its last answer until the new one is in. The
+ // user's own names for LoRA characters (Rename) go in here, so every place
+ // that reads the list shows them.
+ const list = useMemo(() => {
+ const cloud = backend !== 'cloud' ? [] : cloudRows?.list ?? []
+ const local = !tauri ? [] : localRows?.list ?? []
+ return withCharacterNames(mergeHubCharacters(cloud, local, saved.map((c) => hubFromSaved(c, c.thumb))), names)
+ }, [backend, cloudRows, tauri, localRows, saved, names])
+ return { list, loading: (backend === 'cloud' && cloudRows === null) || (tauri && localRows === null) }
+}
+
+/** The most photos the stage shows of one character. */
+export const STAGE_PHOTOS = 30
+
+/**
+ * The photos of a character, for the stage: the saved photos of a photo
+ * character, the training photos a local character still has on this
+ * machine, or the one picture a cloud character brings (its base look).
+ * Addresses made here are given back when the character changes.
+ */
+export function useCharacterPhotos(c: HubCharacter | null): { photos: string[]; loading: boolean } {
+ const [asked, setAsked] = useState<{ key: string; photos: string[] } | null>(null)
+ const key = c?.key ?? ''
+ const blobs = c?.photos
+ const ref = c?.kind === 'local' ? c.ref : undefined
+ const image = c?.image ?? null
+ const own = useMemo(() => (blobs?.length ? blobs.slice(0, STAGE_PHOTOS).map((b) => URL.createObjectURL(b)) : null), [blobs])
+ useEffect(() => () => { for (const u of own ?? []) URL.revokeObjectURL(u) }, [own])
+ useEffect(() => {
+ let live = true
+ if (!key || own || !ref) return
+ trainingPhotos(ref, STAGE_PHOTOS)
+ .then((photos) => { if (live) setAsked({ key, photos }) })
+ .catch(() => { if (live) setAsked({ key, photos: [] }) })
+ return () => { live = false }
+ }, [key, own, ref])
+ if (!key) return { photos: [], loading: false }
+ if (own) return { photos: own, loading: false }
+ if (ref) return { photos: asked?.key === key ? asked.photos : [], loading: asked?.key !== key }
+ return { photos: image ? [image] : [], loading: false }
}
/** Which character a loaded picture came from, by its address, so a line
diff --git a/src/index.css b/src/index.css
index f5925339..c9d71624 100644
--- a/src/index.css
+++ b/src/index.css
@@ -3194,5 +3194,100 @@ input[type="range"].neuron-range:disabled { cursor: not-allowed; opacity: 0.5; }
.hub-fs-10 { font-size: calc(10px / var(--ui-scale, 1.15)); line-height: 1.3; letter-spacing: 0.08em; text-transform: uppercase; font-weight: 600; }
/* The segments of the area (Sound, Resolution) take the sketch's 12 px. */
.hub-seg { --text-control: calc(12px / var(--ui-scale, 1.15)); }
+.hub-fs-20 { font-size: calc(20px / var(--ui-scale, 1.15)); line-height: 1.2; letter-spacing: -0.01em; }
+
+/* The stage (variant B, David 16.11.2026, uebergabe-310/character-design):
+ the tabs across the top, the character on the left, its photos or the
+ panel of an action on the right, the bar across the foot. A grid, so the
+ parts of the one click swap (its body and its bar are siblings) land in
+ the same places as the Composer's. Nothing here moves by itself. */
+.lu-hub .hub-stage {
+ display: grid;
+ grid-template-columns: minmax(0, 210px) minmax(0, 1fr);
+ grid-template-rows: auto minmax(0, 1fr) auto;
+ column-gap: 28px;
+ flex: 1 1 0%;
+ min-height: 0;
+}
+.lu-hub .hub-tabs { grid-column: 1 / -1; grid-row: 1; display: flex; align-items: center; gap: 16px; min-height: 38px; }
+.lu-hub .hub-tablist { display: flex; align-items: stretch; align-self: stretch; gap: 20px; flex: 1 1 0%; min-width: 0; overflow-x: auto; }
+.lu-hub .hub-tab { display: inline-flex; align-items: center; gap: 7px; flex: none; white-space: nowrap; margin-bottom: -1px; border-bottom: 1.5px solid transparent; }
+.lu-hub .hub-tab--on { border-bottom-color: var(--hub-text); }
+.lu-hub .hub-card { grid-column: 1; grid-row: 2; min-width: 0; min-height: 0; overflow-y: auto; padding: 16px 0; }
+.lu-hub .hub-body { grid-column: 2; grid-row: 2; min-width: 0; min-height: 0; overflow-y: auto; }
+.lu-hub .hub-foot { grid-column: 1 / -1; grid-row: 3; min-width: 0; padding: 8px 0 12px; }
+.lu-hub .hub-portrait { display: block; aspect-ratio: 4 / 5; margin-bottom: 12px; border-radius: 8px; background-size: cover; background-position: 50% 20%; }
+.lu-hub .hub-portrait--none { display: grid; place-items: center; background: var(--hub-fill); }
+.lu-hub .hub-initial { font-size: calc(52px / var(--ui-scale, 1.15)); font-weight: 600; line-height: 1; }
+.lu-hub .hub-photos { display: grid; grid-template-columns: repeat(auto-fill, minmax(104px, 1fr)); gap: 8px; }
+.lu-hub .hub-photos img { display: block; width: 100%; aspect-ratio: 1; object-fit: cover; border-radius: 6px; }
+/* The switch between the actions: text with one quiet ground for the one
+ that is picked, no frame of its own inside the bar. */
+.lu-hub .hub-act { display: inline-flex; gap: 2px; }
+.lu-hub .hub-act-item { display: inline-flex; align-items: center; gap: 6px; height: 28px; padding: 0 10px; border: 1px solid transparent; border-radius: 6px; color: var(--hub-muted); white-space: nowrap; }
+.lu-hub .hub-act-item--on { border-color: var(--hub-edge); background: var(--hub-hov); color: var(--hub-text); font-weight: 500; }
+@media (max-width: 520px) {
+ .lu-hub .hub-act-item { padding: 0 8px; }
+ .lu-hub .hub-act-item svg { display: none; }
+}
+@media (max-width: 700px) {
+ .lu-hub .hub-stage { grid-template-columns: minmax(0, 1fr); }
+ .lu-hub .hub-card { display: none; }
+ .lu-hub .hub-body { grid-column: 1; }
+}
+
+/* The pages of the area: "New character" and the training. */
+.lu-hub .hub-page { display: flex; flex-direction: column; flex: 1 1 0%; min-height: 0; }
+.lu-hub .hub-new { display: grid; grid-template-columns: minmax(0, 1.3fr) minmax(0, 1fr); align-content: start; gap: 48px; flex: 1 1 0%; min-height: 0; overflow-y: auto; padding: 20px 0 16px; }
+@media (max-width: 760px) {
+ .lu-hub .hub-new { grid-template-columns: minmax(0, 1fr); gap: 24px; }
+}
+.lu-hub .hub-drop { border: 1px dashed color-mix(in srgb, var(--hub-dim) 60%, transparent); border-radius: 8px; }
+.lu-hub .hub-drop--over { border-color: var(--hub-acc); background: var(--hub-fill); }
+.lu-hub .hub-thumb { display: block; width: 84px; height: 84px; object-fit: cover; border-radius: 6px; }
+.lu-hub .hub-name-field { border-color: var(--hub-edge); }
+.lu-hub input.hub-name-field:not(.hub-fs-20) { font-size: calc(16px / var(--ui-scale, 1.15)); line-height: 1.4; }
+.lu-hub .hub-path { font-family: ui-monospace, 'JetBrains Mono', 'SF Mono', Menlo, monospace; font-size: calc(12px / var(--ui-scale, 1.15)); }
+.lu-hub .hub-radio { position: relative; width: 15px; height: 15px; border: 1.5px solid var(--hub-dim); border-radius: 50%; }
+.lu-hub .hub-radio--on { border-color: var(--hub-acc); }
+.lu-hub .hub-radio--on::after { content: ''; position: absolute; inset: 3px; border-radius: 50%; background: var(--hub-acc); }
+
+/* No character yet: the steps beside the four examples, centred on each
+ other. The four small drawings are the only pictures of the area that
+ move; with reduced motion they stand still. */
+.lu-hub .hub-empty { display: flex; align-items: center; gap: 56px; flex: 1 1 0%; min-height: 0; overflow-y: auto; padding: 16px 8px; }
+@media (max-width: 820px) {
+ .lu-hub .hub-empty { flex-direction: column; align-items: stretch; gap: 28px; }
+}
+.lu-hub .hub-ex { width: 120px; height: 80px; border-radius: 6px; background: var(--hub-fill); }
+.light .lu-hub .hub-ex-mark { filter: invert(1); }
+.lu-hub .hub-ex-a { animation: lu-hub-ex-a 6s ease-in-out infinite; }
+.lu-hub .hub-ex-b { opacity: 0; animation: lu-hub-ex-b 6s ease-in-out infinite; }
+.lu-hub .hub-ex-tilt { animation: lu-hub-ex-tilt 2.4s ease-in-out infinite; }
+.lu-hub .hub-ex-bar { animation: lu-hub-ex-bar 1.4s ease-in-out infinite; }
+@keyframes lu-hub-ex-a {
+ 0%, 40%, 100% { opacity: 1; }
+ 50%, 90% { opacity: 0; }
+}
+@keyframes lu-hub-ex-b {
+ 0%, 40%, 100% { opacity: 0; }
+ 50%, 90% { opacity: 1; }
+}
+@keyframes lu-hub-ex-tilt {
+ 0%, 100% { transform: rotate(-9deg); }
+ 50% { transform: rotate(9deg); }
+}
+@keyframes lu-hub-ex-bar {
+ 0%, 100% { transform: scaleY(0.45); }
+ 50% { transform: scaleY(1); }
+}
+@media (prefers-reduced-motion: reduce) {
+ .lu-hub .hub-ex-a,
+ .lu-hub .hub-ex-b,
+ .lu-hub .hub-ex-tilt,
+ .lu-hub .hub-ex-bar { animation: none; }
+ .lu-hub .hub-ex-a { opacity: 0; }
+ .lu-hub .hub-ex-b { opacity: 1; }
+}
/* The NEW mark on the Character pill: accent on a faint accent ground. */
.lu-new-mark { font-size: 7px; font-weight: 600; letter-spacing: 0.06em; line-height: 1.4; }
diff --git a/src/lib/__tests__/saved-characters.test.ts b/src/lib/__tests__/saved-characters.test.ts
index 0cb93424..d53f048f 100644
--- a/src/lib/__tests__/saved-characters.test.ts
+++ b/src/lib/__tests__/saved-characters.test.ts
@@ -5,7 +5,7 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import {
MAX_CHARACTER_PHOTOS, __resetSavedCharacters, deleteSavedCharacter, listSavedCharacters,
- saveCharacter, subscribeSavedCharacters,
+ renameSavedCharacter, saveCharacter, subscribeSavedCharacters,
} from '../saved-characters'
const photo = (text: string) => new Blob([text], { type: 'image/jpeg' })
@@ -70,3 +70,27 @@ describe('deleting and listening', () => {
expect(heard).toHaveBeenCalledTimes(2)
})
})
+
+describe('renaming (3.1.0)', () => {
+ it('gives the character another name, keeps its photos and tells the listeners', async () => {
+ const { character } = await saveCharacter('Oma', [photo('one'), photo('two')])
+ const heard = vi.fn()
+ const off = subscribeSavedCharacters(heard)
+ const renamed = await renameSavedCharacter(character.id, ' Greta ')
+ off()
+ expect(renamed.name).toBe('Greta')
+ expect(heard).toHaveBeenCalledTimes(1)
+ const list = await listSavedCharacters()
+ expect(list.map((c) => [c.id, c.name, c.photos.length])).toEqual([[character.id, 'Greta', 2]])
+ })
+
+ it('refuses a name another character has, an empty name and a character that is gone', async () => {
+ const a = (await saveCharacter('Oma', [photo('one')])).character
+ await saveCharacter('Opa', [photo('two')])
+ await expect(renameSavedCharacter(a.id, 'opa')).rejects.toThrow('already a character called opa')
+ await expect(renameSavedCharacter(a.id, ' ')).rejects.toThrow('Give the character a name.')
+ await expect(renameSavedCharacter('nope', 'X')).rejects.toThrow('no longer there')
+ // Its own name in another case is a rename, not a clash.
+ expect((await renameSavedCharacter(a.id, 'OMA')).name).toBe('OMA')
+ })
+})
diff --git a/src/lib/create/__tests__/character-lora.test.ts b/src/lib/create/__tests__/character-lora.test.ts
new file mode 100644
index 00000000..c3c30ae5
--- /dev/null
+++ b/src/lib/create/__tests__/character-lora.test.ts
@@ -0,0 +1,74 @@
+// @vitest-environment jsdom
+/**
+ * A dropped LoRA file as a character (3.1.0, "New character"): the file goes
+ * to the backend in pieces, in order, and the last one is marked.
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const io = vi.hoisted(() => ({ calls: [] as { cmd: string; args: Record<string, unknown> }[], answer: (_cmd: string, _args: Record<string, unknown>): unknown => ({}) }))
+vi.mock('../../../api/backend', () => ({
+ isTauri: () => true,
+ backendCall: vi.fn(async (cmd: string, args: Record<string, unknown> = {}) => {
+ io.calls.push({ cmd, args })
+ return io.answer(cmd, args)
+ }),
+}))
+
+import { characterLoraFolder, importCharacterLora, isLoraFile, nameFromLoraFile, shortFolder } from '../character-lora'
+
+beforeEach(() => { io.calls = []; io.answer = () => ({}) })
+
+describe('the file and its folder', () => {
+ it('reads a name out of the file name', () => {
+ expect(nameFromLoraFile('char_mira_vale_zimage.safetensors')).toBe('mira vale')
+ expect(nameFromLoraFile('Mira-v2.safetensors')).toBe('Mira v2')
+ expect(isLoraFile({ name: 'x.SafeTensors' })).toBe(true)
+ expect(isLoraFile({ name: 'x.png' })).toBe(false)
+ })
+
+ it('shortens the home folder, and leaves a Windows path alone', () => {
+ expect(shortFolder('/Users/dave/Library/Application Support/lu-labs/loras')).toBe('~/Library/Application Support/lu-labs/loras')
+ expect(shortFolder('D:\\ComfyUI\\models\\loras')).toBe('D:\\ComfyUI\\models\\loras')
+ })
+
+ it('names the folder, or says that there is none', async () => {
+ io.answer = () => ({ status: 'ok', path: '/x/loras' })
+ expect(await characterLoraFolder()).toEqual({ status: 'ok', path: '/x/loras' })
+ io.answer = () => ({ status: 'no_comfy' })
+ expect(await characterLoraFolder()).toEqual({ status: 'no_comfy' })
+ })
+})
+
+describe('the import', () => {
+ it('sends the pieces in order and marks the last', async () => {
+ const file = new Blob(['abcdefghij'])
+ io.answer = (_cmd, a) => (a.last ? { status: 'saved', file: 'char_Mira_zimage.safetensors', path: '/x/char_Mira_zimage.safetensors', keyFormat: 'same' } : { status: 'more' })
+ const seen: number[] = []
+ const r = await importCharacterLora(file, 'Mira', (got) => seen.push(got), 4)
+ expect(r).toEqual({ status: 'saved', file: 'char_Mira_zimage.safetensors', path: '/x/char_Mira_zimage.safetensors', keyFormat: 'same' })
+ const pieces = io.calls.filter((c) => c.cmd === 'character_lora_import')
+ expect(pieces.map((c) => [c.args.offset, c.args.last])).toEqual([[0, false], [4, false], [8, true]])
+ expect(pieces.map((c) => atob(String(c.args.dataB64))).join('')).toBe('abcdefghij')
+ expect(pieces.every((c) => c.args.name === 'Mira')).toBe(true)
+ expect(seen).toEqual([4, 8, 10])
+ })
+
+ it('a character of that name, or no folder, ends it without an error', async () => {
+ io.answer = () => ({ status: 'exists', file: 'char_Mira_zimage.safetensors' })
+ expect(await importCharacterLora(new Blob(['abc']), 'Mira')).toEqual({ status: 'exists', file: 'char_Mira_zimage.safetensors' })
+ io.answer = () => ({ status: 'no_comfy' })
+ expect(await importCharacterLora(new Blob(['abc']), 'Mira')).toEqual({ status: 'no_comfy' })
+ })
+
+ it('a layout LU does not know comes back as unknown', async () => {
+ io.answer = () => ({ status: 'saved', file: 'f', path: 'p', keyFormat: 'something' })
+ expect(await importCharacterLora(new Blob(['abc']), 'Mira')).toMatchObject({ keyFormat: 'unknown' })
+ })
+
+ it('a failure on the way takes the pieces away again', async () => {
+ io.answer = (cmd) => { if (cmd === 'character_lora_import') throw new Error('This file is not a LoRA LU can read. Nothing was added.'); return {} }
+ await expect(importCharacterLora(new Blob(['abc']), 'Mira')).rejects.toThrow('not a LoRA')
+ expect(io.calls.at(-1)).toEqual({ cmd: 'character_lora_import_cancel', args: { name: 'Mira' } })
+ await expect(importCharacterLora(new Blob([]), 'Mira')).rejects.toThrow('empty')
+ })
+})
diff --git a/src/lib/create/__tests__/character-names.test.ts b/src/lib/create/__tests__/character-names.test.ts
new file mode 100644
index 00000000..d9a09205
--- /dev/null
+++ b/src/lib/create/__tests__/character-names.test.ts
@@ -0,0 +1,31 @@
+/**
+ * Rename in the Character area (3.1.0): the user's own name for a LoRA
+ * character is a label on this computer, by the key of the list.
+ */
+import { describe, it, expect, beforeEach } from 'vitest'
+import { cleanCharacterName, useCharacterNames, withCharacterNames } from '../character-names'
+
+beforeEach(() => useCharacterNames.setState({ names: {} }))
+
+describe('names the user gave', () => {
+ it('a name is trimmed, keeps single spaces and stays under 40 characters', () => {
+ expect(cleanCharacterName(' Mira Vale ')).toBe('Mira Vale')
+ expect(cleanCharacterName('x'.repeat(60))).toHaveLength(40)
+ })
+
+ it('a rename shows in the list, the other characters keep their names', () => {
+ useCharacterNames.getState().rename('cloud:1', ' Greta ')
+ const list = withCharacterNames([{ key: 'cloud:1', name: 'char one' }, { key: 'local:a', name: 'a' }], useCharacterNames.getState().names)
+ expect(list.map((c) => c.name)).toEqual(['Greta', 'a'])
+ })
+
+ it('an empty name and forget both give the character its own name back', () => {
+ const s = useCharacterNames.getState()
+ s.rename('cloud:1', 'Greta')
+ s.rename('cloud:1', ' ')
+ expect(useCharacterNames.getState().names).toEqual({})
+ s.rename('cloud:1', 'Greta')
+ s.forget('cloud:1')
+ expect(useCharacterNames.getState().names).toEqual({})
+ })
+})
diff --git a/src/lib/create/character-hub.ts b/src/lib/create/character-hub.ts
index 06d98e76..34509db0 100644
--- a/src/lib/create/character-hub.ts
+++ b/src/lib/create/character-hub.ts
@@ -62,8 +62,10 @@ export const ACTION_LINE: Record<HubAction, string> = {
talk: 'Your character says your text',
}
-/** Where the area stands: who, what, or the panel of an action. */
-export type HubStep = 'who' | 'what' | 'panel'
+/** Where the area stands: who (no character picked yet), new (the page
+ * that makes one), what (a character on the stage, no action yet), or the
+ * panel of an action. */
+export type HubStep = 'who' | 'new' | 'what' | 'panel'
// Characters from every source.
diff --git a/src/lib/create/character-lora.ts b/src/lib/create/character-lora.ts
new file mode 100644
index 00000000..b3fbf6d7
--- /dev/null
+++ b/src/lib/create/character-lora.ts
@@ -0,0 +1,103 @@
+// A LoRA file of the user's own as a character (3.1.0, "New character").
+//
+// Where this machine keeps character files, the button that opens that
+// folder, and the way a dropped `.safetensors` gets there: the WebView hands
+// a dropped file over as bytes, not as a path, so it goes to the backend in
+// pieces (src-tauri commands/character_files.rs, take_piece) and gets its
+// name `char_<name>_zimage.safetensors` once its header reads as a LoRA.
+
+import { backendCall, isTauri } from '../../api/backend'
+
+/** One piece, before base64. Well under the backend's limit of 16 MB. */
+export const LORA_PIECE_BYTES = 4 * 1024 * 1024
+
+export type LoraFolder = { status: 'ok'; path: string } | { status: 'no_comfy' }
+
+/** The LoRA folder of this machine, or null outside the desktop app. */
+export async function characterLoraFolder(): Promise<LoraFolder | null> {
+ if (!isTauri()) return null
+ try {
+ const r = await backendCall<{ status?: string; path?: string }>('character_lora_folder')
+ return r?.status === 'ok' && r.path ? { status: 'ok', path: r.path } : { status: 'no_comfy' }
+ } catch {
+ return null
+ }
+}
+
+/** Shows that folder in the file manager. It is made first if it is not there. */
+export async function openCharacterLoraFolder(): Promise<void> {
+ await backendCall('character_lora_folder_open')
+}
+
+/** A home folder shortened to `~`, as a path reads in a sentence. */
+export function shortFolder(path: string): string {
+ return path.replace(/^\/Users\/[^/]+\//, '~/').replace(/^\/home\/[^/]+\//, '~/')
+}
+
+export function isLoraFile(file: { name: string }): boolean {
+ return file.name.toLowerCase().endsWith('.safetensors')
+}
+
+/** The name a dropped file suggests: `char_mira_zimage.safetensors` and
+ * `mira_v2.safetensors` both read "mira…". */
+export function nameFromLoraFile(fileName: string): string {
+ const base = fileName.replace(/\.safetensors$/i, '')
+ const m = /^char_(.+)_zimage$/i.exec(base)
+ return (m ? m[1] : base).replace(/[_-]+/g, ' ').trim().slice(0, 40)
+}
+
+export type LoraImport =
+ | { status: 'saved'; file: string; path: string; keyFormat: 'same' | 'known' | 'unknown' }
+ | { status: 'exists'; file: string }
+ | { status: 'no_comfy' }
+
+function pieceBase64(piece: Blob): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader()
+ reader.onerror = () => reject(new Error('The file could not be read.'))
+ reader.onload = () => {
+ const url = String(reader.result)
+ resolve(url.slice(url.indexOf(',') + 1))
+ }
+ reader.readAsDataURL(piece)
+ })
+}
+
+/**
+ * Puts a dropped LoRA file into the LoRA folder under the character's name.
+ * `onProgress` hears the bytes that are there. A failure on the way removes
+ * what was written; a character of that name is never replaced.
+ */
+export async function importCharacterLora(
+ file: Blob,
+ name: string,
+ onProgress?: (received: number, total: number) => void,
+ pieceBytes: number = LORA_PIECE_BYTES,
+): Promise<LoraImport> {
+ const total = file.size
+ if (total === 0) throw new Error('This file is empty.')
+ let offset = 0
+ try {
+ for (;;) {
+ const piece = file.slice(offset, offset + pieceBytes)
+ const last = offset + piece.size >= total
+ const r = await backendCall<{ status: string; file?: string; path?: string; keyFormat?: string; received?: number }>(
+ 'character_lora_import',
+ { name, offset, dataB64: await pieceBase64(piece), last },
+ )
+ if (r.status === 'no_comfy') return { status: 'no_comfy' }
+ if (r.status === 'exists') return { status: 'exists', file: r.file ?? '' }
+ if (r.status === 'saved') {
+ onProgress?.(total, total)
+ const keyFormat = r.keyFormat === 'same' || r.keyFormat === 'known' ? r.keyFormat : 'unknown'
+ return { status: 'saved', file: r.file ?? '', path: r.path ?? '', keyFormat }
+ }
+ offset += piece.size
+ onProgress?.(offset, total)
+ if (last) throw new Error('The file did not arrive whole. Nothing was added, drop it again.')
+ }
+ } catch (err) {
+ void backendCall('character_lora_import_cancel', { name }).catch(() => undefined)
+ throw err
+ }
+}
diff --git a/src/lib/create/character-names.ts b/src/lib/create/character-names.ts
new file mode 100644
index 00000000..1959d59b
--- /dev/null
+++ b/src/lib/create/character-names.ts
@@ -0,0 +1,47 @@
+// Names the user gave characters on this computer (3.1.0, Rename in the
+// Character area). A photo character is renamed where it is stored
+// (lib/saved-characters). A LoRA character cannot be: the cloud has no rename
+// call, and a local file is named after its trigger word, which the training
+// learned. So the new name is a label here, by the key of the list
+// (lib/create/character-hub HubCharacter.key); the trigger word stays.
+
+import { create } from 'zustand'
+import { persist } from 'zustand/middleware'
+import { safeJSONStorage } from '../storage-quota'
+
+export const MAX_CHARACTER_LABEL = 40
+
+/** A name as it is kept: trimmed, single spaces, at most 40 characters. */
+export function cleanCharacterName(name: string): string {
+ return name.trim().replace(/\s+/g, ' ').slice(0, MAX_CHARACTER_LABEL)
+}
+
+interface CharacterNames {
+ names: Record<string, string>
+ /** An empty name takes the label away again. */
+ rename: (key: string, name: string) => void
+ forget: (key: string) => void
+}
+
+export const useCharacterNames = create<CharacterNames>()(
+ persist(
+ (set) => ({
+ names: {},
+ rename: (key, name) => set((s) => {
+ const clean = cleanCharacterName(name)
+ const { [key]: _old, ...rest } = s.names
+ return { names: clean ? { ...rest, [key]: clean } : rest }
+ }),
+ forget: (key) => set((s) => {
+ const { [key]: _gone, ...rest } = s.names
+ return { names: rest }
+ }),
+ }),
+ { name: 'lu-character-names', storage: safeJSONStorage() },
+ ),
+)
+
+/** The list with the user's own names put in. */
+export function withCharacterNames<T extends { key: string; name: string }>(list: readonly T[], names: Record<string, string>): T[] {
+ return list.map((c) => (names[c.key] ? { ...c, name: names[c.key] } : c))
+}
diff --git a/src/lib/saved-characters.ts b/src/lib/saved-characters.ts
index 55005b60..c83eff06 100644
--- a/src/lib/saved-characters.ts
+++ b/src/lib/saved-characters.ts
@@ -195,6 +195,27 @@ export async function saveCharacter(name: string, photos: readonly Blob[]): Prom
return { character: revive(row), added: take.length, dropped: photos.length - take.length, merged: !!existing }
}
+/**
+ * Gives a saved character another name. A name another character already
+ * has (upper and lower case count as the same) is refused, so two saves
+ * never fold into one by a rename.
+ */
+export async function renameSavedCharacter(id: string, name: string): Promise<SavedCharacter> {
+ const clean = name.trim().replace(/\s+/g, ' ').slice(0, MAX_CHARACTER_NAME)
+ if (!clean) throw new Error('Give the character a name.')
+ const rows = await readAll()
+ const row = rows.find((r) => r.id === id)
+ if (!row) throw new Error('This character is no longer there.')
+ if (rows.some((r) => r.id !== id && r.name.toLowerCase() === clean.toLowerCase())) {
+ throw new Error(`There is already a character called ${clean}.`)
+ }
+ const next: StoredCharacter = { ...row, name: clean }
+ await write(next)
+ await mirrorAll()
+ changed()
+ return revive(next)
+}
+
export async function deleteSavedCharacter(id: string): Promise<void> {
if (!hasIDB()) memory.delete(id)
else await request('readwrite', (s) => s.delete(id))