Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

feat(create): train a style, concept or pose next to a character

purple0218489ddcc3
diff --git a/e2e/howto/mac-train.spec.ts b/e2e/howto/mac-train.spec.ts
index 396cd306..567d491b 100644
--- a/e2e/howto/mac-train.spec.ts
+++ b/e2e/howto/mac-train.spec.ts
@@ -7,7 +7,7 @@ import { Rec, HOWTO_OUT } from './rec'
// Train new tab is MacTrainControls (isMlxImageHost), no longer a note
// that training does not run on a Mac.
// - SpecialIntentControls.tsx MacTrainControls: without the image engine and
-// Z-Image Turbo it reads "Training a character on this Mac needs Z-Image
+// Z-Image Turbo it reads "Training on this Mac needs Z-Image
// Turbo. Install it in the Model Manager first, then come back here."
// With them: the field "Trigger word, e.g. davechar", the lengths Quick,
// Standard, Thorough (lib/trainer-presets.ts TRAIN_PRESETS: 400, 1200,
diff --git a/e2e/style-train.spec.ts b/e2e/style-train.spec.ts
new file mode 100644
index 00000000..23c8a5d6
--- /dev/null
+++ b/e2e/style-train.spec.ts
@@ -0,0 +1,136 @@
+import { test, expect, type Page } from '@playwright/test'
+import { readFileSync, readdirSync } from 'node:fs'
+import { join } from 'node:path'
+import { tauriMockInit, DEFAULT_ASSISTANT_REPLY, DEFAULT_MODEL_NAME, type TauriMockOptions } from './support/tauri-mock'
+import { routeCloud, seedOnboardingDone, cloudSwitch } from './support/cloud-mock'
+import { mlxCalls } from './support/recorded'
+
+/**
+ * 3.0.9 P8 (Discord, 28.10.2026: "can the built-in trainer do styles,
+ * concepts, poses?"). The Train tab has a Style / concept mode next to
+ * Character: the field is the style's name, the trigger word is a choice,
+ * every picture is captioned by what is in it, the steps are the mode's own,
+ * and the result is `style_<name>_zimage`, switched on in the Image tab's
+ * LoRA stack with its strength, not a character on the shelf.
+ *
+ * LU_P8_PICS: a folder of pictures for the board (the box run's own style
+ * set); without it the board gets one-pixel pictures. LU_SHOTS: where the
+ * screenshots go.
+ */
+
+const ZIMAGE_MAC: TauriMockOptions = {
+ assistantReply: DEFAULT_ASSISTANT_REPLY, modelName: DEFAULT_MODEL_NAME, platform: 'mac',
+ mlx: { engineInstalled: true, mfluxEngineInstalled: true, installedImages: ['z-image-turbo-4bit'], trainPolls: 2, trainAdapterReady: true },
+}
+
+const ONE_PIXEL_PNG = Buffer.from(
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==',
+ 'base64',
+)
+
+function pictures(n: number) {
+ const dir = process.env.LU_P8_PICS
+ if (dir) {
+ return readdirSync(dir).filter((f) => /\.(png|jpe?g|webp)$/i.test(f)).sort().slice(0, n)
+ .map((f) => ({ name: f, mimeType: f.endsWith('.png') ? 'image/png' : 'image/jpeg', buffer: readFileSync(join(dir, f)) }))
+ }
+ return Array.from({ length: n }, (_, i) => ({ name: `picture-${i}.png`, mimeType: 'image/png', buffer: ONE_PIXEL_PNG }))
+}
+
+const shot = async (page: Page, name: string) => {
+ if (!process.env.LU_SHOTS) return
+ // The switches and drawers slide; the picture is of the state they reach.
+ await page.waitForTimeout(800)
+ await page.screenshot({ path: `${process.env.LU_SHOTS}/${name}.png` })
+}
+
+async function openTrainTab(page: Page) {
+ await page.addInitScript(tauriMockInit, ZIMAGE_MAC)
+ await seedOnboardingDone(page)
+ await routeCloud(page, { license: 'active', access: true, mediaLive: true })
+ await page.setViewportSize({ width: 1440, height: 900 })
+ await page.goto('/')
+ await expect(cloudSwitch(page)).toBeVisible({ timeout: 20_000 })
+ await page.getByRole('button', { name: /^Create$/ }).click()
+ await page.getByRole('radio', { name: 'Character Studio', exact: true }).click()
+ await page.getByRole('radio', { name: 'Train new', exact: true }).click()
+}
+
+const calls = async (page: Page, cmd: string) => (await mlxCalls(page)).filter((c) => c.cmd === cmd)
+
+test('mac: a style is trained with content captions and lands switched on in the LoRA stack', async ({ page }) => {
+ await openTrainTab(page)
+ const controls = page.getByTestId('mac-train-controls')
+ await expect(controls).toBeVisible({ timeout: 15_000 })
+ await expect(page.getByRole('radio', { name: 'Character', exact: true })).toBeChecked()
+ await shot(page, 'p8-1-train-tab-character')
+
+ await page.getByRole('radio', { name: 'Style / concept', exact: true }).click()
+ await expect(page.getByTestId('style-mode-note')).toContainText('Teaches a look, a concept or a pose')
+ await expect(page.getByText('Drop 4 to 100 pictures in the style here')).toBeVisible()
+ await expect(page.getByTestId('mac-train-hint')).toContainText('Standard, 1600 steps')
+ await expect(page.getByTestId('mac-train-hint')).toContainText('The style lands in your LoRA folder')
+ await controls.getByPlaceholder('Name, e.g. inkwash').fill('p8lino')
+ await page.getByRole('radio', { name: 'Quick', exact: true }).click()
+ await expect(page.getByTestId('mac-train-hint')).toContainText('Quick, 600 steps')
+
+ const files = pictures(4)
+ await page.locator('input[type="file"][accept="image/*"]').first().setInputFiles(files)
+ await expect(controls).toContainText('4/100 photos')
+ await expect(page.getByTestId('train-caption-help')).toContainText('what is left unnamed is what the LoRA learns')
+ const fields = page.getByPlaceholder('e.g. a fox in a forest')
+ await expect(fields).toHaveCount(4)
+ await fields.nth(0).fill('a fox in a forest')
+ await fields.nth(1).fill('an old lighthouse on a rocky cliff')
+ await expect(page.getByText("Training runs on this Mac and lands the style in the Mac's LoRA folder.")).toBeVisible()
+ await shot(page, 'p8-2-style-mode-ready')
+
+ await page.getByRole('button', { name: /^Create$/ }).last().click()
+ await expect.poll(async () => (await calls(page, 'mlx_train_start')).length, { timeout: 30_000 }).toBe(1)
+ const [clear] = await calls(page, 'mlx_train_clear')
+ expect(clear.raw.set).toBe('style-p8lino')
+ const staged = (await calls(page, 'mlx_train_stage')).map((c) => c.raw.caption)
+ expect(staged).toEqual(['p8lino, a fox in a forest', 'p8lino, an old lighthouse on a rocky cliff', 'p8lino', 'p8lino'])
+ const [start] = await calls(page, 'mlx_train_start')
+ expect(start.raw).toMatchObject({ set: 'style-p8lino', trigger: 'p8lino', steps: 600, kind: 'style' })
+
+ // Through: no shelf, the Image tab with the style switched on.
+ await expect(page.getByRole('radio', { name: 'Image', exact: true })).toBeChecked({ timeout: 20_000 })
+ await expect(page.getByText(/Training failed/)).toHaveCount(0)
+ await page.getByRole('button', { name: 'Advanced settings' }).click()
+ const drawer = page.locator('aside').filter({ hasText: 'Advanced settings' })
+ const expert = drawer.getByRole('button', { name: 'Expert', exact: true })
+ await expect(expert).toBeVisible({ timeout: 15_000 })
+ if (!(await drawer.getByText(/^LoRA stack/).isVisible())) await expert.click()
+ await expect(drawer.getByText('· 1 active')).toBeVisible({ timeout: 15_000 })
+ const strength = drawer.getByRole('textbox', { name: 'Strength of style_p8lino_zimage' })
+ await expect(strength).toHaveValue('0.80')
+ await strength.fill('0.6')
+ await strength.blur()
+ await expect(strength).toHaveValue('0.60')
+ await expect(drawer.getByText(/^LoRA stack/)).toBeVisible()
+ await shot(page, 'p8-3-style-in-lora-stack')
+ await expect(drawer.getByText(/^LoRA stack/)).toBeVisible()
+
+ // The character shelf does not list a style.
+ await page.keyboard.press('Escape')
+ await page.getByRole('radio', { name: 'Character Studio', exact: true }).click()
+ await page.getByRole('radio', { name: 'Use character', exact: true }).click()
+ await expect(page.getByTestId('mac-no-characters')).toBeVisible({ timeout: 15_000 })
+ await expect(page.getByTitle('Trigger word: p8lino')).toHaveCount(0)
+})
+
+test('mac: a style without trigger word is captioned by its content alone', async ({ page }) => {
+ await openTrainTab(page)
+ await page.getByRole('radio', { name: 'Style / concept', exact: true }).click()
+ await page.getByTestId('mac-train-controls').getByPlaceholder('Name, e.g. inkwash').fill('p8lino')
+ await page.getByTestId('style-trigger').uncheck()
+ await expect(page.getByTestId('style-trigger-hint')).toContainText('No trigger word')
+ await page.locator('input[type="file"][accept="image/*"]').first().setInputFiles(pictures(4))
+ await page.getByPlaceholder('e.g. a fox in a forest').nth(0).fill('a fox in a forest')
+ await shot(page, 'p8-4-style-without-trigger')
+ await page.getByRole('button', { name: /^Create$/ }).last().click()
+ await expect.poll(async () => (await calls(page, 'mlx_train_start')).length, { timeout: 30_000 }).toBe(1)
+ const staged = (await calls(page, 'mlx_train_stage')).map((c) => c.raw.caption)
+ expect(staged).toEqual(['a fox in a forest', '', '', ''])
+})
diff --git a/e2e/support/tauri-mock.ts b/e2e/support/tauri-mock.ts
index a2635bd4..c51e1bad 100644
--- a/e2e/support/tauri-mock.ts
+++ b/e2e/support/tauri-mock.ts
@@ -534,7 +534,7 @@ export function tauriMockInit(opts: TauriMockOptions) {
// Character training on the Mac (commands/mlx_train.rs): the photos of the
// set, and the one run.
const trainSets = new Map<string, number>()
- let trainRun: { job: string; polls: number; cancelled: boolean; trigger: string; steps: number } | null = null
+ let trainRun: { job: string; polls: number; cancelled: boolean; trigger: string; steps: number; file: string } | null = null
// One install slot per kind, exactly like the Rust side: null means idle
// (nothing was ever started), a number counts polls since the install began.
const slot: Record<'image' | 'imageEngine' | 'video' | 'videoEngine' | 'music', number | null> = {
@@ -1763,12 +1763,14 @@ export function tauriMockInit(opts: TauriMockOptions) {
return Promise.resolve({ staged: `photo-${trainSets.get(set)}.png` })
}
case 'mlx_train_start': {
- record('__E2E_MLX_CALLS__', { cmd, set: m?.set, trigger: m?.trigger, steps: m?.steps, run: m?.run })
+ record('__E2E_MLX_CALLS__', { cmd, set: m?.set, trigger: m?.trigger, steps: m?.steps, run: m?.run, kind: m?.kind })
const photos = trainSets.get(String(m?.set)) ?? 0
if (photos < 4) return Promise.reject('Add at least 4 photos of your character first.')
const steps = Math.ceil((m?.steps ?? 1200) / photos) * photos
- trainRun = { job: 'e2e-train-1', polls: 0, cancelled: false, trigger: String(m?.trigger), steps }
- return Promise.resolve({ ok: true, jobId: trainRun.job, pid: 4545, base: 'z-image-turbo-4bit', photos, epochs: steps / photos, steps, output: `/tmp/lu-e2e/loras/char_${trainRun.trigger}_zimage.safetensors` })
+ // The file the Rust side names by kind (mlx_train.rs `trained_file`, 3.0.9 P8).
+ const file = `${m?.kind === 'style' ? 'style' : 'char'}_${String(m?.trigger)}_zimage.safetensors`
+ trainRun = { job: 'e2e-train-1', polls: 0, cancelled: false, trigger: String(m?.trigger), steps, file }
+ return Promise.resolve({ ok: true, jobId: trainRun.job, pid: 4545, base: 'z-image-turbo-4bit', photos, epochs: steps / photos, steps, output: `/tmp/lu-e2e/loras/${file}` })
}
case 'mlx_train_progress': {
if (!trainRun) return Promise.resolve({ job: null, status: 'idle', phase: '', percent: 0, step: 0, steps: 0, trigger: null, error: null, output: null, logs: [], running: false })
@@ -1779,14 +1781,14 @@ export function tauriMockInit(opts: TauriMockOptions) {
// The character lands in the LoRA folder, where the Use shelf reads it.
const w = window as unknown as { __E2E_MLX_LORAS__?: Array<{ name: string }> }
w.__E2E_MLX_LORAS__ ??= [...(opts.mlx?.loras ?? [])]
- const file = `char_${trainRun.trigger}_zimage.safetensors`
+ const file = trainRun.file
if (!w.__E2E_MLX_LORAS__.some((l) => l.name === file)) w.__E2E_MLX_LORAS__.push({ name: file })
}
return Promise.resolve({
job: trainRun.job, status, phase: done ? '' : 'Training', percent: done ? 100 : 40,
step: done ? trainRun.steps : Math.round(trainRun.steps / 3), steps: trainRun.steps, trigger: trainRun.trigger,
error: status === 'error' ? opts.mlx?.trainError : status === 'cancelled' ? 'cancelled' : null,
- output: status === 'complete' ? `/tmp/lu-e2e/loras/char_${trainRun.trigger}_zimage.safetensors` : null, logs: [], running: status === 'running',
+ output: status === 'complete' ? `/tmp/lu-e2e/loras/${trainRun.file}` : null, logs: [], running: status === 'running',
})
}
case 'mlx_train_cancel':
diff --git a/src-tauri/src/commands/mlx_train.rs b/src-tauri/src/commands/mlx_train.rs
index af4ac780..a83c6bc8 100644
--- a/src-tauri/src/commands/mlx_train.rs
+++ b/src-tauri/src/commands/mlx_train.rs
@@ -136,10 +136,11 @@ fn base_pack(root: &Path) -> Option<&'static Pack> {
BASES.into_iter().find(|p| mflux::pack_complete(&root.join(p.dir)))
}
-/// The file of a character, as the Windows trainer names it
-/// (`parseLocalCharacterLora` in `src/api/trainer.ts`).
-fn character_file(trigger: &str) -> String {
- format!("char_{trigger}_zimage.safetensors")
+/// The file a run writes: a character's, as the Windows trainer names it
+/// (`parseLocalCharacterLora` in `src/api/trainer.ts`), or since 3.0.9 (P8)
+/// a style's (`TrainKind::output_name`).
+fn trained_file(kind: crate::commands::trainer::TrainKind, name: &str) -> String {
+ format!("{}.safetensors", kind.output_name(name))
}
fn memory_refusal(total_bytes: u64) -> Option<String> {
@@ -599,7 +600,7 @@ fn start(runs: &Runs, mut cmd: Command, pid_file: &Path) -> Result<std::process:
cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
let mut slot = runs.pid();
if slot.is_some() {
- return Err("A character is already being trained on this Mac. Wait for it to finish.".to_string());
+ return Err("A training is already running on this Mac. Wait for it to finish.".to_string());
}
if runs.stopped.swap(false, SeqCst) {
return Err(STOPPED.to_string());
@@ -684,6 +685,9 @@ struct StartArgs {
steps: Option<u32>,
#[serde(default)]
run: Option<String>,
+ /// "style" for a style / concept LoRA; missing is a character.
+ #[serde(default)]
+ kind: Option<String>,
}
pub async fn train_start(state: &AppState, args: &Value) -> CmdResult {
@@ -698,7 +702,7 @@ pub async fn train_start(state: &AppState, args: &Value) -> CmdResult {
return Err(bad_request("The MLX image engine is not set up. Install Z-Image Turbo in the Model Manager first."));
}
let Some(base) = base_pack(&root) else {
- return Err(bad_request("Training a character on a Mac needs Z-Image Turbo. Install it in the Model Manager first."));
+ return Err(bad_request("Training on a Mac needs Z-Image Turbo. Install it in the Model Manager first."));
};
if let Some(refusal) = memory_refusal(crate::commands::system::total_memory_bytes()) {
return Err(bad_request(refusal));
@@ -706,7 +710,7 @@ pub async fn train_start(state: &AppState, args: &Value) -> CmdResult {
let data = set_dir(&root, &a.set).map_err(bad_request)?;
let photos = count_photos(&data);
if photos < MIN_PHOTOS {
- return Err(bad_request(format!("Add at least {MIN_PHOTOS} photos of your character first.")));
+ return Err(bad_request(format!("Add at least {MIN_PHOTOS} photos first.")));
}
// One model in the memory at a time. What is being made holds its model
// until it is through, and is not ended for a training.
@@ -722,7 +726,7 @@ pub async fn train_start(state: &AppState, args: &Value) -> CmdResult {
let job = uuid::Uuid::new_v4().simple().to_string();
let claim = RUNS
.claim(a.run.clone(), &job, &trigger)
- .ok_or_else(|| bad_request("A character is already being trained on this Mac. Wait for it to finish."))?;
+ .ok_or_else(|| bad_request("A training is already running on this Mac. Wait for it to finish."))?;
// What the sidecar holds goes first, as before an image of the engine.
let _ = super::mlx_unload(state, &Value::Null).await;
@@ -730,7 +734,8 @@ pub async fn train_start(state: &AppState, args: &Value) -> CmdResult {
let epochs = epochs_for(steps, photos);
let work = runs_root(&root).join(&job);
let loras = crate::commands::mlx_loras::loras_root();
- let output = loras.join(character_file(&trigger));
+ let kind = crate::commands::trainer::TrainKind::from_arg(a.kind.as_deref());
+ let output = loras.join(trained_file(kind, &trigger));
let config = work.join("config.json");
let job_file = work.join("job.json");
let written = std::fs::create_dir_all(&work)
@@ -867,7 +872,17 @@ mod tests {
#[test]
fn a_character_is_the_file_the_use_shelf_reads() {
// `parseLocalCharacterLora` in src/api/trainer.ts.
- assert_eq!(character_file("luxfox"), "char_luxfox_zimage.safetensors");
+ assert_eq!(trained_file(crate::commands::trainer::TrainKind::Character, "luxfox"), "char_luxfox_zimage.safetensors");
+ }
+
+ #[test]
+ fn a_style_is_a_file_of_its_own_beside_the_characters() {
+ use crate::commands::trainer::TrainKind;
+ // `parseLocalStyleLora` in src/api/trainer.ts; the shelf skips it.
+ assert_eq!(trained_file(TrainKind::Style, "inkwash"), "style_inkwash_zimage.safetensors");
+ let start = &production()[production().find("pub async fn train_start").unwrap()..];
+ assert!(start.contains("TrainKind::from_arg(a.kind.as_deref())"));
+ assert!(start.contains("loras.join(trained_file(kind, &trigger))"));
}
#[test]
diff --git a/src-tauri/src/commands/trainer.rs b/src-tauri/src/commands/trainer.rs
index c42588a7..bd9bea8c 100644
--- a/src-tauri/src/commands/trainer.rs
+++ b/src-tauri/src/commands/trainer.rs
@@ -163,6 +163,49 @@ impl TrainPreset {
}
}
+/// 3.0.9 P8: what a run learns. Both kinds run the same recipe on the same
+/// bases; the frontend writes the captions (`lib/train-kind.ts`), so the
+/// kind only decides the file name, the closing line and whether the set's
+/// photos become a character's reference images.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum TrainKind {
+ Character,
+ Style,
+}
+
+impl TrainKind {
+ /// `"style"` from the frontend; anything else, a missing value from an
+ /// older frontend included, is a character.
+ pub(crate) fn from_arg(arg: Option<&str>) -> Self {
+ match arg.map(str::trim) {
+ Some("style") => TrainKind::Style,
+ _ => TrainKind::Character,
+ }
+ }
+
+ /// The trained file's stem. `char_<name>_zimage` is what the Use shelf
+ /// reads (`parseLocalCharacterLora`); a style must not land there.
+ pub(crate) fn output_name(self, name: &str) -> String {
+ match self {
+ TrainKind::Character => format!("char_{name}_zimage"),
+ TrainKind::Style => format!("style_{name}_zimage"),
+ }
+ }
+
+ pub(crate) fn finished_line(self, file: &str, at: &Path, trigger: &str) -> String {
+ match self {
+ TrainKind::Character => format!(
+ "Character ready: {file} is saved at {} and already in the LoRA picker on the Image tab. Put '{trigger}' in a prompt with the LoRA active.",
+ at.display(),
+ ),
+ TrainKind::Style => format!(
+ "Style ready: {file} is saved at {} and switched on in the LoRA picker on the Image tab. Set its strength there.",
+ at.display(),
+ ),
+ }
+ }
+}
+
/// The floor `vram_verdict` checks against, coupled to the precision that
/// will actually run: a card refused for lacking fp8-recipe memory when fp8
/// storage is in fact on (or the reverse) was praezisionsblind, exactly the
@@ -2854,6 +2897,8 @@ fn training_command(vpy: &str, repo: &Path, step: &TrainStep<'_>) -> Command {
}
#[allow(non_snake_case)]
+// The arguments are the fields of the IPC call (api/trainer.ts), one each.
+#[allow(clippy::too_many_arguments)]
#[tauri::command]
pub fn start_character_training(
app: tauri::AppHandle,
@@ -2863,8 +2908,10 @@ pub fn start_character_training(
triggerWord: String,
steps: Option<u32>,
preset: Option<String>,
+ kind: Option<String>,
) -> Result<serde_json::Value, String> {
let preset = TrainPreset::from_arg(preset.as_deref());
+ let kind = TrainKind::from_arg(kind.as_deref());
{
let mut run = state.trainer_run.lock().unwrap();
if run.status == "running" {
@@ -3167,7 +3214,7 @@ pub fn start_character_training(
}
set_status(&run, "running", &format!("Step 3/4: Training ({steps} steps). This runs for a while, the counter follows every step."));
let steps_s = steps.to_string();
- let out_name = format!("char_{lora_name}_zimage");
+ let out_name = kind.output_name(&lora_name);
let out_dir_s = out_dir.to_string_lossy().to_string();
let mut c3 = training_command(&vpy_s, &repo, &TrainStep {
dit: &dit_s,
@@ -3219,17 +3266,13 @@ pub fn start_character_training(
return;
}
// The set's photos now belong to this file: Edit hands them out as
- // reference images of the character (character_files.rs).
- crate::commands::character_files::write_training_marker(&set_dir, &final_path);
+ // reference images of the character (character_files.rs). A style's
+ // pictures are no one's likeness, so they stay out of that.
+ if kind == TrainKind::Character {
+ crate::commands::character_files::write_training_marker(&set_dir, &final_path);
+ }
- set_status(
- &run,
- "complete",
- &format!(
- "Character ready: {out_name}.safetensors is saved at {} and already in the LoRA picker on the Image tab. Put '{trigger}' in a prompt with the LoRA active.",
- final_path.display(),
- ),
- );
+ set_status(&run, "complete", &kind.finished_line(&format!("{out_name}.safetensors"), &final_path, &trigger));
info!("character training complete");
});
@@ -5955,4 +5998,33 @@ mod captions_and_low_vram_tests {
assert!(run.contains("preset.text_encoder_batch()"));
assert!(run.contains(" preset,\n });"), "the training step gets the preset");
}
+
+ #[test]
+ fn a_style_run_writes_a_style_file_and_an_older_frontend_trains_a_character() {
+ assert_eq!(TrainKind::from_arg(Some("style")), TrainKind::Style);
+ assert_eq!(TrainKind::from_arg(Some(" style ")), TrainKind::Style);
+ assert_eq!(TrainKind::from_arg(Some("character")), TrainKind::Character);
+ assert_eq!(TrainKind::from_arg(Some("pose")), TrainKind::Character);
+ assert_eq!(TrainKind::from_arg(None), TrainKind::Character, "an older frontend sends nothing");
+ assert_eq!(TrainKind::Character.output_name("anna"), "char_anna_zimage");
+ assert_eq!(TrainKind::Style.output_name("inkwash"), "style_inkwash_zimage");
+ // The Use shelf and the Edit references read `char_..._zimage`; a style
+ // must not look like one (character_files.rs `trigger_of`).
+ assert!(crate::commands::character_files::trigger_of("style_inkwash_zimage.safetensors").is_none());
+ let style = TrainKind::Style.finished_line("style_inkwash_zimage.safetensors", Path::new("/l/x"), "inkwash");
+ assert!(style.starts_with("Style ready"), "{style}");
+ assert!(!style.contains("Character"), "{style}");
+ }
+
+ #[test]
+ fn the_run_threads_the_kind_into_the_file_name_and_keeps_a_style_out_of_the_references() {
+ let src = include_str!("trainer.rs");
+ let run = &src[src.find("pub fn start_character_training").expect("start fn")..];
+ let run = &run[..run.find("pub fn character_training_status").expect("end of run")];
+ assert!(run.contains("TrainKind::from_arg(kind.as_deref())"));
+ assert!(run.contains("let out_name = kind.output_name(&lora_name);"));
+ assert!(!run.contains("format!(\"char_{lora_name}_zimage\")"));
+ let marker = run.find("write_training_marker").expect("the marker call");
+ assert!(run[..marker].ends_with("if kind == TrainKind::Character {\n crate::commands::character_files::"), "only a character's photos become references");
+ }
}
diff --git a/src/api/__tests__/mlx-train-caption.test.ts b/src/api/__tests__/mlx-train-caption.test.ts
index ff5c33e5..57115d96 100644
--- a/src/api/__tests__/mlx-train-caption.test.ts
+++ b/src/api/__tests__/mlx-train-caption.test.ts
@@ -59,6 +59,6 @@ describe('die Beschreibung je Foto auf dem Mac', () => {
it('unter Windows und Linux geht das Rezept mit', async () => {
io.mac = false
await startCharacterTraining('luxfox', 'luxfox', 'luxfox', 400, 'low-vram')
- expect(io.backend[0]).toEqual({ cmd: 'start_character_training', args: { setId: 'luxfox', name: 'luxfox', triggerWord: 'luxfox', steps: 400, preset: 'low-vram' } })
+ expect(io.backend[0]).toEqual({ cmd: 'start_character_training', args: { setId: 'luxfox', name: 'luxfox', triggerWord: 'luxfox', steps: 400, preset: 'low-vram', kind: null } })
})
})
diff --git a/src/api/mlx-train.ts b/src/api/mlx-train.ts
index 60156b0f..5ff1f032 100644
--- a/src/api/mlx-train.ts
+++ b/src/api/mlx-train.ts
@@ -54,8 +54,11 @@ export async function stageMacTrainPhoto(set: string, bytes: number[] | Uint8Arr
return invokeMedia<{ staged: string }>('mlx_train_stage', { set, data: bytesToBase64(bytes), caption })
}
-export async function startMacTraining(set: string, trigger: string, steps?: number): Promise<{ status: string }> {
- await invokeMedia('mlx_train_start', { set, trigger, steps: steps ?? null, run: RUN })
+/** `trigger` is the name the file is made of (`char_<trigger>_zimage`, or
+ * `style_<trigger>_zimage` for kind 'style'); the captions carry the trigger
+ * word itself. */
+export async function startMacTraining(set: string, trigger: string, steps?: number, kind?: 'character' | 'style'): Promise<{ status: string }> {
+ await invokeMedia('mlx_train_start', { set, trigger, steps: steps ?? null, run: RUN, kind: kind ?? null })
return { status: 'started' }
}
@@ -86,12 +89,13 @@ export function macTrainRunStatus(p: MacTrainProgress): { status: string; phase:
* arrives with Z-Image Turbo, so one install answers both (GH #194). */
export function macTrainMissing(s: Pick<MacTrainStatus, 'engineReady' | 'base'>): string | null {
if (s.engineReady && s.base) return null
- return 'Training a character on this Mac needs Z-Image Turbo, about 6 GB. The standard setup does not install it.'
+ // Said for a character and a style alike (3.0.9 P8): both train on it.
+ return 'Training on this Mac needs Z-Image Turbo, about 6 GB. The standard setup does not install it.'
}
-export function macTrainNote(stepsNote: string, s: Pick<MacTrainStatus, 'adapterReady' | 'adapterBytes'>): string {
+export function macTrainNote(stepsNote: string, s: Pick<MacTrainStatus, 'adapterReady' | 'adapterBytes'>, kind: 'character' | 'style' = 'character'): string {
const first = s.adapterReady ? '' : ` The first run also downloads a ${Math.round(s.adapterBytes / 1_000_000)} MB training adapter.`
- return `Runs on this Mac and takes a while (${stepsNote}). The local chat model pauses for the run.${first} The character lands in your LoRA folder.`
+ return `Runs on this Mac and takes a while (${stepsNote}). The local chat model pauses for the run.${first} The ${kind === 'style' ? 'style' : 'character'} lands in your LoRA folder.`
}
function bytesToBase64(bytes: number[] | Uint8Array): string {
diff --git a/src/api/trainer.ts b/src/api/trainer.ts
index 8f2b4449..e2284d42 100644
--- a/src/api/trainer.ts
+++ b/src/api/trainer.ts
@@ -6,6 +6,7 @@
import { backendCall } from './backend'
import { customModelDirs } from '../lib/custom-model-dirs'
import type { TrainVramPreset } from '../lib/trainer-presets'
+import type { TrainKind } from '../lib/train-kind'
export interface TrainerInstallState {
status: string
@@ -222,11 +223,14 @@ export async function startCharacterTraining(
/** 3.0.8 D20: 'standard' or 'low-vram'. Unknown or missing means Normal on
* the Rust side (`TrainPreset::from_arg`). */
preset?: TrainVramPreset,
+ /** 3.0.9 P8: 'style' writes `style_<name>_zimage`. Missing means a
+ * character on the Rust side (`TrainKind::from_arg`). */
+ kind?: TrainKind,
): Promise<{ status: string }> {
const mac = await onMac()
// The Mac trainer has one recipe; Normal / Low VRAM is a CUDA matter (D20).
- if (mac) return mac.startMacTraining(setId, triggerWord, steps)
- return backendCall('start_character_training', { setId, name, triggerWord, steps: steps ?? null, preset: preset ?? null })
+ if (mac) return mac.startMacTraining(setId, name, steps, kind)
+ return backendCall('start_character_training', { setId, name, triggerWord, steps: steps ?? null, preset: preset ?? null, kind: kind ?? null })
}
export async function characterTrainingStatus(): Promise<TrainingRunStatus> {
@@ -253,6 +257,15 @@ export function parseLocalCharacterLora(file: string): { file: string; trigger:
return { file: file.trim(), trigger: m[1] }
}
+/** 3.0.9 P8: a local style / concept LoRA, `style_<name>_zimage.safetensors`
+ * (start_character_training with kind 'style'). Not a character: the Use
+ * shelf leaves it out, the LoRA stack offers it as a Z-Image LoRA. */
+export function parseLocalStyleLora(file: string): { file: string; name: string } | null {
+ const m = /(?:^|[\\/])style_(.+)_zimage\.safetensors$/i.exec(file.trim())
+ if (!m) return null
+ return { file: file.trim(), name: m[1] }
+}
+
/** Takes a local character off the disk: its LoRA file goes to the system's
* Trash (the Recycle Bin on Windows), so a delete by mistake can be put back
* from there. The same backend command the Model Manager deletes with, so
diff --git a/src/components/create/experimental/SpecialIntentControls.tsx b/src/components/create/experimental/SpecialIntentControls.tsx
index 21c81a69..f4a9150e 100644
--- a/src/components/create/experimental/SpecialIntentControls.tsx
+++ b/src/components/create/experimental/SpecialIntentControls.tsx
@@ -36,7 +36,8 @@ import { LOCAL_MUSIC_TEXT, SECONDS_LENGTH, musicHowtoLines, musicLength, musicTe
import { MAC_MUSIC_MIN_SECONDS } from '../../../lib/mac-music'
import { createRunModel, studioShownValue } from '../../../lib/render/create-studio'
import { galleryLabelShort } from '../../../lib/render/gallery-label'
-import { TRAIN_PRESETS, TRAIN_VRAM_PRESETS, LOW_VRAM_NOTE, trainStepsNote, trainVramSuggestion, type TrainVramPreset } from '../../../lib/trainer-presets'
+import { TRAIN_VRAM_PRESETS, LOW_VRAM_NOTE, trainStepsNote, trainVramSuggestion, type TrainVramPreset } from '../../../lib/trainer-presets'
+import { STYLE_MODE_NOTE, STYLE_NAME_PLACEHOLDER, STYLE_TRIGGER_HINT_OFF, STYLE_TRIGGER_HINT_ON, STYLE_TRIGGER_LABEL, TRAIN_KINDS, trainPresetsFor, type TrainKind } from '../../../lib/train-kind'
import { useGraphicsCardGb } from '../../../hooks/useGraphicsMemory'
import { trainerPathPlaceholder } from '../../../lib/trainer-path-placeholder'
import { trainerRootHint } from '../../../lib/trainer-root-hint'
@@ -434,12 +435,53 @@ function TrainerReinstallModal({
// Local training readiness + inputs (2.5.8 A5). Three gates render in order:
// trainer env (one-time musubi setup) -> Z-Image base files -> the actual
// trigger/steps inputs. The Rust side is the source of truth for readiness.
+// 3.0.9 P8: Character or Style / concept, above the inputs of both local
+// trainers (CUDA and Mac). The cloud trains characters only, so it has none.
+function TrainKindPicker() {
+ const trainKind = useCreateStore((s) => s.trainKind)
+ const setTrainKind = useCreateStore((s) => s.setTrainKind)
+ const trainStyleTrigger = useCreateStore((s) => s.trainStyleTrigger)
+ const setTrainStyleTrigger = useCreateStore((s) => s.setTrainStyleTrigger)
+ const isGenerating = useCreateStore((s) => s.isGenerating)
+ return (
+ <div className="flex flex-col items-center gap-1" data-testid="train-kind">
+ <Segmented
+ size="sm"
+ layoutId="train-kind"
+ value={trainKind}
+ onChange={(v) => { if (!isGenerating) setTrainKind(v as TrainKind) }}
+ options={TRAIN_KINDS.map((k) => ({ value: k.value, label: k.label }))}
+ />
+ {trainKind === 'style' && (
+ <>
+ <div className="t-label text-gray-500 max-w-[560px] text-center" data-testid="style-mode-note">{STYLE_MODE_NOTE}</div>
+ <label className="t-label text-gray-400 flex items-center gap-1.5 cursor-pointer select-none">
+ <input
+ type="checkbox"
+ checked={trainStyleTrigger}
+ disabled={isGenerating}
+ onChange={(e) => setTrainStyleTrigger(e.target.checked)}
+ data-testid="style-trigger"
+ />
+ {STYLE_TRIGGER_LABEL}
+ </label>
+ <div className="t-label text-gray-600 max-w-[560px] text-center" data-testid="style-trigger-hint">
+ {trainStyleTrigger ? STYLE_TRIGGER_HINT_ON : STYLE_TRIGGER_HINT_OFF}
+ </div>
+ </>
+ )}
+ </div>
+ )
+}
+
function LocalTrainControls() {
const triggerWord = useCreateStore((s) => s.triggerWord)
const setTriggerWord = useCreateStore((s) => s.setTriggerWord)
const trainImages = useCreateStore((s) => s.trainImages)
const trainSteps = useCreateStore((s) => s.trainSteps)
const setTrainSteps = useCreateStore((s) => s.setTrainSteps)
+ const trainKind = useCreateStore((s) => s.trainKind)
+ const presets = trainPresetsFor(trainKind)
const trainVramPreset = useCreateStore((s) => s.trainVramPreset)
const setTrainVramPreset = useCreateStore((s) => s.setTrainVramPreset)
const isGenerating = useCreateStore((s) => s.isGenerating)
@@ -674,11 +716,13 @@ function LocalTrainControls() {
}
return (
<div className="flex flex-col items-center gap-1.5">
+ <TrainKindPicker />
<div className="flex items-center justify-center gap-2 flex-wrap">
<input
value={triggerWord}
onChange={(e) => setTriggerWord(e.target.value)}
- placeholder="Trigger word, e.g. davechar"
+ placeholder={trainKind === 'style' ? STYLE_NAME_PLACEHOLDER : 'Trigger word, e.g. davechar'}
+ aria-label={trainKind === 'style' ? 'Style name' : 'Trigger word'}
className="t-control w-44 px-2.5 h-[var(--control-h-sm)] rounded-md bg-white/[0.03] border border-white/[0.06] text-gray-200 placeholder-gray-600 focus:outline-none focus:border-white/15"
/>
<Segmented
@@ -686,7 +730,7 @@ function LocalTrainControls() {
layoutId="train-steps"
value={String(trainSteps)}
onChange={(v) => setTrainSteps(Number(v))}
- options={TRAIN_PRESETS.map((p) => ({ value: String(p.steps), label: p.label }))}
+ options={presets.map((p) => ({ value: String(p.steps), label: p.label }))}
/>
<Segmented
size="sm"
@@ -705,7 +749,7 @@ function LocalTrainControls() {
3.0.0: `(400 STEPS)` allein sagt nicht, welche der drei Stufen
gerade gilt, und ein Tester hielt Quick deshalb fuer wirkungslos,
obwohl Quick genau diese 400 sind. */}
- <span>Runs on your GPU and takes a while ({trainStepsNote(trainSteps)}). The local chat model pauses for the run. The character lands in your local LoRAs.</span>
+ <span>Runs on your GPU and takes a while ({trainStepsNote(trainSteps, presets)}). The local chat model pauses for the run. The {trainKind === 'style' ? 'style' : 'character'} lands in your local LoRAs.</span>
{/* The run repairs its own environment now (A2), so this is no
longer the only way out of a broken install. It stays because
the button used to render ONLY while the environment counted as
@@ -759,6 +803,8 @@ function MacTrainControls() {
const trainImages = useCreateStore((s) => s.trainImages)
const trainSteps = useCreateStore((s) => s.trainSteps)
const setTrainSteps = useCreateStore((s) => s.setTrainSteps)
+ const trainKind = useCreateStore((s) => s.trainKind)
+ const presets = trainPresetsFor(trainKind)
const isGenerating = useCreateStore((s) => s.isGenerating)
const setView = useUIStore((s) => s.setView)
const setCategoryFilter = useModelStore((s) => s.setCategoryFilter)
@@ -789,6 +835,7 @@ function MacTrainControls() {
const missing = macTrainMissing(status)
return (
<div className="flex flex-col items-center gap-1.5" data-testid="mac-train-controls">
+ <TrainKindPicker />
{missing && (
<div className="flex items-center justify-center gap-2 flex-wrap max-w-[560px]">
<span className="t-label text-gray-400 text-center" data-testid="mac-train-note">{missing}</span>
@@ -801,7 +848,8 @@ function MacTrainControls() {
<input
value={triggerWord}
onChange={(e) => setTriggerWord(e.target.value)}
- placeholder="Trigger word, e.g. davechar"
+ placeholder={trainKind === 'style' ? STYLE_NAME_PLACEHOLDER : 'Trigger word, e.g. davechar'}
+ aria-label={trainKind === 'style' ? 'Style name' : 'Trigger word'}
className="t-control w-44 px-2.5 h-[var(--control-h-sm)] rounded-md bg-white/[0.03] border border-white/[0.06] text-gray-200 placeholder-gray-600 focus:outline-none focus:border-white/15"
/>
<Segmented
@@ -809,7 +857,7 @@ function MacTrainControls() {
layoutId="train-steps"
value={String(trainSteps)}
onChange={(v) => setTrainSteps(Number(v))}
- options={TRAIN_PRESETS.map((p) => ({ value: String(p.steps), label: p.label }))}
+ options={presets.map((p) => ({ value: String(p.steps), label: p.label }))}
/>
<span className="t-label text-gray-600">
{trainImages.length}/{maxTrainImages('local')} photos{trainImages.length < MIN_TRAIN_IMAGES ? `, need at least ${MIN_TRAIN_IMAGES}` : ''}
@@ -817,7 +865,7 @@ function MacTrainControls() {
</div>
{!isGenerating && (
<div className="t-label text-gray-600 text-center max-w-[560px]" data-testid="mac-train-hint">
- {macTrainNote(trainStepsNote(trainSteps), status)}{' '}
+ {macTrainNote(trainStepsNote(trainSteps, presets), status, trainKind)}{' '}
<button
onClick={() => { void openMlxLoraFolder().catch(() => undefined) }}
className="underline underline-offset-2 text-gray-500 hover:text-gray-300"
diff --git a/src/components/create/experimental/Stage.tsx b/src/components/create/experimental/Stage.tsx
index 3b1ef264..075b5222 100644
--- a/src/components/create/experimental/Stage.tsx
+++ b/src/components/create/experimental/Stage.tsx
@@ -39,6 +39,7 @@ import { SavedCharacterChips } from './SavedCharacters'
import { loadPhotosAsReferences, sendPhotosToStudio } from './characterPhotos'
import { MIN_TRAIN_IMAGES, maxTrainImages } from '../../../lib/train-image-cap'
import { TRAIN_CAPTION_HELP, TRAIN_CAPTION_MAX, TRAIN_CAPTION_PLACEHOLDER } from '../../../lib/train-captions'
+import { STYLE_CAPTION_HELP, STYLE_CAPTION_PLACEHOLDER, STYLE_DROP_HINT, STYLE_DROP_TITLE } from '../../../lib/train-kind'
import { describeAvailability, describeTrainPhoto, type DescribeAvailability } from '../../../lib/render/describe-train-photos'
import { MAC_IMAGE_SETUP_SIZE, macVideoSetupCopy } from '../../../lib/mac-setup-sizes'
import { macVideoSetupPlan, type MacVideoSetupPlan } from '../../../api/mlx-starter'
@@ -926,6 +927,12 @@ export function TrainSetBoard() {
// Windows and Linux, mflux on a Mac; both read the photo's .txt caption).
// The cloud trainer takes photos only, so it shows no field it would not use.
const captions = backend !== 'cloud'
+ // 3.0.9 P8: a style / concept set is captioned by what is in each picture,
+ // not by what changes about a person. The cloud trains characters only.
+ const trainKind = useCreateStore((s) => s.trainKind)
+ const style = captions && trainKind === 'style'
+ const captionHelp = style ? STYLE_CAPTION_HELP : TRAIN_CAPTION_HELP
+ const captionPlaceholder = style ? STYLE_CAPTION_PLACEHOLDER : TRAIN_CAPTION_PLACEHOLDER
const [describe, setDescribe] = useState<DescribeAvailability | null>(null)
const [describing, setDescribing] = useState<{ done: number; total: number } | null>(null)
const describeAbort = useRef<AbortController | null>(null)
@@ -949,7 +956,7 @@ export function TrainSetBoard() {
setDescribing({ done: 0, total: todo.length })
for (const [n, img] of todo.entries()) {
if (own.signal.aborted) break
- const text = await describeTrainPhoto(img.blob as Blob, own.signal)
+ const text = await describeTrainPhoto(img.blob as Blob, own.signal, style ? 'style' : 'character')
if (text && !(useCreateStore.getState().trainCaptions[img.name] ?? '').trim()) setTrainCaption(img.name, text)
setDescribing({ done: n + 1, total: todo.length })
}
@@ -988,9 +995,9 @@ export function TrainSetBoard() {
className="flex-1 rounded-xl border-2 border-dashed border-white/10 hover:border-white/25 transition-colors flex flex-col items-center justify-center gap-2 text-gray-500 hover:text-gray-300"
>
<UploadCloud size={28} />
- <div className="t-body">Drop {MIN_TRAIN_IMAGES} to {maxTrainImages(backend)} photos of your character here</div>
+ <div className="t-body">Drop {MIN_TRAIN_IMAGES} to {maxTrainImages(backend)} {style ? STYLE_DROP_TITLE : 'photos of your character here'}</div>
<div className="t-label text-gray-600">
- One person or character, varied angles and lighting works best
+ {style ? STYLE_DROP_HINT : 'One person or character, varied angles and lighting works best'}
</div>
</button>
) : null}
@@ -1003,7 +1010,7 @@ export function TrainSetBoard() {
<>
{captions && (
<div className="flex items-start justify-center gap-2 flex-wrap shrink-0" data-testid="train-caption-help">
- <span className="t-label text-gray-500 max-w-[640px] text-center">{TRAIN_CAPTION_HELP}</span>
+ <span className="t-label text-gray-500 max-w-[640px] text-center">{captionHelp}</span>
{describing ? (
<button
type="button"
@@ -1047,9 +1054,9 @@ export function TrainSetBoard() {
onChange={(e) => setTrainCaption(img.name, e.target.value)}
maxLength={TRAIN_CAPTION_MAX}
disabled={isGenerating}
- placeholder={TRAIN_CAPTION_PLACEHOLDER}
- title={trainCaptions[img.name] || TRAIN_CAPTION_PLACEHOLDER}
- aria-label={`What changes in ${img.name}`}
+ placeholder={captionPlaceholder}
+ title={trainCaptions[img.name] || captionPlaceholder}
+ aria-label={style ? `What is in ${img.name}` : `What changes in ${img.name}`}
className="t-label w-full px-1.5 h-6 rounded-md bg-white/[0.03] border border-white/[0.06] text-gray-300 placeholder-gray-600 focus:outline-none focus:border-white/15 disabled:opacity-60"
/>
)}
@@ -1071,8 +1078,8 @@ export function TrainSetBoard() {
// A Mac trains with its own image engine, on Z-Image Turbo, and
// keeps the character in the Mac's LoRA folder (api/mlx-train).
: isMlxImageHost()
- ? "Training runs on this Mac and lands the character in the Mac's LoRA folder."
- : 'Training runs on your GPU and lands the character in your local LoRAs.'}
+ ? `Training runs on this Mac and lands the ${style ? 'style' : 'character'} in the Mac's LoRA folder.`
+ : `Training runs on your GPU and lands the ${style ? 'style' : 'character'} in your local LoRAs.`}
</div>
</>
)}
diff --git a/src/components/create/experimental/__tests__/beschriftung-und-wenig-vram-oberflaeche.test.tsx b/src/components/create/experimental/__tests__/beschriftung-und-wenig-vram-oberflaeche.test.tsx
index 73a8acc9..7cc8c795 100644
--- a/src/components/create/experimental/__tests__/beschriftung-und-wenig-vram-oberflaeche.test.tsx
+++ b/src/components/create/experimental/__tests__/beschriftung-und-wenig-vram-oberflaeche.test.tsx
@@ -57,8 +57,8 @@ beforeEach(() => {
useCreateStore.setState({
backend: 'local', characterTab: 'train', isGenerating: false,
trainImages: [photo('a.png'), photo('b.png'), photo('c.png'), photo('d.png')],
- trainCaptions: {}, trainVramPreset: 'standard', triggerWord: 'davechar',
- })
+ trainCaptions: {}, trainVramPreset: 'standard', triggerWord: 'davechar', trainKind: 'character', trainSteps: 1200,
+ } as never)
})
describe('die Textzeile unter jedem Foto (D28)', () => {
@@ -106,7 +106,7 @@ describe('die Textzeile unter jedem Foto (D28)', () => {
it('der Lauf gibt jedem Foto seine Zeile und dem Trainer das Rezept', () => {
const src = readFileSync(resolve(__dirname, '../../../../hooks/useCreate.ts'), 'utf8')
expect(src).toContain('buildTrainCaption(trigger, state.trainCaptions[img.name])')
- expect(src).toContain('startCharacterTraining(setId, trigger, trigger, state.trainSteps, state.trainVramPreset)')
+ expect(src).toContain('startCharacterTraining(setId, trigger, trigger, state.trainSteps, state.trainVramPreset, kind)')
expect(src).not.toContain('`${trigger}, a photo of ${trigger}`')
})
})
@@ -154,3 +154,23 @@ describe('Normal / Low VRAM (D20)', () => {
expect(merged.trainCaptions).toEqual({})
})
})
+
+describe('3.0.9 P8: Style / concept', () => {
+ it('fragt je Bild nach dem Inhalt, nicht nach dem, was sich an einer Person aendert', () => {
+ useCreateStore.getState().setTrainKind('style')
+ render(<TrainSetBoard />)
+ expect(screen.getAllByPlaceholderText('e.g. a fox in a forest')).toHaveLength(4)
+ expect(screen.queryAllByPlaceholderText('e.g. red jacket, short hair, beach')).toHaveLength(0)
+ expect(screen.getByTestId('train-caption-help').textContent).toContain('what is left unnamed is what the LoRA learns')
+ expect(screen.getByText(/lands the style in your local LoRAs/)).toBeTruthy()
+ })
+
+ it('der Waehler steht auch im Windows-Trainer, mit den Stufen des Stils', async () => {
+ render(<SpecialControls intent="character" />)
+ fireEvent.click(await screen.findByRole('radio', { name: 'Style / concept' }))
+ expect(screen.getByPlaceholderText('Name, e.g. inkwash')).toBeTruthy()
+ expect(screen.getByText(/Standard, 1600 steps.*The style lands in your local LoRAs/)).toBeTruthy()
+ // Normal / Low VRAM bleibt, der Stil laeuft auf demselben Rezept.
+ expect(screen.getByRole('radio', { name: 'Low VRAM' })).toBeTruthy()
+ })
+})
diff --git a/src/components/create/experimental/__tests__/die-stufe-des-trainers-kommt-an.test.tsx b/src/components/create/experimental/__tests__/die-stufe-des-trainers-kommt-an.test.tsx
index 37e1486e..c8ff2189 100644
--- a/src/components/create/experimental/__tests__/die-stufe-des-trainers-kommt-an.test.tsx
+++ b/src/components/create/experimental/__tests__/die-stufe-des-trainers-kommt-an.test.tsx
@@ -113,7 +113,7 @@ describe('die gewaehlte Stufe steht im Hinweistext', () => {
// der Oberflaeche nicht mehr vor.
expect(trainStepsNote(400)).toBe('Quick, 400 steps')
expect(quelle).not.toContain('({trainSteps} steps)')
- expect(quelle).toContain('({trainStepsNote(trainSteps)})')
+ expect(quelle).toContain('({trainStepsNote(trainSteps, presets)})')
})
it('GEGENPFAD: eine Zahl ohne Stufe nennt keine Stufe', () => {
@@ -125,7 +125,8 @@ describe('die gewaehlte Stufe steht im Hinweistext', () => {
it('der Waehler hat genau die drei Stufen aus der Tabelle', async () => {
render(<SpecialControls intent="character" />)
for (const p of TRAIN_PRESETS) await screen.findByRole('radio', { name: p.label })
- expect(quelle).toContain('TRAIN_PRESETS.map((p) => ({ value: String(p.steps), label: p.label }))')
+ // 3.0.9 P8: die Stufen kommen aus dem Modus, Character sind TRAIN_PRESETS.
+ expect(quelle).toContain('presets.map((p) => ({ value: String(p.steps), label: p.label }))')
})
})
@@ -133,13 +134,13 @@ describe('die gewaehlte Zahl erreicht den Lauf', () => {
it('der Auftrag an den Trainer traegt die Zahl der Stufe', async () => {
await startCharacterTraining('t3char', 't3char', 't3char', 400)
expect(backendCall).toHaveBeenCalledWith('start_character_training', {
- setId: 't3char', name: 't3char', triggerWord: 't3char', steps: 400, preset: null,
+ setId: 't3char', name: 't3char', triggerWord: 't3char', steps: 400, preset: null, kind: null,
})
})
it('der Absendeweg nimmt die Zahl aus dem Store, nicht eine eigene', () => {
const hook = readFileSync(resolve(__dirname, '../../../..', 'hooks/useCreate.ts'), 'utf8')
- expect(hook).toContain('await startCharacterTraining(setId, trigger, trigger, state.trainSteps, state.trainVramPreset)')
+ expect(hook).toContain('await startCharacterTraining(setId, trigger, trigger, state.trainSteps, state.trainVramPreset, kind)')
})
it('und der Trainer legt sie auf die Befehlszeile', () => {
diff --git a/src/components/create/experimental/__tests__/train-kind-oberflaeche.test.tsx b/src/components/create/experimental/__tests__/train-kind-oberflaeche.test.tsx
new file mode 100644
index 00000000..84b88010
--- /dev/null
+++ b/src/components/create/experimental/__tests__/train-kind-oberflaeche.test.tsx
@@ -0,0 +1,73 @@
+// @vitest-environment jsdom
+/**
+ * 3.0.9 P8 (Discord, 28.10.2026): the Train tab offers "Style / concept" next
+ * to "Character". The switch says what the mode is for, renames the field,
+ * brings its own step presets and the trigger word choice, and the photo board
+ * asks for the content of each picture instead of what changes on a person.
+ *
+ * Run: npx vitest run src/components/create/experimental/__tests__/train-kind-oberflaeche.test.tsx
+ */
+import { describe, it, expect, vi, afterEach } from 'vitest'
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+
+vi.mock('../../../../api/mlx-image', async (orig) => ({ ...(await orig<typeof import('../../../../api/mlx-image')>()), isMlxImageHost: () => true }))
+vi.mock('../../../../api/mlx-train', async (orig) => ({
+ ...(await orig<typeof import('../../../../api/mlx-train')>()),
+ getMacTrainStatus: vi.fn(async () => ({ engineReady: true, base: 'z-image-turbo-4bit', adapterReady: true, adapterBytes: 340_194_488, minRamGB: 24, memoryRefusal: null, running: false })),
+}))
+
+import { SpecialControls } from '../SpecialIntentControls'
+import { useCreateStore } from '../../../../stores/createStore'
+import { STYLE_MODE_NOTE, STYLE_TRIGGER_HINT_OFF } from '../../../../lib/train-kind'
+
+function arrange() {
+ useCreateStore.setState({ backend: 'local', error: null, triggerWord: '', trainImages: [], trainKind: 'character', trainSteps: 1200, trainStyleTrigger: true } as never)
+ const s = useCreateStore.getState()
+ s.setIntent('character')
+ s.setCharacterTab('train')
+}
+
+afterEach(() => cleanup())
+
+describe('the Style / concept mode in the Train tab', () => {
+ it('starts as Character, as before', async () => {
+ arrange()
+ render(<SpecialControls intent="character" />)
+ await screen.findByPlaceholderText('Trigger word, e.g. davechar')
+ expect(screen.getByRole('radio', { name: 'Character' }).getAttribute('aria-checked')).toBe('true')
+ expect(screen.queryByTestId('style-mode-note')).toBeNull()
+ expect(screen.getByTestId('mac-train-hint').textContent).toMatch(/Standard, 1200 steps.*The character lands/)
+ })
+
+ it('switching says what it is for, renames the field and takes its own steps', async () => {
+ arrange()
+ render(<SpecialControls intent="character" />)
+ fireEvent.click(await screen.findByRole('radio', { name: 'Style / concept' }))
+ expect(useCreateStore.getState().trainKind).toBe('style')
+ expect(screen.getByTestId('style-mode-note').textContent).toBe(STYLE_MODE_NOTE)
+ expect(screen.getByPlaceholderText('Name, e.g. inkwash')).toBeTruthy()
+ expect(useCreateStore.getState().trainSteps).toBe(1600)
+ expect(screen.getByTestId('mac-train-hint').textContent).toMatch(/Standard, 1600 steps.*The style lands/)
+ fireEvent.click(screen.getByRole('radio', { name: 'Thorough' }))
+ expect(useCreateStore.getState().trainSteps).toBe(3000)
+ })
+
+ it('the trigger word is a choice, and the hint says what leaving it out means', async () => {
+ arrange()
+ useCreateStore.getState().setTrainKind('style')
+ render(<SpecialControls intent="character" />)
+ const box = await screen.findByTestId('style-trigger') as HTMLInputElement
+ expect(box.checked).toBe(true)
+ fireEvent.click(box)
+ expect(useCreateStore.getState().trainStyleTrigger).toBe(false)
+ expect(screen.getByTestId('style-trigger-hint').textContent).toBe(STYLE_TRIGGER_HINT_OFF)
+ })
+
+ it('COUNTER-CHECK: the cloud trains characters only and shows no switch', async () => {
+ arrange()
+ useCreateStore.setState({ backend: 'cloud' } as never)
+ render(<SpecialControls intent="character" />)
+ await screen.findByPlaceholderText('Trigger word, e.g. davechar')
+ expect(screen.queryByTestId('train-kind')).toBeNull()
+ })
+})
diff --git a/src/hooks/__tests__/style-training-run.test.ts b/src/hooks/__tests__/style-training-run.test.ts
new file mode 100644
index 00000000..6c696464
--- /dev/null
+++ b/src/hooks/__tests__/style-training-run.test.ts
@@ -0,0 +1,140 @@
+// @vitest-environment jsdom
+/**
+ * 3.0.9 P8 (Discord, 28.10.2026: "can the trainer do styles, concepts,
+ * poses?"): the Train tab has a Style / concept mode next to Character. The
+ * run is the character run with other captions, its own training set and a
+ * `style_<name>_zimage` file that lands switched on in the Image tab's LoRA
+ * stack, not on the character shelf.
+ *
+ * Runs through the Mac trainer, mocked: nothing is trained.
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import { renderHook } from '@testing-library/react'
+
+vi.mock('../../api/mlx-image', () => ({
+ isMlxImageHost: () => true,
+ isMlxImageModel: (name: string) => name.startsWith('MLX '),
+ mlxStatus: vi.fn(async () => ({ installed: false })),
+ listMlxImageModels: vi.fn(async () => []),
+ buildMlxImageModels: vi.fn(() => []),
+ mergeImageModels: vi.fn((a: unknown[]) => a),
+ mlxModelIdFor: vi.fn(() => 'z-image-turbo-4bit'),
+ generateMlxImageDataUrl: vi.fn(async () => { throw new Error('no image in a training test') }),
+}))
+vi.mock('../../api/mlx-video', async (orig) => ({
+ ...((await orig()) as Record<string, unknown>),
+ getVideoStatus: vi.fn(async () => ({ available: false, installedModels: [] })),
+ listVideoModels: vi.fn(async () => []),
+ buildMlxVideoModels: vi.fn(() => []),
+}))
+vi.mock('../../api/comfyui', async (orig) => ({
+ ...((await orig()) as Record<string, unknown>),
+ checkComfyConnection: vi.fn(async () => false),
+}))
+vi.mock('../../api/vram-handoff', async (orig) => ({
+ ...((await orig()) as Record<string, unknown>),
+ evictChatBackendsForRender: vi.fn(async () => null),
+ restoreChatBackendsAfterRender: vi.fn(),
+}))
+vi.mock('../../api/mlx-loras', async (orig) => ({
+ ...((await orig()) as Record<string, unknown>),
+ listMlxLoras: vi.fn(async () => ({ loras: [], folder: '/loras' })),
+}))
+
+const train = vi.hoisted(() => ({ calls: [] as unknown[][], finish: false }))
+vi.mock('../../api/mlx-train', async (orig) => ({
+ ...((await orig()) as Record<string, unknown>),
+ getMacTrainStatus: vi.fn(async () => ({ engineReady: true, base: 'z-image-turbo-4bit', adapterReady: true, adapterBytes: 1, minRamGB: 24, memoryRefusal: null, running: false })),
+ clearMacTrainSet: vi.fn(async (set: string) => { train.calls.push(['clear', set]) }),
+ stageMacTrainPhoto: vi.fn(async (set: string, _bytes: unknown, caption: string) => { train.calls.push(['stage', set, caption]); return { staged: 'x.png' } }),
+ startMacTraining: vi.fn(async (set: string, trigger: string, steps?: number, kind?: string) => {
+ train.calls.push(['start', set, trigger, steps, kind])
+ if (!train.finish) throw new Error('stopped here')
+ return { status: 'started' }
+ }),
+ getMacTrainProgress: vi.fn(async () => ({
+ job: 'j', status: 'complete', phase: 'done', percent: 100, step: 600, steps: 600,
+ trigger: 'inkwash', error: null, output: '/loras/style_inkwash_zimage.safetensors', logs: [], running: false,
+ })),
+}))
+
+import { useCreate } from '../useCreate'
+import { useCreateStore } from '../../stores/createStore'
+
+const photo = (name: string) => ({ name, url: 'blob:x', blob: new Blob([new Uint8Array([137, 80, 78, 71])], { type: 'image/png' }) })
+const state = () => useCreateStore.getState()
+
+function arrange(kind: 'character' | 'style', trigger = true) {
+ useCreateStore.setState({
+ backend: 'local', isGenerating: false, error: null, gallery: [], selectedLoras: [], loraStrengths: {},
+ imageModelList: [], videoModelList: [], trainKind: 'character', trainSteps: 1200,
+ } as never)
+ const s = state()
+ s.setIntent('character')
+ s.setCharacterTab('train')
+ s.setTrainKind(kind)
+ s.setTrainStyleTrigger(trigger)
+ useCreateStore.setState({ triggerWord: 'inkwash', trainImages: ['a', 'b', 'c', 'd'].map(photo) } as never)
+ s.setTrainCaption('a', 'a fox in a forest')
+}
+
+beforeEach(() => {
+ train.calls.length = 0
+ train.finish = false
+})
+afterEach(() => { vi.useRealTimers() })
+
+describe('a style / concept training run', () => {
+ it('captions by content, keeps its own set and tells the trainer it is a style', async () => {
+ arrange('style')
+ const { result } = renderHook(() => useCreate())
+ await result.current.generate()
+ expect(train.calls[0]).toEqual(['clear', 'style-inkwash'])
+ const stages = train.calls.filter((c) => c[0] === 'stage')
+ expect(stages[0]).toEqual(['stage', 'style-inkwash', 'inkwash, a fox in a forest'])
+ expect(stages[1]).toEqual(['stage', 'style-inkwash', 'inkwash'])
+ for (const c of stages) expect(String(c[2])).not.toContain('a photo of')
+ // The mode brought its own Standard (1600), not the character's 1200.
+ expect(train.calls.at(-1)).toEqual(['start', 'style-inkwash', 'inkwash', 1600, 'style'])
+ })
+
+ it('without a trigger word the caption is only what is in the picture', async () => {
+ arrange('style', false)
+ const { result } = renderHook(() => useCreate())
+ await result.current.generate()
+ const stages = train.calls.filter((c) => c[0] === 'stage')
+ expect(stages[0][2]).toBe('a fox in a forest')
+ expect(stages[1][2]).toBe('')
+ })
+
+ it('a character run is what it was', async () => {
+ arrange('character')
+ const { result } = renderHook(() => useCreate())
+ await result.current.generate()
+ expect(train.calls[0]).toEqual(['clear', 'inkwash'])
+ expect(train.calls[1]).toEqual(['stage', 'inkwash', 'inkwash, a photo of inkwash, a fox in a forest'])
+ expect(train.calls.at(-1)).toEqual(['start', 'inkwash', 'inkwash', 1200, 'character'])
+ })
+
+ it('an empty name names what is missing for a style', async () => {
+ arrange('style')
+ useCreateStore.setState({ triggerWord: '' } as never)
+ const { result } = renderHook(() => useCreate())
+ await result.current.generate()
+ expect(train.calls).toHaveLength(0)
+ expect(state().error).toMatch(/Give the style a name first/)
+ })
+
+ it('a finished style lands switched on in the Image tab, not on the character shelf', async () => {
+ vi.useFakeTimers({ toFake: ['setTimeout'] })
+ arrange('style')
+ train.finish = true
+ const { result } = renderHook(() => useCreate())
+ const run = result.current.generate()
+ await vi.advanceTimersByTimeAsync(4000)
+ await run
+ expect(state().intent()).toBe('image')
+ expect(state().selectedLoras).toEqual([expect.objectContaining({ name: 'style_inkwash_zimage.safetensors' })])
+ expect(state().error).toBeNull()
+ })
+})
diff --git a/src/hooks/useCreate.ts b/src/hooks/useCreate.ts
index 6165052f..0484bde3 100644
--- a/src/hooks/useCreate.ts
+++ b/src/hooks/useCreate.ts
@@ -75,7 +75,7 @@ import { transparentPrompt, wantsTransparent } from '../lib/transparent-image'
import { scenePromptFor } from '../lib/ltx-multishot'
import { intentTakesOptionalPrompt, intentTakesPrompt } from '../components/create/experimental/intents'
import { knownMacMemoryGb } from '../lib/mac-memory'
-import { MIN_TRAIN_IMAGES, tooFewTrainPhotosLine } from '../lib/train-image-cap'
+import { MIN_TRAIN_IMAGES, maxTrainImages, tooFewTrainPhotosLine } from '../lib/train-image-cap'
import { improveKindForIntent, IMPROVING_PROMPT, type ImproveOutcome } from '../lib/render/improve-prompt'
import { elapsedLine } from '../lib/elapsed-line'
import { improvePrompt } from '../lib/render/improve-prompt-run'
@@ -95,6 +95,7 @@ import {
} from '../api/trainer'
import { getMacTrainStatus, macTrainMissing } from '../api/mlx-train'
import { buildTrainCaption } from '../lib/train-captions'
+import { buildStyleCaption, missingNameLine, trainedLine, trainedLoraFile } from '../lib/train-kind'
import { useCreateStore, EDIT_MAX_DENOISE, characterImageRun, deriveIntent, type CreateState } from '../stores/createStore'
import { useWorkflowStore } from '../stores/workflowStore'
import { useSettingsStore } from '../stores/settingsStore'
@@ -554,9 +555,13 @@ export function useCreate() {
// below go there by themselves (api/trainer.ts); what differs is how the
// memory is handed over.
const mac = isMlxImageHost()
+ // 3.0.9 P8: a style / concept run shares the whole path; it differs in
+ // the captions, the file name and where it lands (lib/train-kind.ts).
+ // The field holds the character's trigger word or the style's name.
+ const kind = state.trainKind
const trigger = state.triggerWord.trim()
if (!trigger) {
- setError('Pick a trigger word first, e.g. davechar. It becomes the token that summons your character.')
+ setError(missingNameLine(kind))
return
}
// Blobs are runtime-only — after an app restart the thumbnails would
@@ -567,7 +572,9 @@ export function useCreate() {
? 'Your photos did not survive the app restart. Re-add them, then train.'
// The local trainer's cap (100), the one the drop zone names, not
// the cloud's 30. A Mac trains locally too.
- : tooFewTrainPhotosLine('local'))
+ : kind === 'style'
+ ? `Add at least ${MIN_TRAIN_IMAGES} pictures in the style first (up to ${maxTrainImages('local')}).`
+ : tooFewTrainPhotosLine('local'))
return
}
// GH #194: the Train tab of a Mac without Z-Image Turbo takes a trigger
@@ -592,7 +599,10 @@ export function useCreate() {
// back in the finally below. exclusiveVramMode 'never' skips it.
let trainingEviction: RenderEviction | null = null
try {
- const setId = trigger
+ // A style gets a set of its own: a character's set holds the photos
+ // Edit hands out as that character's references (character_files.rs),
+ // and clearing it for a style of the same name would take them.
+ const setId = kind === 'style' ? `style-${trigger}` : trigger
await clearTrainingSet(setId)
let n = 0
for (const img of staged) {
@@ -600,7 +610,12 @@ export function useCreate() {
// Musubi has no trigger flag, the token must lead every caption. A
// photo's own description (D28: clothes, hair, place) follows it, so
// only what stays the same is learned into the trigger word.
- await stageTrainingImage(setId, img.name, bytes, buildTrainCaption(trigger, state.trainCaptions[img.name]))
+ // A style's line names what is in the picture, with the name in front
+ // only when it is to be a trigger word (P8).
+ const caption = kind === 'style'
+ ? buildStyleCaption(state.trainStyleTrigger ? trigger : '', state.trainCaptions[img.name])
+ : buildTrainCaption(trigger, state.trainCaptions[img.name])
+ await stageTrainingImage(setId, img.name, bytes, caption)
n += 1
setProgress(2 + Math.round((n / staged.length) * 5), `Staging photos (${n}/${staged.length})...`)
}
@@ -619,7 +634,7 @@ export function useCreate() {
// step 27 while the chat model was brought back beside it).
if (trainingCancelRequested.current) return
setProgress(8, 'Starting the training run...')
- await startCharacterTraining(setId, trigger, trigger, state.trainSteps, state.trainVramPreset)
+ await startCharacterTraining(setId, trigger, trigger, state.trainSteps, state.trainVramPreset, kind)
let cancelRounds = 0
for (;;) {
await new Promise((r) => setTimeout(r, 3000))
@@ -648,12 +663,21 @@ export function useCreate() {
setProgress(10, headline || 'Preparing training data...')
}
} else if (s.status === 'complete') {
- setProgress(100, 'Character ready!')
+ setProgress(100, trainedLine(kind))
// The LoRA file just landed in models/loras — drop the node cache so
// the Use shelf and the LoRA picker list it without a restart.
clearNodeCache()
- useCreateStore.getState().bumpCharactersVersion()
- useCreateStore.getState().setCharacterTab('use')
+ const store = useCreateStore.getState()
+ store.bumpCharactersVersion()
+ if (kind === 'style') {
+ // No shelf for a style: it is a LoRA of the Image tab, switched
+ // on there, with its strength slider (P8).
+ const file = trainedLoraFile('style', trigger)
+ store.setIntent('image')
+ if (!useCreateStore.getState().selectedLoras.some((l) => l.name === file)) store.toggleLora(file)
+ } else {
+ store.setCharacterTab('use')
+ }
return
} else if (s.status === 'cancelled') {
return
diff --git a/src/lib/__tests__/train-kind.test.ts b/src/lib/__tests__/train-kind.test.ts
new file mode 100644
index 00000000..eae848f0
--- /dev/null
+++ b/src/lib/__tests__/train-kind.test.ts
@@ -0,0 +1,100 @@
+/**
+ * 3.0.9 P8: the Style / concept mode of the local trainer (lib/train-kind.ts).
+ * Run: npx vitest run src/lib/__tests__/train-kind.test.ts
+ */
+import { describe, it, expect, beforeEach } from 'vitest'
+import fs from 'node:fs'
+import path from 'node:path'
+import {
+ buildStyleCaption, trainedLoraFile, trainPresetsFor, trainStepsDefaultFor, STYLE_TRAIN_PRESETS,
+ STYLE_TRAIN_STEPS_DEFAULT, DESCRIBE_STYLE_SYSTEM, isTrainKind,
+} from '../train-kind'
+import { TRAIN_PRESETS, TRAIN_STEPS_DEFAULT, trainStepsNote } from '../trainer-presets'
+import { knownLora, loraRows } from '../lora-stack'
+import { parseLocalCharacterLora, parseLocalStyleLora } from '../../api/trainer'
+import { useCreateStore } from '../../stores/createStore'
+
+describe('style captions', () => {
+ it('lead with the trigger word and never say "a photo of"', () => {
+ expect(buildStyleCaption('inkwash', 'a fox in a forest')).toBe('inkwash, a fox in a forest')
+ expect(buildStyleCaption('inkwash', '')).toBe('inkwash')
+ expect(buildStyleCaption('inkwash', null)).toBe('inkwash')
+ expect(buildStyleCaption('inkwash', 'a fox')).not.toContain('photo')
+ })
+
+ it('without a trigger word are the description alone, cleaned like a character\'s', () => {
+ expect(buildStyleCaption('', ' a fox,\n in a forest. ')).toBe('a fox, in a forest')
+ expect(buildStyleCaption('', '')).toBe('')
+ })
+})
+
+describe('the style file', () => {
+ it('is named like the Rust trainer names it (sanitize_component, TrainKind::output_name)', () => {
+ expect(trainedLoraFile('style', 'inkwash')).toBe('style_inkwash_zimage.safetensors')
+ expect(trainedLoraFile('character', 'anna')).toBe('char_anna_zimage.safetensors')
+ expect(trainedLoraFile('style', 'ink wash!')).toBe('style_ink_wash_zimage.safetensors')
+ expect(trainedLoraFile('style', '__x__')).toBe('style_x_zimage.safetensors')
+ const rust = fs.readFileSync(path.join(__dirname, '..', '..', '..', 'src-tauri', 'src', 'commands', 'trainer.rs'), 'utf8')
+ expect(rust).toContain('TrainKind::Style => format!("style_{name}_zimage")')
+ expect(rust).toContain(".take(48)")
+ })
+
+ it('is no character, but a Z-Image LoRA the stack offers with its strength', () => {
+ const f = 'style_inkwash_zimage.safetensors'
+ expect(parseLocalCharacterLora(f)).toBeNull()
+ expect(parseLocalStyleLora(f)).toEqual({ file: f, name: 'inkwash' })
+ expect(parseLocalStyleLora('sub/style_a_b_zimage.safetensors')?.name).toBe('a_b')
+ expect(parseLocalStyleLora('char_anna_zimage.safetensors')).toBeNull()
+ expect(knownLora(f)).toEqual({ family: 'zimage', familyLabel: 'Z-Image' })
+ expect(loraRows([f], [], 'zimage')[0]).toMatchObject({ name: f, fits: true })
+ expect(loraRows([f], [], 'flux')[0]).toMatchObject({ fits: false, familyLabel: 'Z-Image' })
+ })
+})
+
+describe('the style presets', () => {
+ it('are three, longer than the character ones, with Standard as default', () => {
+ expect(STYLE_TRAIN_PRESETS.map((p) => p.label)).toEqual(TRAIN_PRESETS.map((p) => p.label))
+ expect(STYLE_TRAIN_PRESETS.map((p) => p.steps)).toEqual([600, 1600, 3000])
+ expect(STYLE_TRAIN_PRESETS.find((p) => p.label === 'Standard')?.steps).toBe(STYLE_TRAIN_STEPS_DEFAULT)
+ expect(trainPresetsFor('character')).toBe(TRAIN_PRESETS)
+ expect(trainStepsDefaultFor('character')).toBe(TRAIN_STEPS_DEFAULT)
+ // Inside the clamp of both trainers (100..4000).
+ for (const p of STYLE_TRAIN_PRESETS) expect(p.steps).toBeGreaterThanOrEqual(100)
+ for (const p of STYLE_TRAIN_PRESETS) expect(p.steps).toBeLessThanOrEqual(4000)
+ })
+
+ it('name their level in the note', () => {
+ expect(trainStepsNote(1600, STYLE_TRAIN_PRESETS)).toBe('Standard, 1600 steps')
+ expect(trainStepsNote(1600)).toBe('1600 steps')
+ })
+})
+
+describe('the mode in the store', () => {
+ beforeEach(() => useCreateStore.setState({ trainKind: 'character', trainSteps: 1200 } as never))
+
+ it('takes the steps of the other mode along when they match none of its presets', () => {
+ const s = useCreateStore.getState()
+ s.setTrainKind('style')
+ expect(useCreateStore.getState().trainSteps).toBe(1600)
+ s.setTrainKind('character')
+ expect(useCreateStore.getState().trainSteps).toBe(1200)
+ useCreateStore.setState({ trainSteps: 400 } as never)
+ s.setTrainKind('style')
+ expect(useCreateStore.getState().trainSteps).toBe(1600)
+ })
+
+ it('turns an unknown mode into a character', () => {
+ useCreateStore.getState().setTrainKind('pose' as never)
+ expect(useCreateStore.getState().trainKind).toBe('character')
+ expect(isTrainKind('style')).toBe(true)
+ expect(isTrainKind('pose')).toBe(false)
+ })
+})
+
+describe('Describe photos in style mode', () => {
+ it('names the content and leaves the style out', () => {
+ expect(DESCRIBE_STYLE_SYSTEM).toMatch(/style LoRA/)
+ expect(DESCRIBE_STYLE_SYSTEM).toMatch(/Never describe the art style/)
+ expect(DESCRIBE_STYLE_SYSTEM).toMatch(/never name an artist/)
+ })
+})
diff --git a/src/lib/lora-stack.ts b/src/lib/lora-stack.ts
index 632cea9a..fe0e746f 100644
--- a/src/lib/lora-stack.ts
+++ b/src/lib/lora-stack.ts
@@ -4,7 +4,7 @@
// One of them was a Z-Image character LoRA riding into the Animate lane.
// This file decides, from the one list ComfyUI reports, which picks a run uses
// and which LoRAs the stack offers for the model that is picked.
-import { parseLocalCharacterLora } from '../api/trainer'
+import { parseLocalCharacterLora, parseLocalStyleLora } from '../api/trainer'
import { getLoraAddonBundles } from '../api/model-bundles'
import type { ModelType } from '../api/comfyui'
@@ -39,13 +39,14 @@ function catalog(): Map<string, KnownLora> {
/**
* What the app knows about a file in models/loras, or null when it knows
- * nothing. Two kinds are known: a character from Character Studio (trainer
- * naming `char_<name>_zimage`, a Z-Image LoRA) and the catalogue's own add-ons
+ * nothing. Two kinds are known: a character or a style from Character Studio
+ * (trainer naming `char_<name>_zimage` / `style_<name>_zimage`, Z-Image) and the catalogue's own add-ons
* (the MiniMax H3 turbo LoRA, Pixel Art XL). Everything else is a file the
* user put there, and the app does not guess a family from its name.
*/
export function knownLora(name: string): KnownLora | null {
- if (parseLocalCharacterLora(name)) return { family: 'zimage', familyLabel: 'Z-Image' }
+ // A style from the same trainer (3.0.9 P8) is the same kind of file.
+ if (parseLocalCharacterLora(name) || parseLocalStyleLora(name)) return { family: 'zimage', familyLabel: 'Z-Image' }
return catalog().get(fileOf(name).toLowerCase()) ?? null
}
diff --git a/src/lib/render/describe-train-photos.ts b/src/lib/render/describe-train-photos.ts
index 60620f81..e34ce1d5 100644
--- a/src/lib/render/describe-train-photos.ts
+++ b/src/lib/render/describe-train-photos.ts
@@ -14,6 +14,7 @@ import { runInLane } from '../run-slot'
import { isThinkingCompatible } from '../model-compatibility'
import { laneOf, currentLaneFacts } from '../run-lane-of-model'
import { cleanTrainDescription } from '../train-captions'
+import { DESCRIBE_STYLE_SYSTEM, type TrainKind } from '../train-kind'
export interface DescribeAvailability {
available: boolean
@@ -98,7 +99,7 @@ async function base64Of(blob: Blob): Promise<string> {
}
/** One photo's description from the local chat model, or null. */
-export async function describeTrainPhoto(blob: Blob, signal?: AbortSignal): Promise<string | null> {
+export async function describeTrainPhoto(blob: Blob, signal?: AbortSignal, kind: TrainKind = 'character'): Promise<string | null> {
const model = useModelStore.getState().activeModel
if (!model || signal?.aborted) return null
if (laneOf(model, currentLaneFacts()) !== 'local') return null
@@ -113,7 +114,7 @@ export async function describeTrainPhoto(blob: Blob, signal?: AbortSignal): Prom
const effortDefault = meta && 'effortDefault' in meta ? meta.effortDefault : undefined
const image = await photoForModel(blob)
const messages: ChatMessage[] = [
- { role: 'system', content: DESCRIBE_SYSTEM },
+ { role: 'system', content: kind === 'style' ? DESCRIBE_STYLE_SYSTEM : DESCRIBE_SYSTEM },
{ role: 'user', content: 'Caption this photo.', images: [image] },
]
const own = new AbortController()
diff --git a/src/lib/train-kind.ts b/src/lib/train-kind.ts
new file mode 100644
index 00000000..1fb2f841
--- /dev/null
+++ b/src/lib/train-kind.ts
@@ -0,0 +1,117 @@
+/**
+ * 3.0.9 P8: was der lokale Trainer lernt, eine Figur oder einen Stil.
+ *
+ * Bis 3.0.8 kannte der Trainer nur Figuren: Triggerwort Pflicht, jede Zeile
+ * `${trigger}, a photo of ${trigger}`, Datei `char_<trigger>_zimage`. Fuer
+ * einen Malstil, ein Konzept oder eine Pose passt davon wenig (Discord,
+ * 28.10.2026): "a photo of" zieht jedes Bild Richtung Foto, und die Figuren-
+ * Ablage zeigt den Stil dann als Figur.
+ *
+ * Modus "Style / concept":
+ * - Beschriftung: der optionale Triggerwort-Anfang und dann, was AUF dem Bild
+ * ist (Motiv, Ort). Was ungenannt bleibt, lernt der LoRA: der Stil, die Pose.
+ * - Triggerwort optional. Ohne wirkt der LoRA bei jedem Bild, sobald er aktiv
+ * ist; die Staerke im LoRA-Regler bestimmt, wie sehr.
+ * - Datei `style_<name>_zimage.safetensors`. Die Bild-Lane erkennt sie als
+ * Z-Image-LoRA (lib/lora-stack.ts), die Figuren-Ablage zeigt sie nicht.
+ * - Mehr Schritte: ein Stil muss ueber viele Motive hinweg gelernt werden.
+ * Lernrate und Rang bleiben die des Figuren-Rezepts (1e-4, siehe
+ * trainer.rs / mlx_train.rs); die Schritte sind der Hebel.
+ */
+import { TRAIN_PRESETS, TRAIN_STEPS_DEFAULT, type TrainPreset } from './trainer-presets'
+import { cleanTrainDescription } from './train-captions'
+
+export type TrainKind = 'character' | 'style'
+
+export const TRAIN_KIND_DEFAULT: TrainKind = 'character'
+
+export function isTrainKind(v: unknown): v is TrainKind {
+ return v === 'character' || v === 'style'
+}
+
+export const TRAIN_KINDS: { value: TrainKind; label: string }[] = [
+ { value: 'character', label: 'Character' },
+ { value: 'style', label: 'Style / concept' },
+]
+
+/** Die drei Stufen im Stil-Modus. Standard ist die Voreinstellung. */
+export const STYLE_TRAIN_PRESETS: TrainPreset[] = [
+ { steps: 600, label: 'Quick' },
+ { steps: 1600, label: 'Standard' },
+ { steps: 3000, label: 'Thorough' },
+]
+
+export const STYLE_TRAIN_STEPS_DEFAULT = 1600
+
+export function trainPresetsFor(kind: TrainKind): TrainPreset[] {
+ return kind === 'style' ? STYLE_TRAIN_PRESETS : TRAIN_PRESETS
+}
+
+export function trainStepsDefaultFor(kind: TrainKind): number {
+ return kind === 'style' ? STYLE_TRAIN_STEPS_DEFAULT : TRAIN_STEPS_DEFAULT
+}
+
+/** Die Zeile fuer ein Bild im Stil-Modus. `trigger` leer heisst: kein
+ * Triggerwort, die Zeile ist nur die Beschreibung (auch leer erlaubt, dann
+ * lernt der LoRA alles unbedingt). */
+export function buildStyleCaption(trigger: string, description?: string | null): string {
+ const t = trigger.trim()
+ const extra = cleanTrainDescription(description ?? '')
+ if (t && extra) return `${t}, ${extra}`
+ if (t) return t
+ return extra
+}
+
+/** Der Dateiname, den der Trainer schreibt, wie `sanitize_component` in
+ * trainer.rs: alles ausser ASCII-Buchstaben, Ziffern, `-` und `_` wird `_`,
+ * `_` an den Enden faellt weg, hoechstens 48 Zeichen. */
+export function trainedLoraFile(kind: TrainKind, name: string): string {
+ const clean = name.replace(/[^A-Za-z0-9_-]/g, '_').replace(/^_+|_+$/g, '').slice(0, 48)
+ return `${kind === 'style' ? 'style' : 'char'}_${clean}_zimage.safetensors`
+}
+
+// ── Texte (UI, also englisch) ───────────────────────────────────────────
+
+/** Was unter dem Modus-Waehler steht, solange "Style / concept" gilt. */
+export const STYLE_MODE_NOTE =
+ 'Teaches a look, a concept or a pose instead of one person. Use 10 to 30 pictures that share the style but show different subjects. The result is a LoRA in the Image tab: switch it on and set its strength there.'
+
+export const STYLE_NAME_PLACEHOLDER = 'Name, e.g. inkwash'
+
+export const STYLE_TRIGGER_LABEL = 'Use the name as trigger word'
+
+export const STYLE_TRIGGER_HINT_ON =
+ 'Put the name in a prompt to call the style up; without it the LoRA stays mild.'
+
+export const STYLE_TRIGGER_HINT_OFF =
+ 'No trigger word: the style applies to every picture while the LoRA is on. The strength slider sets how much.'
+
+export const STYLE_CAPTION_HELP =
+ 'Optional: under each picture, name what is in it, like the subject and the place. Do not name the style, the colors or the pose you want to teach: what is left unnamed is what the LoRA learns.'
+
+export const STYLE_CAPTION_PLACEHOLDER = 'e.g. a fox in a forest'
+
+export const STYLE_DROP_TITLE = 'pictures in the style here'
+
+export const STYLE_DROP_HINT = 'One look, concept or pose, shown on many different subjects'
+
+/** Die Systemzeile fuer "Describe photos" im Stil-Modus: der Inhalt, nie der
+ * Stil. Gegenstueck zu `DESCRIBE_SYSTEM` (lib/render/describe-train-photos). */
+export const DESCRIBE_STYLE_SYSTEM = [
+ 'You caption images for training a style LoRA.',
+ 'Name ONLY what is shown: the subject, objects, the place or background.',
+ 'Never describe the art style, medium, technique, brushwork, color palette, lighting mood or the pose, and never name an artist.',
+ 'Answer with one line of short comma separated phrases, at most 15 words, no sentence, no quotes, nothing else.',
+].join('\n')
+
+/** Die Fertig-Meldung im Fortschritt. */
+export function trainedLine(kind: TrainKind): string {
+ return kind === 'style' ? 'Style ready! It is switched on in the Image tab.' : 'Character ready!'
+}
+
+/** Fehler, wenn das Namensfeld leer ist. */
+export function missingNameLine(kind: TrainKind): string {
+ return kind === 'style'
+ ? 'Give the style a name first, e.g. inkwash. It becomes the name of the LoRA file.'
+ : 'Pick a trigger word first, e.g. davechar. It becomes the token that summons your character.'
+}
diff --git a/src/lib/trainer-presets.ts b/src/lib/trainer-presets.ts
index bdac0e39..1baa1d6a 100644
--- a/src/lib/trainer-presets.ts
+++ b/src/lib/trainer-presets.ts
@@ -36,16 +36,16 @@ export const TRAIN_PRESETS: TrainPreset[] = [
export const TRAIN_STEPS_DEFAULT = 1200
/** Die Stufe zu einer Schrittzahl, oder null fuer eine Zahl, die keine ist. */
-export function trainPresetLabel(steps: number): string | null {
- return TRAIN_PRESETS.find((p) => p.steps === steps)?.label ?? null
+export function trainPresetLabel(steps: number, presets: TrainPreset[] = TRAIN_PRESETS): string | null {
+ return presets.find((p) => p.steps === steps)?.label ?? null
}
/**
* Was im Hinweistext in der Klammer steht: die wirksame Zahl, und davor die
* Stufe, wenn es eine ist.
*/
-export function trainStepsNote(steps: number): string {
- const label = trainPresetLabel(steps)
+export function trainStepsNote(steps: number, presets: TrainPreset[] = TRAIN_PRESETS): string {
+ const label = trainPresetLabel(steps, presets)
return label ? `${label}, ${steps} steps` : `${steps} steps`
}
diff --git a/src/stores/createStore.ts b/src/stores/createStore.ts
index 30f68ed2..e8326aea 100644
--- a/src/stores/createStore.ts
+++ b/src/stores/createStore.ts
@@ -8,6 +8,7 @@ import type { FixupPrompt } from '../lib/render-fixups'
import { persist } from 'zustand/middleware'
import { safeJSONStorage } from '../lib/storage-quota'
import { TRAIN_STEPS_DEFAULT, TRAIN_VRAM_PRESET_DEFAULT, isTrainVramPreset, type TrainVramPreset } from '../lib/trainer-presets'
+import { TRAIN_KIND_DEFAULT, isTrainKind, trainPresetsFor, trainStepsDefaultFor, type TrainKind } from '../lib/train-kind'
import { TRAIN_CAPTION_MAX } from '../lib/train-captions'
import { isMobile } from '../lib/device-kind'
import { isRecord } from '../types/json-guards'
@@ -402,6 +403,12 @@ export interface CreateState {
/** 3.0.8 D20: the local trainer's recipe, Normal or Low VRAM. Persisted:
* it follows the card, which does not change between sessions. */
trainVramPreset: TrainVramPreset
+ /** 3.0.9 P8: what the local trainer learns, a character or a style /
+ * concept / pose (lib/train-kind.ts). Persisted like the steps. */
+ trainKind: TrainKind
+ /** 3.0.9 P8: in style mode, whether the name leads every caption as a
+ * trigger word. Off: the LoRA works without one. Persisted. */
+ trainStyleTrigger: boolean
/** The shelf character selected for use-mode generation. Runtime-only. */
selectedCharacter: CharacterRef | null
/** Lipsync speech / voice-clone reference audio. Runtime-only (blob). */
@@ -631,6 +638,8 @@ export interface CreateState {
setTrainSteps: (n: number) => void
setTrainCaption: (name: string, text: string) => void
setTrainVramPreset: (p: TrainVramPreset) => void
+ setTrainKind: (k: TrainKind) => void
+ setTrainStyleTrigger: (on: boolean) => void
setSelectedCharacter: (c: CharacterRef | null) => void
setAudioInput: (m: MediaRef | null) => void
setVoiceFromJob: (v: { jobId: string; label: string } | null) => void
@@ -1017,6 +1026,8 @@ export const useCreateStore = create<CreateState>()(
trainSteps: TRAIN_STEPS_DEFAULT,
trainCaptions: {} as Record<string, string>,
trainVramPreset: TRAIN_VRAM_PRESET_DEFAULT as TrainVramPreset,
+ trainKind: TRAIN_KIND_DEFAULT as TrainKind,
+ trainStyleTrigger: true,
selectedCharacter: null as CharacterRef | null,
audioInput: null as MediaRef | null,
voiceFromJob: null as { jobId: string; label: string } | null,
@@ -1335,6 +1346,15 @@ export const useCreateStore = create<CreateState>()(
return { trainCaptions }
}),
setTrainVramPreset: (p) => set({ trainVramPreset: isTrainVramPreset(p) ? p : TRAIN_VRAM_PRESET_DEFAULT }),
+ // The steps follow the mode: each has its own three presets, and a
+ // number of the other mode would match none of the switch's options.
+ setTrainKind: (k) => set((s) => {
+ const trainKind = isTrainKind(k) ? k : TRAIN_KIND_DEFAULT
+ if (trainKind === s.trainKind) return {}
+ const fits = trainPresetsFor(trainKind).some((p) => p.steps === s.trainSteps)
+ return { trainKind, ...(fits ? {} : { trainSteps: trainStepsDefaultFor(trainKind) }) }
+ }),
+ setTrainStyleTrigger: (on) => set({ trainStyleTrigger: !!on }),
setSelectedCharacter: (selectedCharacter) => set((s) => withOwnStudioOptions(s, { selectedCharacter })),
// Upload and voice-pick are mutually exclusive speech sources.
setAudioInput: (audioInput) => {
@@ -1788,6 +1808,8 @@ export const useCreateStore = create<CreateState>()(
triggerWord: state.triggerWord,
trainSteps: state.trainSteps,
trainVramPreset: state.trainVramPreset,
+ trainKind: state.trainKind,
+ trainStyleTrigger: state.trainStyleTrigger,
// Studio: the picked step's option values are a preference like the
// ones above. cloudStudioCredits is NOT here on purpose: a saved
// price from yesterday is a lie, see the field's own doc comment.
@@ -1847,6 +1869,9 @@ export const useCreateStore = create<CreateState>()(
if ('galleryFolders' in safe) safe.galleryFolders = sanitizeFolders(safe.galleryFolders)
// 3.0.8 D20: an unknown recipe name would reach the trainer as text.
if ('trainVramPreset' in safe && !isTrainVramPreset(safe.trainVramPreset)) safe.trainVramPreset = TRAIN_VRAM_PRESET_DEFAULT
+ // 3.0.9 P8: same for the mode, it picks the LoRA's file name.
+ if ('trainKind' in safe && !isTrainKind(safe.trainKind)) safe.trainKind = TRAIN_KIND_DEFAULT
+ if ('trainStyleTrigger' in safe && typeof safe.trainStyleTrigger !== 'boolean') safe.trainStyleTrigger = true
// The persisted slice is ~30 independent scalar preferences (see
// partialize). They are adopted as written, which is what the store
// has always done; the fields that could actually do damage — the