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(gpu): the boot starts of ComfyUI and Ollama apply the picked card

purple4119bcdbcd85
diff --git a/src-tauri/src/commands/gpu.rs b/src-tauri/src/commands/gpu.rs
index b3dc0e32..31ec88ab 100644
--- a/src-tauri/src/commands/gpu.rs
+++ b/src-tauri/src/commands/gpu.rs
@@ -1653,8 +1653,14 @@ pub struct GpuSelection {
#[tauri::command]
pub fn set_gpu_selection(state: State<'_, AppState>, selection: GpuSelection) -> Result<(), String> {
- let mut sel = state.gpu_selection.lock().map_err(|e| e.to_string())?;
- *sel = selection;
+ {
+ let mut sel = state.gpu_selection.lock().map_err(|e| e.to_string())?;
+ *sel = selection.clone();
+ }
+ // 3.1.0: kept across a restart, so the boot starts of ComfyUI and Ollama
+ // have it before the frontend is up (gpu_roles.rs, "The picks across a
+ // restart").
+ crate::commands::gpu_roles::persist_pick(crate::commands::gpu_roles::CONFIG_KEY_SELECTION, &selection);
Ok(())
}
@@ -2010,8 +2016,10 @@ End of search: 3 match(es) found.
"{rel} still has the old lock-wraps-apply_gpu_env shape (the MutexGuard \
was alive for the whole call, including any nvidia-smi I/O inside it)"
);
+ // 3.1.0: process.rs reads it through gpu_roles::apply_role_env,
+ // which calls effective_selection (checked below).
assert!(
- src.contains("gpu_roles::effective_selection(state,"),
+ src.contains("gpu_roles::effective_selection(state,") || src.contains("gpu_roles::apply_role_env(state,"),
"{rel} has no call site that reads the selection through gpu_roles::effective_selection"
);
}
@@ -2021,6 +2029,9 @@ End of search: 3 match(es) found.
assert!(body.contains("state.gpu_selection.lock().ok().map(|s| s.clone())"), "the selection is not cloned out of its lock");
assert!(body.contains("state.gpu_roles.lock().ok().map(|r| r.clone())"), "the roles are not cloned out of their lock");
assert!(!body.contains("apply_gpu_env"), "effective_selection must not forward while it holds a lock");
+ let helper = roles.split("pub fn apply_role_env(").nth(1).expect("apply_role_env in gpu_roles.rs");
+ let helper = &helper[..helper.find("\n}\n").expect("end of apply_role_env")];
+ assert!(helper.contains("effective_selection(state, role)") && !helper.contains(".lock()"), "apply_role_env must read through effective_selection and hold no lock");
}
#[test]
diff --git a/src-tauri/src/commands/gpu_roles.rs b/src-tauri/src/commands/gpu_roles.rs
index b97bf008..5985f645 100644
--- a/src-tauri/src/commands/gpu_roles.rs
+++ b/src-tauri/src/commands/gpu_roles.rs
@@ -159,13 +159,97 @@ pub fn chat_card(state: &AppState) -> Option<GpuRef> {
#[tauri::command]
pub fn set_gpu_roles(state: State<'_, AppState>, roles: GpuRoles) -> Result<(), String> {
- let mut r = state.gpu_roles.lock().map_err(|e| e.to_string())?;
- *r = roles;
+ {
+ let mut r = state.gpu_roles.lock().map_err(|e| e.to_string())?;
+ *r = roles.clone();
+ }
// A device found for the old pick must not be reused for the new one.
clear_device_cache();
+ persist_pick(CONFIG_KEY_ROLES, &roles);
Ok(())
}
+// ── The picks across a restart ─────────────────────────────────────────
+//
+// Until 3.1.0 both picks lived only in memory and came down from the
+// frontend after the window loaded. The boot path starts ComfyUI and Ollama
+// before that (lib.rs, auto_start_*), and neither start applied a card at all,
+// so "Card per task" (3.0.8) never reached a ComfyUI or an Ollama that LU
+// started together with itself; LU's own ComfyUI install turns that
+// autostart on. Now every pick is also written to config.json, read back
+// into AppState when the app starts, and both boot starts apply it the same
+// way the manual starts do. The frontend stays the source: its sync on every
+// boot writes the same values again.
+
+pub const CONFIG_KEY_SELECTION: &str = "gpu_selection";
+pub const CONFIG_KEY_ROLES: &str = "gpu_roles";
+
+/// The picks stored in a config.json value. Anything missing or unreadable
+/// is "no pick", which is what a machine that never set one has.
+pub fn picks_from_config(config: &serde_json::Value) -> (GpuSelection, GpuRoles) {
+ let selection = config
+ .get(CONFIG_KEY_SELECTION)
+ .and_then(|v| serde_json::from_value::<GpuSelection>(v.clone()).ok())
+ .unwrap_or_default();
+ let roles = config
+ .get(CONFIG_KEY_ROLES)
+ .and_then(|v| serde_json::from_value::<GpuRoles>(v.clone()).ok())
+ .unwrap_or_default();
+ (selection, roles)
+}
+
+/// The picks stored in the config file at `path`.
+pub fn picks_from_file(path: &std::path::Path) -> (GpuSelection, GpuRoles) {
+ std::fs::read_to_string(path)
+ .ok()
+ .and_then(|raw| serde_json::from_str::<serde_json::Value>(&raw).ok())
+ .map(|v| picks_from_config(&v))
+ .unwrap_or_default()
+}
+
+/// The picks of this install, for AppState at startup.
+pub fn load_persisted_picks() -> (GpuSelection, GpuRoles) {
+ picks_from_file(&crate::os_paths::app_config_json())
+}
+
+/// Write one pick into the config file at `path`, only when it changed (the
+/// frontend sends both on every boot). Other keys stay as they are.
+pub fn persist_pick_in<T: Serialize>(path: &std::path::Path, key: &str, value: &T) {
+ let Ok(value) = serde_json::to_value(value) else { return };
+ let mut config = std::fs::read_to_string(path)
+ .ok()
+ .and_then(|raw| serde_json::from_str::<serde_json::Value>(&raw).ok())
+ .filter(|v| v.is_object())
+ .unwrap_or_else(|| serde_json::json!({}));
+ if config.get(key) == Some(&value) {
+ return;
+ }
+ config[key] = value;
+ if let Some(dir) = path.parent() {
+ let _ = std::fs::create_dir_all(dir);
+ }
+ let _ = std::fs::write(path, serde_json::to_string_pretty(&config).unwrap_or_default());
+}
+
+pub fn persist_pick<T: Serialize>(key: &str, value: &T) {
+ persist_pick_in(&crate::os_paths::app_config_json(), key, value);
+}
+
+/// Put the card of `role` on a command about to start ComfyUI (`Comfy`) or
+/// Ollama (`Chat`). The one place both the manual and the boot starts go
+/// through, so the two can no longer drift apart. Returns the split when it
+/// applies, for the start log.
+pub fn apply_role_env(state: &AppState, role: GpuRole, cmd: &mut std::process::Command) -> Option<ComfySplit> {
+ // The roles are cloned out of their lock inside effective_selection;
+ // apply_gpu_env may run nvidia-smi and must never hold a lock (B2).
+ let selection = effective_selection(state, role);
+ let split = if role == GpuRole::Comfy { comfy_split(state) } else { None };
+ if let Some(sel) = selection {
+ crate::commands::gpu::apply_gpu_env(cmd, &sel);
+ }
+ split
+}
+
#[tauri::command]
pub fn get_gpu_roles(state: State<'_, AppState>) -> Result<GpuRoles, String> {
let r = state.gpu_roles.lock().map_err(|e| e.to_string())?;
@@ -532,6 +616,76 @@ Available devices:
assert!(split_note(r.split().unwrap()).contains("gpu:1"));
}
+ /// The autostart fix: a pick written by set_gpu_* comes back after a
+ /// restart, other config keys survive, garbage reads as "no pick".
+ #[test]
+ fn the_picks_survive_a_restart_through_config_json() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("config.json");
+ std::fs::write(&path, r#"{"comfyui_autostart":true,"comfyui_port":8188}"#).unwrap();
+ let roles = GpuRoles { chat: Some(card(0, "RTX 4090")), comfy: Some(card(1, "RTX 3060")), ..Default::default() };
+ let selection = GpuSelection { vendor: "nvidia".into(), indices: vec![0, 1] };
+ persist_pick_in(&path, CONFIG_KEY_ROLES, &roles);
+ persist_pick_in(&path, CONFIG_KEY_SELECTION, &selection);
+ let (s, r) = picks_from_file(&path);
+ assert_eq!(r, roles);
+ assert_eq!((s.vendor.as_str(), s.indices.as_slice()), ("nvidia", [0u32, 1].as_slice()));
+ let raw: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
+ assert_eq!(raw["comfyui_autostart"], serde_json::json!(true), "other keys are kept");
+ // The split too, under the frontend's name.
+ let with_split = GpuRoles { comfy_split: split(1, 0), ..Default::default() };
+ persist_pick_in(&path, CONFIG_KEY_ROLES, &with_split);
+ assert!(std::fs::read_to_string(&path).unwrap().contains("comfySplit"));
+ assert_eq!(picks_from_file(&path).1, with_split);
+ }
+
+ #[test]
+ fn no_file_or_a_broken_one_is_no_pick() {
+ let dir = tempfile::tempdir().unwrap();
+ let (s, r) = picks_from_file(&dir.path().join("missing.json"));
+ assert_eq!((s.vendor.as_str(), s.indices.len(), r), ("auto", 0, GpuRoles::default()));
+ let bad = dir.path().join("bad.json");
+ std::fs::write(&bad, r#"{"gpu_roles":"nonsense","gpu_selection":{"vendor":5}}"#).unwrap();
+ let (s, r) = picks_from_file(&bad);
+ assert_eq!((s.vendor.as_str(), r), ("auto", GpuRoles::default()));
+ // A config that is not an object is not overwritten into one silently
+ // with lost keys: it was unreadable anyway, the pick starts it fresh.
+ std::fs::write(&bad, "[]").unwrap();
+ persist_pick_in(&bad, CONFIG_KEY_ROLES, &GpuRoles::default());
+ assert!(serde_json::from_str::<serde_json::Value>(&std::fs::read_to_string(&bad).unwrap()).unwrap().is_object());
+ }
+
+ /// The autostart path and the manual one put the same card on the
+ /// command, because both go through apply_role_env.
+ #[test]
+ fn apply_role_env_puts_the_comfy_card_and_the_chat_card_on_the_command() {
+ let state = AppState::new();
+ *state.gpu_selection.lock().unwrap() = GpuSelection::default();
+ *state.gpu_roles.lock().unwrap() =
+ GpuRoles { chat: Some(GpuRef { vendor: "amd".into(), index: 0, name: "RX A".into() }), comfy: Some(GpuRef { vendor: "amd".into(), index: 1, name: "RX B".into() }), ..Default::default() };
+ let env = |cmd: &std::process::Command| -> Vec<String> {
+ let mut v: Vec<String> = cmd.get_envs().filter_map(|(k, v)| v.map(|v| format!("{}={}", k.to_string_lossy(), v.to_string_lossy()))).collect();
+ v.sort();
+ v
+ };
+ let mut comfy = std::process::Command::new("never-run");
+ assert_eq!(apply_role_env(&state, GpuRole::Comfy, &mut comfy), None);
+ assert!(env(&comfy).contains(&"HIP_VISIBLE_DEVICES=1".to_string()), "{:?}", env(&comfy));
+ let mut chat = std::process::Command::new("never-run");
+ apply_role_env(&state, GpuRole::Chat, &mut chat);
+ assert!(env(&chat).contains(&"HIP_VISIBLE_DEVICES=0".to_string()), "{:?}", env(&chat));
+ // With the split, ComfyUI gets both NVIDIA cards and says so.
+ *state.gpu_roles.lock().unwrap() = GpuRoles { comfy_split: split(1, 0), ..Default::default() };
+ let mut comfy = std::process::Command::new("never-run");
+ assert!(apply_role_env(&state, GpuRole::Comfy, &mut comfy).is_some());
+ assert!(env(&comfy).iter().any(|e| e.starts_with("CUDA_VISIBLE_DEVICES=")), "{:?}", env(&comfy));
+ // No pick at all: no variable, exactly as before 3.0.8.
+ *state.gpu_roles.lock().unwrap() = GpuRoles::default();
+ let mut none = std::process::Command::new("never-run");
+ apply_role_env(&state, GpuRole::Comfy, &mut none);
+ assert!(env(&none).iter().all(|e| !e.contains("VISIBLE_DEVICES")), "{:?}", env(&none));
+ }
+
#[test]
fn a_role_with_an_unknown_vendor_is_ignored() {
let global = GpuSelection { vendor: "amd".into(), indices: vec![0] };
diff --git a/src-tauri/src/commands/process.rs b/src-tauri/src/commands/process.rs
index 27776e91..0b7021ea 100644
--- a/src-tauri/src/commands/process.rs
+++ b/src-tauri/src/commands/process.rs
@@ -1730,10 +1730,8 @@ fn start_ollama_blocking(state: &AppState) -> Result<serde_json::Value, String>
// long that subprocess I/O takes.
// 3.0.8 (A2): the chat role's card when one is set, the global pick
// otherwise (commands/gpu_roles.rs).
- let gpu_selection = crate::commands::gpu_roles::effective_selection(state, crate::commands::gpu_roles::GpuRole::Chat);
- if let Some(sel) = gpu_selection {
- crate::commands::gpu::apply_gpu_env(&mut cmd, &sel);
- }
+ // 3.1.0: through apply_role_env, the one helper the boot start uses too.
+ crate::commands::gpu_roles::apply_role_env(state, crate::commands::gpu_roles::GpuRole::Chat, &mut cmd);
#[cfg(target_os = "windows")]
cmd.creation_flags(CREATE_NO_WINDOW);
let result = cmd.spawn();
@@ -2288,15 +2286,11 @@ pub(crate) fn start_comfyui_blocking(state: &AppState) -> Result<serde_json::Val
// can never spill onto the chat's card.
// 3.1.0 (C56): with "One model across two cards" ComfyUI sees both
// cards, the model card first (gpu_roles.rs, ComfySplit).
- let gpu_selection = crate::commands::gpu_roles::effective_selection(state, crate::commands::gpu_roles::GpuRole::Comfy);
- if let Some(split) = crate::commands::gpu_roles::comfy_split(state) {
- let line = format!("[start] {}", crate::commands::gpu_roles::split_note(&split));
- println!("[ComfyUI] {line}");
+ // 3.1.0: through apply_role_env, the one helper the boot start uses too.
+ if let Some(split) = crate::commands::gpu_roles::apply_role_env(state, crate::commands::gpu_roles::GpuRole::Comfy, &mut cmd) {
+ println!("[ComfyUI] [start] {}", crate::commands::gpu_roles::split_note(&split));
info!(model = split.model.index, helper = split.helper.index, "comfyui split over two cards");
}
- if let Some(sel) = gpu_selection {
- crate::commands::gpu::apply_gpu_env(&mut cmd, &sel);
- }
#[cfg(target_os = "windows")]
cmd.creation_flags(CREATE_NO_WINDOW);
let mut child = cmd.spawn()
@@ -3410,6 +3404,8 @@ pub fn auto_start_ollama(state: &AppState) {
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
+ // 3.1.0: the chat card, like start_ollama. This start applied none.
+ crate::commands::gpu_roles::apply_role_env(state, crate::commands::gpu_roles::GpuRole::Chat, &mut cmd);
#[cfg(target_os = "windows")]
cmd.creation_flags(CREATE_NO_WINDOW);
match cmd.spawn() {
@@ -3785,6 +3781,14 @@ pub fn auto_start_comfyui(state: &AppState) {
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
+ // 3.1.0: the card, like the manual start. Until now this path
+ // applied none, so "Card per task" (3.0.8) never reached a
+ // ComfyUI started with LU, and LU's own ComfyUI install turns this
+ // start on. The pick comes from config.json (AppState::new).
+ if let Some(split) = crate::commands::gpu_roles::apply_role_env(state, crate::commands::gpu_roles::GpuRole::Comfy, &mut cmd) {
+ println!("[ComfyUI] Auto-start: {}", crate::commands::gpu_roles::split_note(&split));
+ info!(model = split.model.index, helper = split.helper.index, "comfyui split over two cards");
+ }
#[cfg(target_os = "windows")]
cmd.creation_flags(CREATE_NO_WINDOW);
match cmd.spawn() {
@@ -6218,3 +6222,31 @@ mod process_tree_kill_tests {
);
}
}
+
+#[cfg(test)]
+mod boot_start_gpu_tests {
+ /// 3.1.0: the boot starts of ComfyUI and Ollama applied no card at all
+ /// since 3.0.8, so "Card per task" never reached a ComfyUI or Ollama LU
+ /// started together with itself. Every start, manual and boot, now goes
+ /// through the one helper with its service's role. Read as source, like
+ /// the extra-model-paths guard above, because the property is "what does
+ /// each spawn site call"; the helper itself is tested in gpu_roles.rs.
+ #[test]
+ fn every_comfyui_and_ollama_start_applies_its_card() {
+ let src = std::fs::read_to_string(std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/commands/process.rs")).unwrap();
+ let src = &src[..src.find("#[cfg(test)]").unwrap()];
+ for (name, role) in [
+ ("fn start_comfyui_blocking", "GpuRole::Comfy"),
+ ("pub fn auto_start_comfyui", "GpuRole::Comfy"),
+ ("fn start_ollama_blocking", "GpuRole::Chat"),
+ ("pub fn auto_start_ollama", "GpuRole::Chat"),
+ ] {
+ let start = src.find(name).unwrap_or_else(|| panic!("{name} is gone"));
+ let body = &src[start..start + src[start..].find("\n}\n").expect("unterminated fn")];
+ let call = body.find("gpu_roles::apply_role_env(state,").unwrap_or_else(|| panic!("{name} applies no card"));
+ assert!(body[call..].starts_with(&format!("gpu_roles::apply_role_env(state, crate::commands::gpu_roles::{role}")), "{name} applies the wrong role");
+ let spawn = body.rfind(".spawn()").unwrap_or_else(|| panic!("{name} spawns nothing"));
+ assert!(call < spawn, "{name} applies the card after the spawn");
+ }
+ }
+}
diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs
index 485cc049..dc0ceb96 100644
--- a/src-tauri/src/state.rs
+++ b/src-tauri/src/state.rs
@@ -466,6 +466,9 @@ impl AppState {
// Fixes a pre-existing bug where `set_comfyui_port` wrote to disk but
// startup never read it back. Same loader now handles the new host field.
let (initial_port, initial_host) = load_comfy_config_values();
+ // 3.1.0: the GPU picks of the last session, so the boot starts of
+ // ComfyUI and Ollama apply them (commands/gpu_roles.rs).
+ let (initial_gpu_selection, initial_gpu_roles) = crate::commands::gpu_roles::load_persisted_picks();
if initial_port != 8188 {
println!("[ComfyUI] Loaded persisted port: {}", initial_port);
}
@@ -525,8 +528,9 @@ impl AppState {
chat_workspace_overrides: Arc::new(Mutex::new(HashMap::new())),
// Bug BB v2.5.0 — start in "auto" mode so existing installs are
// unchanged until the user explicitly picks a GPU in Settings.
- gpu_selection: Mutex::new(GpuSelection::default()),
- gpu_roles: Mutex::new(crate::commands::gpu_roles::GpuRoles::default()),
+ // "auto" unless the user picked a card in an earlier session.
+ gpu_selection: Mutex::new(initial_gpu_selection),
+ gpu_roles: Mutex::new(initial_gpu_roles),
flash_attn_cache: Mutex::new(HashMap::new()),
comfy_gpu_cache: Mutex::new(HashMap::new()),
comfy_gpu_mode: Mutex::new("auto".to_string()),