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.

fix(create): ask before a new training replaces a character of the same name

purpled32af59903bd
diff --git a/src/components/create/experimental/SpecialIntentControls.tsx b/src/components/create/experimental/SpecialIntentControls.tsx
index 04388a6f..70929f66 100644
--- a/src/components/create/experimental/SpecialIntentControls.tsx
+++ b/src/components/create/experimental/SpecialIntentControls.tsx
@@ -56,6 +56,7 @@ import { Slider } from '../ui/Slider'
import { cn } from '../ui/cn'
import { useClickAway } from '../ui/useClickAway'
import { Modal } from '../../ui/Modal'
+import { useTrainReplaceStore } from '../../../stores/trainReplaceStore'
import { ModalActions, ModalButton } from '../../ui/ModalActions'
import { MIN_TRAIN_IMAGES, maxTrainImages } from '../../../lib/train-image-cap'
@@ -251,6 +252,7 @@ function CharacterPanel() {
return (
<div className="space-y-2">
+ <TrainReplaceDialog />
<div className="flex items-center justify-center">
<Segmented
size="sm"
@@ -1672,3 +1674,27 @@ function TriggerWordNote() {
if (!note) return null
return <p role="status" data-testid="trigger-word-note" className={`w-full text-center t-micro ${HINWEIS_TEXT.ruhig}`}>{note}</p>
}
+
+/** C8: asks before a new training replaces the character of the same name
+ * (stores/trainReplaceStore.ts). Same Modal as the shelf's delete question. */
+function TrainReplaceDialog() {
+ const pending = useTrainReplaceStore((s) => s.pending)
+ const answer = useTrainReplaceStore((s) => s.answer)
+ useEffect(() => useTrainReplaceStore.getState().mount(), [])
+ return (
+ <Modal open={!!pending} onClose={() => answer('rename')} title="Replace character?">
+ <p className="t-micro text-gray-600 dark:text-gray-300 mb-3">
+ A character named <span className="text-gray-900 dark:text-white font-mono">{pending}</span> already exists on this computer.
+ Training with the same trigger word replaces its file when the run ends, and the old character is gone.
+ </p>
+ <ModalActions>
+ <ModalButton variant="quiet" onClick={() => answer('rename')} data-testid="train-replace-rename">
+ Pick another name
+ </ModalButton>
+ <ModalButton variant="danger" onClick={() => answer('replace')} data-testid="train-replace-confirm">
+ Replace
+ </ModalButton>
+ </ModalActions>
+ </Modal>
+ )
+}
diff --git a/src/components/create/experimental/__tests__/train-replace-dialog.test.tsx b/src/components/create/experimental/__tests__/train-replace-dialog.test.tsx
new file mode 100644
index 00000000..d60caf1c
--- /dev/null
+++ b/src/components/create/experimental/__tests__/train-replace-dialog.test.tsx
@@ -0,0 +1,38 @@
+// @vitest-environment jsdom
+/**
+ * C8: the question "Replace character?" is on screen in Character › Train new
+ * and its buttons answer the waiting run (stores/trainReplaceStore.ts).
+ *
+ * Run: npx vitest run src/components/create/experimental/__tests__/train-replace-dialog.test.tsx
+ */
+import { describe, it, expect, vi, afterEach } from 'vitest'
+import { act, 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: 1, minRamGB: 24, memoryRefusal: null, running: false })),
+}))
+
+import { SpecialControls } from '../SpecialIntentControls'
+import { useCreateStore } from '../../../../stores/createStore'
+import { useTrainReplaceStore } from '../../../../stores/trainReplaceStore'
+
+afterEach(() => cleanup())
+
+describe('C8: the replace question in Train new', () => {
+ it.each([
+ ['train-replace-confirm', 'replace'],
+ ['train-replace-rename', 'rename'],
+ ])('%s answers %s', async (button, expected) => {
+ useCreateStore.setState({ backend: 'local', error: null, triggerWord: 'luxfox', trainImages: [] } as never)
+ useCreateStore.getState().setIntent('character')
+ useCreateStore.getState().setCharacterTab('train')
+ render(<SpecialControls intent="character" />)
+ let answer!: Promise<string>
+ act(() => { answer = useTrainReplaceStore.getState().ask('luxfox') })
+ expect((await screen.findByText(/already exists on this computer/)).textContent).toContain('luxfox')
+ fireEvent.click(screen.getByTestId(button))
+ await expect(answer).resolves.toBe(expected)
+ })
+})
diff --git a/src/hooks/__tests__/training-asks-before-replacing-a-character.test.ts b/src/hooks/__tests__/training-asks-before-replacing-a-character.test.ts
new file mode 100644
index 00000000..9541fe84
--- /dev/null
+++ b/src/hooks/__tests__/training-asks-before-replacing-a-character.test.ts
@@ -0,0 +1,69 @@
+/**
+ * C8 (funde-C.md): "Train new" with the trigger word of a character already
+ * on this machine (luxfox) went straight to mlx_train_start, and the run's end
+ * wrote the new LoRA over char_luxfox_zimage.safetensors. The old character
+ * was gone, not in the Trash.
+ *
+ * Now runCharacterTraining looks for a character of the same trigger first
+ * and asks (stores/trainReplaceStore.ts, dialog in the Character panel). Only
+ * "Replace" goes on; anything else stops before a photo is staged.
+ *
+ * Run: npx vitest run src/hooks/__tests__/training-asks-before-replacing-a-character.test.ts
+ */
+import { describe, it, expect, beforeEach } from 'vitest'
+import fs from 'node:fs'
+import path from 'node:path'
+import { characterThisWouldReplace, useTrainReplaceStore } from '../../stores/trainReplaceStore'
+
+const src = fs.readFileSync(path.join(__dirname, '..', 'useCreate.ts'), 'utf8')
+const training = src.slice(src.indexOf('const runCharacterTraining = useCallback('), src.indexOf('const runOnce = useCallback('))
+
+beforeEach(() => useTrainReplaceStore.setState({ pending: null, resolve: null, listeners: 0 }))
+
+describe('C8: a new training asks before it replaces a character of the same name', () => {
+ it('the run reads the local characters and asks before staging or starting', () => {
+ const look = training.indexOf('characterThisWouldReplace(trigger, await listLocalCharacters()')
+ const ask = training.indexOf('useTrainReplaceStore.getState().ask(existing)')
+ const stage = training.indexOf('await stageTrainingImage(')
+ const clear = training.indexOf('await clearTrainingSet(')
+ const begin = training.indexOf('await startCharacterTraining(')
+ expect(look).toBeGreaterThan(0)
+ expect(ask).toBeGreaterThan(look)
+ expect(clear).toBeGreaterThan(ask)
+ expect(stage).toBeGreaterThan(ask)
+ expect(begin).toBeGreaterThan(ask)
+ })
+
+ it('only an explicit "replace" goes on', () => {
+ const ask = training.slice(training.indexOf('const existing = characterThisWouldReplace('))
+ expect(ask).toMatch(/ask\(existing\) !== 'replace'\) \{\s*setError\([^)]*already exists[^)]*\)\s*return/)
+ })
+
+ it('finds the existing character by trigger, case blind, and only then', () => {
+ const shelf = [{ triggerWord: 'luxfox' }, { triggerWord: 'mia' }]
+ expect(characterThisWouldReplace('luxfox', shelf)).toBe('luxfox')
+ expect(characterThisWouldReplace('Luxfox', shelf)).toBe('luxfox')
+ expect(characterThisWouldReplace('luxfox2', shelf)).toBeNull()
+ })
+
+ it('the dialog answers the waiting run', async () => {
+ const unmount = useTrainReplaceStore.getState().mount()
+ const answer = useTrainReplaceStore.getState().ask('luxfox')
+ expect(useTrainReplaceStore.getState().pending).toBe('luxfox')
+ useTrainReplaceStore.getState().answer('replace')
+ await expect(answer).resolves.toBe('replace')
+ expect(useTrainReplaceStore.getState().pending).toBeNull()
+ unmount()
+ })
+
+ it('with no dialog on screen the ask never replaces and never hangs', async () => {
+ await expect(useTrainReplaceStore.getState().ask('luxfox')).resolves.toBe('rename')
+ })
+
+ it('a dialog that goes away mid-question answers "rename"', async () => {
+ const unmount = useTrainReplaceStore.getState().mount()
+ const answer = useTrainReplaceStore.getState().ask('luxfox')
+ unmount()
+ await expect(answer).resolves.toBe('rename')
+ })
+})
diff --git a/src/hooks/__tests__/useCreate-mac-character.test.ts b/src/hooks/__tests__/useCreate-mac-character.test.ts
index 24f2c55c..d9b1059d 100644
--- a/src/hooks/__tests__/useCreate-mac-character.test.ts
+++ b/src/hooks/__tests__/useCreate-mac-character.test.ts
@@ -82,6 +82,7 @@ vi.mock('../../api/mlx-train', async (orig) => ({
import { useCreate } from '../useCreate'
import { useCreateStore } from '../../stores/createStore'
+import { useTrainReplaceStore } from '../../stores/trainReplaceStore'
import type { ClassifiedModel } from '../../api/comfyui'
const model = (name: string, type: ClassifiedModel['type'], extra: Partial<ClassifiedModel> = {}): ClassifiedModel =>
@@ -139,6 +140,8 @@ describe('Use character on the Mac', () => {
it('trains on the Mac through the Mac trainer, never the image engine', async () => {
arrange(ZIMAGE, 'train')
+ // A new character: none of this name is on the Mac yet (C8 asks otherwise).
+ mlxLoras.files = []
const photo = (name: string) => ({ name, url: 'blob:x', blob: new Blob([new Uint8Array([137, 80, 78, 71])], { type: 'image/png' }) })
useCreateStore.setState({ triggerWord: 'davechar', trainImages: ['a', 'b', 'c', 'd'].map(photo) } as never)
const { result } = renderHook(() => useCreate())
@@ -151,4 +154,33 @@ describe('Use character on the Mac', () => {
expect(state().error).toBe('Training a character on a Mac needs Z-Image Turbo. Install it in the Model Manager first.')
expect(state().isGenerating).toBe(false)
})
+
+ // C8: davechar is on the Mac already (char_davechar_zimage.safetensors).
+ // A new run with that trigger would write over it at the end.
+ it('C8: never trains over an existing character without a yes', async () => {
+ arrange(ZIMAGE, 'train')
+ const photo = (name: string) => ({ name, url: 'blob:x', blob: new Blob([new Uint8Array([137, 80, 78, 71])], { type: 'image/png' }) })
+ useCreateStore.setState({ triggerWord: 'davechar', trainImages: ['a', 'b', 'c', 'd'].map(photo) } as never)
+ const { result } = renderHook(() => useCreate())
+ await result.current.generate()
+ expect(train.calls).toEqual([])
+ expect(state().error).toMatch(/“davechar” already exists/)
+ expect(state().isGenerating).toBe(false)
+ })
+
+ it('C8: asks, and "Replace" goes on with the run', async () => {
+ arrange(ZIMAGE, 'train')
+ const photo = (name: string) => ({ name, url: 'blob:x', blob: new Blob([new Uint8Array([137, 80, 78, 71])], { type: 'image/png' }) })
+ useCreateStore.setState({ triggerWord: 'davechar', trainImages: ['a', 'b', 'c', 'd'].map(photo) } as never)
+ const unmount = useTrainReplaceStore.getState().mount()
+ const asked: (string | null)[] = []
+ const stop = useTrainReplaceStore.subscribe((s) => {
+ if (s.pending) { asked.push(s.pending); queueMicrotask(() => useTrainReplaceStore.getState().answer('replace')) }
+ })
+ const { result } = renderHook(() => useCreate())
+ await result.current.generate()
+ stop(); unmount()
+ expect(asked).toEqual(['davechar'])
+ expect(train.calls.map((c) => c[0])).toEqual(['clear', 'stage', 'stage', 'stage', 'stage', 'start'])
+ })
})
diff --git a/src/hooks/useCreate.ts b/src/hooks/useCreate.ts
index 03b5de5b..3245bf2c 100644
--- a/src/hooks/useCreate.ts
+++ b/src/hooks/useCreate.ts
@@ -96,6 +96,7 @@ import {
import { getMacTrainStatus, macTrainMissing } from '../api/mlx-train'
import { buildTrainCaption } from '../lib/train-captions'
import { trainTriggerWord } from '../lib/train-trigger'
+import { characterThisWouldReplace, useTrainReplaceStore } from '../stores/trainReplaceStore'
import { useCreateStore, EDIT_MAX_DENOISE, characterImageRun, deriveIntent, type CreateState } from '../stores/createStore'
import { useWorkflowStore } from '../stores/workflowStore'
import { useSettingsStore } from '../stores/settingsStore'
@@ -114,7 +115,7 @@ import { anyImageEngineReady, editCanvas, imageLaneModels, installedMlxEnhancers
import { characterBaseModel, characterRunBlock } from '../lib/character-base'
import {
CHAIN_STEP_IMAGE, CHAIN_STEP_VIDEO, CharacterChainCancelled, characterLoraFile, characterStartImage,
- isLocalCharacter, withTriggerWord,
+ isLocalCharacter, listLocalCharacters, withTriggerWord,
} from '../lib/characters'
import {
characterImagePrompt, characterImageSize, characterRunPlan, characterVideoLaneEmpty, CHARACTER_VIDEO_LANES, withCharacterLora, withoutCharacterLoras,
@@ -584,6 +585,17 @@ export function useCreate() {
return
}
}
+ // C8: the run ends by writing char_<trigger>_zimage.safetensors, the same
+ // path an existing character of that name lives at. Ask before that
+ // character is replaced, not after (stores/trainReplaceStore.ts). A list
+ // that cannot be read (ComfyUI not up) does not block the run.
+ const existing = characterThisWouldReplace(trigger, await listLocalCharacters().catch(() => []))
+ if (existing) {
+ if (await useTrainReplaceStore.getState().ask(existing) !== 'replace') {
+ setError(`A character named “${existing}” already exists. Pick another trigger word, or confirm that the new training replaces it.`)
+ return
+ }
+ }
setError(null)
setIsGenerating(true)
trainingActive.current = true
diff --git a/src/stores/trainReplaceStore.ts b/src/stores/trainReplaceStore.ts
new file mode 100644
index 00000000..ae95bdcc
--- /dev/null
+++ b/src/stores/trainReplaceStore.ts
@@ -0,0 +1,57 @@
+// C8 (funde-C.md): "Train new" with the trigger word of a character that is
+// already on this machine wrote the new LoRA over the old one at the end of
+// the run (char_<trigger>_zimage.safetensors, same path), with no question
+// and nothing in the Trash. The run now asks first.
+//
+// The same promise bridge as codexConfirmStore: runCharacterTraining awaits
+// an answer, the store parks the resolver, the dialog in the Character panel
+// resolves it on click. With no dialog on screen (nothing mounted to answer)
+// the ask answers 'rename' at once, so a run can never hang on a question
+// nobody sees, and never overwrites without one.
+
+import { create } from 'zustand'
+
+export type TrainReplaceAnswer = 'replace' | 'rename'
+
+interface TrainReplaceState {
+ /** The name of the character the dialog asks about, null when closed. */
+ pending: string | null
+ resolve: ((a: TrainReplaceAnswer) => void) | null
+ /** How many dialogs are mounted to answer. */
+ listeners: number
+ ask: (name: string) => Promise<TrainReplaceAnswer>
+ answer: (a: TrainReplaceAnswer) => void
+ mount: () => () => void
+}
+
+export const useTrainReplaceStore = create<TrainReplaceState>((set, get) => ({
+ pending: null,
+ resolve: null,
+ listeners: 0,
+ ask: (name) => {
+ if (get().listeners === 0) return Promise.resolve('rename')
+ // A question still open is answered "rename" by the new one: one card.
+ get().resolve?.('rename')
+ return new Promise<TrainReplaceAnswer>((resolve) => set({ pending: name, resolve }))
+ },
+ answer: (a) => {
+ const r = get().resolve
+ set({ pending: null, resolve: null })
+ r?.(a)
+ },
+ mount: () => {
+ set((s) => ({ listeners: s.listeners + 1 }))
+ return () => {
+ set((s) => ({ listeners: Math.max(0, s.listeners - 1) }))
+ if (get().listeners === 0) get().answer('rename')
+ }
+ },
+}))
+
+/** The existing character a new run with `trigger` would overwrite, or null.
+ * Case does not count: the Mac's file system treats char_Luxfox and
+ * char_luxfox as one file. */
+export function characterThisWouldReplace(trigger: string, existing: { triggerWord: string }[]): string | null {
+ const t = trigger.toLowerCase()
+ return existing.find((c) => c.triggerWord.toLowerCase() === t)?.triggerWord ?? null
+}