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: add cli support

Louis10d9649fb595
diff --git a/mlx-server/Sources/MLXServer/MLXServerCommand.swift b/mlx-server/Sources/MLXServer/MLXServerCommand.swift
index f4f6871ff..fdfaff465 100644
--- a/mlx-server/Sources/MLXServer/MLXServerCommand.swift
+++ b/mlx-server/Sources/MLXServer/MLXServerCommand.swift
@@ -22,6 +22,9 @@ struct MLXServerCommand: AsyncParsableCommand {
@Option(name: .long, help: "API key for authentication (optional)")
var apiKey: String = ""
+ @Option(name: .long, help: "Model ID reported by the API (defaults to parent directory name)")
+ var modelId: String = ""
+
func run() async throws {
// Set GPU memory limit to prevent OOM issues
Memory.cacheLimit = 20 * 1024 * 1024 // 20GB limit
@@ -33,9 +36,11 @@ struct MLXServerCommand: AsyncParsableCommand {
log("[mlx] Context size: \(ctxSize)")
log("[mlx] Memory cache limit: \(Memory.cacheLimit / (1024 * 1024))MB")
- // Extract model ID from path
+ // Resolve model ID: use --model-id if provided, otherwise derive from parent directory
let modelURL = URL(fileURLWithPath: model)
- let modelId = modelURL.deletingPathExtension().lastPathComponent
+ let resolvedModelId = modelId.isEmpty
+ ? modelURL.deletingPathExtension().lastPathComponent
+ : modelId
// Load the model
let modelRunner = ModelRunner()
@@ -50,7 +55,7 @@ struct MLXServerCommand: AsyncParsableCommand {
// Set up the HTTP server
let server = MLXHTTPServer(
modelRunner: modelRunner,
- modelId: modelId,
+ modelId: resolvedModelId,
apiKey: apiKey
)
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index e57ebdffa..61ad08795 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -8,11 +8,21 @@ repository = "https://github.com/janhq/jan"
edition = "2021"
rust-version = "1.77.2"
resolver = "2"
+default-run = "jan-app"
[lib]
name = "app_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
+[[bin]]
+name = "jan"
+path = "src/bin/jan.rs"
+required-features = ["cli"]
+
+[[bin]]
+name = "jan-app"
+path = "src/main.rs"
+
[features]
default = [
"tauri/wry",
@@ -50,6 +60,7 @@ test-tauri = [
"tauri/test",
"desktop",
]
+cli = ["dep:clap", "dep:env_logger", "dep:dialoguer", "dep:indicatif", "dep:console", "dep:reqwest"]
[build-dependencies]
tauri-build = { version = "2.0.2", features = [] }
@@ -114,7 +125,12 @@ hostname = "0.4"
base64 = "0.22"
tokio-tungstenite = { version = "0.24", features = ["native-tls"] }
glob = "0.3"
-clap = { version = "4.5", features = ["derive"] }
+clap = { version = "4", features = ["derive"], optional = true }
+dialoguer = { version = "0.11", optional = true }
+env_logger = { version = "0.11", optional = true }
+indicatif = { version = "0.17", optional = true }
+console = { version = "0.15", optional = true }
+reqwest = { version = "0.12", features = ["json", "stream"], optional = true }
bollard = { version = "0.18", optional = true }
[dependencies.tauri]
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs
index 9d9b7373c..8941dc2a6 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs
@@ -3,11 +3,12 @@ use hmac::{Hmac, Mac};
use sha2::Sha256;
use std::collections::HashMap;
use std::process::Stdio;
+use std::sync::Arc;
use std::time::Duration;
use tauri::{Manager, Runtime, State};
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::process::Command;
-use tokio::sync::mpsc;
+use tokio::sync::{mpsc, Mutex};
use tokio::time::Instant;
use crate::args::{ArgumentBuilder, LlamacppConfig};
@@ -37,10 +38,9 @@ pub struct UnloadResult {
error: Option<String>,
}
-/// Load a llama model and start the server
-#[tauri::command]
-pub async fn load_llama_model<R: Runtime>(
- app_handle: tauri::AppHandle<R>,
+/// Core model loading logic usable without an AppHandle (CLI / test support).
+pub async fn load_llama_model_impl(
+ process_map_arc: Arc<Mutex<HashMap<i32, LLamaBackendSession>>>,
backend_path: &str,
model_id: String,
model_path: String,
@@ -51,8 +51,7 @@ pub async fn load_llama_model<R: Runtime>(
is_embedding: bool,
timeout: u64,
) -> ServerResult<SessionInfo> {
- let state: State<LlamacppState> = app_handle.state();
- let mut process_map = state.llama_server_process.lock().await;
+ let mut process_map = process_map_arc.lock().await;
log::info!("Attempting to launch server at path: {:?}", backend_path);
log::info!("Using configuration: {:?}", config);
@@ -279,6 +278,36 @@ pub async fn load_llama_model<R: Runtime>(
Ok(session_info)
}
+/// Load a llama model and start the server
+#[tauri::command]
+pub async fn load_llama_model<R: Runtime>(
+ app_handle: tauri::AppHandle<R>,
+ backend_path: &str,
+ model_id: String,
+ model_path: String,
+ port: u16,
+ config: LlamacppConfig,
+ envs: HashMap<String, String>,
+ mmproj_path: Option<String>,
+ is_embedding: bool,
+ timeout: u64,
+) -> ServerResult<SessionInfo> {
+ let state: State<LlamacppState> = app_handle.state();
+ load_llama_model_impl(
+ state.llama_server_process.clone(),
+ backend_path,
+ model_id,
+ model_path,
+ port,
+ config,
+ envs,
+ mmproj_path,
+ is_embedding,
+ timeout,
+ )
+ .await
+}
+
/// Unload a llama model by terminating its process
#[tauri::command]
pub async fn unload_llama_model<R: Runtime>(
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs
index 8242591a3..cffb4bae5 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/lib.rs
@@ -13,8 +13,10 @@ mod gguf;
mod path;
mod process;
pub mod state;
+pub use args::LlamacppConfig;
pub use cleanup::cleanup_llama_processes;
-pub use state::LLamaBackendSession;
+pub use commands::load_llama_model_impl;
+pub use state::{LLamaBackendSession, LlamacppState};
/// Initializes the plugin.
pub fn init<R: Runtime>() -> TauriPlugin<R> {
diff --git a/src-tauri/plugins/tauri-plugin-mlx/src/commands.rs b/src-tauri/plugins/tauri-plugin-mlx/src/commands.rs
index c99299bea..2972416a8 100644
--- a/src-tauri/plugins/tauri-plugin-mlx/src/commands.rs
+++ b/src-tauri/plugins/tauri-plugin-mlx/src/commands.rs
@@ -1,11 +1,12 @@
use std::collections::HashMap;
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
use std::process::Stdio;
+use std::sync::Arc;
use std::time::Duration;
use tauri::{Manager, Runtime, State};
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::process::Command;
-use tokio::sync::mpsc;
+use tokio::sync::{mpsc, Mutex};
use tokio::time::Instant;
use crate::error::{ErrorCode, MlxError, ServerError, ServerResult};
@@ -31,10 +32,12 @@ pub struct MlxConfig {
pub ctx_size: i32,
}
-/// Load a model using the MLX server binary
-#[tauri::command]
-pub async fn load_mlx_model<R: Runtime>(
- app_handle: tauri::AppHandle<R>,
+/// Core model-loading logic, decoupled from Tauri AppHandle.
+/// `binary_path` must point to the mlx-server executable.
+/// `process_map_arc` is the shared session map from MlxState.
+pub async fn load_mlx_model_impl(
+ process_map_arc: Arc<Mutex<HashMap<i32, MlxBackendSession>>>,
+ binary_path: &Path,
model_id: String,
model_path: String,
port: u16,
@@ -43,21 +46,13 @@ pub async fn load_mlx_model<R: Runtime>(
is_embedding: bool,
timeout: u64,
) -> ServerResult<SessionInfo> {
- let state: State<MlxState> = app_handle.state();
- let mut process_map = state.mlx_server_process.lock().await;
-
- // Resolve binary path from app resources
- let binary_path = app_handle
- .path()
- .resource_dir()
- .map_err(|e| MlxError::new(ErrorCode::BinaryNotFound, "Failed to get resource dir".to_string(), Some(e.to_string())))?
- .join("resources/bin/mlx-server");
+ let mut process_map = process_map_arc.lock().await;
log::info!("Attempting to launch MLX server at path: {:?}", binary_path);
log::info!("Using MLX configuration: {:?}", config);
// Validate binary path
- let bin_path = PathBuf::from(&binary_path);
+ let bin_path = PathBuf::from(binary_path);
if !bin_path.exists() {
return Err(MlxError::new(
ErrorCode::BinaryNotFound,
@@ -92,6 +87,8 @@ pub async fn load_mlx_model<R: Runtime>(
model_path.clone(),
"--port".to_string(),
port.to_string(),
+ "--model-id".to_string(),
+ model_id.clone(),
];
if config.ctx_size > 0 {
@@ -278,6 +275,44 @@ pub async fn load_mlx_model<R: Runtime>(
Ok(session_info)
}
+/// Load a model using the MLX server binary (Tauri command wrapper)
+#[tauri::command]
+pub async fn load_mlx_model<R: Runtime>(
+ app_handle: tauri::AppHandle<R>,
+ model_id: String,
+ model_path: String,
+ port: u16,
+ config: MlxConfig,
+ envs: HashMap<String, String>,
+ is_embedding: bool,
+ timeout: u64,
+) -> ServerResult<SessionInfo> {
+ let state: State<MlxState> = app_handle.state();
+ let binary_path = app_handle
+ .path()
+ .resource_dir()
+ .map_err(|e| {
+ MlxError::new(
+ ErrorCode::BinaryNotFound,
+ "Failed to get resource dir".to_string(),
+ Some(e.to_string()),
+ )
+ })?
+ .join("resources/bin/mlx-server");
+ load_mlx_model_impl(
+ state.mlx_server_process.clone(),
+ &binary_path,
+ model_id,
+ model_path,
+ port,
+ config,
+ envs,
+ is_embedding,
+ timeout,
+ )
+ .await
+}
+
/// Unload an MLX model by terminating its process
#[tauri::command]
pub async fn unload_mlx_model<R: Runtime>(
diff --git a/src-tauri/plugins/tauri-plugin-mlx/src/lib.rs b/src-tauri/plugins/tauri-plugin-mlx/src/lib.rs
index 1f28c535a..344593c6f 100644
--- a/src-tauri/plugins/tauri-plugin-mlx/src/lib.rs
+++ b/src-tauri/plugins/tauri-plugin-mlx/src/lib.rs
@@ -10,6 +10,8 @@ mod process;
pub mod state;
pub use cleanup::cleanup_mlx_processes;
+pub use commands::{load_mlx_model_impl, MlxConfig};
+pub use state::MlxState;
/// Initializes the MLX plugin.
pub fn init<R: Runtime>() -> TauriPlugin<R> {
diff --git a/src-tauri/src/bin/jan.rs b/src-tauri/src/bin/jan.rs
new file mode 100644
index 000000000..d8e245360
--- /dev/null
+++ b/src-tauri/src/bin/jan.rs
@@ -0,0 +1,1068 @@
+//! jan — headless CLI for Jan.
+//!
+//! Shares all core logic with the Jan desktop app.
+//! Build with: cargo build --features cli --bin jan
+
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use clap::{Args, CommandFactory, FromArgMatches, Parser, Subcommand};
+use console::Style;
+use indicatif::{ProgressBar, ProgressStyle};
+
+// Import the library crate so we can access core modules.
+// The lib target is named "app_lib" (see [lib] section in Cargo.toml).
+use app_lib::core::cli::{
+ cli_delete_thread, cli_get_config, cli_get_data_folder, cli_get_thread,
+ cli_list_messages, cli_list_threads, discover_llamacpp_binary,
+ discover_mlx_binary, download_hf_model, fetch_hf_gguf_files, init_llamacpp_state,
+ init_mlx_state, list_models, load_llama_model_impl, load_mlx_model_impl,
+ looks_like_hf_repo, resolve_model_by_id, resolve_model_engine, HfFileInfo,
+ LlamacppConfig, MlxConfig,
+};
+use std::path::PathBuf;
+
+// ── Top-level CLI ──────────────────────────────────────────────────────────
+
+#[derive(Parser)]
+#[command(
+ name = "jan",
+ about = "Serve local AI models and wire them to agents — no cloud required",
+ long_about = "Jan runs local AI models (LlamaCPP / MLX) and exposes them via an\n\
+OpenAI-compatible API, then wires AI coding agents like Claude Code or opencode\n\
+directly to your own hardware — no cloud account, no usage fees, full privacy.\n\n\
+Models downloaded in the Jan desktop app are automatically available here.",
+ after_help = "Examples:\n \
+ jan launch claude # pick a model, then run Claude Code against it\n \
+ jan launch claude --model qwen3.5-35b-a3b # use a specific model\n \
+ jan launch opencode --model qwen3.5-35b-a3b # wire opencode to a local model\n \
+ jan serve qwen3.5-35b-a3b # expose a model at localhost:6767/v1\n \
+ jan serve qwen3.5-35b-a3b --fit # auto-fit context to available VRAM\n \
+ jan serve qwen3.5-35b-a3b --detach # run in the background\n \
+ jan models list # show all installed models",
+ version
+)]
+struct Cli {
+ #[command(subcommand)]
+ command: Commands,
+}
+
+#[derive(Subcommand)]
+enum Commands {
+ /// Load a local model and expose it at localhost:6767/v1 (auto-detects LlamaCPP or MLX)
+ #[command(display_order = 1)]
+ Serve {
+ #[command(flatten)]
+ args: ServeArgs,
+ },
+ /// Start a local model, then launch an AI agent with it pre-wired (env vars set automatically)
+ #[command(display_order = 2)]
+ Launch {
+ /// Agent or program to run after the model is ready (e.g. claude, opencode)
+ program: String,
+ /// Arguments forwarded to the program
+ #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
+ program_args: Vec<String>,
+ /// Model ID to load (omit to pick interactively)
+ #[arg(long)]
+ model: Option<String>,
+ /// Port the model server listens on
+ #[arg(long, default_value_t = 6767)]
+ port: u16,
+ /// API key for the model server (exported as OPENAI_API_KEY and ANTHROPIC_AUTH_TOKEN)
+ #[arg(long, default_value = "jan")]
+ api_key: String,
+ /// GPU layers to offload (-1 = all layers, 0 = CPU only)
+ #[arg(long, default_value_t = -1)]
+ n_gpu_layers: i32,
+ /// Context window size in tokens (0 = model default)
+ #[arg(long, default_value_t = 4096)]
+ ctx_size: i32,
+ /// Auto-fit context to available VRAM (default: on when launching claude)
+ #[arg(long)]
+ fit: Option<bool>,
+ },
+ /// List and inspect conversation threads saved by the Jan app
+ #[command(display_order = 10)]
+ Threads {
+ #[command(subcommand)]
+ cmd: ThreadsCommands,
+ },
+ /// List and load models installed in the Jan data folder
+ #[command(display_order = 11)]
+ Models {
+ #[command(subcommand)]
+ cmd: ModelsCommands,
+ },
+ /// Show app configuration and data folder location
+ #[command(display_order = 12)]
+ App {
+ #[command(subcommand)]
+ cmd: AppCommands,
+ },
+}
+
+
+// ── Threads subcommands ────────────────────────────────────────────────────
+
+#[derive(Subcommand)]
+enum ThreadsCommands {
+ /// Print all threads as JSON
+ List,
+ /// Print a single thread's metadata as JSON
+ Get {
+ /// Thread ID
+ id: String,
+ },
+ /// Permanently delete a thread and all its messages
+ Delete {
+ /// Thread ID
+ id: String,
+ },
+ /// Print all messages in a thread as JSON
+ Messages {
+ /// Thread ID
+ thread_id: String,
+ },
+}
+
+// ── Serve args (shared by `models load` and top-level `serve`) ────────────
+
+#[derive(Args)]
+struct ServeArgs {
+ /// Model ID to load (omit to pick interactively from installed models)
+ model_id: Option<String>,
+ /// Path to the GGUF file (auto-resolved from model.yml when omitted)
+ #[arg(long)]
+ model_path: Option<String>,
+ /// Path to the inference binary (auto-discovered from Jan data folder when omitted)
+ #[arg(long)]
+ bin: Option<String>,
+ /// Port the model server listens on (0 = pick a random free port)
+ #[arg(long, default_value_t = 6767)]
+ port: u16,
+ /// mmproj path for vision-language models (auto-resolved from model.yml when omitted)
+ #[arg(long)]
+ mmproj: Option<String>,
+ /// Treat the model as an embedding model
+ #[arg(long, default_value_t = false)]
+ embedding: bool,
+ /// Seconds to wait for the model server to become ready
+ #[arg(long, default_value_t = 120)]
+ timeout: u64,
+ /// GPU layers to offload (-1 = all layers, 0 = CPU only)
+ #[arg(long, default_value_t = -1)]
+ n_gpu_layers: i32,
+ /// Context window size in tokens (0 = model default)
+ #[arg(long, default_value_t = 4096)]
+ ctx_size: i32,
+ /// Auto-fit context to available VRAM, maximising the context window
+ #[arg(long, default_value_t = false)]
+ fit: bool,
+ /// CPU threads for inference (0 = auto-detect)
+ #[arg(long, default_value_t = 0)]
+ threads: i32,
+ /// API key required by clients (sets LLAMA_API_KEY / MLX_API_KEY on the server)
+ #[arg(long, default_value = "")]
+ api_key: String,
+ /// Run in the background (detach from terminal) and print the PID
+ #[arg(long, short = 'd', default_value_t = false)]
+ detach: bool,
+ /// Log file for background mode (default: <data-folder>/logs/serve.log)
+ #[arg(long)]
+ log: Option<String>,
+}
+
+// ── Models subcommands ─────────────────────────────────────────────────────
+
+#[derive(Subcommand)]
+enum ModelsCommands {
+ /// Print all installed models as JSON (from the Jan data folder)
+ List {
+ /// Filter by engine: llamacpp, mlx, or all
+ #[arg(long, default_value = "all")]
+ engine: String,
+ },
+ /// Load a model and serve it — alias for the top-level `serve` command
+ Load {
+ #[command(flatten)]
+ args: ServeArgs,
+ },
+ /// Load an MLX model directly (macOS / Apple Silicon only)
+ LoadMlx {
+ /// Model ID as shown by `jan models list --engine mlx`
+ #[arg(long)]
+ model_id: String,
+ /// Path to the MLX model directory (auto-resolved from model.yml when omitted)
+ #[arg(long)]
+ model_path: Option<String>,
+ /// Path to the mlx-server binary (auto-discovered from Jan.app when omitted)
+ #[arg(long)]
+ bin: Option<String>,
+ /// Port the model server listens on (0 = pick a random free port)
+ #[arg(long, default_value_t = 6767)]
+ port: u16,
+ /// Context window size in tokens (0 = model default)
+ #[arg(long, default_value_t = 0)]
+ ctx_size: i32,
+ /// Treat the model as an embedding model
+ #[arg(long, default_value_t = false)]
+ embedding: bool,
+ /// Seconds to wait for the model server to become ready
+ #[arg(long, default_value_t = 120)]
+ timeout: u64,
+ /// API key required by clients (sets MLX_API_KEY on the server)
+ #[arg(long, default_value = "")]
+ api_key: String,
+ },
+}
+
+// ── App subcommands ────────────────────────────────────────────────────────
+
+#[derive(Subcommand)]
+enum AppCommands {
+ /// Print the Jan data folder path (where models, threads, and config are stored)
+ DataFolder,
+ /// Print the Jan configuration as JSON
+ Config,
+}
+
+// ── ASCII logo ─────────────────────────────────────────────────────────────
+
+/// Build a centered, bright-yellow ASCII logo for the help header.
+fn make_logo() -> String {
+ // "JAN" in ANSI Shadow block letters
+ let lines = [
+ r" ██╗ █████╗ ███╗ ██╗",
+ r" ██║██╔══██╗████╗ ██║",
+ r" ██║███████║██╔██╗██║",
+ r"██ ██║██╔══██║██║╚████║",
+ r"╚█████╔╝██║ ██║██║ ╚███║",
+ r" ╚════╝ ╚═╝ ╚═╝╚═╝ ╚══╝",
+ ];
+
+ let art_width: usize = 26; // visual columns of the widest line
+ let term_cols = console::Term::stdout().size().1 as usize;
+ let pad = (term_cols.saturating_sub(art_width)) / 2;
+ let indent = " ".repeat(pad);
+
+ let yellow = Style::new().yellow().bold();
+
+ let mut out: Vec<String> = lines
+ .iter()
+ .map(|l| format!("{}{}", indent, yellow.apply_to(l)))
+ .collect();
+
+ // Tagline beneath the wordmark
+ let tagline = "Your models · Your hardware · Your rules";
+ let tpad = (term_cols.saturating_sub(tagline.len())) / 2;
+ out.push(String::new());
+ out.push(format!(
+ "{}{}",
+ " ".repeat(tpad),
+ Style::new().dim().apply_to(tagline)
+ ));
+ out.push(String::new());
+
+ out.join("\n")
+}
+
+// ── Entry point ────────────────────────────────────────────────────────────
+
+#[tokio::main]
+async fn main() {
+ // Default to warn so verbose plugin logs don't clutter the spinner output.
+ // Override with RUST_LOG=debug for troubleshooting.
+ env_logger::Builder::from_env(
+ env_logger::Env::default().default_filter_or("warn"),
+ )
+ .init();
+
+ // Inject the logo at runtime so we can use ANSI styling.
+ let logo = make_logo();
+ let matches = Cli::command()
+ .before_help(logo.clone())
+ .before_long_help(logo)
+ .get_matches();
+ let cli = Cli::from_arg_matches(&matches).unwrap_or_else(|e| e.exit());
+
+ match cli.command {
+ Commands::Threads { cmd } => handle_threads(cmd).await,
+ Commands::Models { cmd } => handle_models(cmd).await,
+ Commands::App { cmd } => handle_app(cmd),
+ Commands::Serve { args } => handle_serve(args).await,
+ Commands::Launch { program, program_args, model, port, api_key, n_gpu_layers, ctx_size, fit } =>
+ handle_launch(program, program_args, model, port, api_key, n_gpu_layers, ctx_size, fit).await,
+ }
+}
+
+
+// ── Threads handlers ───────────────────────────────────────────────────────
+
+async fn handle_threads(cmd: ThreadsCommands) {
+ match cmd {
+ ThreadsCommands::List => match cli_list_threads().await {
+ Ok(threads) => {
+ println!("{}", serde_json::to_string_pretty(&threads).unwrap());
+ }
+ Err(e) => {
+ eprintln!("Error: {e}");
+ std::process::exit(1);
+ }
+ },
+
+ ThreadsCommands::Get { id } => match cli_get_thread(&id) {
+ Ok(thread) => println!("{}", serde_json::to_string_pretty(&thread).unwrap()),
+ Err(e) => {
+ eprintln!("Error: {e}");
+ std::process::exit(1);
+ }
+ },
+
+ ThreadsCommands::Delete { id } => match cli_delete_thread(&id) {
+ Ok(()) => println!("{}", serde_json::json!({ "deleted": true, "id": id })),
+ Err(e) => {
+ eprintln!("Error: {e}");
+ std::process::exit(1);
+ }
+ },
+
+ ThreadsCommands::Messages { thread_id } => match cli_list_messages(&thread_id) {
+ Ok(messages) => println!("{}", serde_json::to_string_pretty(&messages).unwrap()),
+ Err(e) => {
+ eprintln!("Error: {e}");
+ std::process::exit(1);
+ }
+ },
+ }
+}
+
+// ── Models handlers ────────────────────────────────────────────────────────
+
+async fn handle_models(cmd: ModelsCommands) {
+ match cmd {
+ ModelsCommands::List { engine } => {
+ let engines: &[&str] = match engine.as_str() {
+ "all" => &["llamacpp", "mlx"],
+ other => &[other],
+ };
+ let mut output: Vec<serde_json::Value> = Vec::new();
+ for eng in engines {
+ for (id, yml) in list_models(eng) {
+ output.push(serde_json::json!({
+ "id": id,
+ "engine": eng,
+ "name": yml.name,
+ "model_path": yml.model_path,
+ "size_bytes": yml.size_bytes,
+ "embedding": yml.embedding,
+ "capabilities": yml.capabilities,
+ "mmproj_path": yml.mmproj_path,
+ }));
+ }
+ }
+ println!("{}", serde_json::to_string_pretty(&output).unwrap());
+ }
+
+ ModelsCommands::Load { args } => handle_serve(args).await,
+
+ ModelsCommands::LoadMlx {
+ model_id,
+ model_path,
+ bin,
+ port,
+ ctx_size,
+ embedding,
+ timeout,
+ api_key,
+ } => {
+ use std::path::Path;
+
+ // Resolve model path from model.yml when not explicitly given
+ let resolved_model_path = match model_path {
+ Some(p) => p,
+ None => match resolve_model_by_id(&model_id, "mlx") {
+ Ok((mp, _)) => mp.to_string_lossy().into_owned(),
+ Err(e) => {
+ eprintln!("Error: {e}");
+ std::process::exit(1);
+ }
+ },
+ };
+
+ // Resolve binary path: use --bin if provided, otherwise auto-discover
+ let bin_path = match bin {
+ Some(b) => b,
+ None => match discover_mlx_binary() {
+ Some(p) => p.to_string_lossy().into_owned(),
+ None => {
+ eprintln!(
+ "Error: mlx-server binary not found. \
+ Install Jan from https://jan.ai or pass --bin <path>."
+ );
+ std::process::exit(1);
+ }
+ },
+ };
+
+ let mlx_state = Arc::new(init_mlx_state());
+ let mut envs = HashMap::new();
+ if !api_key.is_empty() {
+ envs.insert("MLX_API_KEY".to_string(), api_key);
+ }
+
+ match load_mlx_model_impl(
+ mlx_state.mlx_server_process.clone(),
+ Path::new(&bin_path),
+ model_id,
+ resolved_model_path,
+ port,
+ MlxConfig { ctx_size },
+ envs,
+ embedding,
+ timeout,
+ )
+ .await
+ {
+ Ok(info) => println!("{}", serde_json::to_string_pretty(&info).unwrap()),
+ Err(e) => {
+ eprintln!(
+ "Error loading MLX model:\n{}",
+ serde_json::to_string_pretty(&e)
+ .unwrap_or_else(|_| format!("{e:?}"))
+ );
+ std::process::exit(1);
+ }
+ }
+ }
+ }
+}
+
+// ── Spinner helper ─────────────────────────────────────────────────────────
+
+fn make_spinner(msg: impl Into<std::borrow::Cow<'static, str>>) -> ProgressBar {
+ let pb = ProgressBar::new_spinner();
+ pb.set_style(
+ ProgressStyle::default_spinner()
+ .tick_strings(&["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"])
+ .template("{spinner:.cyan} {msg}")
+ .unwrap(),
+ );
+ pb.set_message(msg);
+ pb.enable_steady_tick(std::time::Duration::from_millis(80));
+ pb
+}
+
+// ── HuggingFace auto-download ──────────────────────────────────────────────
+
+/// Read `HF_TOKEN` or `HUGGING_FACE_HUB_TOKEN` from the environment.
+fn hf_token() -> Option<String> {
+ std::env::var("HF_TOKEN")
+ .or_else(|_| std::env::var("HUGGING_FACE_HUB_TOKEN"))
+ .ok()
+ .filter(|s| !s.is_empty())
+}
+
+/// Format a byte count as a human-readable string (GB / MB / KB).
+fn fmt_bytes(b: u64) -> String {
+ if b >= 1_000_000_000 {
+ format!("{:.1} GB", b as f64 / 1_000_000_000.0)
+ } else if b >= 1_000_000 {
+ format!("{:.0} MB", b as f64 / 1_000_000.0)
+ } else {
+ format!("{:.0} KB", b as f64 / 1_000.0)
+ }
+}
+
+/// Show an interactive picker for a list of HF GGUF files and return the chosen one.
+///
+/// If there is only one file it is returned immediately without prompting.
+fn pick_hf_file(files: &[HfFileInfo]) -> &HfFileInfo {
+ if files.len() == 1 {
+ return &files[0];
+ }
+
+ let labels: Vec<String> = files
+ .iter()
+ .map(|f| format!("{:<55} {}", f.filename, fmt_bytes(f.size)))
+ .collect();
+
+ let idx = dialoguer::Select::new()
+ .with_prompt("Select a quantization to download")
+ .items(&labels)
+ .default(0)
+ .interact()
+ .unwrap_or_else(|_| std::process::exit(1));
+
+ &files[idx]
+}
+
+/// Fetch GGUF files from HuggingFace, let the user pick one, download it,
+/// and return the local model ID ready to load.
+///
+/// Exits the process on any unrecoverable error.
+async fn auto_download_hf_model(repo_id: &str) -> String {
+ let token = hf_token();
+ let tok_ref = token.as_deref();
+
+ // Fetch available GGUF files from the HF API
+ eprintln!();
+ let fetch_pb = make_spinner(format!("Fetching file list for '{repo_id}' from HuggingFace…"));
+ let files = fetch_hf_gguf_files(repo_id, tok_ref)
+ .await
+ .unwrap_or_else(|e| {
+ fetch_pb.finish_with_message(format!("✗ {e}"));
+ std::process::exit(1);
+ });
+ fetch_pb.finish_and_clear();
+
+ // Let the user pick which quantization to download
+ let chosen = pick_hf_file(&files);
+ eprintln!(" Downloading {}", chosen.filename);
+ eprintln!(" Size {}", fmt_bytes(chosen.size));
+ eprintln!();
+
+ // Progress bar — byte-count style
+ let dl_pb = ProgressBar::new(chosen.size);
+ dl_pb.set_style(
+ ProgressStyle::default_bar()
+ .template(
+ " {bar:45.yellow/dim} {bytes:>9}/{total_bytes} {bytes_per_sec} eta {eta}",
+ )
+ .unwrap()
+ .progress_chars("█▉▊▋▌▍▎▏ "),
+ );
+
+ let dl_pb_clone = dl_pb.clone();
+ let model_id = download_hf_model(repo_id, chosen, tok_ref, move |done, _total| {
+ dl_pb_clone.set_position(done);
+ })
+ .await
+ .unwrap_or_else(|e| {
+ dl_pb.finish_with_message(format!("✗ Download failed: {e}"));
+ std::process::exit(1);
+ });
+
+ dl_pb.finish_and_clear();
+ eprintln!(" ✓ Saved to Jan data folder\n");
+
+ model_id
+}
+
+// ── Interactive model picker ────────────────────────────────────────────────
+
+fn select_model_interactively() -> String {
+ let mut all: Vec<(String, String)> = Vec::new(); // (id, engine)
+ for engine in &["llamacpp", "mlx"] {
+ for (id, _) in list_models(engine) {
+ all.push((id, engine.to_string()));
+ }
+ }
+
+ if all.is_empty() {
+ eprintln!("No models found. Download a model from the Jan app first.");
+ std::process::exit(1);
+ }
+
+ let labels: Vec<String> = all
+ .iter()
+ .map(|(id, engine)| format!("{} ({})", id, engine))
+ .collect();
+
+ let selection = dialoguer::Select::new()
+ .with_prompt("Select a model")
+ .items(&labels)
+ .default(0)
+ .interact()
+ .unwrap_or_else(|_| std::process::exit(1));
+
+ all.remove(selection).0
+}
+
+// ── Detached spawn ─────────────────────────────────────────────────────────
+
+fn spawn_detached(model_id: &str, args: &ServeArgs) {
+ let exe = std::env::current_exe().expect("cannot resolve current exe");
+
+ // Rebuild argv from ServeArgs fields so we have full control
+ // (avoids needing to filter --detach/-d from the raw OS args).
+ // Use --flag=value format throughout to avoid negative numbers being
+ // misinterpreted as short flags (e.g. --n-gpu-layers -1 → -1 looks like a flag).
+ let mut argv: Vec<String> = vec!["serve".into(), model_id.to_string()];
+ if let Some(p) = &args.model_path { argv.push(format!("--model-path={p}")); }
+ if let Some(b) = &args.bin { argv.push(format!("--bin={b}")); }
+ argv.push(format!("--port={}", args.port));
+ if let Some(m) = &args.mmproj { argv.push(format!("--mmproj={m}")); }
+ if args.embedding { argv.push("--embedding".into()); }
+ argv.push(format!("--timeout={}", args.timeout));
+ argv.push(format!("--n-gpu-layers={}", args.n_gpu_layers));
+ argv.push(format!("--ctx-size={}", args.ctx_size));
+ argv.push(format!("--threads={}", args.threads));
+ if !args.api_key.is_empty() { argv.push(format!("--api-key={}", args.api_key)); }
+ if args.fit { argv.push("--fit".into()); }
+
+ // Resolve log file path
+ let log_path: PathBuf = args.log.as_deref()
+ .map(PathBuf::from)
+ .unwrap_or_else(|| cli_get_data_folder().join("logs").join("serve.log"));
+
+ if let Some(parent) = log_path.parent() {
+ let _ = std::fs::create_dir_all(parent);
+ }
+
+ let log_file = std::fs::OpenOptions::new()
+ .create(true).append(true).open(&log_path)
+ .unwrap_or_else(|e| { eprintln!("Cannot open log file {}: {e}", log_path.display()); std::process::exit(1); });
+ let log_out = log_file.try_clone().expect("clone log file");
+
+ let mut cmd = std::process::Command::new(&exe);
+ cmd.args(&argv)
+ .stdin(std::process::Stdio::null())
+ .stdout(log_out)
+ .stderr(log_file);
+
+ // Detach from the current terminal session on Unix
+ #[cfg(unix)]
+ {
+ use std::os::unix::process::CommandExt;
+ unsafe {
+ cmd.pre_exec(|| {
+ nix::unistd::setsid()
+ .map(|_| ())
+ .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e.to_string()))
+ });
+ }
+ }
+
+ let child = cmd.spawn().unwrap_or_else(|e| {
+ eprintln!("Failed to spawn detached process: {e}");
+ std::process::exit(1);
+ });
+
+ println!("{}", serde_json::to_string_pretty(&serde_json::json!({
+ "pid": child.id(),
+ "model_id": model_id,
+ "log": log_path.display().to_string(),
+ })).unwrap());
+}
+
+// ── Serve handler (shared by `models load` and top-level `serve`) ──────────
+
+async fn handle_serve(args: ServeArgs) {
+ // Resolve model_id first — may trigger interactive picker before we potentially detach.
+ let model_id = args.model_id.clone().unwrap_or_else(select_model_interactively);
+
+ if args.detach {
+ spawn_detached(&model_id, &args);
+ return;
+ }
+
+ let ServeArgs {
+ model_id: _,
+ model_path,
+ bin,
+ port,
+ mmproj,
+ embedding,
+ timeout,
+ n_gpu_layers,
+ ctx_size: ctx_size_arg,
+ threads,
+ api_key,
+ fit,
+ detach: _,
+ log: _,
+ } = args;
+
+ // When --fit is on, let llama.cpp decide the context size automatically
+ let ctx_size = if fit { 0 } else { ctx_size_arg };
+
+ // Auto-detect engine from data folder.
+ // If the model isn't found locally and the ID looks like a HuggingFace repo,
+ // offer to download it automatically before proceeding.
+ let (engine, resolved_model_path, resolved_mmproj) =
+ match resolve_model_engine(&model_id) {
+ Ok((eng, mp, mmp)) => (
+ eng,
+ model_path.unwrap_or_else(|| mp.to_string_lossy().into_owned()),
+ mmproj.or_else(|| mmp.map(|p| p.to_string_lossy().into_owned())),
+ ),
+ Err(_) if model_path.is_some() => {
+ // Explicit --model-path provided: skip engine detection entirely.
+ ("llamacpp".to_string(), model_path.unwrap(), mmproj)
+ }
+ Err(_) if looks_like_hf_repo(&model_id) => {
+ // Looks like a HuggingFace repo ID — download then resolve.
+ auto_download_hf_model(&model_id).await;
+ match resolve_model_engine(&model_id) {
+ Ok((eng, mp, mmp)) => (
+ eng,
+ mp.to_string_lossy().into_owned(),
+ mmp.map(|p| p.to_string_lossy().into_owned()),
+ ),
+ Err(e) => {
+ eprintln!("Error after download: {e}");
+ std::process::exit(1);
+ }
+ }
+ }
+ Err(e) => {
+ eprintln!("Error: {e}");
+ std::process::exit(1);
+ }
+ };
+
+ let pb = make_spinner(format!("Loading {} ({engine})…", model_id));
+
+ if engine == "mlx" {
+ use std::path::Path;
+
+ let bin_path = match bin {
+ Some(b) => b,
+ None => match discover_mlx_binary() {
+ Some(p) => p.to_string_lossy().into_owned(),
+ None => {
+ pb.finish_with_message("✗ mlx-server binary not found".to_string());
+ eprintln!("Install Jan from https://jan.ai or pass --bin <path>.");
+ std::process::exit(1);
+ }
+ },
+ };
+
+ let mlx_state = Arc::new(init_mlx_state());
+ let mut envs = HashMap::new();
+ if !api_key.is_empty() {
+ envs.insert("MLX_API_KEY".to_string(), api_key);
+ }
+
+ match load_mlx_model_impl(
+ mlx_state.mlx_server_process.clone(),
+ Path::new(&bin_path),
+ model_id.clone(),
+ resolved_model_path,
+ port,
+ MlxConfig { ctx_size },
+ envs,
+ embedding,
+ timeout,
+ )
+ .await
+ {
+ Ok(info) => {
+ let url = format!("http://127.0.0.1:{}", info.port);
+ pb.finish_with_message(format!("✓ {model_id} ready · {url}"));
+ eprintln!();
+ eprintln!(" Endpoint {url}/v1");
+ eprintln!();
+ eprintln!(" Press Ctrl+C to stop.");
+ wait_for_shutdown(info.pid).await;
+ }
+ Err(e) => {
+ pb.finish_with_message(format!("✗ Failed to load {model_id}"));
+ eprintln!(
+ "\n{}",
+ serde_json::to_string_pretty(&e).unwrap_or_else(|_| format!("{e:?}"))
+ );
+ std::process::exit(1);
+ }
+ }
+ } else {
+ // LlamaCPP path
+ let bin_path = match bin {
+ Some(b) => b,
+ None => match discover_llamacpp_binary() {
+ Some(p) => p.to_string_lossy().into_owned(),
+ None => {
+ pb.finish_with_message("✗ llama-server binary not found".to_string());
+ eprintln!("Install a backend from Jan's settings or pass --bin <path>.");
+ std::process::exit(1);
+ }
+ },
+ };
+
+ let llama_state = Arc::new(init_llamacpp_state());
+ let mut envs = HashMap::new();
+ if !api_key.is_empty() {
+ envs.insert("LLAMA_API_KEY".to_string(), api_key);
+ }
+
+ let config = LlamacppConfig {
+ version_backend: "cli/llama-server".to_string(),
+ auto_update_engine: false,
+ auto_unload: false,
+ timeout: timeout as i32,
+ llamacpp_env: String::new(),
+ fit,
+ fit_target: String::new(),
+ fit_ctx: String::new(),
+ chat_template: String::new(),
+ n_gpu_layers,
+ offload_mmproj: true,
+ cpu_moe: false,
+ n_cpu_moe: 0,
+ override_tensor_buffer_t: String::new(),
+ ctx_size,
+ threads,
+ threads_batch: 0,
+ n_predict: -1,
+ batch_size: 512,
+ ubatch_size: 512,
+ device: String::new(),
+ split_mode: String::new(),
+ main_gpu: 0,
+ flash_attn: "auto".to_string(),
+ cont_batching: true,
+ no_mmap: false,
+ mlock: false,
+ no_kv_offload: false,
+ cache_type_k: String::new(),
+ cache_type_v: String::new(),
+ defrag_thold: -1.0,
+ rope_scaling: String::new(),
+ rope_scale: 0.0,
+ rope_freq_base: 0.0,
+ rope_freq_scale: 0.0,
+ ctx_shift: false,
+ };
+
+ match load_llama_model_impl(
+ llama_state.llama_server_process.clone(),
+ &bin_path,
+ model_id.clone(),
+ resolved_model_path,
+ port,
+ config,
+ envs,
+ resolved_mmproj,
+ embedding,
+ timeout,
+ )
+ .await
+ {
+ Ok(info) => {
+ let url = format!("http://127.0.0.1:{}", info.port);
+ pb.finish_with_message(format!("✓ {model_id} ready · {url}"));
+ eprintln!();
+ eprintln!(" Endpoint {url}/v1");
+ eprintln!();
+ eprintln!(" Press Ctrl+C to stop.");
+ wait_for_shutdown(info.pid).await;
+ }
+ Err(e) => {
+ pb.finish_with_message(format!("✗ Failed to load {model_id}"));
+ eprintln!(
+ "\n{}",
+ serde_json::to_string_pretty(&e).unwrap_or_else(|_| format!("{e:?}"))
+ );
+ std::process::exit(1);
+ }
+ }
+ }
+}
+
+/// Block until Ctrl+C, then terminate the child process.
+async fn wait_for_shutdown(pid: i32) {
+ tokio::signal::ctrl_c().await.ok();
+ eprintln!("\nShutting down (pid {pid})...");
+ #[cfg(unix)]
+ {
+ use nix::sys::signal::{kill, Signal};
+ use nix::unistd::Pid;
+ let _ = kill(Pid::from_raw(pid), Signal::SIGTERM);
+ }
+}
+
+// ── Launch handler ─────────────────────────────────────────────────────────
+
+#[allow(clippy::too_many_arguments)]
+async fn handle_launch(
+ program: String,
+ program_args: Vec<String>,
+ model: Option<String>,
+ port: u16,
+ api_key: String,
+ n_gpu_layers: i32,
+ ctx_size: i32,
+ fit: Option<bool>,
+) {
+ let model_id = model.unwrap_or_else(select_model_interactively);
+
+ // Detect claude early so we can set fit default before starting the server.
+ let prog_name = std::path::Path::new(&program)
+ .file_name()
+ .and_then(|n| n.to_str())
+ .unwrap_or(&program);
+ let is_claude = prog_name.contains("claude");
+
+ // --fit defaults to true when launching claude (maximises context window).
+ let effective_fit = fit.unwrap_or(is_claude);
+
+ // Start the model server inline (same process, no detach).
+ let (pid, actual_port) = start_model_server(&model_id, port, api_key.clone(), n_gpu_layers, ctx_size, effective_fit).await;
+
+ let base_url = format!("http://127.0.0.1:{actual_port}");
+ let v1_url = format!("{base_url}/v1");
+
+ let anthropic_key_var = if is_claude { "ANTHROPIC_AUTH_TOKEN" } else { "ANTHROPIC_API_KEY" };
+
+ eprintln!();
+ eprintln!(" OPENAI_BASE_URL={v1_url}");
+ eprintln!(" OPENAI_API_KEY={api_key}");
+ eprintln!(" ANTHROPIC_BASE_URL={base_url}");
+ eprintln!(" {anthropic_key_var}={api_key}");
+ eprintln!(" ANTHROPIC_DEFAULT_OPUS_MODEL={model_id}");
+ eprintln!(" ANTHROPIC_DEFAULT_SONNET_MODEL={model_id}");
+ eprintln!(" ANTHROPIC_DEFAULT_HAIKU_MODEL={model_id}");
+ eprintln!();
+ eprintln!(" → Launching: {program}");
+ eprintln!();
+
+ let mut cmd = std::process::Command::new(&program);
+ cmd.args(&program_args)
+ .env("OPENAI_BASE_URL", &v1_url)
+ .env("OPENAI_API_KEY", &api_key)
+ .env("ANTHROPIC_BASE_URL", &base_url)
+ .env(anthropic_key_var, &api_key)
+ .env("ANTHROPIC_DEFAULT_OPUS_MODEL", &model_id)
+ .env("ANTHROPIC_DEFAULT_SONNET_MODEL", &model_id)
+ .env("ANTHROPIC_DEFAULT_HAIKU_MODEL", &model_id);
+ let status = cmd.status();
+
+ // Kill the model server when the program exits.
+ #[cfg(unix)]
+ {
+ use nix::sys::signal::{kill, Signal};
+ use nix::unistd::Pid;
+ let _ = kill(Pid::from_raw(pid), Signal::SIGTERM);
+ }
+
+ match status {
+ Ok(s) => std::process::exit(s.code().unwrap_or(0)),
+ Err(e) => {
+ eprintln!("Error launching '{program}': {e}");
+ std::process::exit(1);
+ }
+ }
+}
+
+/// Start the model server and return `(pid, actual_port)`.
+/// Resolves the engine automatically (LlamaCPP or MLX).
+async fn start_model_server(
+ model_id: &str,
+ port: u16,
+ api_key: String,
+ n_gpu_layers: i32,
+ ctx_size: i32,
+ fit: bool,
+) -> (i32, u16) {
+ // Auto-download from HuggingFace if the model isn't installed locally.
+ if resolve_model_engine(model_id).is_err() && looks_like_hf_repo(model_id) {
+ auto_download_hf_model(model_id).await;
+ }
+
+ let (engine, model_path, mmproj) = match resolve_model_engine(model_id) {
+ Ok(r) => r,
+ Err(e) => { eprintln!("Error: {e}"); std::process::exit(1); }
+ };
+ let model_path = model_path.to_string_lossy().into_owned();
+
+ let pb = make_spinner(format!("Loading {} ({engine})…", model_id));
+
+ if engine == "mlx" {
+ use std::path::Path;
+ let bin_path = discover_mlx_binary().unwrap_or_else(|| {
+ pb.finish_with_message("✗ mlx-server binary not found".to_string());
+ std::process::exit(1);
+ });
+ let mlx_state = Arc::new(init_mlx_state());
+ let mut envs = HashMap::new();
+ if !api_key.is_empty() { envs.insert("MLX_API_KEY".into(), api_key.clone()); }
+ let info = load_mlx_model_impl(
+ mlx_state.mlx_server_process.clone(),
+ Path::new(&bin_path),
+ model_id.to_string(),
+ model_path,
+ port,
+ MlxConfig { ctx_size },
+ envs,
+ false,
+ 120,
+ ).await.unwrap_or_else(|e| {
+ pb.finish_with_message(format!("✗ Failed to load {model_id}"));
+ eprintln!("{}", serde_json::to_string_pretty(&e).unwrap_or_else(|_| format!("{e:?}")));
+ std::process::exit(1);
+ });
+ let url = format!("http://127.0.0.1:{}", info.port);
+ pb.finish_with_message(format!("✓ {model_id} ready · {url}"));
+ (info.pid, info.port as u16)
+ } else {
+ let bin_path = discover_llamacpp_binary()
+ .map(|p| p.to_string_lossy().into_owned())
+ .unwrap_or_else(|| {
+ pb.finish_with_message("✗ llama-server binary not found".to_string());
+ std::process::exit(1);
+ });
+ let llama_state = Arc::new(init_llamacpp_state());
+ let mut envs = HashMap::new();
+ if !api_key.is_empty() { envs.insert("LLAMA_API_KEY".into(), api_key.clone()); }
+ // When fit is on, let llama.cpp decide the context size automatically.
+ let effective_ctx_size = if fit { 0 } else { ctx_size };
+ let config = LlamacppConfig {
+ version_backend: "cli/llama-server".to_string(),
+ auto_update_engine: false, auto_unload: false,
+ timeout: 120, llamacpp_env: String::new(),
+ fit, fit_target: String::new(), fit_ctx: String::new(),
+ chat_template: String::new(), n_gpu_layers, offload_mmproj: true,
+ cpu_moe: false, n_cpu_moe: 0, override_tensor_buffer_t: String::new(),
+ ctx_size: effective_ctx_size, threads: 0, threads_batch: 0, n_predict: -1,
+ batch_size: 512, ubatch_size: 512, device: String::new(),
+ split_mode: String::new(), main_gpu: 0, flash_attn: "auto".into(),
+ cont_batching: true, no_mmap: false, mlock: false, no_kv_offload: false,
+ cache_type_k: String::new(), cache_type_v: String::new(),
+ defrag_thold: -1.0, rope_scaling: String::new(),
+ rope_scale: 0.0, rope_freq_base: 0.0, rope_freq_scale: 0.0, ctx_shift: false,
+ };
+ let info = load_llama_model_impl(
+ llama_state.llama_server_process.clone(),
+ &bin_path,
+ model_id.to_string(),
+ model_path,
+ port,
+ config,
+ envs,
+ mmproj.map(|p| p.to_string_lossy().into_owned()),
+ false,
+ 120,
+ ).await.unwrap_or_else(|e| {
+ pb.finish_with_message(format!("✗ Failed to load {model_id}"));
+ eprintln!("{}", serde_json::to_string_pretty(&e).unwrap_or_else(|_| format!("{e:?}")));
+ std::process::exit(1);
+ });
+ let url = format!("http://127.0.0.1:{}", info.port);
+ pb.finish_with_message(format!("✓ {model_id} ready · {url}"));
+ (info.pid, info.port as u16)
+ }
+}
+
+// ── App handlers ───────────────────────────────────────────────────────────
+
+fn handle_app(cmd: AppCommands) {
+ match cmd {
+ AppCommands::DataFolder => {
+ let folder = cli_get_data_folder();
+ println!(
+ "{}",
+ serde_json::to_string_pretty(&serde_json::json!({ "data_folder": folder }))
+ .unwrap()
+ );
+ }
+
+ AppCommands::Config => match cli_get_config() {
+ Ok(config) => println!("{}", serde_json::to_string_pretty(&config).unwrap()),
+ Err(e) => {
+ eprintln!("Error: {e}");
+ std::process::exit(1);
+ }
+ },
+ }
+}
diff --git a/src-tauri/src/core/app/commands.rs b/src-tauri/src/core/app/commands.rs
index 13a8b2e7b..8aa550e77 100644
--- a/src-tauri/src/core/app/commands.rs
+++ b/src-tauri/src/core/app/commands.rs
@@ -6,6 +6,60 @@ use super::{
};
use crate::core::state::AppState;
+/// Resolve the Jan config file path without an AppHandle (for CLI use).
+/// Mirrors the logic in get_configuration_file_path() using the dirs crate.
+pub fn resolve_config_file_path() -> PathBuf {
+ let package_name = env!("CARGO_PKG_NAME");
+
+ // On Linux, prefer the XDG config dir first (matches Tauri behaviour)
+ #[cfg(target_os = "linux")]
+ if let Some(config_dir) = dirs::config_dir() {
+ let path = config_dir.join(package_name);
+ if path.exists() {
+ return path.join(CONFIGURATION_FILE_NAME);
+ }
+ }
+
+ // Primary path: data_dir/Jan (e.g. ~/Library/Application Support/Jan on macOS)
+ if let Some(data_dir) = dirs::data_dir() {
+ let path = data_dir.join(package_name);
+ if !path.exists() {
+ let _ = fs::create_dir_all(&path);
+ }
+ return path.join(CONFIGURATION_FILE_NAME);
+ }
+
+ // Last resort: home directory
+ let home = std::env::var("HOME")
+ .or_else(|_| std::env::var("USERPROFILE"))
+ .unwrap_or_default();
+ PathBuf::from(home).join(CONFIGURATION_FILE_NAME)
+}
+
+/// Resolve the Jan data folder path without an AppHandle (for CLI use).
+/// Reads AppConfiguration from the config file; falls back to the default location.
+pub fn resolve_jan_data_folder() -> PathBuf {
+ let config_file = resolve_config_file_path();
+
+ if config_file.exists() {
+ if let Ok(content) = fs::read_to_string(&config_file) {
+ if let Ok(config) = serde_json::from_str::<AppConfiguration>(&content) {
+ return PathBuf::from(config.data_folder);
+ }
+ }
+ }
+
+ // Default: data_dir/Jan/data (mirrors default_data_folder_path)
+ let app_name = std::env::var("APP_NAME").unwrap_or_else(|_| "Jan".to_string());
+ if let Some(data_dir) = dirs::data_dir() {
+ return data_dir.join(&app_name).join("data");
+ }
+ let home = std::env::var("HOME")
+ .or_else(|_| std::env::var("USERPROFILE"))
+ .unwrap_or_default();
+ PathBuf::from(home).join(&app_name).join("data")
+}
+
#[tauri::command]
pub fn get_app_configurations<R: Runtime>(app_handle: tauri::AppHandle<R>) -> AppConfiguration {
let mut app_default_configuration = AppConfiguration::default();
diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rs
new file mode 100644
index 000000000..d73548b90
--- /dev/null
+++ b/src-tauri/src/core/cli/mod.rs
@@ -0,0 +1,568 @@
+//! CLI adapter layer — thin wrappers that call core logic without an AppHandle.
+//!
+//! This module is only compiled when the `cli` feature is enabled.
+
+use std::collections::HashMap;
+use std::path::PathBuf;
+use std::sync::Arc;
+
+use tokio::sync::Mutex;
+
+use crate::core::app::commands::{resolve_config_file_path, resolve_jan_data_folder};
+use crate::core::server::proxy;
+use crate::core::state::AppState;
+use crate::core::threads::{
+ constants::THREADS_FILE,
+ helpers::read_messages_from_file,
+ utils::{ensure_data_dirs, get_data_dir, get_thread_dir, get_thread_metadata_path},
+};
+use tauri_plugin_llamacpp::state::LlamacppState;
+use tauri_plugin_mlx::state::MlxState;
+
+// Re-export impl functions and config types so the binary can call them directly
+pub use tauri_plugin_llamacpp::{load_llama_model_impl, LlamacppConfig};
+pub use tauri_plugin_mlx::{load_mlx_model_impl, MlxConfig};
+pub use tauri_plugin_mlx::state::SessionInfo;
+
+// ── State constructors ─────────────────────────────────────────────────────
+
+pub fn init_app_state() -> AppState {
+ AppState::default()
+}
+
+pub fn init_llamacpp_state() -> LlamacppState {
+ LlamacppState::new()
+}
+
+pub fn init_mlx_state() -> MlxState {
+ MlxState::new()
+}
+
+// ── Thread operations ──────────────────────────────────────────────────────
+
+/// List all threads from the Jan data folder.
+pub async fn cli_list_threads() -> Result<Vec<serde_json::Value>, String> {
+ use std::fs;
+
+ let data_folder = resolve_jan_data_folder();
+ ensure_data_dirs(&data_folder)?;
+ let data_dir = get_data_dir(&data_folder);
+ let mut threads = Vec::new();
+
+ if !data_dir.exists() {
+ return Ok(threads);
+ }
+
+ for entry in fs::read_dir(&data_dir).map_err(|e| e.to_string())? {
+ let entry = entry.map_err(|e| e.to_string())?;
+ let path = entry.path();
+ if path.is_dir() {
+ let metadata_path = path.join(THREADS_FILE);
+ if metadata_path.exists() {
+ let data = fs::read_to_string(&metadata_path).map_err(|e| e.to_string())?;
+ if let Ok(thread) = serde_json::from_str(&data) {
+ threads.push(thread);
+ }
+ }
+ }
+ }
+
+ Ok(threads)
+}
+
+/// List messages for a thread.
+pub fn cli_list_messages(thread_id: &str) -> Result<Vec<serde_json::Value>, String> {
+ let data_folder = resolve_jan_data_folder();
+ read_messages_from_file(&data_folder, thread_id)
+}
+
+/// Delete a thread directory.
+pub fn cli_delete_thread(thread_id: &str) -> Result<(), String> {
+ use std::fs;
+
+ let data_folder = resolve_jan_data_folder();
+ let thread_dir = get_thread_dir(&data_folder, thread_id);
+ if thread_dir.exists() {
+ fs::remove_dir_all(thread_dir).map_err(|e| e.to_string())?;
+ }
+ Ok(())
+}
+
+/// Get thread metadata by ID.
+pub fn cli_get_thread(thread_id: &str) -> Result<serde_json::Value, String> {
+ let data_folder = resolve_jan_data_folder();
+ let path = get_thread_metadata_path(&data_folder, thread_id);
+ if !path.exists() {
+ return Err(format!("Thread '{thread_id}' not found"));
+ }
+ let data = std::fs::read_to_string(&path).map_err(|e| e.to_string())?;
+ serde_json::from_str(&data).map_err(|e| e.to_string())
+}
+
+// ── Server operations ──────────────────────────────────────────────────────
+
+/// Start the OpenAI-compatible proxy server. Returns the port it's listening on.
+pub async fn cli_start_server(
+ app_state: Arc<AppState>,
+ llama_state: Arc<LlamacppState>,
+ mlx_state: Arc<MlxState>,
+ host: String,
+ port: u16,
+ prefix: String,
+ api_key: String,
+ proxy_timeout: u64,
+) -> Result<u16, String> {
+ proxy::start_server(
+ app_state.server_handle.clone(),
+ llama_state.llama_server_process.clone(),
+ mlx_state.mlx_server_process.clone(),
+ host,
+ port,
+ prefix,
+ api_key,
+ vec![vec![]],
+ proxy_timeout,
+ app_state.provider_configs.clone(),
+ )
+ .await
+ .map_err(|e| e.to_string())
+}
+
+/// Stop the running proxy server.
+pub async fn cli_stop_server(app_state: Arc<AppState>) -> Result<(), String> {
+ proxy::stop_server(app_state.server_handle.clone())
+ .await
+ .map_err(|e| e.to_string())
+}
+
+/// Check whether the proxy server is currently running.
+pub async fn cli_is_server_running(app_state: Arc<AppState>) -> bool {
+ proxy::is_server_running(app_state.server_handle.clone()).await
+}
+
+// ── Model discovery ───────────────────────────────────────────────────────
+
+/// Parsed representation of a `model.yml` file.
+#[derive(Debug, serde::Deserialize)]
+pub struct ModelYml {
+ pub model_path: String,
+ pub name: Option<String>,
+ #[serde(default)]
+ pub size_bytes: u64,
+ #[serde(default)]
+ pub embedding: bool,
+ pub mmproj_path: Option<String>,
+ #[serde(default)]
+ pub capabilities: Vec<String>,
+}
+
+/// A discovered model entry: `(model_id, yml)`.
+pub type ModelEntry = (String, ModelYml);
+
+/// Scan `<data_folder>/<engine>/models/` for `model.yml` files.
+///
+/// `engine` is `"llamacpp"` or `"mlx"`. Returns one entry per model found.
+pub fn list_models(engine: &str) -> Vec<ModelEntry> {
+ use std::fs;
+
+ let data_folder = resolve_jan_data_folder();
+ let models_root = data_folder.join(engine).join("models");
+
+ if !models_root.exists() {
+ return Vec::new();
+ }
+
+ let mut results = Vec::new();
+ let mut stack = vec![models_root.clone()];
+
+ while let Some(dir) = stack.pop() {
+ let yml_path = dir.join("model.yml");
+ if yml_path.exists() {
+ if let Ok(content) = fs::read_to_string(&yml_path) {
+ if let Ok(yml) = serde_yaml::from_str::<ModelYml>(&content) {
+ // model_id = path relative to models_root
+ let model_id = dir
+ .strip_prefix(&models_root)
+ .unwrap_or(&dir)
+ .to_string_lossy()
+ .into_owned();
+ results.push((model_id, yml));
+ continue; // don't recurse into a model directory
+ }
+ }
+ }
+ // Recurse into subdirectories
+ if let Ok(entries) = fs::read_dir(&dir) {
+ for entry in entries.flatten() {
+ if entry.path().is_dir() {
+ stack.push(entry.path());
+ }
+ }
+ }
+ }
+
+ results.sort_by(|a, b| a.0.cmp(&b.0));
+ results
+}
+
+/// Detect which engine owns `model_id` by probing the data folder, and
+/// resolve its paths. Tries `llamacpp` first, then `mlx`.
+/// Returns `(engine, model_path, mmproj_path)`.
+pub fn resolve_model_engine(
+ model_id: &str,
+) -> Result<(String, PathBuf, Option<PathBuf>), String> {
+ let data_folder = resolve_jan_data_folder();
+ for engine in &["llamacpp", "mlx"] {
+ let yml_path = data_folder
+ .join(engine)
+ .join("models")
+ .join(model_id)
+ .join("model.yml");
+ if yml_path.exists() {
+ let (model_path, mmproj_path) = resolve_model_by_id(model_id, engine)?;
+ return Ok((engine.to_string(), model_path, mmproj_path));
+ }
+ }
+ Err(format!(
+ "Model '{}' not found for any engine. \
+ Run `jan-cli models list` or `jan-cli models list --engine mlx` to see available models.",
+ model_id
+ ))
+}
+
+/// Resolve the absolute model file path (and optional mmproj path) for a
+/// given model ID and engine.
+///
+/// `model_path` in the YAML can be:
+/// - absolute (`/…` or `C:\…`) — used verbatim
+/// - relative — joined with the Jan data folder
+pub fn resolve_model_by_id(
+ model_id: &str,
+ engine: &str,
+) -> Result<(PathBuf, Option<PathBuf>), String> {
+ let data_folder = resolve_jan_data_folder();
+ let yml_path = data_folder
+ .join(engine)
+ .join("models")
+ .join(model_id)
+ .join("model.yml");
+
+ if !yml_path.exists() {
+ return Err(format!(
+ "Model '{}' not found for engine '{}'. \
+ Run `jan-cli models list` to see available models.",
+ model_id, engine
+ ));
+ }
+
+ let content = std::fs::read_to_string(&yml_path).map_err(|e| e.to_string())?;
+ let yml: ModelYml = serde_yaml::from_str(&content).map_err(|e| e.to_string())?;
+
+ let resolve_path = |p: &str| -> PathBuf {
+ let pb = PathBuf::from(p);
+ if pb.is_absolute() {
+ pb
+ } else {
+ data_folder.join(p)
+ }
+ };
+
+ let model_path = resolve_path(&yml.model_path);
+ let mmproj_path = yml.mmproj_path.as_deref().map(resolve_path);
+
+ Ok((model_path, mmproj_path))
+}
+
+// ── Binary auto-discovery ──────────────────────────────────────────────────
+
+/// Find the llama-server binary inside the Jan data folder.
+///
+/// Walks `<data_folder>/llamacpp/backends/<version>/<backend>/` and checks
+/// two locations per backend (same logic as the llamacpp-extension):
+/// 1. `<backend_dir>/build/bin/llama-server[.exe]`
+/// 2. `<backend_dir>/llama-server[.exe]`
+///
+/// Returns the first binary found, or `None` if no installed backend is found.
+pub fn discover_llamacpp_binary() -> Option<PathBuf> {
+ use std::fs;
+
+ let data_folder = resolve_jan_data_folder();
+ let backends_dir = data_folder.join("llamacpp").join("backends");
+
+ if !backends_dir.exists() {
+ return None;
+ }
+
+ let exe = if cfg!(windows) { "llama-server.exe" } else { "llama-server" };
+
+ // Collect version directories, sorted descending so we prefer the latest.
+ let mut version_entries: Vec<_> = fs::read_dir(&backends_dir)
+ .ok()?
+ .filter_map(|e| e.ok())
+ .filter(|e| e.path().is_dir())
+ .collect();
+ version_entries.sort_by(|a, b| b.file_name().cmp(&a.file_name()));
+
+ for version_entry in version_entries {
+ let version_dir = version_entry.path();
+ let mut backend_entries: Vec<_> = fs::read_dir(&version_dir)
+ .ok()?
+ .filter_map(|e| e.ok())
+ .filter(|e| e.path().is_dir())
+ .collect();
+ backend_entries.sort_by(|a, b| a.file_name().cmp(&b.file_name()));
+
+ for backend_entry in backend_entries {
+ let backend_dir = backend_entry.path();
+
+ // Primary location: <backend>/build/bin/llama-server
+ let primary = backend_dir.join("build").join("bin").join(exe);
+ if primary.exists() {
+ return Some(primary);
+ }
+
+ // Fallback: <backend>/llama-server
+ let fallback = backend_dir.join(exe);
+ if fallback.exists() {
+ return Some(fallback);
+ }
+ }
+ }
+
+ None
+}
+
+/// Find the mlx-server binary.
+///
+/// Checks standard locations in order:
+/// 1. `/Applications/Jan.app/Contents/Resources/bin/mlx-server` (installed app)
+/// 2. Next to the running binary (for dev/custom installs)
+pub fn discover_mlx_binary() -> Option<PathBuf> {
+ // 1. Standard macOS app bundle locations (try both path variants)
+ for candidate in &[
+ "/Applications/Jan.app/Contents/Resources/resources/bin/mlx-server",
+ "/Applications/Jan.app/Contents/Resources/bin/mlx-server",
+ ] {
+ let p = PathBuf::from(candidate);
+ if p.exists() {
+ return Some(p);
+ }
+ }
+
+ // 2. Next to the current executable (useful for dev builds / custom installs)
+ if let Ok(exe_dir) = std::env::current_exe().map(|p| p.parent().map(|d| d.to_path_buf()).unwrap_or_default()) {
+ let next_to_bin = exe_dir.join("mlx-server");
+ if next_to_bin.exists() {
+ return Some(next_to_bin);
+ }
+ }
+
+ None
+}
+
+// ── HuggingFace download ───────────────────────────────────────────────────
+
+/// A single file entry from a HuggingFace repository.
+#[derive(Debug, Clone)]
+pub struct HfFileInfo {
+ /// Original filename in the repo (e.g. `qwen3-30b.Q4_K_M.gguf`)
+ pub filename: String,
+ /// Total size in bytes (from HF metadata or LFS pointer)
+ pub size: u64,
+ /// SHA-256 from the LFS pointer, used for integrity validation
+ pub sha256: Option<String>,
+ /// Direct download URL (`https://huggingface.co/{repo}/resolve/main/{file}`)
+ pub download_url: String,
+}
+
+/// Return `true` if `s` looks like a HuggingFace repo ID (`owner/repo`).
+///
+/// A valid HF repo ID has exactly one `/`, both parts non-empty, no
+/// filesystem path markers, and only alphanumeric / `-` / `_` / `.` chars.
+pub fn looks_like_hf_repo(s: &str) -> bool {
+ if s.starts_with('/') || s.starts_with('.') || s.starts_with('~') {
+ return false;
+ }
+ let Some((owner, name)) = s.split_once('/') else {
+ return false;
+ };
+ if owner.is_empty() || name.is_empty() || name.contains('/') {
+ return false;
+ }
+ let ok = |c: char| c.is_alphanumeric() || matches!(c, '-' | '_' | '.');
+ owner.chars().all(ok) && name.chars().all(ok)
+}
+
+/// Fetch the list of GGUF files available in a HuggingFace repository.
+///
+/// Results are sorted by size ascending so smaller quantizations appear first.
+/// Passes `hf_token` as a Bearer token when provided.
+pub async fn fetch_hf_gguf_files(
+ repo_id: &str,
+ hf_token: Option<&str>,
+) -> Result<Vec<HfFileInfo>, String> {
+ let url = format!(
+ "https://huggingface.co/api/models/{}?blobs=true&files_metadata=true",
+ repo_id
+ );
+
+ let client = reqwest::Client::new();
+ let mut req = client.get(&url);
+ if let Some(tok) = hf_token {
+ req = req.bearer_auth(tok);
+ }
+
+ let resp = req.send().await.map_err(|e| e.to_string())?;
+ let status = resp.status();
+
+ if !status.is_success() {
+ return Err(match status.as_u16() {
+ 401 | 403 => format!(
+ "HuggingFace returned {status} for '{repo_id}'. \
+ The repo may be gated — set the HF_TOKEN environment variable."
+ ),
+ 404 => format!(
+ "HuggingFace repo '{repo_id}' not found. \
+ Check the repo ID or run `jan models list` to see local models."
+ ),
+ _ => format!("HuggingFace API error {status} for '{repo_id}'."),
+ });
+ }
+
+ let body: serde_json::Value = resp.json().await.map_err(|e| e.to_string())?;
+
+ let siblings = body["siblings"]
+ .as_array()
+ .ok_or_else(|| "Unexpected HuggingFace API response format".to_string())?;
+
+ let mut files: Vec<HfFileInfo> = siblings
+ .iter()
+ .filter_map(|s| {
+ let name = s["rfilename"].as_str()?;
+ if !name.to_lowercase().ends_with(".gguf") {
+ return None;
+ }
+ // Prefer LFS size, fall back to top-level size field
+ let size = s["lfs"]["size"]
+ .as_u64()
+ .or_else(|| s["size"].as_u64())
+ .unwrap_or(0);
+ let sha256 = s["lfs"]["sha256"].as_str().map(str::to_owned);
+ let download_url = format!(
+ "https://huggingface.co/{}/resolve/main/{}",
+ repo_id, name
+ );
+ Some(HfFileInfo {
+ filename: name.to_owned(),
+ size,
+ sha256,
+ download_url,
+ })
+ })
+ .collect();
+
+ if files.is_empty() {
+ return Err(format!(
+ "No GGUF files found in HuggingFace repo '{repo_id}'. \
+ For MLX/safetensors repos use `jan models load-mlx`."
+ ));
+ }
+
+ // Smaller quantizations first
+ files.sort_by_key(|f| f.size);
+ Ok(files)
+}
+
+/// Download one GGUF file from HuggingFace and write a `model.yml` for it.
+///
+/// The model is stored at:
+/// `<data_folder>/llamacpp/models/<repo_id>/<filename>`
+///
+/// `on_progress(downloaded, total)` is called after each chunk.
+/// Returns the local model ID (same as `repo_id`).
+pub async fn download_hf_model(
+ repo_id: &str,
+ file: &HfFileInfo,
+ hf_token: Option<&str>,
+ on_progress: impl Fn(u64, u64) + Send,
+) -> Result<String, String> {
+ use futures_util::StreamExt;
+ use tokio::io::AsyncWriteExt;
+
+ let data_folder = resolve_jan_data_folder();
+ let model_dir = data_folder
+ .join("llamacpp")
+ .join("models")
+ .join(repo_id);
+ tokio::fs::create_dir_all(&model_dir)
+ .await
+ .map_err(|e| e.to_string())?;
+
+ let dest_path = model_dir.join(&file.filename);
+
+ // ── Download ──────────────────────────────────────────────────────────
+ let client = reqwest::Client::new();
+ let mut req = client.get(&file.download_url);
+ if let Some(tok) = hf_token {
+ req = req.bearer_auth(tok);
+ }
+
+ let resp = req.send().await.map_err(|e| e.to_string())?;
+ if !resp.status().is_success() {
+ return Err(format!("Download request failed: {}", resp.status()));
+ }
+
+ // Use the server-reported content-length, fall back to metadata size
+ let total = resp.content_length().unwrap_or(file.size);
+ let mut downloaded: u64 = 0;
+
+ let mut dest = tokio::fs::File::create(&dest_path)
+ .await
+ .map_err(|e| e.to_string())?;
+
+ let mut stream = resp.bytes_stream();
+ while let Some(chunk) = stream.next().await {
+ let chunk = chunk.map_err(|e| e.to_string())?;
+ dest.write_all(&chunk).await.map_err(|e| e.to_string())?;
+ downloaded += chunk.len() as u64;
+ on_progress(downloaded, total);
+ }
+ dest.flush().await.map_err(|e| e.to_string())?;
+
+ // ── Write model.yml ───────────────────────────────────────────────────
+ // model_path is relative to the Jan data folder
+ let rel_path = format!(
+ "llamacpp/models/{}/{}",
+ repo_id, file.filename
+ );
+ let display_name = repo_id.split('/').last().unwrap_or(repo_id);
+
+ let mut yml = format!(
+ "model_path: {rel_path}\nname: {display_name}\nsize_bytes: {}\nembedding: false\n",
+ file.size
+ );
+ if let Some(sha) = &file.sha256 {
+ yml.push_str(&format!("model_sha256: {sha}\n"));
+ }
+
+ tokio::fs::write(model_dir.join("model.yml"), yml)
+ .await
+ .map_err(|e| e.to_string())?;
+
+ Ok(repo_id.to_string())
+}
+
+// ── App config ────────────────────────────────────────────────────────────
+
+pub fn cli_get_data_folder() -> PathBuf {
+ resolve_jan_data_folder()
+}
+
+pub fn cli_get_config() -> Result<serde_json::Value, String> {
+ let path = resolve_config_file_path();
+ if !path.exists() {
+ return Err(format!("Config file not found at: {}", path.display()));
+ }
+ let data = std::fs::read_to_string(&path).map_err(|e| e.to_string())?;
+ serde_json::from_str(&data).map_err(|e| e.to_string())
+}
diff --git a/src-tauri/src/core/mod.rs b/src-tauri/src/core/mod.rs
index 3d6a37d27..86844f8c9 100644
--- a/src-tauri/src/core/mod.rs
+++ b/src-tauri/src/core/mod.rs
@@ -1,4 +1,6 @@
pub mod app;
+#[cfg(feature = "cli")]
+pub mod cli;
pub mod downloads;
pub mod extensions;
pub mod filesystem;
diff --git a/src-tauri/src/core/server/commands.rs b/src-tauri/src/core/server/commands.rs
index 598ede199..d5c3d823e 100644
--- a/src-tauri/src/core/server/commands.rs
+++ b/src-tauri/src/core/server/commands.rs
@@ -5,6 +5,7 @@ use tauri_plugin_mlx::state::MlxState;
use crate::core::server::proxy;
use crate::core::state::AppState;
+
#[derive(serde::Deserialize)]
pub struct StartServerConfig {
pub host: String,
@@ -46,7 +47,7 @@ pub async fn start_server<R: Runtime>(
api_key,
vec![trusted_hosts],
proxy_timeout,
- app_handle,
+ state.provider_configs.clone(),
)
.await
.map_err(|e| e.to_string())?;
diff --git a/src-tauri/src/core/server/proxy.rs b/src-tauri/src/core/server/proxy.rs
index 50eaef61f..4decc9648 100644
--- a/src-tauri/src/core/server/proxy.rs
+++ b/src-tauri/src/core/server/proxy.rs
@@ -9,11 +9,10 @@ use std::collections::HashMap;
use std::convert::Infallible;
use std::net::SocketAddr;
use std::sync::Arc;
-use tauri::Manager;
use tauri_plugin_llamacpp::LLamaBackendSession;
use tokio::sync::Mutex;
-use crate::core::state::{AppState, ServerHandle};
+use crate::core::state::{ProviderConfig, ServerHandle};
/// Transform Anthropic /messages API body to OpenAI /chat/completions body
fn transform_anthropic_to_openai(body: &serde_json::Value) -> Option<serde_json::Value> {
@@ -425,13 +424,13 @@ pub fn get_destination_path(original_path: &str, prefix: &str) -> String {
use tauri_plugin_mlx::state::{MlxBackendSession, SessionInfo};
/// Handles the proxy request logic
-async fn proxy_request<R: tauri::Runtime>(
+async fn proxy_request(
req: Request<Body>,
client: Client,
config: ProxyConfig,
sessions: Arc<Mutex<HashMap<i32, LLamaBackendSession>>>,
mlx_sessions: Arc<Mutex<HashMap<i32, MlxBackendSession>>>,
- app_handle: tauri::AppHandle<R>,
+ provider_configs: Arc<Mutex<HashMap<String, ProviderConfig>>>,
) -> Result<Response<Body>, hyper::Error> {
if req.method() == hyper::Method::OPTIONS {
log::debug!(
@@ -725,32 +724,30 @@ async fn proxy_request<R: tauri::Runtime>(
match serde_json::from_slice::<serde_json::Value>(&body_bytes) {
Ok(json_body) => {
if let Some(model_id) = json_body.get("model").and_then(|v| v.as_str()) {
- let state = app_handle.state::<AppState>();
- let provider_configs = state.provider_configs.lock().await;
+ let pc = provider_configs.lock().await;
// Try to find a provider for this model
- provider_name = provider_configs
+ provider_name = pc
.iter()
.find(|(_, config)| config.models.iter().any(|m| m == model_id))
.map(|(_, config)| config.provider.clone())
.or_else(|| {
if let Some(sep_pos) = model_id.find('/') {
let potential_provider: &str = &model_id[..sep_pos];
- if provider_configs.contains_key(potential_provider) {
+ if pc.contains_key(potential_provider) {
return Some(potential_provider.to_string());
}
}
- provider_configs.get(model_id).map(|c| c.provider.clone())
+ pc.get(model_id).map(|c| c.provider.clone())
});
- drop(provider_configs);
+ drop(pc);
if let Some(ref p) = provider_name {
log::info!("Using remote provider '{p}' for model '{model_id}'");
- let state = app_handle.state::<AppState>();
- let provider_configs = state.provider_configs.lock().await;
- let provider_config = provider_configs.get(p.as_str()).cloned();
- drop(provider_configs);
+ let pc2 = provider_configs.lock().await;
+ let provider_config = pc2.get(p.as_str()).cloned();
+ drop(pc2);
if let Some(provider_cfg) = provider_config {
target_base_url = provider_cfg.base_url.clone().map(|url| {
@@ -859,11 +856,10 @@ async fn proxy_request<R: tauri::Runtime>(
log::debug!("Extracted model_id: {model_id}");
// First, check if there's a registered remote provider for this model
- let state = app_handle.state::<AppState>();
- let provider_configs = state.provider_configs.lock().await;
+ let pc = provider_configs.lock().await;
// Try to find a provider that has this model configured
- let provider_name = provider_configs
+ let provider_name = pc
.iter()
.find(|(_, config)| {
// Check if any model in this provider matches
@@ -874,32 +870,31 @@ async fn proxy_request<R: tauri::Runtime>(
// 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: &str = &model_id[..sep_pos];
- if provider_configs.contains_key(potential_provider) {
+ if pc.contains_key(potential_provider) {
return Some(potential_provider.to_string());
}
}
// Also check if the model_id itself matches a provider name
- provider_configs.get(model_id).map(|c| c.provider.clone())
+ pc.get(model_id).map(|c| c.provider.clone())
});
- drop(provider_configs);
+ drop(pc);
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}'");
// 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.as_str()).cloned();
+ let pc2 = provider_configs.lock().await;
+ let provider_config = pc2.get(provider.as_str()).cloned();
// Log registered providers for debugging
log::debug!(
"Registered providers: {:?}",
- provider_configs.keys().collect::<Vec<_>>()
+ pc2.keys().collect::<Vec<_>>()
);
- drop(provider_configs);
+ drop(pc2);
if let Some(provider_cfg) = provider_config {
if let Some(api_url) = provider_cfg.base_url.clone() {
@@ -1060,9 +1055,8 @@ async fn proxy_request<R: tauri::Runtime>(
};
// Get remote provider models
- let state = app_handle.state::<AppState>();
- let provider_configs = state.provider_configs.lock().await;
- let remote_models: Vec<_> = provider_configs
+ let pc = provider_configs.lock().await;
+ let remote_models: Vec<_> = pc
.values()
.flat_map(|provider_cfg| provider_cfg.models.clone())
.map(|model_id| {
@@ -1554,7 +1548,7 @@ pub async fn is_server_running(server_handle: Arc<Mutex<Option<ServerHandle>>>)
}
#[allow(clippy::too_many_arguments)]
-pub async fn start_server<R: tauri::Runtime>(
+pub async fn start_server(
server_handle: Arc<Mutex<Option<ServerHandle>>>,
sessions: Arc<Mutex<HashMap<i32, LLamaBackendSession>>>,
mlx_sessions: Arc<Mutex<HashMap<i32, MlxBackendSession>>>,
@@ -1564,7 +1558,7 @@ pub async fn start_server<R: tauri::Runtime>(
proxy_api_key: String,
trusted_hosts: Vec<Vec<String>>,
proxy_timeout: u64,
- app_handle: tauri::AppHandle<R>,
+ provider_configs: Arc<Mutex<HashMap<String, ProviderConfig>>>,
) -> Result<u16, Box<dyn std::error::Error + Send + Sync>> {
start_server_internal(
server_handle,
@@ -1576,12 +1570,12 @@ pub async fn start_server<R: tauri::Runtime>(
proxy_api_key,
trusted_hosts,
proxy_timeout,
- app_handle,
+ provider_configs,
)
.await
}
-async fn start_server_internal<R: tauri::Runtime>(
+async fn start_server_internal(
server_handle: Arc<Mutex<Option<ServerHandle>>>,
sessions: Arc<Mutex<HashMap<i32, LLamaBackendSession>>>,
mlx_sessions: Arc<Mutex<HashMap<i32, MlxBackendSession>>>,
@@ -1591,7 +1585,7 @@ async fn start_server_internal<R: tauri::Runtime>(
proxy_api_key: String,
trusted_hosts: Vec<Vec<String>>,
proxy_timeout: u64,
- app_handle: tauri::AppHandle<R>,
+ provider_configs: Arc<Mutex<HashMap<String, ProviderConfig>>>,
) -> Result<u16, Box<dyn std::error::Error + Send + Sync>> {
let mut handle_guard = server_handle.lock().await;
if handle_guard.is_some() {
@@ -1621,7 +1615,7 @@ async fn start_server_internal<R: tauri::Runtime>(
let config = config.clone();
let sessions = sessions.clone();
let mlx_sessions = mlx_sessions.clone();
- let app_handle = app_handle.clone();
+ let provider_configs = provider_configs.clone();
async move {
Ok::<_, Infallible>(service_fn(move |req| {
@@ -1631,7 +1625,7 @@ async fn start_server_internal<R: tauri::Runtime>(
config.clone(),
sessions.clone(),
mlx_sessions.clone(),
- app_handle.clone(),
+ provider_configs.clone(),
)
}))
}
@@ -1646,7 +1640,7 @@ async fn start_server_internal<R: tauri::Runtime>(
};
log::info!("Jan API server started on http://{addr}");
- let server_task = tauri::async_runtime::spawn(async move {
+ let server_task = tokio::spawn(async move {
if let Err(e) = server.await {
log::error!("Server error: {e}");
return Err(Box::new(e) as Box<dyn std::error::Error + Send + Sync>);
diff --git a/src-tauri/src/core/state.rs b/src-tauri/src/core/state.rs
index 5b0234689..ee2a755d2 100644
--- a/src-tauri/src/core/state.rs
+++ b/src-tauri/src/core/state.rs
@@ -10,7 +10,7 @@ use tokio::sync::{oneshot, Mutex};
/// Server handle type for managing the proxy server lifecycle
pub type ServerHandle =
- tauri::async_runtime::JoinHandle<Result<(), Box<dyn std::error::Error + Send + Sync>>>;
+ tokio::task::JoinHandle<Result<(), Box<dyn std::error::Error + Send + Sync>>>;
/// Provider configuration for remote model providers
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
@@ -44,8 +44,8 @@ pub struct AppState {
pub tool_call_cancellations: Arc<Mutex<HashMap<String, oneshot::Sender<()>>>>,
pub mcp_settings: Arc<Mutex<McpSettings>>,
pub mcp_shutdown_in_progress: Arc<Mutex<bool>>,
- pub mcp_monitoring_tasks: Arc<Mutex<HashMap<String, tauri::async_runtime::JoinHandle<()>>>>,
- pub background_cleanup_handle: Arc<Mutex<Option<tauri::async_runtime::JoinHandle<()>>>>,
+ pub mcp_monitoring_tasks: Arc<Mutex<HashMap<String, tokio::task::JoinHandle<()>>>>,
+ pub background_cleanup_handle: Arc<Mutex<Option<tokio::task::JoinHandle<()>>>>,
pub mcp_server_pids: Arc<Mutex<HashMap<String, u32>>>,
/// Remote provider configurations (e.g., Anthropic, OpenAI, etc.)
pub provider_configs: Arc<Mutex<HashMap<String, ProviderConfig>>>,
diff --git a/src-tauri/src/core/threads/commands.rs b/src-tauri/src/core/threads/commands.rs
index 07bf46094..56e754ab6 100644
--- a/src-tauri/src/core/threads/commands.rs
+++ b/src-tauri/src/core/threads/commands.rs
@@ -16,6 +16,7 @@ use super::{
get_thread_dir, get_thread_metadata_path,
},
};
+use crate::core::app::commands::get_jan_data_folder_path;
/// Lists all threads by reading their metadata from the threads directory or database.
/// Returns a vector of thread metadata as JSON values.
@@ -30,8 +31,9 @@ pub async fn list_threads<R: Runtime>(
}
// Use file-based storage on desktop
- ensure_data_dirs(app_handle.clone())?;
- let data_dir = get_data_dir(app_handle.clone());
+ let data_folder = get_jan_data_folder_path(app_handle);
+ ensure_data_dirs(&data_folder)?;
+ let data_dir = get_data_dir(&data_folder);
let mut threads = Vec::new();
if !data_dir.exists() {
@@ -72,14 +74,15 @@ pub async fn create_thread<R: Runtime>(
}
// Use file-based storage on desktop
- ensure_data_dirs(app_handle.clone())?;
+ let data_folder = get_jan_data_folder_path(app_handle);
+ ensure_data_dirs(&data_folder)?;
let uuid = Uuid::new_v4().to_string();
thread["id"] = serde_json::Value::String(uuid.clone());
- let thread_dir = get_thread_dir(app_handle.clone(), &uuid);
+ let thread_dir = get_thread_dir(&data_folder, &uuid);
if !thread_dir.exists() {
fs::create_dir_all(&thread_dir).map_err(|e| e.to_string())?;
}
- let path = get_thread_metadata_path(app_handle.clone(), &uuid);
+ let path = get_thread_metadata_path(&data_folder, &uuid);
let data = serde_json::to_string_pretty(&thread).map_err(|e| e.to_string())?;
fs::write(path, data).map_err(|e| e.to_string())?;
Ok(thread)
@@ -98,15 +101,16 @@ pub async fn modify_thread<R: Runtime>(
}
// Use file-based storage on desktop
+ let data_folder = get_jan_data_folder_path(app_handle);
let thread_id = thread
.get("id")
.and_then(|id| id.as_str())
.ok_or("Missing thread id")?;
- let thread_dir = get_thread_dir(app_handle.clone(), thread_id);
+ let thread_dir = get_thread_dir(&data_folder, thread_id);
if !thread_dir.exists() {
return Err("Thread directory does not exist".to_string());
}
- let path = get_thread_metadata_path(app_handle.clone(), thread_id);
+ let path = get_thread_metadata_path(&data_folder, thread_id);
let data = serde_json::to_string_pretty(&thread).map_err(|e| e.to_string())?;
fs::write(path, data).map_err(|e| e.to_string())?;
Ok(())
@@ -124,7 +128,8 @@ pub async fn delete_thread<R: Runtime>(
}
// Use file-based storage on desktop
- let thread_dir = get_thread_dir(app_handle.clone(), &thread_id);
+ let data_folder = get_jan_data_folder_path(app_handle);
+ let thread_dir = get_thread_dir(&data_folder, &thread_id);
if thread_dir.exists() {
let _ = fs::remove_dir_all(thread_dir);
}
@@ -144,7 +149,8 @@ pub async fn list_messages<R: Runtime>(
}
// Use file-based storage on desktop
- read_messages_from_file(app_handle, &thread_id)
+ let data_folder = get_jan_data_folder_path(app_handle);
+ read_messages_from_file(&data_folder, &thread_id)
}
/// Appends a new message to a thread's messages.jsonl file.
@@ -160,6 +166,7 @@ pub async fn create_message<R: Runtime>(
}
// Use file-based storage on desktop
+ let data_folder = get_jan_data_folder_path(app_handle);
let thread_id = {
let id = message
.get("thread_id")
@@ -167,7 +174,7 @@ pub async fn create_message<R: Runtime>(
.ok_or("Missing thread_id")?;
id.to_string()
};
- let path = get_messages_path(app_handle.clone(), &thread_id);
+ let path = get_messages_path(&data_folder, &thread_id);
if message.get("id").is_none() {
let uuid = Uuid::new_v4().to_string();
@@ -180,7 +187,7 @@ pub async fn create_message<R: Runtime>(
let _guard = lock.lock().await;
// Ensure directory exists right before file operations to handle race conditions
- ensure_thread_dir_exists(app_handle.clone(), &thread_id)?;
+ ensure_thread_dir_exists(&data_folder, &thread_id)?;
let mut file: File = fs::OpenOptions::new()
.create(true)
@@ -212,6 +219,7 @@ pub async fn modify_message<R: Runtime>(
}
// Use file-based storage on desktop
+ let data_folder = get_jan_data_folder_path(app_handle);
let thread_id = message
.get("thread_id")
.and_then(|v| v.as_str())
@@ -226,7 +234,7 @@ pub async fn modify_message<R: Runtime>(
let lock = get_lock_for_thread(thread_id).await;
let _guard = lock.lock().await;
- let mut messages = read_messages_from_file(app_handle.clone(), thread_id)?;
+ let mut messages = read_messages_from_file(&data_folder, thread_id)?;
if let Some(index) = messages
.iter()
.position(|m| m.get("id").and_then(|v| v.as_str()) == Some(message_id))
@@ -234,7 +242,7 @@ pub async fn modify_message<R: Runtime>(
messages[index] = message.clone();
// Rewrite all messages
- let path = get_messages_path(app_handle.clone(), thread_id);
+ let path = get_messages_path(&data_folder, thread_id);
write_messages_to_file(&messages, &path)?;
}
}
@@ -256,16 +264,17 @@ pub async fn delete_message<R: Runtime>(
}
// Use file-based storage on desktop
+ let data_folder = get_jan_data_folder_path(app_handle);
// Acquire per-thread lock before modifying
{
let lock = get_lock_for_thread(&thread_id).await;
let _guard = lock.lock().await;
- let mut messages = read_messages_from_file(app_handle.clone(), &thread_id)?;
+ let mut messages = read_messages_from_file(&data_folder, &thread_id)?;
messages.retain(|m| m.get("id").and_then(|v| v.as_str()) != Some(message_id.as_str()));
// Rewrite remaining messages
- let path = get_messages_path(app_handle.clone(), &thread_id);
+ let path = get_messages_path(&data_folder, &thread_id);
write_messages_to_file(&messages, &path)?;
}
@@ -285,7 +294,8 @@ pub async fn get_thread_assistant<R: Runtime>(
}
// Use file-based storage on desktop
- let path = get_thread_metadata_path(app_handle, &thread_id);
+ let data_folder = get_jan_data_folder_path(app_handle);
+ let path = get_thread_metadata_path(&data_folder, &thread_id);
if !path.exists() {
return Err("Thread not found".to_string());
}
@@ -316,7 +326,8 @@ pub async fn create_thread_assistant<R: Runtime>(
}
// Use file-based storage on desktop
- let path = get_thread_metadata_path(app_handle.clone(), &thread_id);
+ let data_folder = get_jan_data_folder_path(app_handle);
+ let path = get_thread_metadata_path(&data_folder, &thread_id);
if !path.exists() {
return Err("Thread not found".to_string());
}
@@ -329,7 +340,7 @@ pub async fn create_thread_assistant<R: Runtime>(
} else {
thread["assistants"] = serde_json::Value::Array(vec![assistant.clone()]);
}
- update_thread_metadata(app_handle, &thread_id, &thread)?;
+ update_thread_metadata(&data_folder, &thread_id, &thread)?;
Ok(assistant)
}
@@ -347,7 +358,8 @@ pub async fn modify_thread_assistant<R: Runtime>(
}
// Use file-based storage on desktop
- let path = get_thread_metadata_path(app_handle.clone(), &thread_id);
+ let data_folder = get_jan_data_folder_path(app_handle);
+ let path = get_thread_metadata_path(&data_folder, &thread_id);
if !path.exists() {
return Err("Thread not found".to_string());
}
@@ -368,7 +380,7 @@ pub async fn modify_thread_assistant<R: Runtime>(
.position(|a| a.get("id").and_then(|v| v.as_str()) == Some(assistant_id))
{
assistants[index] = assistant.clone();
- update_thread_metadata(app_handle, &thread_id, &thread)?;
+ update_thread_metadata(&data_folder, &thread_id, &thread)?;
}
}
Ok(assistant)
diff --git a/src-tauri/src/core/threads/helpers.rs b/src-tauri/src/core/threads/helpers.rs
index 75eb7d69f..ace5ae425 100644
--- a/src-tauri/src/core/threads/helpers.rs
+++ b/src-tauri/src/core/threads/helpers.rs
@@ -1,6 +1,6 @@
use std::fs::{self, File};
use std::io::{BufRead, BufReader, Write};
-use tauri::Runtime;
+use std::path::Path;
// For async file write serialization
use std::collections::HashMap;
@@ -44,11 +44,11 @@ pub fn write_messages_to_file(
}
/// Read messages from a thread's messages.jsonl file
-pub fn read_messages_from_file<R: Runtime>(
- app_handle: tauri::AppHandle<R>,
+pub fn read_messages_from_file(
+ data_folder: &Path,
thread_id: &str,
) -> Result<Vec<serde_json::Value>, String> {
- let path = get_messages_path(app_handle, thread_id);
+ let path = get_messages_path(data_folder, thread_id);
if !path.exists() {
return Ok(vec![]);
}
@@ -80,12 +80,12 @@ pub fn read_messages_from_file<R: Runtime>(
}
/// Update thread metadata by writing to thread.json
-pub fn update_thread_metadata<R: Runtime>(
- app_handle: tauri::AppHandle<R>,
+pub fn update_thread_metadata(
+ data_folder: &Path,
thread_id: &str,
thread: &serde_json::Value,
) -> Result<(), String> {
- let path = get_thread_metadata_path(app_handle, thread_id);
+ let path = get_thread_metadata_path(data_folder, thread_id);
let data = serde_json::to_string_pretty(thread).map_err(|e| e.to_string())?;
fs::write(path, data).map_err(|e| e.to_string())?;
Ok(())
diff --git a/src-tauri/src/core/threads/mod.rs b/src-tauri/src/core/threads/mod.rs
index 99c00253e..094503b68 100644
--- a/src-tauri/src/core/threads/mod.rs
+++ b/src-tauri/src/core/threads/mod.rs
@@ -11,7 +11,7 @@
*/
pub mod commands;
-mod constants;
+pub mod constants;
#[cfg(any(target_os = "android", target_os = "ios"))]
pub mod db;
pub mod helpers;
diff --git a/src-tauri/src/core/threads/tests.rs b/src-tauri/src/core/threads/tests.rs
index 17dfb580e..bcc944cee 100644
--- a/src-tauri/src/core/threads/tests.rs
+++ b/src-tauri/src/core/threads/tests.rs
@@ -237,10 +237,8 @@ async fn test_desktop_storage_backend() {
"Message should be retrievable from file-based storage"
);
- // Clean up - get the actual data directory used by the app
- use super::utils::get_data_dir;
- let actual_data_dir = get_data_dir(app.handle().clone());
- let _ = fs::remove_dir_all(actual_data_dir);
+ // Clean up
+ let _ = fs::remove_dir_all(&_data_dir);
}
}
diff --git a/src-tauri/src/core/threads/utils.rs b/src-tauri/src/core/threads/utils.rs
index b5b6b5e3c..3c6174c57 100644
--- a/src-tauri/src/core/threads/utils.rs
+++ b/src-tauri/src/core/threads/utils.rs
@@ -1,43 +1,35 @@
use std::fs;
-use std::path::PathBuf;
-use tauri::Runtime;
+use std::path::{Path, PathBuf};
use super::constants::{MESSAGES_FILE, THREADS_DIR, THREADS_FILE};
-use crate::core::app::commands::get_jan_data_folder_path;
-pub fn get_data_dir<R: Runtime>(app_handle: tauri::AppHandle<R>) -> PathBuf {
- get_jan_data_folder_path(app_handle).join(THREADS_DIR)
+pub fn get_data_dir(data_folder: &Path) -> PathBuf {
+ data_folder.join(THREADS_DIR)
}
-pub fn get_thread_dir<R: Runtime>(app_handle: tauri::AppHandle<R>, thread_id: &str) -> PathBuf {
- get_data_dir(app_handle).join(thread_id)
+pub fn get_thread_dir(data_folder: &Path, thread_id: &str) -> PathBuf {
+ get_data_dir(data_folder).join(thread_id)
}
-pub fn get_thread_metadata_path<R: Runtime>(
- app_handle: tauri::AppHandle<R>,
- thread_id: &str,
-) -> PathBuf {
- get_thread_dir(app_handle, thread_id).join(THREADS_FILE)
+pub fn get_thread_metadata_path(data_folder: &Path, thread_id: &str) -> PathBuf {
+ get_thread_dir(data_folder, thread_id).join(THREADS_FILE)
}
-pub fn get_messages_path<R: Runtime>(app_handle: tauri::AppHandle<R>, thread_id: &str) -> PathBuf {
- get_thread_dir(app_handle, thread_id).join(MESSAGES_FILE)
+pub fn get_messages_path(data_folder: &Path, thread_id: &str) -> PathBuf {
+ get_thread_dir(data_folder, thread_id).join(MESSAGES_FILE)
}
-pub fn ensure_data_dirs<R: Runtime>(app_handle: tauri::AppHandle<R>) -> Result<(), String> {
- let data_dir = get_data_dir(app_handle.clone());
+pub fn ensure_data_dirs(data_folder: &Path) -> Result<(), String> {
+ let data_dir = get_data_dir(data_folder);
if !data_dir.exists() {
fs::create_dir_all(&data_dir).map_err(|e| e.to_string())?;
}
Ok(())
}
-pub fn ensure_thread_dir_exists<R: Runtime>(
- app_handle: tauri::AppHandle<R>,
- thread_id: &str,
-) -> Result<(), String> {
- ensure_data_dirs(app_handle.clone())?;
- let thread_dir = get_thread_dir(app_handle, thread_id);
+pub fn ensure_thread_dir_exists(data_folder: &Path, thread_id: &str) -> Result<(), String> {
+ ensure_data_dirs(data_folder)?;
+ let thread_dir = get_thread_dir(data_folder, thread_id);
if !thread_dir.exists() {
fs::create_dir_all(&thread_dir).map_err(|e| e.to_string())?;
}
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index c5d02c94c..128b6fb44 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -2,6 +2,8 @@ pub mod core;
pub mod openclaw_cli;
pub use core::openclaw::OpenClawState;
+
+#[cfg(not(feature = "cli"))]
use core::{
app::commands::get_jan_data_folder_path,
downloads::models::DownloadManagerState,
@@ -9,12 +11,18 @@ use core::{
setup::{self, setup_mcp},
state::AppState,
};
+#[cfg(not(feature = "cli"))]
use jan_utils::generate_app_token;
+#[cfg(not(feature = "cli"))]
use std::{collections::HashMap, sync::Arc};
+#[cfg(not(feature = "cli"))]
use tauri::{Emitter, Manager, RunEvent};
+#[cfg(not(feature = "cli"))]
use tauri_plugin_store::StoreExt;
+#[cfg(not(feature = "cli"))]
use tokio::sync::Mutex;
+#[cfg(not(feature = "cli"))]
#[cfg_attr(
all(mobile, any(target_os = "android", target_os = "ios")),
tauri::mobile_entry_point