Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
Merge pull request #7605 from dataCenter430/fix/GPU-detection-losing
dataCenter4308df4bf887e8e
diff --git a/src-tauri/plugins/tauri-plugin-hardware/src/commands.rs b/src-tauri/plugins/tauri-plugin-hardware/src/commands.rsindex ac13eb7f2..a8f4b4213 100644--- a/src-tauri/plugins/tauri-plugin-hardware/src/commands.rs+++ b/src-tauri/plugins/tauri-plugin-hardware/src/commands.rs@@ -5,52 +5,76 @@ use crate::{};use sysinfo::System;-#[tauri::command]-pub fn get_system_info() -> SystemInfo {- SYSTEM_INFO- .get_or_init(|| {- let mut system = System::new();- system.refresh_memory();+fn compute_system_info() -> SystemInfo {+ let mut system = System::new();+ system.refresh_memory();++ let mut gpu_map = std::collections::HashMap::new();+ for gpu in nvidia::get_nvidia_gpus() {+ gpu_map.insert(gpu.uuid.clone(), gpu);+ }++ let vulkan_gpus = vulkan::get_vulkan_gpus();- let mut gpu_map = std::collections::HashMap::new();- for gpu in nvidia::get_nvidia_gpus() {+ for gpu in vulkan_gpus {+ match gpu_map.get_mut(&gpu.uuid) {+ // for existing NVIDIA GPUs, add Vulkan info+ Some(nvidia_gpu) => {+ nvidia_gpu.vulkan_info = gpu.vulkan_info;+ }+ None => {gpu_map.insert(gpu.uuid.clone(), gpu);}+ }+ }- let vulkan_gpus = vulkan::get_vulkan_gpus();+ let os_type = if cfg!(target_os = "windows") {+ "windows"+ } else if cfg!(target_os = "macos") {+ "macos"+ } else if cfg!(target_os = "linux") {+ "linux"+ } else {+ "unknown"+ };+ let os_name = System::long_os_version().unwrap_or("Unknown".to_string());- for gpu in vulkan_gpus {- match gpu_map.get_mut(&gpu.uuid) {- // for existing NVIDIA GPUs, add Vulkan info- Some(nvidia_gpu) => {- nvidia_gpu.vulkan_info = gpu.vulkan_info;- }- None => {- gpu_map.insert(gpu.uuid.clone(), gpu);- }- }- }+ SystemInfo {+ cpu: CpuStaticInfo::new(),+ os_type: os_type.to_string(),+ os_name,+ total_memory: system.total_memory() / 1024 / 1024, // bytes to MiB+ gpus: gpu_map.into_values().collect(),+ }+}- let os_type = if cfg!(target_os = "windows") {- "windows"- } else if cfg!(target_os = "macos") {- "macos"- } else if cfg!(target_os = "linux") {- "linux"- } else {- "unknown"- };- let os_name = System::long_os_version().unwrap_or("Unknown".to_string());+#[tauri::command]+pub fn get_system_info() -> SystemInfo {+ // Fast path: use cache if present+ {+ let guard = SYSTEM_INFO.read().expect("RwLock poisoned");+ if let Some(ref info) = *guard {+ return info.clone();+ }+ }+ // Cache miss or invalidated: compute and store+ let info = compute_system_info();+ {+ let mut guard = SYSTEM_INFO.write().expect("RwLock poisoned");+ *guard = Some(info.clone());+ }+ info+}- SystemInfo {- cpu: CpuStaticInfo::new(),- os_type: os_type.to_string(),- os_name,- total_memory: system.total_memory() / 1024 / 1024, // bytes to MiB- gpus: gpu_map.into_values().collect(),- }- })- .clone()+/// Invalidates cached hardware info so the next get_system_info() re-detects GPUs.+/// Call this after system resume on Linux to fix "No GPU detected" (driver state is+/// reset after sleep and the previous cache may be stale or empty).+#[tauri::command]+pub fn refresh_system_info() {+ #[cfg(target_os = "linux")]+ nvidia::invalidate_nvml();+ let mut guard = SYSTEM_INFO.write().expect("RwLock poisoned");+ *guard = None;}#[tauri::command]diff --git a/src-tauri/plugins/tauri-plugin-hardware/src/lib.rs b/src-tauri/plugins/tauri-plugin-hardware/src/lib.rsindex 3a069892e..751d7921a 100644--- a/src-tauri/plugins/tauri-plugin-hardware/src/lib.rs+++ b/src-tauri/plugins/tauri-plugin-hardware/src/lib.rs@@ -8,10 +8,12 @@ pub mod vendor;pub use constants::*;pub use types::*;-use std::sync::OnceLock;+use std::sync::RwLock;use tauri::Runtime;-static SYSTEM_INFO: OnceLock<SystemInfo> = OnceLock::new();+/// Cached system info. Uses Option so we can invalidate on Linux after sleep/resume+/// (GPU detection can return empty until the driver is ready again).+static SYSTEM_INFO: RwLock<Option<SystemInfo>> = RwLock::new(None);pub use commands::get_system_info;@@ -20,7 +22,8 @@ pub fn init<R: Runtime>() -> tauri::plugin::TauriPlugin<R> {tauri::plugin::Builder::new("hardware").invoke_handler(tauri::generate_handler![commands::get_system_info,- commands::get_system_usage+ commands::get_system_usage,+ commands::refresh_system_info]).build()}diff --git a/src-tauri/plugins/tauri-plugin-hardware/src/vendor/nvidia.rs b/src-tauri/plugins/tauri-plugin-hardware/src/vendor/nvidia.rsindex 083c0fdae..4779b0386 100644--- a/src-tauri/plugins/tauri-plugin-hardware/src/vendor/nvidia.rs+++ b/src-tauri/plugins/tauri-plugin-hardware/src/vendor/nvidia.rs@@ -4,11 +4,13 @@ use crate::types::{GpuInfo, GpuUsage};use {crate::types::Vendor,nvml_wrapper::{error::NvmlError, Nvml},- std::sync::OnceLock,+ std::sync::RwLock,};+/// NVML handle. On Linux we use RwLock so we can invalidate after sleep/resume+/// and re-initialize when the driver is ready again.#[cfg(not(any(target_os = "android", target_os = "ios")))]-static NVML: OnceLock<Option<Nvml>> = OnceLock::new();+static NVML: RwLock<Option<Nvml>> = RwLock::new(None);#[derive(Debug, Clone, serde::Serialize)]pub struct NvidiaInfo {@@ -16,34 +18,59 @@ pub struct NvidiaInfo {pub compute_capability: String,}+/// Run a closure with the current NVML handle, initializing if needed.#[cfg(not(any(target_os = "android", target_os = "ios")))]-fn get_nvml() -> Option<&'static Nvml> {- NVML.get_or_init(|| {- // Try to initialize NVML, with fallback for Linux- let result = Nvml::init().or_else(|e| {- if cfg!(target_os = "linux") {- log::debug!("NVML init failed, trying Linux fallback: {}", e);- let lib_path = std::ffi::OsStr::new("libnvidia-ml.so.1");- Nvml::builder().lib_path(lib_path).init()- } else {- Err(e)- }- });-- match result {- Ok(nvml) => {- log::debug!("NVML initialized successfully");- Some(nvml)- }- Err(e) => {- log::debug!("Unable to initialize NVML: {}", e);- None+fn with_nvml<F, R>(f: F) -> R+where+ F: FnOnce(Option<&Nvml>) -> R,+{+ // Try read first for the common case (already initialized)+ {+ let guard = NVML.read().expect("RwLock poisoned");+ if guard.is_some() {+ return f(guard.as_ref());+ }+ }+ // Not initialized or was invalidated: try to init+ {+ let mut guard = NVML.write().expect("RwLock poisoned");+ if guard.is_none() {+ let result = Nvml::init().or_else(|e| {+ if cfg!(target_os = "linux") {+ log::debug!("NVML init failed, trying Linux fallback: {}", e);+ let lib_path = std::ffi::OsStr::new("libnvidia-ml.so.1");+ Nvml::builder().lib_path(lib_path).init()+ } else {+ Err(e)+ }+ });+ match result {+ Ok(nvml) => {+ log::debug!("NVML initialized successfully");+ *guard = Some(nvml);+ }+ Err(e) => {+ log::debug!("Unable to initialize NVML: {}", e);+ }}}- })- .as_ref()+ return f(guard.as_ref());+ }}+/// Invalidates the NVML handle so the next use re-initializes. Call after system+/// resume on Linux when the GPU driver state has been reset.+#[cfg(target_os = "linux")]+pub fn invalidate_nvml() {+ let mut guard = NVML.write().expect("RwLock poisoned");+ *guard = None;+ log::debug!("NVML invalidated (e.g. after resume); will re-init on next use");+}++/// No-op on non-Linux; invalidation is only needed for Linux sleep/resume.+#[cfg(not(target_os = "linux"))]+pub fn invalidate_nvml() {}+impl GpuInfo {pub fn get_usage_nvidia(&self) -> GpuUsage {#[cfg(any(target_os = "android", target_os = "ios"))]@@ -72,14 +99,16 @@ impl GpuInfo {#[cfg(not(any(target_os = "android", target_os = "ios")))]fn get_nvidia_memory_usage(&self, index: u32) -> Result<GpuUsage, NvmlError> {- let nvml = get_nvml().ok_or(NvmlError::Unknown)?;- let device = nvml.device_by_index(index)?;- let mem_info = device.memory_info()?;-- Ok(GpuUsage {- uuid: self.uuid.clone(),- used_memory: mem_info.used / (1024 * 1024), // bytes to MiB- total_memory: mem_info.total / (1024 * 1024), // bytes to MiB+ with_nvml(|nvml| {+ let nvml = nvml.ok_or(NvmlError::Unknown)?;+ let device = nvml.device_by_index(index)?;+ let mem_info = device.memory_info()?;++ Ok(GpuUsage {+ uuid: self.uuid.clone(),+ used_memory: mem_info.used / (1024 * 1024), // bytes to MiB+ total_memory: mem_info.total / (1024 * 1024), // bytes to MiB+ })})}}@@ -100,32 +129,34 @@ pub fn get_nvidia_gpus() -> Vec<GpuInfo> {#[cfg(not(any(target_os = "android", target_os = "ios")))]fn get_nvidia_gpus_internal() -> Vec<GpuInfo> {- let nvml = match get_nvml() {- Some(nvml) => nvml,- None => {- log::debug!("NVML not available");- return vec![];- }- };+ with_nvml(|nvml| {+ let nvml = match nvml {+ Some(n) => n,+ None => {+ log::debug!("NVML not available");+ return vec![];+ }+ };- let (num_gpus, driver_version) = match (nvml.device_count(), nvml.sys_driver_version()) {- (Ok(count), Ok(version)) => (count, version),- (Err(e), _) | (_, Err(e)) => {- log::error!("Failed to get NVIDIA system info: {}", e);- return vec![];- }- };+ let (num_gpus, driver_version) = match (nvml.device_count(), nvml.sys_driver_version()) {+ (Ok(count), Ok(version)) => (count, version),+ (Err(e), _) | (_, Err(e)) => {+ log::error!("Failed to get NVIDIA system info: {}", e);+ return vec![];+ }+ };- let mut gpus = Vec::with_capacity(num_gpus as usize);+ let mut gpus = Vec::with_capacity(num_gpus as usize);- for i in 0..num_gpus {- match create_gpu_info(nvml, i, &driver_version) {- Ok(gpu_info) => gpus.push(gpu_info),- Err(e) => log::warn!("Failed to get info for NVIDIA GPU {}: {}", i, e),+ for i in 0..num_gpus {+ match create_gpu_info(nvml, i, &driver_version) {+ Ok(gpu_info) => gpus.push(gpu_info),+ Err(e) => log::warn!("Failed to get info for NVIDIA GPU {}: {}", i, e),+ }}- }- gpus+ gpus+ })}#[cfg(not(any(target_os = "android", target_os = "ios")))]diff --git a/web-app/src/providers/GlobalEventHandler.tsx b/web-app/src/providers/GlobalEventHandler.tsxindex 8295ba9a5..6ed3dd360 100644--- a/web-app/src/providers/GlobalEventHandler.tsx+++ b/web-app/src/providers/GlobalEventHandler.tsx@@ -2,6 +2,8 @@ import { useEffect } from 'react'import { events } from '@janhq/core'import { useModelProvider } from '@/hooks/useModelProvider'import { useServiceHub } from '@/hooks/useServiceHub'+import { useHardware } from '@/hooks/useHardware'+import { isPlatformTauri } from '@/lib/platform/utils'/*** GlobalEventHandler handles global events that should be processed across all screens@@ -10,6 +12,26 @@ import { useServiceHub } from '@/hooks/useServiceHub'export function GlobalEventHandler() {const { setProviders } = useModelProvider()const serviceHub = useServiceHub()+ const setHardwareData = useHardware((state) => state.setHardwareData)++ // Re-detect GPU when app becomes visible again (e.g. after system sleep on Linux - #6447)+ useEffect(() => {+ if (!isPlatformTauri()) return++ const handleVisibilityChange = async () => {+ if (document.visibilityState !== 'visible') return+ try {+ await serviceHub.hardware().refreshHardwareInfo()+ const data = await serviceHub.hardware().getHardwareInfo()+ if (data) setHardwareData(data)+ } catch (e) {+ console.error('Failed to refresh hardware info after visibility change:', e)+ }+ }++ document.addEventListener('visibilitychange', handleVisibilityChange)+ return () => document.removeEventListener('visibilitychange', handleVisibilityChange)+ }, [serviceHub, setHardwareData])// Handle settingsChanged event globallyuseEffect(() => {diff --git a/web-app/src/routes/settings/hardware.tsx b/web-app/src/routes/settings/hardware.tsxindex 99915c5ef..13457771e 100644--- a/web-app/src/routes/settings/hardware.tsx+++ b/web-app/src/routes/settings/hardware.tsx@@ -118,6 +118,24 @@ function HardwareContent() {}}+ const handleRefreshHardware = async () => {+ try {+ setIsLoading(true)+ await serviceHub.hardware().refreshHardwareInfo()+ const [hardwareData, systemUsage] = await Promise.all([+ serviceHub.hardware().getHardwareInfo(),+ serviceHub.hardware().getSystemUsage(),+ ])+ if (hardwareData) setHardwareData(hardwareData)+ if (systemUsage) updateSystemUsage(systemUsage)+ if (!IS_MACOS) fetchDevices()+ } catch (error) {+ console.error('Failed to refresh hardware:', error)+ } finally {+ setIsLoading(false)+ }+ }+return (<div className="flex flex-col h-svh w-full"><HeaderPage>@@ -275,7 +293,21 @@ function HardwareContent() {{/* Llamacpp Devices Information */}{!IS_MACOS && llamacpp && (- <Card title="GPUs">+ <Card+ title="GPUs"+ header={+ <div className="flex items-center justify-end mb-2">+ <Button+ variant="ghost"+ size="sm"+ onClick={handleRefreshHardware}+ disabled={isLoading}+ >+ {isLoading ? '...' : 'Refresh'}+ </Button>+ </div>+ }+ >{llamacppDevicesLoading ? (<CardItem title="Loading devices..." actions={<></>} />) : llamacppDevicesError ? (diff --git a/web-app/src/services/hardware/default.ts b/web-app/src/services/hardware/default.tsindex 5f4df438c..3bdfb516d 100644--- a/web-app/src/services/hardware/default.ts+++ b/web-app/src/services/hardware/default.ts@@ -21,4 +21,8 @@ export class DefaultHardwareService implements HardwareService {console.log('setActiveGpus called with data:', data)// No-op - not implemented in default service}++ async refreshHardwareInfo(): Promise<void> {+ // No-op outside Tauri (e.g. web)+ }}diff --git a/web-app/src/services/hardware/tauri.ts b/web-app/src/services/hardware/tauri.tsindex efcd23c37..7f2e26f33 100644--- a/web-app/src/services/hardware/tauri.ts+++ b/web-app/src/services/hardware/tauri.ts@@ -30,4 +30,8 @@ export class TauriHardwareService extends DefaultHardwareService {// TODO: llama.cpp extension should handle thisconsole.log(data)}++ async refreshHardwareInfo(): Promise<void> {+ await invoke('plugin:hardware|refresh_system_info')+ }}diff --git a/web-app/src/services/hardware/types.ts b/web-app/src/services/hardware/types.tsindex 3307298f6..a32be25a8 100644--- a/web-app/src/services/hardware/types.ts+++ b/web-app/src/services/hardware/types.ts@@ -18,6 +18,8 @@ export interface HardwareService {getSystemUsage(): Promise<SystemUsage | null>getLlamacppDevices(): Promise<DeviceList[]>setActiveGpus(data: { gpus: number[] }): Promise<void>+ /** Invalidates cached GPU detection so next getHardwareInfo() re-detects. Use after system resume (e.g. Linux sleep). */+ refreshHardwareInfo(): Promise<void>}// Re-export hardware types for conveniencediff --git a/web-app/src/test/setup.ts b/web-app/src/test/setup.tsindex 3fc6bd621..eb4a43b9f 100644--- a/web-app/src/test/setup.ts+++ b/web-app/src/test/setup.ts@@ -28,6 +28,7 @@ const mockServiceHub = {getSystemUsage: vi.fn().mockResolvedValue(null),getLlamacppDevices: vi.fn().mockResolvedValue([]), // cspell: disable-linesetActiveGpus: vi.fn().mockResolvedValue(undefined),+ refreshHardwareInfo: vi.fn().mockResolvedValue(undefined),// Legacy methods for backward compatibilitygetGpuInfo: vi.fn().mockResolvedValue([]),getCpuInfo: vi.fn().mockResolvedValue({}),