Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(server): map address-in-use bind failure to actionable message
thinhlpga13dd766b125
diff --git a/src-tauri/src/core/server/proxy.rs b/src-tauri/src/core/server/proxy.rsindex 7c56b8c7d..e4ddfca14 100644--- a/src-tauri/src/core/server/proxy.rs+++ b/src-tauri/src/core/server/proxy.rs@@ -2287,6 +2287,27 @@ fn is_insecure_public_bind(host: &str, api_key: &str) -> bool {!is_loopback && api_key.is_empty()}+/// Convert a TCP bind failure into a user-facing message. Address-in-use+/// (Windows error 10048 / WSAEADDRINUSE, Unix EADDRINUSE) almost always means+/// a leftover Jan process or another service still owns the port after a+/// restart, so name the port and the remedy instead of surfacing a bare OS+/// errno. Any other error is passed through unchanged.+fn map_bind_error(+ addr: SocketAddr,+ err: std::io::Error,+) -> Box<dyn std::error::Error + Send + Sync> {+ if err.kind() == std::io::ErrorKind::AddrInUse {+ let msg = format!(+ "Port {port} ({addr}) is already in use. A previous Jan process may still be \+ running or another application may be using the port. Close the leftover \+ process and try again, or pick a different port in Settings > Local API Server.",+ port = addr.port()+ );+ return msg.into();+ }+ Box::new(err)+}+pub(crate) fn add_cors_headers_with_host_and_origin(builder: hyper::http::response::Builder,_host: &str,@@ -2419,7 +2440,7 @@ async fn start_server_internal(Ok(l) => l,Err(e) => {log::error!("Failed to bind to {addr}: {e}");- return Err(Box::new(e));+ return Err(map_bind_error(addr, e));}};log::info!("Jan API server started on http://{addr}");@@ -2907,7 +2928,8 @@ async fn forward_non_streaming(#[cfg(test)]mod tests {- use super::is_insecure_public_bind;+ use super::{is_insecure_public_bind, map_bind_error};+ use std::net::SocketAddr;#[test]fn loopback_never_warns() {@@ -2928,4 +2950,24 @@ mod tests {assert!(!is_insecure_public_bind("0.0.0.0", "secret"));assert!(!is_insecure_public_bind("192.168.1.10", "secret"));}++ #[test]+ fn addr_in_use_maps_to_actionable_message() {+ let addr: SocketAddr = "127.0.0.1:1337".parse().unwrap();+ let err = std::io::Error::new(std::io::ErrorKind::AddrInUse, "Address already in use");+ let msg = map_bind_error(addr, err).to_string();+ assert!(msg.contains("1337"), "should name the port: {msg}");+ assert!(+ msg.contains("already in use") && msg.contains("process"),+ "should explain the leftover-process remedy: {msg}"+ );+ }++ #[test]+ fn non_addr_in_use_error_passes_through() {+ let addr: SocketAddr = "127.0.0.1:1337".parse().unwrap();+ let err = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "denied");+ let msg = map_bind_error(addr, err).to_string();+ assert!(msg.contains("denied"), "should keep the original error: {msg}");+ }}diff --git a/src-tauri/src/core/system/commands.rs b/src-tauri/src/core/system/commands.rsindex 73b39914e..f66baa170 100644--- a/src-tauri/src/core/system/commands.rs+++ b/src-tauri/src/core/system/commands.rs@@ -405,19 +405,47 @@ pub fn launch_claude_code_with_config(small_model: Option<String>,custom_env_vars: Vec<serde_json::Value>,) -> Result<(), String> {- // Clone values for logging before moving- let api_url_log = api_url.clone();- let big_model_log = big_model.clone();- let medium_model_log = medium_model.clone();- let small_model_log = small_model.clone();+ let env_vars = build_claude_code_env_vars(+ api_url,+ api_key,+ big_model,+ medium_model,+ small_model,+ custom_env_vars,+ )?;++ // Claude Code talks to Jan's local API server, which authenticates inbound+ // requests against its own key (the proxy_api_key). ANTHROPIC_AUTH_TOKEN+ // MUST therefore be the local server key, and there is no valid placeholder:+ // anything else reaches the proxy, passes its key check, and then gets+ // rejected by the remote provider as a bogus credential (an opaque 403).+ // Refuse to launch with a clear message rather than ship a fake key.+ write_claude_code_env_vars(&env_vars)+}++/// Build the environment variable map for the Claude Code integration.+/// Returns an error if no local API key is set, since the proxy will not+/// authenticate the session otherwise.+fn build_claude_code_env_vars(+ api_url: String,+ api_key: Option<String>,+ big_model: Option<String>,+ medium_model: Option<String>,+ small_model: Option<String>,+ custom_env_vars: Vec<serde_json::Value>,+) -> Result<Vec<(String, String)>, String> {+ let token = api_key+ .filter(|k| !k.trim().is_empty())+ .ok_or_else(|| {+ "No local API key is set. Open Settings > Local API Server, set an API key, \+ and try again: Claude Code needs a real key to authenticate with the local \+ server and reach remote models."+ .to_string()+ })?;let mut env_vars: Vec<(String, String)> = Vec::with_capacity(8);env_vars.push(("ANTHROPIC_BASE_URL".to_string(), api_url));-- env_vars.push((- "ANTHROPIC_AUTH_TOKEN".to_string(),- api_key.unwrap_or_else(|| "jan".to_string()),- ));+ env_vars.push(("ANTHROPIC_AUTH_TOKEN".to_string(), token));if let Some(model) = big_model {env_vars.push(("ANTHROPIC_DEFAULT_OPUS_MODEL".to_string(), model));@@ -441,15 +469,14 @@ pub fn launch_claude_code_with_config(}}- log::info!(- "Launching Claude Code with API URL: {}, models: opus={:?}, sonnet={:?}, haiku={:?}, custom_envs={}",- api_url_log,- big_model_log,- medium_model_log,- small_model_log,- custom_env_vars.len()- );+ Ok(env_vars)+}+/// Persist the Claude Code environment variables to the user's shell config+/// (macOS/Linux) or the Windows registry, then return the result.+fn write_claude_code_env_vars(+ env_vars: &[(String, String)],+) -> Result<(), String> {// Build the command environment// Export environment variables to the user's shell config file@@ -470,7 +497,7 @@ pub fn launch_claude_code_with_config(.open(&env_file_path){Ok(_) => {- write_env_to_shell(&env_file_path, &env_vars)?;+ write_env_to_shell(&env_file_path, env_vars)?;Ok(())}Err(_) => {@@ -534,7 +561,7 @@ pub fn launch_claude_code_with_config(.open(&env_file_path){Ok(_) => {- write_env_to_shell(&env_file_path, &env_vars)?;+ write_env_to_shell(&env_file_path, env_vars)?;Ok(())}Err(_) => {@@ -546,7 +573,7 @@ pub fn launch_claude_code_with_config(}} else {// On Windows, set persistent user environment variables using setx- for (key, value) in &env_vars {+ for (key, value) in env_vars {let output = std::process::Command::new("setx").arg(key).arg(value)@@ -1167,4 +1194,61 @@ mod tests {"/home/user/.local/share/jan")));}+ #[test]+ fn claude_code_env_uses_real_token_when_set() {+ let env = build_claude_code_env_vars(+ "http://127.0.0.1:1337".to_string(),+ Some("sk-real-secret".to_string()),+ None,+ None,+ None,+ vec![],+ )+ .unwrap();+ let token = env+ .iter()+ .find(|(k, _)| k == "ANTHROPIC_AUTH_TOKEN")+ .map(|(_, v)| v.as_str())+ .unwrap();+ assert_eq!(token, "sk-real-secret");+ assert!(env+ .iter()+ .all(|(_, v)| v != "jan"),+ "placeholder must never be shipped as a token");+ }++ #[test]+ fn claude_code_env_rejects_missing_key() {+ let err = build_claude_code_env_vars(+ "http://127.0.0.1:1337".to_string(),+ None,+ None,+ None,+ None,+ vec![],+ )+ .unwrap_err();+ assert!(+ err.contains("API key"),+ "should tell the user a local API key is required: {err}"+ );+ }++ #[test]+ fn claude_code_env_rejects_blank_key() {+ let err = build_claude_code_env_vars(+ "http://127.0.0.1:1337".to_string(),+ Some(" ".to_string()),+ None,+ None,+ None,+ vec![],+ )+ .unwrap_err();+ assert!(+ err.contains("API key"),+ "a whitespace-only key is not a real credential: {err}"+ );+ }}+