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(trainer): ein Abbruch in den ersten Sekunden haelt jetzt

Davide9cac6963165
diff --git a/src-tauri/src/commands/trainer.rs b/src-tauri/src/commands/trainer.rs
index 5e26d140..f330525f 100644
--- a/src-tauri/src/commands/trainer.rs
+++ b/src-tauri/src/commands/trainer.rs
@@ -1946,6 +1946,17 @@ pub fn start_character_training(
return;
}
+ // Cancel can arrive while no child is alive: during the environment
+ // probe (a plain Command::output, nothing in pid_slot) or between two
+ // children. The flag alone does nothing then, and the next child
+ // would be spawned only to be killed on its first poll, or, worse,
+ // never noticed. Measured on the box on 06.09.2026: a Cancel 14 s
+ // after Create left the run training on while the UI had gone idle.
+ if cancel_requested(&cancel) {
+ set_status(&run, "cancelled", "cancelled");
+ return;
+ }
+
// 1) latent cache
set_status(&run, "running", "Step 1/4: Caching image latents...");
let mut c1 = Command::new(&vpy_s);
@@ -1959,6 +1970,10 @@ pub fn start_character_training(
return;
}
+ if cancel_requested(&cancel) {
+ set_status(&run, "cancelled", "cancelled");
+ return;
+ }
// 2) text-encoder cache (fp8 keeps the 4B Qwen TE inside 12 GB)
set_status(&run, "running", "Step 2/4: Caching text encoder outputs...");
let mut c2 = Command::new(&vpy_s);
@@ -1974,6 +1989,10 @@ pub fn start_character_training(
return;
}
+ if cancel_requested(&cancel) {
+ set_status(&run, "cancelled", "cancelled");
+ return;
+ }
// 3) the train itself — documented 12 GB combo: fp8 base + block swap
// + gradient checkpointing + 8-bit optimizer. ComfyUI's model cache
// would eat the same VRAM the trainer needs — ask it to let go first.
@@ -1996,7 +2015,7 @@ pub fn start_character_training(
push_log(&run, &format!("Did not free ComfyUI's VRAM ({target}): {why}"));
}
}
- set_status(&run, "running", &format!("Step 3/4: Training ({steps} steps). This runs for a while, live log below..."));
+ set_status(&run, "running", &format!("Step 3/4: Training ({steps} steps). This runs for a while, the counter follows every step."));
let accelerate = {
#[cfg(target_os = "windows")]
{ root.join("venv").join("Scripts").join("accelerate.exe") }
@@ -2031,6 +2050,10 @@ pub fn start_character_training(
return;
}
+ if cancel_requested(&cancel) {
+ set_status(&run, "cancelled", "cancelled");
+ return;
+ }
// 4) convert to the Diffusers key layout ComfyUI loads, straight into
// the loras dir (musubi's documented `--target other` conversion).
set_status(&run, "running", "Step 4/4: Converting the LoRA for ComfyUI...");
@@ -3352,6 +3375,23 @@ mod progress_line_tests {
assert_eq!(steps, [(0, 400), (1, 400), (2, 400)], "each \\r update is its own line");
}
+ #[test]
+ fn a_cancel_with_no_child_alive_still_ends_the_run_before_the_next_spawn() {
+ // The probe runs Command::output (nothing in pid_slot) and between two
+ // children nothing is alive either, so Cancel there only sets the flag.
+ // Each of the four children is preceded by a check of that flag.
+ let src = include_str!("trainer.rs");
+ let body = &src[src.find("pub fn start_character_training").expect("start fn")..];
+ let body = &body[..body.find("info!(\"character training complete\")").expect("end of the run")];
+ let checks = body.matches("if cancel_requested(&cancel) {").count();
+ assert_eq!(checks, 4, "one cancel check per child, before its spawn");
+ for label in ["\"latent cache\"", "\"text encoder cache\"", "\"training\"", "\"lora convert\""] {
+ let spawn = body.find(label).expect(label);
+ let check = body[..spawn].rfind("if cancel_requested(&cancel) {").expect("a check before the spawn");
+ assert!(body[check..spawn].matches("run_streamed(").count() == 1, "the check right before {label}");
+ }
+ }
+
#[test]
fn what_the_dying_child_prints_after_a_cancel_is_not_the_log() {
// The box showed a raw KeyboardInterrupt traceback in the live log
diff --git a/src/hooks/__tests__/der-abbruch-haelt.test.ts b/src/hooks/__tests__/der-abbruch-haelt.test.ts
new file mode 100644
index 00000000..858cd547
--- /dev/null
+++ b/src/hooks/__tests__/der-abbruch-haelt.test.ts
@@ -0,0 +1,62 @@
+/**
+ * Stop during a character training has to stick.
+ *
+ * Measured on the Windows box on 06.09.2026 (t9): a Cancel 0.6 s or 14 s
+ * after Create, while the card was still being freed or the environment
+ * probed, reset the UI to idle and brought the chat model back, while the
+ * trainer went on to step 27 of 400 beside it. The Rust start resets the
+ * cancel flag, so a cancel that arrives before the start is lost, and one
+ * that lands in the probe has no child to kill.
+ *
+ * Now the run remembers the request: a cancel before the start skips the
+ * start, and after the start the poll loop re-sends the cancel until the
+ * backend reports the run gone, and only then gives the card back.
+ *
+ * Run: npx vitest run src/hooks/__tests__/der-abbruch-haelt.test.ts
+ */
+import { describe, it, expect } from 'vitest'
+import fs from 'node:fs'
+import path from 'node:path'
+
+const src = fs.readFileSync(path.join(__dirname, '..', 'useCreate.ts'), 'utf8')
+const training = src.slice(src.indexOf('const runCharacterTraining = useCallback('), src.indexOf('const generateInner = useCallback('))
+const cancel = src.slice(src.indexOf('const cancel = useCallback('), src.indexOf('return {', src.indexOf('const cancel = useCallback(')))
+
+describe('a Stop during the training holds', () => {
+ it('a cancel that came during the hand-off skips the start', () => {
+ const evict = training.indexOf('await evictChatBackendsForRender()')
+ const check = training.indexOf('if (trainingCancelRequested.current) return')
+ const begin = training.indexOf('await startCharacterTraining(')
+ expect(evict).toBeGreaterThan(0)
+ expect(check).toBeGreaterThan(evict)
+ expect(begin).toBeGreaterThan(check)
+ })
+
+ it('after the start, a run the backend still reports gets the cancel again', () => {
+ const loop = training.slice(training.indexOf('for (;;) {'))
+ const running = loop.indexOf("if (s.status === 'running') {")
+ const resend = loop.indexOf('await cancelCharacterTraining()')
+ expect(running).toBeGreaterThan(0)
+ expect(resend).toBeGreaterThan(running)
+ // bounded: it does not wait on a backend that never answers
+ expect(loop).toContain('if (++cancelRounds >= 20) return')
+ })
+
+ it('the loop keeps polling after Stop reset the UI, until the backend confirms', () => {
+ const loop = training.slice(training.indexOf('for (;;) {'))
+ expect(loop).toContain('if (!useCreateStore.getState().isGenerating && !trainingCancelRequested.current) return')
+ expect(loop).not.toContain('if (!useCreateStore.getState().isGenerating) return')
+ })
+
+ it('Stop marks the request before it asks the backend', () => {
+ const mark = cancel.indexOf('trainingCancelRequested.current = true')
+ const ask = cancel.indexOf('await cancelCharacterTraining()')
+ expect(mark).toBeGreaterThan(0)
+ expect(ask).toBeGreaterThan(mark)
+ })
+
+ it('the card comes back in the finally, after the loop, never inside Stop', () => {
+ expect(training.indexOf('void restoreChatBackendsAfterRender(trainingEviction)')).toBeGreaterThan(training.indexOf('} finally {'))
+ expect(cancel).not.toContain('restoreChatBackendsAfterRender')
+ })
+})
diff --git a/src/hooks/useCreate.ts b/src/hooks/useCreate.ts
index 0c422ac0..51581735 100644
--- a/src/hooks/useCreate.ts
+++ b/src/hooks/useCreate.ts
@@ -107,6 +107,8 @@ export function useCreate() {
// A local character-training run is a Rust child process, not a ComfyUI
// prompt — cancel() must reach it through its own command.
const trainingActive = useRef(false)
+ /** Stop pressed while a training run was being set up or running. */
+ const trainingCancelRequested = useRef(false)
// Cleanup on unmount
useEffect(() => {
@@ -388,6 +390,7 @@ export function useCreate() {
setError(null)
setIsGenerating(true)
trainingActive.current = true
+ trainingCancelRequested.current = false
// The trainer is a 12 GB recipe on a 12 GB card. A resident chat model
// (the built-in engine, Ollama, LM Studio) squats 2 to 9 GB of that and
// the run dies in the text-encoder cache or the first training step with
@@ -410,15 +413,29 @@ export function useCreate() {
try {
trainingEviction = await evictChatBackendsForRender()
} catch { /* VRAM housekeeping is best-effort */ }
+ // Stop pressed during the hand-off: there is no run to cancel yet, and
+ // starting one now would hand the card to a trainer nobody is watching
+ // (the box, 06.09.2026: Cancel 0.6 s after Create, training ran on to
+ // 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)
+ let cancelRounds = 0
for (;;) {
await new Promise((r) => setTimeout(r, 3000))
- // cancel() already reset the UI; the Rust child got its kill there.
- if (!useCreateStore.getState().isGenerating) return
+ if (!useCreateStore.getState().isGenerating && !trainingCancelRequested.current) return
const s = await characterTrainingStatus().catch(() => null)
if (!s) continue
if (s.status === 'running') {
+ if (trainingCancelRequested.current) {
+ // Stop was pressed and the backend still reports a run: the
+ // cancel raced the start (the start resets the flag) or landed
+ // in the environment probe. Send it again until the run is
+ // really gone; the card is only given back below, after that.
+ try { await cancelCharacterTraining() } catch { /* next round */ }
+ if (++cancelRounds >= 20) return
+ continue
+ }
if (s.totalSteps > 0) {
setProgress(Math.min(95, 10 + Math.round((s.step / s.totalSteps) * 85)), `Training ${s.step}/${s.totalSteps}...`)
} else {
@@ -1499,6 +1516,9 @@ export function useCreate() {
const cancel = useCallback(async () => {
abortRef.current?.abort()
if (trainingActive.current) {
+ // The run's poll loop reads this: it holds the card until the backend
+ // confirms the run is gone, and re-sends the cancel if it is not.
+ trainingCancelRequested.current = true
// Best effort, and deliberately not fatal: Stop's real job is the
// abandonPrompt below. A training cancel that fails must not stop us
// from taking the render out of the queue — that was the R32 defect