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): Bildunterschrift folgt der Eingabe, Installationssperre atomar, Vorschlag vorbelegt

purple02e241f48a40
diff --git a/src-tauri/src/commands/trainer.rs b/src-tauri/src/commands/trainer.rs
index 2fc75ad3..52fb821c 100644
--- a/src-tauri/src/commands/trainer.rs
+++ b/src-tauri/src/commands/trainer.rs
@@ -166,7 +166,7 @@ fn starts_with_tilde(p: &str) -> bool {
/// quoted back in its own rejection messages, one per platform family so the
/// example is never impossible on the machine reading it (same reasoning as
/// `comfy_path_placeholder.ts` on the frontend, kept in sync by
-/// `k5-trainer-root-validation.test.ts`/`k5-trainer-path-honesty.test.tsx`).
+/// `trainer-path-placeholder.test.ts`/`k5-trainer-path-honesty.test.tsx`).
fn example_trainer_path() -> &'static str {
if cfg!(target_os = "windows") {
"D:\\LU-Trainer"
@@ -1503,6 +1503,45 @@ pub fn parse_step_counter(line: &str) -> Option<(u64, u64)> {
// ── one-time environment install ─────────────────────────────────────────────
+/// RAII claim on `state.trainer_install`'s "installing" slot. N2 (Opus review
+/// of `3ef38668`): the check ("is one already running?") and the set ("mark
+/// one as running") used to share a single lock, but the K5 validation step
+/// added between them (`validate_trainer_root_candidate`, real disk IO) was
+/// pulled OUT from under that lock, so the check and the set became two
+/// separate locks with a window in between. Two concurrent calls could both
+/// see `status != "installing"`, both pass, and both go on to start
+/// `provision_trainer_env` against the same venv.
+///
+/// The fix moves the set back next to the check (claim the slot first, while
+/// still holding the one lock, before any IO), and this guard is what makes a
+/// failed claim reversible: validation runs AFTER the slot is claimed, so a
+/// rejection has to hand the slot back rather than leave it stuck on
+/// "installing" forever. `defuse()` disarms it once the install has
+/// genuinely started (the spawned thread's own `set_status` calls own the
+/// status from there); an undefused guard resets to "idle" on drop, which
+/// covers every early return in between, including the `?` on validation
+/// failure and on a poisoned `gpu_selection` lock.
+struct InstallClaim<'a> {
+ install: &'a Arc<Mutex<crate::state::InstallState>>,
+ active: bool,
+}
+
+impl<'a> InstallClaim<'a> {
+ fn defuse(mut self) {
+ self.active = false;
+ }
+}
+
+impl Drop for InstallClaim<'_> {
+ fn drop(&mut self) {
+ if self.active {
+ if let Ok(mut st) = self.install.lock() {
+ st.status = "idle".to_string();
+ }
+ }
+ }
+}
+
#[allow(non_snake_case)]
#[tauri::command]
pub fn install_character_trainer(
@@ -1510,12 +1549,18 @@ pub fn install_character_trainer(
state: State<'_, AppState>,
installPath: Option<String>,
) -> Result<serde_json::Value, String> {
- {
- let st = state.trainer_install.lock().unwrap();
+ // Check-and-set under ONE lock, held only long enough to claim the slot,
+ // never across the validation below (sysinfo disk lookup, create_dir_all,
+ // a probe write). See `InstallClaim` for why a failed validation still
+ // has to release the slot it just claimed.
+ let claim = {
+ let mut st = state.trainer_install.lock().unwrap();
if st.status == "installing" {
return Ok(serde_json::json!({"status": "already_installing"}));
}
- }
+ st.status = "installing".to_string();
+ InstallClaim { install: &state.trainer_install, active: true }
+ };
// K5 Blocker 2/3 (Opus review of `4fda5a0a`): validated and persisted
// BEFORE the install starts, not after, and an empty field is the way
@@ -1532,7 +1577,6 @@ pub fn install_character_trainer(
{
let mut st = state.trainer_install.lock().unwrap();
- st.status = "installing".to_string();
st.logs.clear();
st.logs.push("Setting up the local character trainer...".to_string());
}
@@ -1554,6 +1598,9 @@ pub fn install_character_trainer(
// later, see `resolve_trainer_gpu`.
let gpu_selection = state.gpu_selection.lock().map_err(|e| e.to_string())?.clone();
cancel.store(false, Ordering::SeqCst);
+ // The slot stays claimed from here on; the thread's own set_status calls
+ // take over reporting the status.
+ claim.defuse();
std::thread::spawn(move || {
let device = resolve_trainer_gpu(&gpu_selection);
@@ -3815,14 +3862,102 @@ mod tests {
/// and a background thread.
#[test]
fn install_character_trainer_validates_before_it_persists() {
+ // N3 (Opus review of `3ef38668`): this used to cut a fixed 1800-byte
+ // window out of the function body, which would have broken from the
+ // wrong cause (an out-of-bounds slice, or a `write_at` that quietly
+ // stops matching) the day the function grows or a comment shifts the
+ // cut point. Both needles below are unique in the whole file (checked
+ // via grep), so searching the rest of the file after `body_start`
+ // instead of a fixed window finds them exactly as reliably and never
+ // goes stale as the function's body changes size.
let src = include_str!("trainer.rs");
let body_start = src.find("pub fn install_character_trainer(").expect("install_character_trainer");
- let body = &src[body_start..body_start + 1800];
+ let body = &src[body_start..];
let validate_at = body.find("validate_trainer_root_candidate(trimmed)?").expect("validation call");
let write_at = body.find("write_config_value(\"trainer_root\", &validated").expect("persist call");
assert!(validate_at < write_at, "the candidate must be validated before it is written to config.json");
}
+ /// N2 (Opus review of `3ef38668`): the check ("already installing?") and
+ /// the set ("claim the slot") used to be two separate locks with the
+ /// expensive path validation running unlocked in between, so two
+ /// concurrent calls could both see an idle status and both go on to
+ /// start `provision_trainer_env`. This drives the exact race against
+ /// `InstallClaim`, the primitive `install_character_trainer` now claims
+ /// the slot through (the full command needs a live `AppHandle` this
+ /// module's tests do not build, same reason as the two tests above).
+ ///
+ /// Both threads are held at a `Barrier` until they can both attempt the
+ /// claim in the same instant, and the "expensive check" is a real sleep
+ /// AFTER the slot is claimed and the lock released, so if the claim were
+ /// still split into two separate locks (the bug) a second thread timed
+ /// to land inside that sleep would see "idle" and wrongly win too.
+ #[test]
+ fn only_one_of_two_concurrent_installs_claims_the_slot() {
+ let install: Arc<Mutex<crate::state::InstallState>> = Arc::new(Mutex::new(crate::state::InstallState::default()));
+ let barrier = std::sync::Barrier::new(2);
+
+ let attempt = |install: &Arc<Mutex<crate::state::InstallState>>| -> &'static str {
+ barrier.wait();
+ let claim = {
+ let mut st = install.lock().unwrap();
+ if st.status == "installing" {
+ return "already_installing";
+ }
+ st.status = "installing".to_string();
+ super::InstallClaim { install, active: true }
+ };
+ // Stands in for `validate_trainer_root_candidate`'s real disk IO:
+ // long enough that a still-racy check-and-set would let a second
+ // thread's check land inside this window and see "idle".
+ std::thread::sleep(std::time::Duration::from_millis(80));
+ claim.defuse();
+ "installing"
+ };
+
+ let (a, b) = std::thread::scope(|scope| {
+ let t1 = scope.spawn(|| attempt(&install));
+ let t2 = scope.spawn(|| attempt(&install));
+ (t1.join().unwrap(), t2.join().unwrap())
+ });
+
+ let outcomes = [a, b];
+ assert_eq!(
+ outcomes.iter().filter(|o| **o == "installing").count(),
+ 1,
+ "exactly one of the two concurrent attempts must claim the slot: got {outcomes:?}"
+ );
+ assert_eq!(
+ outcomes.iter().filter(|o| **o == "already_installing").count(),
+ 1,
+ "the loser must see already_installing, not a second successful claim: got {outcomes:?}"
+ );
+ }
+
+ /// N2, negative control: a claim that is dropped WITHOUT `defuse()` (the
+ /// shape of a failed `validate_trainer_root_candidate`) must hand the
+ /// slot back, not leave it stuck on "installing" forever. Without this,
+ /// N2's own fix would trade a rare double-install race for a guaranteed
+ /// permanent lockout on the very first rejected path.
+ #[test]
+ fn a_claim_dropped_without_defusing_releases_the_slot_for_the_next_attempt() {
+ let install: Arc<Mutex<crate::state::InstallState>> = Arc::new(Mutex::new(crate::state::InstallState::default()));
+ {
+ let mut st = install.lock().unwrap();
+ st.status = "installing".to_string();
+ }
+ let claim = super::InstallClaim { install: &install, active: true };
+ assert_eq!(install.lock().unwrap().status, "installing", "the claim starts out holding the slot");
+ drop(claim); // simulates `validate_trainer_root_candidate(trimmed)?` returning Err
+
+ assert_eq!(install.lock().unwrap().status, "idle", "an undefused claim must reset the slot, not leave it stuck on installing");
+
+ // And a fresh attempt can now claim it, proving the slot is really free.
+ let mut st = install.lock().unwrap();
+ assert_ne!(st.status, "installing");
+ st.status = "installing".to_string();
+ }
+
/// The priority order the review asked for: the Hardware tab's own pick
/// wins, then a `CUDA_VISIBLE_DEVICES` already on the process, then the
/// card with the most memory -- never a bare index 0.
diff --git a/src/components/create/experimental/SpecialIntentControls.tsx b/src/components/create/experimental/SpecialIntentControls.tsx
index 9339f9bb..3a877d07 100644
--- a/src/components/create/experimental/SpecialIntentControls.tsx
+++ b/src/components/create/experimental/SpecialIntentControls.tsx
@@ -296,8 +296,19 @@ function LocalTrainControls() {
// (the old bug behind Blocker 2 -- a broken customized install re-showed
// this gate with an empty field and a caption that still claimed the app
// data default). Runs once per status load, before the customer edits.
+ //
+ // Teil 10, point 3 (Opus review of `3ef38668`): a customer who never opens
+ // this gate never learns that `suggestedRoot` exists at all -- it used to
+ // sit only in the grayed-out placeholder, invisible the moment the field
+ // has focus and gone the instant anything is typed. Nothing here moves an
+ // EXISTING install: this only pre-fills the field, with a real, editable,
+ // clearable value, and only while there is no trainer yet (this whole
+ // gate only renders before `envReady`) and no customized root of the
+ // customer's own to preserve.
useEffect(() => {
- if (!pathTouched && status?.customized) setInstallPath(status.root)
+ if (pathTouched) return
+ if (status?.customized) setInstallPath(status.root)
+ else if (status?.suggestedRoot) setInstallPath(status.suggestedRoot)
}, [status, pathTouched])
// A base-file download outlives this panel. Leave the tab and come back and
@@ -395,10 +406,10 @@ function LocalTrainControls() {
<input
value={installPath}
onChange={(e) => { setInstallPath(e.target.value); setPathTouched(true) }}
- placeholder={`e.g. ${status.suggestedRoot ?? trainerPathPlaceholder(isWindows(), isMacOS())}`}
+ placeholder={`e.g. ${trainerPathPlaceholder(isWindows(), isMacOS())}`}
className="t-control w-64 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"
/>
- <span className="t-label text-gray-600">{trainerRootHint(status, installPath)}</span>
+ <span className="t-label text-gray-600">{trainerRootHint(status, installPath, status.suggestedRoot)}</span>
</div>
)}
{note && <div role="status" tabIndex={0} className="text-xs leading-relaxed text-gray-600 max-w-[520px] max-h-40 overflow-y-auto select-text whitespace-pre-wrap text-center break-words">{note}</div>}
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 a95a26be..9d1cd3c5 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
@@ -40,6 +40,14 @@ vi.mock('../../../../api/trainer', async () => {
characterTrainerStatus: vi.fn(async () => ({
envReady: true,
basesReady: true,
+ // N4 (Opus review of `3ef38668`): the only mock in the tree still
+ // missing the two K5 fields every other `TrainerStatus` mock carries.
+ // Harmless here (this gate never reaches the install-path field once
+ // `envReady` is true), but kept in step so a future field added next
+ // to these two does not silently skip this file too.
+ root: '/data/lu/musubi',
+ customized: false,
+ suggestedRoot: null,
install: { status: 'done', step: '', percent: 100 },
})),
installCharacterTrainer: vi.fn(async () => undefined),
diff --git a/src/components/create/experimental/__tests__/k5-trainer-path-honesty.test.tsx b/src/components/create/experimental/__tests__/k5-trainer-path-honesty.test.tsx
index 1a39115e..a42b789d 100644
--- a/src/components/create/experimental/__tests__/k5-trainer-path-honesty.test.tsx
+++ b/src/components/create/experimental/__tests__/k5-trainer-path-honesty.test.tsx
@@ -131,11 +131,55 @@ describe('K5 Nachbesserung: Blocker 3, ehrliche Zielangabe', () => {
})
})
-describe('K5 Nachbesserung: Punkt 5, Vorschlag statt stillem Umzug', () => {
- it('THE FIX: ein Vorschlagsordner erscheint als Platzhalter, nicht als Wert', async () => {
+describe('Teil 10, Punkt 3: der Vorschlag fuellt das Feld sichtbar vor, statt nur ein Platzhalter zu sein', () => {
+ it('THE FIX: kein Trainer, kein eigener Ordner, ein Vorschlag -- das Feld traegt den echten, editierbaren Wert', async () => {
mockedStatus = baseStatus({ suggestedRoot: '/mnt/e/LU-Trainer' })
render(<SpecialControls intent="character" />)
- const feld = (await screen.findByPlaceholderText('e.g. /mnt/e/LU-Trainer')) as HTMLInputElement
+ const feld = (await screen.findByDisplayValue('/mnt/e/LU-Trainer')) as HTMLInputElement
+ expect(feld.value).toBe('/mnt/e/LU-Trainer')
+ })
+
+ it('THE FIX: darunter steht der Grund fuer den Vorschlag', async () => {
+ mockedStatus = baseStatus({ suggestedRoot: '/mnt/e/LU-Trainer' })
+ render(<SpecialControls intent="character" />)
+ await screen.findByDisplayValue('/mnt/e/LU-Trainer')
+ expect(screen.getByText(/Your model folder is on another drive/)).toBeTruthy()
+ })
+
+ it('THE FIX: das vorbelegte Feld ist editierbar und leerbar', async () => {
+ mockedStatus = baseStatus({ suggestedRoot: '/mnt/e/LU-Trainer' })
+ render(<SpecialControls intent="character" />)
+ const feld = (await screen.findByDisplayValue('/mnt/e/LU-Trainer')) as HTMLInputElement
+ fireEvent.change(feld, { target: { value: '' } })
expect(feld.value).toBe('')
+ fireEvent.click(screen.getByRole('button', { name: 'Set up trainer' }))
+ expect(installCharacterTrainer).toHaveBeenCalledWith(undefined)
+ })
+
+ it('GEGENPROBE: ein eigener, bereits angepasster Ordner uebersteuert den Vorschlag', async () => {
+ // Punkt (b) der Bedingung: ein gesetzter eigener Trainer-Ordner ist
+ // wichtiger als ein Vorschlag, der auf ComfyUI zeigt.
+ mockedStatus = baseStatus({ root: 'E:\\LU-Trainer', customized: true, suggestedRoot: '/mnt/e/LU-Trainer' })
+ render(<SpecialControls intent="character" />)
+ const feld = (await screen.findByDisplayValue('E:\\LU-Trainer')) as HTMLInputElement
+ expect(feld.value).toBe('E:\\LU-Trainer')
+ expect(screen.queryByDisplayValue('/mnt/e/LU-Trainer')).toBeNull()
+ })
+
+ it('GEGENPROBE: kein Vorschlag bekannt, das Feld bleibt leer wie zuvor', async () => {
+ mockedStatus = baseStatus({ suggestedRoot: null })
+ render(<SpecialControls intent="character" />)
+ await screen.findByRole('button', { name: 'Set up trainer' })
+ const feld = screen.getByPlaceholderText(/^e\.g\. \//) as HTMLInputElement
+ expect(feld.value).toBe('')
+ })
+
+ it('GEGENPROBE: eine bestehende Installation ausser Sicht bleibt unangetastet -- kein stilles Umziehen', async () => {
+ // Bedingung (a): ist envReady wahr, rendert dieses Tor ueberhaupt nicht,
+ // also gibt es kein Feld, das den Vorschlag je vorbelegen koennte.
+ mockedStatus = baseStatus({ envReady: true, basesReady: true, dit: 'x', textEncoder: 'x', vae: 'x', suggestedRoot: '/mnt/e/LU-Trainer' })
+ render(<SpecialControls intent="character" />)
+ expect(screen.queryByDisplayValue('/mnt/e/LU-Trainer')).toBeNull()
+ expect(screen.queryByRole('button', { name: 'Set up trainer' })).toBeNull()
})
})
diff --git a/src/lib/__tests__/trainer-root-hint.test.ts b/src/lib/__tests__/trainer-root-hint.test.ts
index a6aa5036..0656da08 100644
--- a/src/lib/__tests__/trainer-root-hint.test.ts
+++ b/src/lib/__tests__/trainer-root-hint.test.ts
@@ -51,4 +51,40 @@ describe('trainerRootHint', () => {
expect(trainerRootHint(status, value)).toContain('configured model folder')
}
})
+
+ it('N1 THE FIX: typing a DIFFERENT path over a pre-filled customized root names the typed path, not the old one', () => {
+ // Teil 9, N1: install broke on E:, the gate reopens with the field
+ // pre-filled to E:, and the customer retypes F: before pressing the
+ // button. The caption has to name F:, the drive the button will use.
+ const hint = trainerRootHint({ root: 'E:\\LU-Trainer', customized: true }, 'F:\\LU-Trainer')
+ expect(hint).toContain('Installs to F:\\LU-Trainer')
+ expect(hint).not.toContain('Installs to E:\\LU-Trainer')
+ })
+
+ it('N1 GEGENPROBE: leaving the pre-filled field untouched still names the customized root', () => {
+ const hint = trainerRootHint({ root: 'E:\\LU-Trainer', customized: true }, 'E:\\LU-Trainer')
+ expect(hint).toContain('Installs to E:\\LU-Trainer')
+ })
+
+ it('point 5 THE FIX: a value that matches the suggested root explains why it is already filled in', () => {
+ const hint = trainerRootHint({ root: '/data/lu/musubi', customized: false }, '/mnt/e/LU-Trainer', '/mnt/e/LU-Trainer')
+ expect(hint).toContain('Installs to /mnt/e/LU-Trainer')
+ expect(hint).toContain('Your model folder is on another drive')
+ expect(hint).toContain('Clear this field to use the app data folder instead')
+ })
+
+ it('point 5 GEGENPROBE: a typed value that happens to differ from the suggestion gets the plain sentence, not the reason', () => {
+ const hint = trainerRootHint({ root: '/data/lu/musubi', customized: false }, '/mnt/f/Other', '/mnt/e/LU-Trainer')
+ expect(hint).toContain('Installs to /mnt/f/Other')
+ expect(hint).not.toContain('Your model folder is on another drive')
+ })
+
+ it('point 5 GEGENPROBE: a customized root that happens to equal the suggestion still gets the customized wording', () => {
+ // suggestedRoot only applies to the un-customized state; a customer who
+ // already made the suggestion their real, saved root gets the normal
+ // customized caption, not the "we suggest this folder" one.
+ const hint = trainerRootHint({ root: '/mnt/e/LU-Trainer', customized: true }, '/mnt/e/LU-Trainer', '/mnt/e/LU-Trainer')
+ expect(hint).not.toContain('Your model folder is on another drive')
+ expect(hint).toContain('Clear this field to go back to the app data folder')
+ })
})
diff --git a/src/lib/trainer-root-hint.ts b/src/lib/trainer-root-hint.ts
index 9b2fcf4f..cd3b666e 100644
--- a/src/lib/trainer-root-hint.ts
+++ b/src/lib/trainer-root-hint.ts
@@ -15,18 +15,34 @@ import type { TrainerStatus } from '../api/trainer'
* to the configured model folder in Settings, regardless of it), and says
* plainly that clearing the field is the way back and nothing at the old
* location is deleted (point 4).
+ *
+ * K5 Nachbesserung Teil 10, N1 (Opus review of `3ef38668`): a customer typing
+ * a DIFFERENT path into the pre-filled field used to still read the old
+ * `status.root`, so the caption named the drive being abandoned instead of
+ * the one the button was about to install to. Every branch below that names
+ * a target now names `trimmed`, the value on screen, not `status.root`.
+ *
+ * `suggestedRoot`, when given and equal to `trimmed`, marks the one state
+ * where the field was pre-filled with a suggestion rather than typed or
+ * loaded from a customized root (K5 architecture point 5): the caption then
+ * explains why a folder is already sitting there instead of just naming it.
*/
export function trainerRootHint(
status: Pick<TrainerStatus, 'root' | 'customized'>,
fieldValue: string,
+ suggestedRoot?: string | null,
): string {
const trimmed = fieldValue.trim()
const baseModels = 'Base model downloads always go to your configured model folder (Settings, ComfyUI), not here.'
if (status.customized && trimmed === '') {
return `Leaving this empty and pressing Set up trainer installs to your app data folder instead. Files already at ${status.root} are kept, not deleted. ${baseModels}`
}
- if (status.customized) {
- return `Installs to ${status.root}. Clear this field to go back to the app data folder. ${baseModels}`
+ if (!status.customized && trimmed !== '' && suggestedRoot && trimmed === suggestedRoot) {
+ return `Installs to ${trimmed}. Your model folder is on another drive, so we suggest this folder too. Clear this field to use the app data folder instead. ${baseModels}`
+ }
+ if (trimmed !== '') {
+ const goBack = status.customized ? 'Clear this field to go back to the app data folder.' : 'Clear this field to use the app data folder instead.'
+ return `Installs to ${trimmed}. ${goBack} ${baseModels}`
}
return `Installs to your app data folder by default. Set a path above to use another drive. ${baseModels}`
}