Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat: patch env config

Louis05f611d21ad8
diff --git a/core/src/types/api/index.ts b/core/src/types/api/index.ts
index 6d6d1c4a6..3cdd9c0fb 100644
--- a/core/src/types/api/index.ts
+++ b/core/src/types/api/index.ts
@@ -149,6 +149,8 @@ export const CoreRoutes = [
...Object.values(ExtensionRoute),
...Object.values(FileSystemRoute),
...Object.values(FileManagerRoute),
+ 'launchClaudeCodeWithConfig',
+ 'writeEnvFileToConfig',
]
export const APIRoutes = [...CoreRoutes, ...Object.values(NativeRoute)]
diff --git a/src-tauri/src/core/server/proxy.rs b/src-tauri/src/core/server/proxy.rs
index 161cb5647..e36e69609 100644
--- a/src-tauri/src/core/server/proxy.rs
+++ b/src-tauri/src/core/server/proxy.rs
@@ -15,34 +15,6 @@ use tokio::sync::Mutex;
use crate::core::state::{AppState, ServerHandle};
-/// Unified session info that can come from either backend
-#[derive(Clone)]
-pub struct UnifiedSessionInfo {
- pub model_id: String,
- pub port: i32,
- pub api_key: String,
-}
-
-impl From<&LLamaBackendSession> for UnifiedSessionInfo {
- fn from(session: &LLamaBackendSession) -> Self {
- UnifiedSessionInfo {
- model_id: session.info.model_id.clone(),
- port: session.info.port,
- api_key: session.info.api_key.clone(),
- }
- }
-}
-
-impl From<&MlxBackendSession> for UnifiedSessionInfo {
- fn from(session: &MlxBackendSession) -> Self {
- UnifiedSessionInfo {
- model_id: session.info.model_id.clone(),
- port: session.info.port,
- api_key: session.info.api_key.clone(),
- }
- }
-}
-
/// Configuration for the proxy server
#[derive(Clone)]
pub struct ProxyConfig {
@@ -53,24 +25,6 @@ pub struct ProxyConfig {
pub port: u16,
}
-/// Remote provider info for routing requests
-#[derive(Clone, Debug)]
-pub struct RemoteProviderInfo {
- pub provider: String,
- pub base_url: String,
- pub api_key: Option<String>,
-}
-
-/// Payload for remote completion request event
-#[derive(Clone, Debug, serde::Serialize)]
-pub struct RemoteCompletionRequest {
- pub request_id: String,
- pub path: String,
- pub model: String,
- pub provider: String,
- pub body: serde_json::Value,
-}
-
/// Determines the final destination path based on the original request path
pub fn get_destination_path(original_path: &str, prefix: &str) -> String {
remove_prefix(original_path, prefix)
@@ -384,7 +338,7 @@ async fn proxy_request<R: tauri::Runtime>(
let state = app_handle.state::<AppState>();
let provider_configs = state.provider_configs.lock().await;
- // Find a provider that has this model configured
+ // Try to find a provider that has this model configured
let provider_name = provider_configs
.iter()
.find(|(_, config)| {
@@ -395,7 +349,7 @@ async fn proxy_request<R: tauri::Runtime>(
.or_else(|| {
// Try to find by provider name in model_id (e.g., "anthropic/claude-3-opus")
if let Some(sep_pos) = model_id.find('/') {
- let potential_provider = &model_id[..sep_pos];
+ let potential_provider: &str = &model_id[..sep_pos];
if provider_configs.contains_key(potential_provider) {
return Some(potential_provider.to_string());
}
@@ -406,7 +360,7 @@ async fn proxy_request<R: tauri::Runtime>(
drop(provider_configs);
- if let Some(provider) = provider_name {
+ if let Some(ref provider) = provider_name {
// Found a remote provider, stream the response directly
log::info!("Found remote provider '{provider}' for model '{model_id}'");
@@ -416,7 +370,7 @@ async fn proxy_request<R: tauri::Runtime>(
// Get the provider config
let state = app_handle.state::<AppState>();
let provider_configs = state.provider_configs.lock().await;
- let provider_config = provider_configs.get(&provider).cloned();
+ let provider_config = provider_configs.get(provider.as_str()).cloned();
// Log registered providers for debugging
log::debug!(
@@ -545,17 +499,20 @@ async fn proxy_request<R: tauri::Runtime>(
// No remote provider found, check for local session
let sessions_guard = sessions.lock().await;
+ // Use original model_id for local session lookup
+ let sessions_find_model = model_id;
+
// Check both llama.cpp and MLX sessions
let llama_session = sessions_guard
.values()
- .find(|s| s.info.model_id == model_id);
+ .find(|s| s.info.model_id == sessions_find_model);
let (mlx_session_info, mlx_count) = {
let mut mlx_session_info: Option<SessionInfo> = None;
let mut mlx_count = 0;
let mlx_guard = mlx_sessions.lock().await;
mlx_count = mlx_guard.len();
- if let Some(session) = mlx_guard.values().find(|s| s.info.model_id == model_id) {
+ if let Some(session) = mlx_guard.values().find(|s| s.info.model_id == sessions_find_model) {
// Clone just the SessionInfo since MlxBackendSession is not Clone
mlx_session_info = Some(session.info.clone());
}
diff --git a/src-tauri/src/core/server/remote_provider_commands.rs b/src-tauri/src/core/server/remote_provider_commands.rs
index 04c8bb5e1..da45d5306 100644
--- a/src-tauri/src/core/server/remote_provider_commands.rs
+++ b/src-tauri/src/core/server/remote_provider_commands.rs
@@ -1,12 +1,10 @@
use std::collections::HashMap;
use std::pin::Pin;
-use std::task::{Context, Poll};
-use futures_util::{Stream, StreamExt, TryStreamExt};
+use futures_util::{StreamExt};
use serde::{Deserialize, Serialize};
use tauri::{AppHandle, Emitter, State};
use tokio::sync::Mutex;
-use tokio_util::bytes::Bytes;
use uuid::Uuid;
use crate::core::state::{AppState, ProviderConfig};
@@ -73,28 +71,6 @@ pub struct Usage {
pub total_tokens: i32,
}
-/// Convert ChatCompletion messages to Anthropic Messages API format
-pub fn convert_messages_to_anthropic(
- messages: &[ChatMessage],
-) -> Vec<serde_json::Value> {
- messages
- .iter()
- .map(|msg| {
- let role = match msg.role.as_str() {
- "user" => "user",
- "assistant" => "assistant",
- "system" => "system",
- "tool" => "user", // Anthropic uses user for tool results
- _ => "user",
- };
- serde_json::json!({
- "role": role,
- "content": msg.content
- })
- })
- .collect()
-}
-
/// Convert OpenAI chat completions chunk to Anthropic messages format
/// OpenAI: {"id":"...","object":"chat.completion.chunk","created":...,"model":"...","choices":[{"index":0,"delta":{"role":"assistant","content":"..."},"finish_reason":null}]}
/// Anthropic: {"type":"content_block_delta","delta":{"text_type":"text_streaming","text":"..."}}
@@ -173,10 +149,14 @@ pub async fn register_provider_config(
provider: request.provider.clone(),
api_key: request.api_key,
base_url: request.base_url,
- custom_headers: request.custom_headers.into_iter().map(|h| crate::core::state::ProviderCustomHeader {
- header: h.header,
- value: h.value,
- }).collect(),
+ custom_headers: request
+ .custom_headers
+ .into_iter()
+ .map(|h| crate::core::state::ProviderCustomHeader {
+ header: h.header,
+ value: h.value,
+ })
+ .collect(),
models: request.models, // Models will be added when they are configured
};
@@ -230,7 +210,6 @@ pub async fn list_provider_configs(
/// Remote chat completion (non-streaming)
#[tauri::command]
pub async fn remote_chat_completion(
- app: AppHandle,
state: State<'_, AppState>,
request: RemoteChatCompletionRequest,
) -> Result<RemoteChatCompletionResponse, String> {
@@ -285,8 +264,13 @@ pub async fn remote_chat_completion(
// Convert to our response format
let id = response_json["id"].as_str().unwrap_or_default().to_string();
- let model = response_json["model"].as_str().unwrap_or(&request.model).to_string();
- let created = response_json["created"].as_i64().unwrap_or(chrono::Utc::now().timestamp());
+ let model = response_json["model"]
+ .as_str()
+ .unwrap_or(&request.model)
+ .to_string();
+ let created = response_json["created"]
+ .as_i64()
+ .unwrap_or(chrono::Utc::now().timestamp());
let choices: Vec<Choice> = response_json["choices"]
.as_array()
@@ -309,9 +293,18 @@ pub async fn remote_chat_completion(
let usage = if let Some(usage) = response_json["usage"].as_object() {
Some(Usage {
- prompt_tokens: usage.get("prompt_tokens").and_then(|v| v.as_i64()).unwrap_or(0) as i32,
- completion_tokens: usage.get("completion_tokens").and_then(|v| v.as_i64()).unwrap_or(0) as i32,
- total_tokens: usage.get("total_tokens").and_then(|v| v.as_i64()).unwrap_or(0) as i32,
+ prompt_tokens: usage
+ .get("prompt_tokens")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(0) as i32,
+ completion_tokens: usage
+ .get("completion_tokens")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(0) as i32,
+ total_tokens: usage
+ .get("total_tokens")
+ .and_then(|v| v.as_i64())
+ .unwrap_or(0) as i32,
})
} else {
None
@@ -353,15 +346,19 @@ pub async fn remote_chat_completion_stream(
let error_request_id = request_id.clone();
tauri::async_runtime::spawn(async move {
- let result = stream_remote_chat(&app_handle, &provider_configs, &request, &request_id_clone).await;
+ let result =
+ stream_remote_chat(&app_handle, &provider_configs, &request, &request_id_clone).await;
if let Err(e) = result {
log::error!("Remote stream error for {request_id_clone}: {e}");
// Emit error event
- let _ = app_handle.emit("remote-stream-error", serde_json::json!({
- "requestId": error_request_id,
- "error": e,
- }));
+ let _ = app_handle.emit(
+ "remote-stream-error",
+ serde_json::json!({
+ "requestId": error_request_id,
+ "error": e,
+ }),
+ );
}
});
@@ -433,20 +430,26 @@ async fn stream_remote_chat(
let data = line.trim_start_matches("data:").trim();
if data == "[DONE]" {
// Emit final event
- let _ = app.emit("remote-stream-chunk", RemoteStreamChunk {
- request_id: request_id.to_string(),
- chunk: data.to_string(),
- done: true,
- });
+ let _ = app.emit(
+ "remote-stream-chunk",
+ RemoteStreamChunk {
+ request_id: request_id.to_string(),
+ chunk: data.to_string(),
+ done: true,
+ },
+ );
return Ok(());
}
// Parse and emit the chunk
- let _ = app.emit("remote-stream-chunk", RemoteStreamChunk {
- request_id: request_id.to_string(),
- chunk: data.to_string(),
- done: false,
- });
+ let _ = app.emit(
+ "remote-stream-chunk",
+ RemoteStreamChunk {
+ request_id: request_id.to_string(),
+ chunk: data.to_string(),
+ done: false,
+ },
+ );
}
} else {
break;
@@ -455,11 +458,14 @@ async fn stream_remote_chat(
}
// Emit final event if we got here without [DONE]
- let _ = app.emit("remote-stream-chunk", RemoteStreamChunk {
- request_id: request_id.to_string(),
- chunk: "".to_string(),
- done: true,
- });
+ let _ = app.emit(
+ "remote-stream-chunk",
+ RemoteStreamChunk {
+ request_id: request_id.to_string(),
+ chunk: "".to_string(),
+ done: true,
+ },
+ );
Ok(())
}
@@ -482,7 +488,10 @@ pub async fn stream_remote_chat_for_proxy(
provider_config: &ProviderConfig,
request: &RemoteChatCompletionRequest,
endpoint: &str,
-) -> Result<Pin<Box<dyn futures_util::Stream<Item = Result<hyper::body::Bytes, std::io::Error>> + Send>>, String> {
+) -> Result<
+ Pin<Box<dyn futures_util::Stream<Item = Result<hyper::body::Bytes, std::io::Error>> + Send>>,
+ String,
+> {
let base_url = provider_config
.base_url
.clone()
@@ -545,7 +554,10 @@ pub async fn stream_remote_chat_with_format_conversion(
request: &RemoteChatCompletionRequest,
target_endpoint: &str,
output_format: &str,
-) -> Result<Pin<Box<dyn futures_util::Stream<Item = Result<hyper::body::Bytes, std::io::Error>> + Send>>, String> {
+) -> Result<
+ Pin<Box<dyn futures_util::Stream<Item = Result<hyper::body::Bytes, std::io::Error>> + Send>>,
+ String,
+> {
let base_url = provider_config
.base_url
.clone()
@@ -588,9 +600,7 @@ pub async fn stream_remote_chat_with_format_conversion(
// Convert stream with format conversion
let converted_stream = response
.bytes_stream()
- .map(move |result| {
- result.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))
- })
+ .map(move |result| result.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e)))
.map(move |result| {
// Convert bytes to string, parse JSON, convert format
match result {
@@ -615,7 +625,9 @@ pub async fn stream_remote_chat_with_format_conversion(
match serde_json::from_str::<serde_json::Value>(data) {
Ok(json) => {
if output_format == "anthropic" {
- if let Some(converted) = convert_stream_chunk(&json, &request_id, &model) {
+ if let Some(converted) =
+ convert_stream_chunk(&json, &request_id, &model)
+ {
output.push_str(&converted);
}
} else {
diff --git a/src-tauri/src/core/system/commands.rs b/src-tauri/src/core/system/commands.rs
index 253ba5671..927330359 100644
--- a/src-tauri/src/core/system/commands.rs
+++ b/src-tauri/src/core/system/commands.rs
@@ -10,6 +10,54 @@ use crate::core::app::models::AppConfiguration;
use crate::core::mcp::helpers::{stop_mcp_servers_with_context, ShutdownContext};
use crate::core::state::AppState;
+// Helper function to write env vars to zshenv
+fn write_env_to_zsh(zshenv_path: &str, env_vars: &[(String, String)], terminal_app: &str) -> Result<(), String> {
+ let marker = "# Jan Local API Server - Claude Code Config";
+ let new_entries: String = env_vars
+ .iter()
+ .map(|(k, v)| format!("export {}='{}'", k, v))
+ .collect();
+
+ let existing_content = std::fs::read_to_string(zshenv_path).unwrap_or_default();
+ let cleaned: Vec<&str> = existing_content
+ .split('\n')
+ .filter(|line| {
+ // Remove Jan config markers and existing ANTHROPIC env vars to replace them
+ !line.starts_with(marker)
+ && !line.starts_with("# Jan Local API Server")
+ && !line.starts_with("export ANTHROPIC_")
+ })
+ .collect();
+
+ let new_content = format!(
+ "{}\n{}\n{}\n",
+ marker,
+ new_entries,
+ marker
+ );
+
+ let final_content = cleaned.join("\n") + &new_content;
+ std::fs::write(zshenv_path, &final_content).map_err(|e| e.to_string())?;
+
+ if terminal_app == "Terminal" {
+ let script = r#"echo "Jan Local API Server: Env vars configured in ~/.zshenv"
+echo "Please restart your terminal or run: source ~/.zshenv"
+echo ""
+echo "Then run: claude""#;
+
+ std::process::Command::new("osascript")
+ .arg("-e")
+ .arg(&format!(
+ r#"tell application "Terminal" to do script "{}""#,
+ script.replace("\"", "\\\"")
+ ))
+ .spawn()
+ .map_err(|e| e.to_string())?;
+ }
+
+ Ok(())
+}
+
#[tauri::command]
pub fn factory_reset<R: Runtime>(app_handle: tauri::AppHandle<R>, state: State<'_, AppState>) {
// close window (not available on mobile platforms)
@@ -128,3 +176,181 @@ pub fn is_library_available(library: &str) -> bool {
}
}
}
+
+#[tauri::command]
+pub fn launch_claude_code_with_config(
+ 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<(), 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 mut env_vars: Vec<(String, String)> = Vec::with_capacity(8);
+ env_vars.push(("ANTHROPIC_BASE_URL".to_string(), api_url));
+
+ if let Some(key) = api_key {
+ env_vars.push(("ANTHROPIC_API_KEY".to_string(), key));
+ }
+
+ if let Some(model) = big_model {
+ env_vars.push(("ANTHROPIC_DEFAULT_OPUS_MODEL".to_string(), model));
+ }
+
+ if let Some(model) = medium_model {
+ env_vars.push(("ANTHROPIC_DEFAULT_SONNET_MODEL".to_string(), model));
+ }
+
+ if let Some(model) = small_model {
+ env_vars.push(("ANTHROPIC_DEFAULT_HAIKU_MODEL".to_string(), model));
+ }
+
+ // Add custom env vars from the custom CLI section
+ for env in &custom_env_vars {
+ if let (Some(key), Some(value)) = (
+ env.get("key").and_then(|v| v.as_str()),
+ env.get("value").and_then(|v| v.as_str()),
+ ) {
+ env_vars.push((key.to_string(), value.to_string()));
+ }
+ }
+
+ 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()
+ );
+
+ // Build the command environment
+ // Export environment variables to ~/.zshenv (always sourced by zsh)
+
+ if cfg!(target_os = "macos") {
+ // On macOS, write to ~/.zshenv
+ let home_dir = std::env::var("HOME").map_err(|e| e.to_string())?;
+ let zshenv_path = format!("{}/.zshenv", home_dir);
+
+ // Try direct write first
+ match std::fs::OpenOptions::new()
+ .write(true)
+ .create(true)
+ .open(&zshenv_path)
+ {
+ Ok(_) => {
+ write_env_to_zsh(&zshenv_path, &env_vars, "Terminal")?;
+ return Ok(());
+ }
+ Err(_) => {
+ // Use admin privileges to write
+ let home_dir = std::env::var("HOME").map_err(|e| e.to_string())?;
+ let zshenv_path = format!("{}/.zshenv", home_dir);
+
+ // Read and clean existing file
+ let marker = "# Jan Local API Server - Claude Code Config";
+ let existing_content = std::fs::read_to_string(&zshenv_path).unwrap_or_default();
+ let cleaned: Vec<&str> = existing_content
+ .split('\n')
+ .filter(|line| {
+ !line.starts_with(marker)
+ && !line.starts_with("# Jan Local API Server")
+ && !line.starts_with("export ANTHROPIC_")
+ })
+ .collect();
+
+ let env_content: String = env_vars
+ .iter()
+ .map(|(k, v)| format!("export {}='{}'\n", k, v))
+ .collect();
+
+ let new_block = format!(
+ "{}\n{}",
+ marker,
+ env_content
+ );
+
+ let final_content = cleaned.join("\n") + "\n" + &new_block + marker;
+
+ // Write to a temp file first, then use osascript to move it
+ let temp_script_path = format!("{}/.jan_zshenv_update.sh", home_dir);
+ std::fs::write(&temp_script_path, &final_content).map_err(|e| e.to_string())?;
+
+ // Use admin privileges to move the temp file to .zshenv
+ let script = format!(
+ r#"do shell script "cp '{}' '{}' && rm '{}' && echo 'Env vars written to ~/.zshenv'" with administrator privileges"#,
+ temp_script_path, zshenv_path, temp_script_path
+ );
+
+ std::process::Command::new("osascript")
+ .arg("-e")
+ .arg(&script)
+ .output()
+ .map_err(|e| e.to_string())?;
+
+ log::info!("Env vars written to ~/.zshenv with admin privileges");
+ return Ok(());
+ }
+ }
+ } else if cfg!(target_os = "linux") {
+ // On Linux, write to ~/.zshenv
+ let home_dir = std::env::var("HOME").map_err(|e| e.to_string())?;
+ let zshenv_path = format!("{}/.zshenv", home_dir);
+
+ // Try to write to ~/.zshenv
+ match std::fs::OpenOptions::new()
+ .write(true)
+ .create(true)
+ .open(&zshenv_path)
+ {
+ Ok(_) => {
+ write_env_to_zsh(&zshenv_path, &env_vars, "")?;
+ return Ok(());
+ }
+ Err(_) => {
+ // Return special message for frontend to show dialog
+ let jan_config_dir = format!("{}/.config/jan", home_dir);
+ let env_file = format!("{}/claude-code-env.zsh", jan_config_dir);
+ return Err(format!("NEED_PERMISSION:{}", env_file));
+ }
+ }
+ } else {
+ // On Windows, write to a batch file
+ let env_export: String = env_vars
+ .iter()
+ .map(|(k, v)| format!("set \"{}={}\"", k, v))
+ .collect();
+
+ let batch_content = format!(
+ r#"@echo off
+REM Jan Local API Server - Claude Code Config
+{}
+
+echo Run: claude
+pause
+"#,
+ env_export
+ );
+
+ let batch_file = "C:\\Users\\Public\\claude_code_env.bat";
+ std::fs::write(batch_file, &batch_content).map_err(|e| e.to_string())?;
+
+ std::process::Command::new("cmd")
+ .arg("/c")
+ .arg("start")
+ .arg("Claude Code")
+ .arg("/K")
+ .arg(format!("{} && claude", env_export))
+ .spawn()
+ .map_err(|e| e.to_string())?;
+
+ log::info!("Env vars exported. Claude Code should now use them.");
+ return Ok(());
+ }
+}
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index adbd2f9cc..b5612bfed 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -89,6 +89,7 @@ pub fn run() {
core::system::commands::factory_reset,
core::system::commands::read_logs,
core::system::commands::is_library_available,
+ core::system::commands::launch_claude_code_with_config,
// Server commands
core::server::commands::start_server,
core::server::commands::stop_server,
@@ -170,6 +171,7 @@ pub fn run() {
core::system::commands::factory_reset,
core::system::commands::read_logs,
core::system::commands::is_library_available,
+ core::system::commands::launch_claude_code_with_config,
// Server commands
core::server::commands::start_server,
core::server::commands::stop_server,
diff --git a/web-app/src/routes/settings/local-api-server.tsx b/web-app/src/routes/settings/local-api-server.tsx
index 40a2c37bb..0a35369c8 100644
--- a/web-app/src/routes/settings/local-api-server.tsx
+++ b/web-app/src/routes/settings/local-api-server.tsx
@@ -24,6 +24,7 @@ import { useEffect, useState, useMemo, useRef } from 'react'
import { toast } from 'sonner'
import { getModelToStart } from '@/utils/getModelToStart'
import { LogViewer } from '@/components/LogViewer'
+import { invoke } from '@tauri-apps/api/core'
import {
Popover,
PopoverTrigger,
@@ -34,7 +35,12 @@ import {
CollapsibleTrigger,
CollapsibleContent,
} from '@/components/ui/collapsible'
-import { IconChevronDown, IconExternalLink, IconPlus, IconX } from '@tabler/icons-react'
+import {
+ IconChevronDown,
+ IconExternalLink,
+ IconPlus,
+ IconX,
+} from '@tabler/icons-react'
import ProvidersAvatar from '@/containers/ProvidersAvatar'
import Capabilities from '@/containers/Capabilities'
import { getModelDisplayName } from '@/lib/utils'
@@ -74,7 +80,12 @@ function LocalAPIServerContent() {
const setActiveModels = useAppState((state) => state.setActiveModels)
// Helper card state (persisted to localStorage)
- const { models: helperModels, setModel: setHelperModel, setEnvVars, setCustomCli } = useClaudeCodeModel()
+ const {
+ models: helperModels,
+ setModel: setHelperModel,
+ setEnvVars,
+ setCustomCli,
+ } = useClaudeCodeModel()
const [isCustomCliDialogOpen, setIsCustomCliDialogOpen] = useState(false)
useEffect(() => {
@@ -247,25 +258,62 @@ function LocalAPIServerContent() {
}
}
+ const handleLaunchClaudeCode = async () => {
+ // Do not append apiPrefix to claude code settings
+ const apiUrl = `http://${serverHost}:${serverPort}`
+ const modelBig = helperModels.big
+ const modelMedium = helperModels.medium
+ const modelSmall = helperModels.small
+ const customEnvVars = helperModels.envVars
+
+ try {
+ // Try to write directly to ~/.zshenv
+ await invoke('launch_claude_code_with_config', {
+ apiUrl,
+ apiKey: apiKey || undefined,
+ bigModel: modelBig || undefined,
+ mediumModel: modelMedium || undefined,
+ smallModel: modelSmall || undefined,
+ customEnvVars: customEnvVars.map((env) => ({
+ key: env.key,
+ value: env.value,
+ })),
+ })
+ toast.success(
+ 'Environment variables updated. Please try relaunching Claude Code in a new terminal window.',
+ {
+ duration: 8000,
+ }
+ )
+ } catch (error) {
+ console.error('Failed to launch Claude Code:', error)
+ const errorMsg = error instanceof Error ? error.message : String(error)
+ toast.error('Failed to configure env vars', {
+ description: errorMsg,
+ })
+ }
+ }
+
const isServerRunning = serverStatus !== 'stopped'
return (
<div className="flex flex-col h-svh w-full">
<HeaderPage>
<div className="flex items-center justify-between w-full mr-2 pr-4">
- <span className='font-medium text-base font-studio'>{t('common:settings')}</span>
+ <span className="font-medium text-base font-studio">
+ {t('common:settings')}
+ </span>
<Popover>
<PopoverTrigger asChild>
- <Button
- size="sm"
- variant="outline"
- className="relative z-50"
- >
+ <Button size="sm" variant="outline" className="relative z-50">
<IconSettings2 size={16} />
Configuration
</Button>
</PopoverTrigger>
- <PopoverContent align='end' className="w-[480px] max-h-[70vh] overflow-y-auto">
+ <PopoverContent
+ align="end"
+ className="w-[480px] max-h-[70vh] overflow-y-auto"
+ >
<div className="space-y-4">
<div className="flex items-center justify-between border-b pb-2">
<h2 className="font-semibold text-sm">
@@ -275,31 +323,46 @@ function LocalAPIServerContent() {
<div className="space-y-3">
<div className="flex items-center justify-between">
<div className="space-y-0.5">
- <p className="text-sm font-medium">{t('settings:localApiServer.serverHost')}</p>
- <p className="text-xs text-muted-foreground">{t('settings:localApiServer.serverHostDesc')}</p>
+ <p className="text-sm font-medium">
+ {t('settings:localApiServer.serverHost')}
+ </p>
+ <p className="text-xs text-muted-foreground">
+ {t('settings:localApiServer.serverHostDesc')}
+ </p>
</div>
<div>
-
- <ServerHostSwitcher isServerRunning={isServerRunning} />
+ <ServerHostSwitcher isServerRunning={isServerRunning} />
</div>
</div>
<div className="flex items-center justify-between">
<div className="space-y-0.5">
- <p className="text-sm font-medium">{t('settings:localApiServer.serverPort')}</p>
- <p className="text-xs text-muted-foreground">{t('settings:localApiServer.serverPortDesc')}</p>
+ <p className="text-sm font-medium">
+ {t('settings:localApiServer.serverPort')}
+ </p>
+ <p className="text-xs text-muted-foreground">
+ {t('settings:localApiServer.serverPortDesc')}
+ </p>
</div>
<PortInput isServerRunning={isServerRunning} />
</div>
<div className="flex items-center justify-between">
<div className="space-y-0.5">
- <p className="text-sm font-medium">{t('settings:localApiServer.apiPrefix')}</p>
- <p className="text-xs text-muted-foreground">{t('settings:localApiServer.apiPrefixDesc')}</p>
+ <p className="text-sm font-medium">
+ {t('settings:localApiServer.apiPrefix')}
+ </p>
+ <p className="text-xs text-muted-foreground">
+ {t('settings:localApiServer.apiPrefixDesc')}
+ </p>
</div>
<ApiPrefixInput isServerRunning={isServerRunning} />
</div>
<div className="flex flex-col space-y-1">
- <p className="text-sm font-medium">{t('settings:localApiServer.apiKey')}</p>
- <p className="text-xs text-muted-foreground">{t('settings:localApiServer.apiKeyDesc')}</p>
+ <p className="text-sm font-medium">
+ {t('settings:localApiServer.apiKey')}
+ </p>
+ <p className="text-xs text-muted-foreground">
+ {t('settings:localApiServer.apiKeyDesc')}
+ </p>
<div className="pt-1">
<ApiKeyInput
isServerRunning={isServerRunning}
@@ -309,16 +372,24 @@ function LocalAPIServerContent() {
</div>
</div>
<div className="flex flex-col space-y-1">
- <p className="text-sm font-medium">{t('settings:localApiServer.trustedHosts')}</p>
- <p className="text-xs text-muted-foreground">{t('settings:localApiServer.trustedHostsDesc')}</p>
+ <p className="text-sm font-medium">
+ {t('settings:localApiServer.trustedHosts')}
+ </p>
+ <p className="text-xs text-muted-foreground">
+ {t('settings:localApiServer.trustedHostsDesc')}
+ </p>
<div className="pt-1">
<TrustedHostsInput isServerRunning={isServerRunning} />
</div>
</div>
<div className="flex items-center justify-between">
<div className="space-y-0.5">
- <p className="text-sm font-medium">{t('settings:localApiServer.proxyTimeout')}</p>
- <p className="text-xs text-muted-foreground">{t('settings:localApiServer.proxyTimeoutDesc')}</p>
+ <p className="text-sm font-medium">
+ {t('settings:localApiServer.proxyTimeout')}
+ </p>
+ <p className="text-xs text-muted-foreground">
+ {t('settings:localApiServer.proxyTimeoutDesc')}
+ </p>
</div>
<ProxyTimeoutInput isServerRunning={isServerRunning} />
</div>
@@ -332,8 +403,12 @@ function LocalAPIServerContent() {
<div className="space-y-3">
<div className="flex items-center justify-between">
<div className="space-y-0.5">
- <p className="text-sm font-medium">{t('settings:localApiServer.cors')}</p>
- <p className="text-xs text-muted-foreground">{t('settings:localApiServer.corsDesc')}</p>
+ <p className="text-sm font-medium">
+ {t('settings:localApiServer.cors')}
+ </p>
+ <p className="text-xs text-muted-foreground">
+ {t('settings:localApiServer.corsDesc')}
+ </p>
</div>
<Switch
checked={corsEnabled}
@@ -343,8 +418,12 @@ function LocalAPIServerContent() {
</div>
<div className="flex items-center justify-between">
<div className="space-y-0.5">
- <p className="text-sm font-medium">{t('settings:localApiServer.verboseLogs')}</p>
- <p className="text-xs text-muted-foreground">{t('settings:localApiServer.verboseLogsDesc')}</p>
+ <p className="text-sm font-medium">
+ {t('settings:localApiServer.verboseLogs')}
+ </p>
+ <p className="text-xs text-muted-foreground">
+ {t('settings:localApiServer.verboseLogsDesc')}
+ </p>
</div>
<Switch
checked={verboseLogs}
@@ -414,11 +493,12 @@ function LocalAPIServerContent() {
<div className="space-y-1">
<div>The server is currently running.</div>
<div className="text-xs font-mono">
- http://{serverHost}:{serverPort}{apiPrefix}
+ http://{serverHost}:{serverPort}
+ {apiPrefix}
</div>
</div>
) : (
- "The server is stopped."
+ 'The server is stopped.'
)
}
/>
@@ -431,7 +511,9 @@ function LocalAPIServerContent() {
href={`http://${serverHost}:${serverPort}`}
target="_blank"
rel="noopener noreferrer"
- className={cn(isServerRunning ? '' : 'pointer-events-none')}
+ className={cn(
+ isServerRunning ? '' : 'pointer-events-none'
+ )}
>
<Button
variant="outline"
@@ -447,11 +529,11 @@ function LocalAPIServerContent() {
</Card>
{/* Helper Card */}
- <Card title='Run with your Claude Code'>
+ <Card title="Run with your Claude Code">
<CardItem
title="Large Model"
description="Opus"
- actions ={
+ actions={
<HelperModelSelector
providers={providers}
activeModels={activeModels}
@@ -464,7 +546,7 @@ function LocalAPIServerContent() {
<CardItem
title="Medium Model"
description="Sonnet"
- actions ={
+ actions={
<HelperModelSelector
providers={providers}
activeModels={activeModels}
@@ -477,7 +559,7 @@ function LocalAPIServerContent() {
<CardItem
title="Small Model"
description="Haiku"
- actions ={
+ actions={
<HelperModelSelector
providers={providers}
activeModels={activeModels}
@@ -487,16 +569,23 @@ function LocalAPIServerContent() {
/>
}
/>
- <div className='flex mt-2 justify-between gap-2'>
- <Button size="sm" variant="outline" onClick={() => setIsCustomCliDialogOpen(true)}>
- <IconPlus className='text-muted-foreground' size={14} />
+ <div className="flex mt-2 justify-between gap-2">
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => setIsCustomCliDialogOpen(true)}
+ >
+ <IconPlus className="text-muted-foreground" size={14} />
Custom CLI
</Button>
- <Button size="sm">Launch claude code</Button>
+ <Button size="sm" onClick={handleLaunchClaudeCode}>
+ Enable Jan in Claude Code
+ </Button>
</div>
{/* Display Custom CLI Configuration */}
- {(helperModels.customCli || helperModels.envVars.length > 0) && (
+ {(helperModels.customCli ||
+ helperModels.envVars.length > 0) && (
<div className="mt-3 text-sm text-muted-foreground">
{helperModels.customCli && (
<div>Command: {helperModels.customCli}</div>
@@ -504,7 +593,9 @@ function LocalAPIServerContent() {
{helperModels.envVars.length > 0 && (
<div className="break-all">
Env:{' '}
- {helperModels.envVars.map((env) => `${env.key}=******`).join(', ')}
+ {helperModels.envVars
+ .map((env) => `${env.key}=******`)
+ .join(', ')}
</div>
)}
</div>
@@ -524,7 +615,7 @@ function LocalAPIServerContent() {
/>
<div className="p-4 shrink-0">
<Card>
- <Collapsible defaultOpen={false} >
+ <Collapsible defaultOpen={false}>
<div className="flex items-center justify-between">
<CollapsibleTrigger className="flex items-center gap-2 hover:no-underline">
<IconChevronDown
@@ -625,13 +716,9 @@ function HelperModelSelector({
}, [filteredModels])
const currentModel = availableModels.find(
- (m) => `${m.providerName}:${m.id}` === selectedModel
+ (m) => m.id === selectedModel
)
- const currentProvider = currentModel
- ? providers.find((p) => p.provider === currentModel.providerName)
- : null
-
// Format model display name with size
const formatModelWithSize = (model: NonNullable<typeof currentModel>) => {
const name = getModelDisplayName(model)
@@ -640,8 +727,8 @@ function HelperModelSelector({
return name
}
- const handleSelect = (model: typeof filteredModels[0]) => {
- onSelect(`${model.providerName}:${model.id}`)
+ const handleSelect = (model: (typeof filteredModels)[0]) => {
+ onSelect(model.id)
setOpen(false)
setSearchValue('')
}
@@ -658,16 +745,7 @@ function HelperModelSelector({
return (
<Popover open={open} onOpenChange={handleOpenChange}>
<PopoverTrigger asChild>
- <Button
- variant="outline"
- size="sm"
- className='max-w-[280px]'
- >
- {currentProvider && (
- <div className="shrink-0">
- <ProvidersAvatar provider={currentProvider} />
- </div>
- )}
+ <Button variant="outline" size="sm" className="max-w-[280px]">
<span
className={cn(
'text-foreground truncate leading-normal',
@@ -737,19 +815,19 @@ function HelperModelSelector({
{/* Models for this provider */}
{models.map((model) => {
- const isSelected =
- selectedModel === `${model.providerName}:${model.id}`
+ const isSelected = selectedModel === model.id
const capabilities = model.capabilities || []
return (
<div
- key={`${model.providerName}:${model.id}`}
+ key={model.id}
title={model.id}
onClick={() => handleSelect(model)}
className={cn(
'mx-1 mb-1 px-2 py-1.5 rounded-sm cursor-pointer flex items-center gap-2 transition-all duration-200',
'hover:bg-secondary/40',
- isSelected && 'bg-secondary/60 hover:bg-secondary/60'
+ isSelected &&
+ 'bg-secondary/60 hover:bg-secondary/60'
)}
>
<div className="flex items-center gap-2 flex-1 min-w-0">