Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(llamacpp): say local models are unsupported on an Intel Mac, not "os error 86" (#9387)
Thinh Lee426db03fb3c
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/commands.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/commands.rsindex d5f01ef95..aebd31ff1 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/commands.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/commands.rs@@ -11,6 +11,7 @@ use tauri_plugin_hardware::vendor::nvidia::{nvidia_driver, CudaVersion, NvidiaDruse super::driver;use super::worker::{self, WorkerHandle};+use crate::error::{ErrorCode, LlamacppError};use crate::state::LlamacppState;#[derive(Debug, Clone, Serialize, Deserialize)]@@ -182,6 +183,26 @@ async fn record_nvidia_driver(versions: Arc<EngineVersions>) {let _ = versions.driver.set(driver);}+/// A start failure as the `String` this command returns. A wrong-processor+/// worker crosses as the structured error, which `parseEngineError` on the web+/// side recovers from the message, so it is shown from its code. Every other+/// failure keeps its plain text.+fn worker_error_string(err: worker::WorkerError) -> String {+ match err {+ worker::WorkerError::WrongArchitecture(detail) => {+ let structured = LlamacppError::new(+ ErrorCode::UnsupportedCpu,+ "The llama.cpp engine in this Jan build does not support this computer's \+ processor."+ .into(),+ Some(detail),+ );+ serde_json::to_string(&structured).unwrap_or(structured.message)+ }+ other => other.to_string(),+ }+}+/// Starts the worker. `slot_cache_mib` is the ceiling on the per-thread KV/// cache directory; 0 turns cross-session KV persistence off, which is a/// user-facing setting because a single saved conversation is hundreds of MiB.@@ -216,7 +237,7 @@ pub async fn start_engine<R: tauri::Runtime>(Some(fault_emitter(app_handle.clone(), versions.clone())),).await- .map_err(|e| e.to_string())?;+ .map_err(worker_error_string)?;if let Some(v) = handle.cuda_toolkit {let _ = versions.toolkit.set(v);}@@ -666,6 +687,22 @@ mod tests {assert_ne!(a, b, "two keys must not collide");}+ // The UI shows an engine error from its code, and recovers the code from the+ // message text, so the wrong-processor failure has to cross as that JSON.+ // Any other spawn failure keeps its plain text.+ #[test]+ fn a_wrong_processor_reaches_the_ui_as_its_own_code() {+ let text = worker_error_string(worker::WorkerError::WrongArchitecture(+ "Bad CPU type in executable (os error 86)".into(),+ ));+ let json: serde_json::Value = serde_json::from_str(&text).unwrap();+ assert_eq!(json["code"], "UNSUPPORTED_CPU");+ assert_eq!(json["details"], "Bad CPU type in executable (os error 86)");++ let plain = worker_error_string(worker::WorkerError::Spawn("no such file".into()));+ assert_eq!(plain, "could not start jan-llama-worker: no such file");+ }+// resolve_worker_exe now needs an AppHandle for the bundle lookup, so the// override branch is exercised through the same precedence it guards: the// override is checked before anything Tauri-dependent.diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/worker.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/worker.rsindex 6a08cf97f..857346be3 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/worker.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/engine/worker.rs@@ -50,6 +50,10 @@ pub struct Handshake {#[derive(Debug, PartialEq, Eq)]pub enum WorkerError {Spawn(String),+ /// The OS refused to run the worker because it is built for another+ /// processor than this computer's: the Apple Silicon engine on an Intel Mac+ /// (#9270). Not a transient failure, so callers say so instead of retrying.+ WrongArchitecture(String),/// The worker exited or said nothing intelligible before serving.Handshake(String),Timeout(Duration),@@ -59,6 +63,10 @@ impl std::fmt::Display for WorkerError {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {match self {Self::Spawn(m) => write!(f, "could not start jan-llama-worker: {m}"),+ Self::WrongArchitecture(m) => write!(+ f,+ "jan-llama-worker is built for a different processor than this computer's: {m}"+ ),Self::Handshake(m) => write!(f, "jan-llama-worker did not come up: {m}"),Self::Timeout(d) => {write!(f, "jan-llama-worker did not report a port within {d:?}")@@ -67,6 +75,20 @@ impl std::fmt::Display for WorkerError {}}+/// `EBADARCH`, which macOS returns from `exec` for a Mach-O with no slice for+/// this CPU ("Bad CPU type in executable"). It is only a macOS code: on Linux+/// the same number is a different errno.+#[cfg(target_os = "macos")]+const EBADARCH: i32 = 86;++fn spawn_error(e: std::io::Error) -> WorkerError {+ #[cfg(target_os = "macos")]+ if e.raw_os_error() == Some(EBADARCH) {+ return WorkerError::WrongArchitecture(e.to_string());+ }+ WorkerError::Spawn(e.to_string())+}+/// A runtime failure worth telling the user about, classified from one worker/// log line. `GGML_ASSERT` calls `abort()`, so for these the line on stderr is/// often the only evidence left of what happened.@@ -646,7 +668,7 @@ pub async fn spawn(.stderr(Stdio::piped()).kill_on_drop(true);- let mut child = cmd.spawn().map_err(|e| WorkerError::Spawn(e.to_string()))?;+ let mut child = cmd.spawn().map_err(spawn_error)?;// Before the handshake, so every error path below drops the job too and// cannot leak a worker that never reported for duty.#[cfg(windows)]@@ -1102,6 +1124,45 @@ pub(crate) mod tests {assert!(matches!(err, WorkerError::Spawn(_)), "got {err:?}");}+ // #9270: a worker built for another processor (the Apple Silicon engine on+ // an Intel Mac) is refused by the kernel with EBADARCH. A thin Mach-O for a+ // CPU no Mac runs today gets the same refusal on any Mac, which is how this+ // is exercised without an Intel machine.+ #[cfg(target_os = "macos")]+ #[tokio::test]+ async fn a_worker_built_for_another_processor_is_its_own_error() {+ use std::os::unix::fs::PermissionsExt;++ let dir = tempfile::tempdir().unwrap();+ let exe = dir.path().join("jan-llama-worker");+ let mut header = Vec::new();+ // mach_header_64: magic, cputype (PowerPC), cpusubtype, MH_EXECUTE, ncmds,+ // sizeofcmds, flags, reserved.+ for word in [0xfeed_facf_u32, 0x12, 0, 2, 0, 0, 0, 0] {+ header.extend_from_slice(&word.to_le_bytes());+ }+ header.resize(64, 0);+ std::fs::write(&exe, header).unwrap();+ std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap();++ let err = spawn(+ &exe,+ Path::new("/tmp/x.ini"),+ 0,+ "k",+ 1,+ 0,+ HashMap::new(),+ None,+ )+ .await+ .expect_err("a worker for another CPU cannot start");+ assert!(+ matches!(err, WorkerError::WrongArchitecture(_)),+ "got {err:?}"+ );+ }+// The tail is what turns "connection refused" into a cause, so it must// keep the newest lines, and only a few of them.#[test]diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/error.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/error.rsindex 4e6bc6143..b71c9a82b 100644--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/error.rs+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/error.rs@@ -18,6 +18,9 @@ pub enum ErrorCode {EngineStopped,/// The worker is alive, but its loopback port cannot be reached.EngineUnreachable,+ /// The bundled engine has no build for this computer's processor, so it+ /// cannot start at all: the Apple Silicon engine on an Intel Mac.+ UnsupportedCpu,// --- Configuration Errors ---InvalidArgument,@@ -267,6 +270,7 @@ mod tests {(ErrorCode::ModelArchNotSupported, "MODEL_ARCH_NOT_SUPPORTED"),(ErrorCode::ModelLoadTimedOut, "MODEL_LOAD_TIMED_OUT"),(ErrorCode::MissingSharedLibrary, "MISSING_SHARED_LIBRARY"),+ (ErrorCode::UnsupportedCpu, "UNSUPPORTED_CPU"),(ErrorCode::GpuDriverTooOld, "GPU_DRIVER_TOO_OLD"),(ErrorCode::OutOfMemory, "OUT_OF_MEMORY"),(ErrorCode::EngineStopped, "ENGINE_STOPPED"),diff --git a/web-app/src/lib/__tests__/engineError.test.ts b/web-app/src/lib/__tests__/engineError.test.tsindex c47029330..c7cb538cb 100644--- a/web-app/src/lib/__tests__/engineError.test.ts+++ b/web-app/src/lib/__tests__/engineError.test.ts@@ -65,6 +65,19 @@ describe('parseEngineError', () => {expect(parsed?.missingLibraries).toBeUndefined()})++ // #9270: start_engine hands the wrong-processor failure over as JSON inside+ // the error text, and the UI must still recover its code from it.+ it('recovers a wrong-processor engine start from the error text', () => {+ const parsed = parseEngineError(+ new Error(+ 'Failed to start model: {"code":"UNSUPPORTED_CPU","message":"The llama.cpp engine in this Jan build does not support this computer\'s processor.","details":"Bad CPU type in executable (os error 86)"}'+ )+ )++ expect(parsed?.code).toBe('UNSUPPORTED_CPU')+ expect(parsed?.details).toBe('Bad CPU type in executable (os error 86)')+ })})describe('describeEngineError', () => {diff --git a/web-app/src/lib/engineError.ts b/web-app/src/lib/engineError.tsindex 78dbdad2e..7188b7d15 100644--- a/web-app/src/lib/engineError.ts+++ b/web-app/src/lib/engineError.ts@@ -14,6 +14,7 @@ export const ENGINE_ERROR_CODES = ['OUT_OF_MEMORY','ENGINE_STOPPED','ENGINE_UNREACHABLE',+ 'UNSUPPORTED_CPU','INVALID_ARGUMENT','IO_ERROR','INTERNAL_ERROR',diff --git a/web-app/src/locales/__tests__/localeKeys.test.ts b/web-app/src/locales/__tests__/localeKeys.test.tsindex a682a8ab3..938de237e 100644--- a/web-app/src/locales/__tests__/localeKeys.test.ts+++ b/web-app/src/locales/__tests__/localeKeys.test.ts@@ -68,6 +68,7 @@ const DYNAMIC_KEYS: Record<string, string[]> = {'engine.OUT_OF_MEMORY','engine.ENGINE_STOPPED','engine.ENGINE_UNREACHABLE',+ 'engine.UNSUPPORTED_CPU','engine.INVALID_ARGUMENT','engine.IO_ERROR','engine.INTERNAL_ERROR',diff --git a/web-app/src/locales/en/model-errors.json b/web-app/src/locales/en/model-errors.jsonindex 5109e2bbc..176481152 100644--- a/web-app/src/locales/en/model-errors.json+++ b/web-app/src/locales/en/model-errors.json@@ -18,6 +18,7 @@"OUT_OF_MEMORY": "There is not enough memory to run this model. A smaller model or a smaller context size usually helps.","ENGINE_STOPPED": "The llama.cpp engine stopped unexpectedly. Sending the message again starts it again; if it keeps stopping, security software or the GPU driver may be the cause.","ENGINE_UNREACHABLE": "The llama.cpp engine is running, but Jan cannot connect to it on this computer (127.0.0.1). A VPN, proxy or security software may be blocking local connections.",+ "UNSUPPORTED_CPU": "Local models are not supported on this computer's processor. Jan's local engine is built for Apple Silicon Macs (M1 or newer), so it cannot start on an Intel Mac. Cloud and custom providers still work.","INVALID_ARGUMENT": "One of the model's settings is not valid.","IO_ERROR": "A file could not be read or written while starting the model.","INTERNAL_ERROR": "Something went wrong inside Jan while starting the model."