Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
refactor(cli): TUI-first surface; drop launch/serve and redundant agent ui
Akarshan Biswas14141984c0e4
diff --git a/src-tauri/src/bin/jan.rs b/src-tauri/src/bin/jan.rsindex e663bb506..f4e1406e4 100644--- a/src-tauri/src/bin/jan.rs+++ b/src-tauri/src/bin/jan.rs@@ -3,12 +3,8 @@//! 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).@@ -16,98 +12,83 @@ use app_lib::core::cli::providers::ProviderOverrides;use app_lib::core::cli::{cli_agent_config_list, cli_agent_config_path, cli_agent_config_set, cli_agent_config_unset,cli_agent_run, cli_agent_status, cli_agent_step, cli_agent_ui, cli_delete_thread,- cli_get_data_folder, cli_get_thread, cli_list_messages, cli_list_threads,- discover_llamacpp_binary, download_hf_model, ensure_router_and_load, fetch_hf_gguf_files,- init_llamacpp_state, list_models, looks_like_hf_repo, resolve_model_engine, HfFileInfo,-};-// MLX is macOS-only; these CLI symbols don't exist on other platforms.-#[cfg(target_os = "macos")]-use app_lib::core::cli::{- discover_mlx_binary, init_mlx_state, load_mlx_model_impl, resolve_model_by_id, MlxConfig,+ cli_get_thread, cli_list_messages, cli_list_threads, list_models,};-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 agent like Claude Code\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.",+ about = "Chat with local AI models in an interactive agent console — no cloud required",+ long_about = "Running `jan` with no arguments opens the interactive agent console (TUI),\n\+where you chat with a local or cloud model that can run tools in your project.\n\n\+The `jan cli` subcommand is the non-interactive fallback: run folder-based\n\+agents headlessly and manage threads and installed models.\n\n\+Models downloaded in the Jan desktop app are available in both.",after_help = "Examples:\n \- jan launch claude # pick a model, then run Claude Code against it\n \- jan launch claude --model janhq/Jan-code-4b-gguf # use a specific model\n \- jan launch openclaw --model janhq/Jan-code-4b-gguf # wire openclaw to a local model\n \- jan serve janhq/Jan-code-4b-gguf # expose a model at localhost:6767/v1\n \- jan serve janhq/Jan-code-4b-gguf --fit # auto-fit context to available VRAM\n \- jan serve janhq/Jan-code-4b-gguf --detach # run in the background\n \- jan models list # show all installed models",+ jan # open the interactive agent console (TUI)\n \+ jan --yolo # TUI with every tool call auto-approved\n \+ jan --task \"fix the failing test\" # seed the TUI with a first message\n \+ jan cli agent run \"fix the failing test\" # run the agent non-interactively\n \+ jan cli models list # show all installed models\n \+ jan cli threads list # list saved conversation threads",version)]struct Cli {#[command(subcommand)]command: Option<Commands>,+ /// Project root containing .jan/agent/agent.toml (bare TUI only)+ #[arg(long, default_value = ".")]+ project: String,+ /// Optional first message to seed the chat with (bare TUI only)+ #[arg(long)]+ task: Option<String>,+ /// Model ID overriding [agent].model in agent.toml (bare TUI only)+ #[arg(long)]+ model: Option<String>,+ /// Max turns per message, clamped 1..=400 (bare TUI only)+ #[arg(long)]+ max_turns: Option<u32>,+ /// Image file to attach to the first message, repeatable (bare TUI only)+ #[arg(long = "image")]+ images: Vec<String>,+ #[command(flatten)]+ providers: ProviderArgs,/// Disable the sandbox and auto-approve every tool call in the default agent/// TUI (no prompts). Ignored when a subcommand is given.#[arg(long)]yolo: bool,}+/// Top-level commands. Bare `jan` opens the interactive TUI; everything else+/// lives under the non-interactive `cli` fallback.#[derive(Subcommand)]enum Commands {- /// Load a local model and expose it at localhost:6767/v1 (auto-detects LlamaCPP or MLX)+ /// Non-interactive CLI: launch agents, run headless agent tasks, manage models and threads#[command(display_order = 1)]- Serve {- #[command(flatten)]- args: ServeArgs,+ Cli {+ #[command(subcommand)]+ cmd: CliCommands,},- /// Start a local model, then launch an AI agent with it pre-wired (env vars set automatically)+ /// Manage provider credentials in ~/.jan/config.toml (used by the TUI and CLI)#[command(display_order = 2)]- Launch {- /// Agent or program to run after the model is ready (e.g. claude, openclaw)- /// Omit to pick interactively from: claude, openclaw- program: Option<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>,- /// Path to the inference binary (auto-discovered from Jan data folder when omitted)- #[arg(long)]- bin: 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 (default: 4096; disables --fit when set explicitly)- #[arg(long)]- ctx_size: Option<i32>,- /// Auto-fit context to available VRAM (default: on when launching claude, unless --ctx-size is set)- #[arg(long)]- fit: Option<bool>,- /// Print full server logs (llama.cpp / mlx output) instead of the loading spinner- #[arg(long, short = 'v', default_value_t = false)]- verbose: bool,- /// When downloading a model, show quantization selection list- #[arg(long, default_value_t = false)]- select: bool,+ Config {+ #[command(subcommand)]+ cmd: AgentConfigCommands,},+}++/// The non-interactive command surface, reached via `jan cli <command>`.+#[derive(Subcommand)]+enum CliCommands {/// 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+ /// List models installed in the Jan data folder#[command(display_order = 11)]Models {#[command(subcommand)]@@ -171,28 +152,6 @@ enum AgentCommands {#[command(flatten)]providers: ProviderArgs,},- /// Open the interactive chat console (optionally seeded with a first message)- Ui {- /// Project root containing .jan/agent/agent.toml- #[arg(long, default_value = ".")]- project: String,- /// Optional first message; omit to start with an empty chat- task: Option<String>,- /// Model ID (overrides [agent].model in agent.toml)- #[arg(long)]- model: Option<String>,- /// Max turns per message (overrides [agent].max_turns; clamped 1..=400)- #[arg(long)]- max_turns: Option<u32>,- /// Image file to attach to the first message (repeatable)- #[arg(long = "image")]- images: Vec<String>,- /// Disable the sandbox and auto-approve every tool call (no prompts)- #[arg(long)]- yolo: bool,- #[command(flatten)]- providers: ProviderArgs,- },/// Run a single turn (debugging)Step {/// Project root containing .jan/agent/agent.toml@@ -217,11 +176,6 @@ enum AgentCommands {#[command(flatten)]providers: ProviderArgs,},- /// Manage standalone provider credentials in ~/.jan/config.toml (no Desktop needed)- Config {- #[command(subcommand)]- cmd: AgentConfigCommands,- },}/// Read/write the user-wide `~/.jan/config.toml` provider store. This is the@@ -282,59 +236,6 @@ enum ThreadsCommands {},}-// ── 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 = 32768)]- 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>,- /// Print full server logs (llama.cpp / mlx output) instead of the loading spinner- #[arg(long, short = 'v', default_value_t = false)]- verbose: bool,- /// When downloading a model, show quantization selection list- #[arg(long, default_value_t = false)]- select: bool,-}-// ── Models subcommands ─────────────────────────────────────────────────────#[derive(Subcommand)]@@ -345,39 +246,6 @@ enum ModelsCommands {#[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)- #[cfg(target_os = "macos")]- 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,- },}// ── ASCII logo ─────────────────────────────────────────────────────────────@@ -436,12 +304,18 @@ async fn main() {let cli = Cli::from_arg_matches(&matches).unwrap_or_else(|e| e.exit());let Some(command) = cli.command else {- let overrides = ProviderArgs {- provider: None,- api_key: None,- }- .into_overrides();- if let Err(e) = cli_agent_ui(".", None, None, None, Vec::new(), overrides, cli.yolo).await {+ let overrides = cli.providers.into_overrides();+ if let Err(e) = cli_agent_ui(+ &cli.project,+ cli.task,+ cli.model,+ cli.max_turns,+ cli.images,+ overrides,+ cli.yolo,+ )+ .await+ {eprintln!("Error: {e}");std::process::exit(1);}@@ -449,44 +323,26 @@ async fn main() {};match command {- Commands::Threads { cmd } => handle_threads(cmd).await,- Commands::Models { cmd } => handle_models(cmd).await,- Commands::Agent { cmd } => handle_agent(cmd).await,- Commands::Serve { args } => handle_serve(args).await,- Commands::Launch {- program,- program_args,- model,- bin,- port,- api_key,- n_gpu_layers,- ctx_size,- fit,- verbose,- select,- } => {- let program = program.unwrap_or_else(select_program_interactively);- let ctx_size_val = ctx_size.unwrap_or(32768);- handle_launch(- program,- program_args,- model,- bin,- port,- api_key,- n_gpu_layers,- ctx_size_val,- fit,- ctx_size.is_none(),- verbose,- select,- )- .await+ Commands::Cli { cmd } => handle_cli(cmd).await,+ Commands::Config { cmd } => {+ if let Err(e) = handle_agent_config(cmd) {+ eprintln!("Error: {e}");+ std::process::exit(1);+ }}}}+// ── CLI dispatch ─────────────────────────────────────────────────────────++async fn handle_cli(cmd: CliCommands) {+ match cmd {+ CliCommands::Threads { cmd } => handle_threads(cmd).await,+ CliCommands::Models { cmd } => handle_models(cmd).await,+ CliCommands::Agent { cmd } => handle_agent(cmd).await,+ }+}+// ── Agent handlers ───────────────────────────────────────────────────────async fn handle_agent(cmd: AgentCommands) {@@ -509,26 +365,6 @@ async fn handle_agent(cmd: AgentCommands) {).await}- AgentCommands::Ui {- project,- task,- model,- max_turns,- images,- yolo,- providers,- } => {- cli_agent_ui(- &project,- task,- model,- max_turns,- images,- providers.into_overrides(),- yolo,- )- .await- }AgentCommands::Step {project,task,@@ -545,7 +381,6 @@ async fn handle_agent(cmd: AgentCommands) {Err(e) => Err(e),}}- AgentCommands::Config { cmd } => handle_agent_config(cmd),};if let Err(e) = result {eprintln!("Error: {e}");@@ -654,1042 +489,6 @@ async fn handle_models(cmd: ModelsCommands) {}println!("{}", serde_json::to_string_pretty(&output).unwrap());}-- ModelsCommands::Load { args } => handle_serve(args).await,-- #[cfg(target_os = "macos")]- 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<String, String> = 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 / progress helpers ─────────────────────────────────────────────--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-}--/// Start a spinner, or print a plain status line if verbose mode is on.-/// Returns `None` in verbose mode so callers know to skip spinner updates.-fn start_progress(verbose: bool, msg: impl Into<String>) -> Option<ProgressBar> {- if verbose {- eprintln!("{}", msg.into());- None- } else {- Some(make_spinner(msg.into()))- }-}--/// Finish the spinner with a final message, or print the message plainly in verbose mode.-fn finish_progress(pb: Option<ProgressBar>, msg: impl AsRef<str>) {- match pb {- Some(pb) => {- pb.finish_and_clear();- eprintln!("{}", msg.as_ref());- }- None => eprintln!("{}", msg.as_ref()),- }-}--// ── 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, select_quantization: bool) -> 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();-- // Select quantization: show picker if select_quantization is true, otherwise auto-pick Q4_K_XL- let chosen = if select_quantization {- pick_hf_file(&files)- } else {- files- .iter()- .find(|f| f.filename.contains("Q4_K_XL"))- .unwrap_or_else(|| files.iter().max_by_key(|f| f.size).unwrap())- };- 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 pickers ────────────────────────────────────────────────────--/// Present an interactive menu for the supported AI agents.-fn select_program_interactively() -> String {- const CHOICES: &[(&str, &str)] = &[- ("claude", "Claude Code — Anthropic's AI coding agent"),- ("openclaw", "OpenClaw — Open-source autonomous AI agent"),- ];-- println!();- let header = Style::new().cyan().bold().apply_to("━━━ Select Agent ━━━");- println!("{}", header);- println!();-- let installed: Vec<bool> = CHOICES- .iter()- .map(|(key, _)| {- is_command_installed(key) || (*key == "openclaw" && is_command_installed("opencode"))- })- .collect();-- if !installed.iter().any(|&i| i) {- eprintln!(" No supported agents are installed.");- eprintln!(" Install Claude Code: npm install -g @anthropic-ai/claude-code");- eprintln!(" Install OpenClaw: curl -fsSL https://openclaw.ai/install.sh | bash -s -- --no-onboard");- std::process::exit(1);- }-- let labels: Vec<String> = CHOICES- .iter()- .zip(installed.iter())- .map(|((_, desc), &ok)| {- if ok {- desc.to_string()- } else {- format!(- "{} {}",- Style::new().dim().apply_to(desc),- Style::new().dim().apply_to("[not installed]")- )- }- })- .collect();-- // Keep re-prompting until the user picks an installed agent- loop {- let idx = dialoguer::Select::new()- .with_prompt("Choose an agent to launch")- .items(&labels)- .default(0)- .interact()- .unwrap_or_else(|_| std::process::exit(1));-- if installed[idx] {- return CHOICES[idx].0.to_string();- }-- eprintln!(- " {} is not installed. Please choose an installed agent.",- CHOICES[idx].1- );- }-}--async fn select_model_interactively(select_quantization: bool) -> 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() {- let default_model = "janhq/Jan-v3-4B-base-instruct-gguf";- println!();- let msg = Style::new()- .yellow()- .apply_to("No models found. Downloading default model...");- println!("{}", msg);- println!();- println!(- " {} {}",- Style::new().dim().apply_to("Model:"),- default_model- );- println!();-- // Auto-download the default model- let model_id = auto_download_hf_model(default_model, select_quantization).await;- return model_id;- }-- println!();- let header = Style::new().cyan().bold().apply_to("━━━ Select Model ━━━");- println!("{}", header);- println!();-- // Group by engine for better display- let mut llamacpp_models: Vec<&String> = Vec::new();- let mut mlx_models: Vec<&String> = Vec::new();-- for (id, engine) in &all {- match engine.as_str() {- "llamacpp" => llamacpp_models.push(id),- "mlx" => mlx_models.push(id),- _ => {}- }- }-- // Build selection list with engine indicator next to model name- let selection_items: Vec<(usize, String)> = all- .iter()- .enumerate()- .map(|(i, (id, engine))| {- let indicator = match engine.as_str() {- "llamacpp" => Style::new().green().apply_to("[LlamaCPP]"),- "mlx" => Style::new().magenta().apply_to("[MLX]"),- _ => Style::new().dim().apply_to("[---]"),- };- (i, format!("{} {}", id, indicator))- })- .collect();-- // If only one model, skip interactive selection- if selection_items.len() == 1 {- println!(" Using model: {}", selection_items[0].1);- println!();- return all[selection_items[0].0].0.clone();- }-- let labels: Vec<String> = selection_items- .iter()- .map(|(_, label)| label.clone())- .collect();-- let selection = dialoguer::Select::new()- .with_prompt("Choose a model")- .items(&labels)- .default(0)- .interact()- .unwrap_or_else(|_| std::process::exit(1));-- all[selection_items[selection].0].0.clone()-}--// ── 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());- }- if args.verbose {- argv.push("--verbose".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::other(e.to_string()))- });- }- }-- // child is intentionally detached via setsid; reaping is the OS's job- #[allow(clippy::zombie_processes)]- 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:- // 1. Use the explicit model_id if it is non-empty.- // 2. When --model-path is given, derive the id from the filename stem (e.g.- // "/path/to/my-model.gguf" → "my-model") so the user never has to pass- // a dummy empty-string id.- // 3. Fall back to the interactive picker only when neither is available.- let model_id = match args.model_id.as_deref() {- Some(id) if !id.is_empty() => id.to_string(),- _ => {- if let Some(ref path) = args.model_path {- PathBuf::from(path)- .file_stem()- .map(|s| s.to_string_lossy().into_owned())- .unwrap_or_else(|| "model".to_string())- } else {- select_model_interactively(args.select).await- }- }- };-- 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: _,- verbose,- select: _,- } = 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, args.select).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 = start_progress(verbose, format!("Loading {} ({engine})…", model_id));-- if engine == "mlx" {- #[cfg(not(target_os = "macos"))]- {- finish_progress(pb, "✗ MLX is only supported on macOS");- eprintln!(- "MLX models require macOS / Apple Silicon. Use a llama.cpp (GGUF) model instead."- );- std::process::exit(1);- }- #[cfg(target_os = "macos")]- {- 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 => {- finish_progress(pb, "✗ mlx-server binary not found");- 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<String, String> = 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);- finish_progress(pb, 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) => {- finish_progress(pb, 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 => {- finish_progress(pb, "✗ llama-server binary not found");- eprintln!("Install a backend from Jan's settings or pass --bin <path>.");- std::process::exit(1);- }- },- };-- let _ = (- n_gpu_layers,- ctx_size,- fit,- threads,- resolved_model_path,- resolved_mmproj,- );- let llama_state = Arc::new(init_llamacpp_state());- let mut envs: HashMap<String, String> = HashMap::new();- if !api_key.is_empty() {- envs.insert("LLAMA_API_KEY".to_string(), api_key.clone());- }-- match ensure_router_and_load(- &llama_state,- &bin_path,- &model_id,- port,- api_key,- embedding,- envs,- timeout,- )- .await- {- Ok(info) => {- let url = format!("http://127.0.0.1:{}", info.port);- finish_progress(pb, 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) => {- finish_progress(pb, format!("✗ Failed to load {model_id}: {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})...");- kill_process(pid);-}--/// Send a termination signal to a child process by PID.-fn kill_process(pid: i32) {- #[cfg(unix)]- {- use nix::sys::signal::{kill, Signal};- use nix::unistd::Pid;- let _ = kill(Pid::from_raw(pid), Signal::SIGTERM);- }- #[cfg(windows)]- {- let _ = std::process::Command::new("taskkill")- .args(["/PID", &pid.to_string(), "/F"])- .status();- }-}--// ── Agent installer ─────────────────────────────────────────────────────────--/// Check if a command is available in PATH-fn is_command_installed(cmd: &str) -> bool {- let which = if cfg!(windows) { "where" } else { "which" };- std::process::Command::new(which)- .arg(cmd)- .output()- .map(|o| o.status.success())- .unwrap_or(false)-}--// ── Launch handler ─────────────────────────────────────────────────────────--#[allow(clippy::too_many_arguments)]-async fn handle_launch(- program: String,- program_args: Vec<String>,- model: Option<String>,- bin: Option<String>,- port: u16,- api_key: String,- n_gpu_layers: i32,- ctx_size: i32,- fit: Option<bool>,- ctx_size_is_default: bool,- verbose: bool,- select: bool,-) {- let model_id = model.unwrap_or_else(|| -> String {- futures::executor::block_on(select_model_interactively(select))- });-- // Detect known agents 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");- let is_openclaw = prog_name.contains("openclaw");-- // --fit defaults to true when launching claude, but only if --ctx-size was- // not explicitly provided (an explicit ctx-size means the user wants that- // exact context, so fit would override it — don't do that).- let effective_fit = fit.unwrap_or(is_claude && ctx_size_is_default);-- // Start the model server inline (same process, no detach).- let (pid, actual_port) = start_model_server(- &model_id,- bin,- port,- api_key.clone(),- n_gpu_layers,- ctx_size,- effective_fit,- verbose,- )- .await;-- // Model is ready — silence server request/response logs so they don't- // flood the launched program's terminal (e.g. Claude Code's shell).- if verbose {- log::set_max_level(log::LevelFilter::Warn);- }-- let base_url = format!("http://127.0.0.1:{actual_port}");- let v1_url = format!("{base_url}/v1");-- // openclaw is configured via ~/.openclaw/openclaw.json, not env vars.- // Write the jan provider entry and set the default model, then launch `openclaw tui`.- let mut program_args = program_args;- if is_openclaw {- configure_openclaw(&v1_url, &api_key, &model_id);- // openclaw's TUI is a sub-command; prepend it unless the caller already did- if program_args.first().map(|s| s.as_str()) != Some("tui") {- program_args.insert(0, "tui".to_string());- }- eprintln!();- eprintln!(" ~/.openclaw/openclaw.json → jan provider configured");- eprintln!(" agents.defaults.model.primary = jan/{model_id}");- } else {- 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!(" OPENAI_MODEL={model_id}");- 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!();- let launch_cmd = if is_openclaw {- format!("openclaw {}", program_args.join(" "))- } else {- format!("{} {}", program, program_args.join(" "))- };- eprintln!(" → Launching: {}", launch_cmd);- eprintln!();-- // For openclaw, use npx if not installed locally- let (cmd_program, cmd_args) = if is_openclaw {- if is_command_installed("openclaw") {- (program.clone(), program_args.clone())- } else {- let mut args = vec!["openclaw".to_string()];- args.extend(program_args.clone());- ("npx".to_string(), args)- }- } else {- (program.clone(), program_args.clone())- };-- let mut cmd = std::process::Command::new(&cmd_program);- cmd.args(&cmd_args);- if is_openclaw {- // Clear any provider API keys that could override openclaw's config- for var in &[- "OPENAI_API_KEY",- "OPENAI_BASE_URL",- "ANTHROPIC_API_KEY",- "ANTHROPIC_AUTH_TOKEN",- "ANTHROPIC_OAUTH_TOKEN",- "GEMINI_API_KEY",- "MISTRAL_API_KEY",- "GROQ_API_KEY",- "XAI_API_KEY",- "OPENROUTER_API_KEY",- ] {- cmd.env_remove(var);- }- } else {- let anthropic_key_var = if is_claude {- "ANTHROPIC_AUTH_TOKEN"- } else {- "ANTHROPIC_API_KEY"- };- cmd.env("OPENAI_BASE_URL", &v1_url)- .env("OPENAI_API_KEY", &api_key)- .env("OPENAI_MODEL", &model_id)- .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.- kill_process(pid);-- match status {- Ok(s) => std::process::exit(s.code().unwrap_or(0)),- Err(e) => {- eprintln!("Error launching '{program}': {e}");- std::process::exit(1);- }- }-}--// ── openclaw config writer ─────────────────────────────────────────────────--/// Write (or merge into) `~/.openclaw/openclaw.json` so that openclaw uses-/// the local Jan server as its provider and selects `model_id` by default.-///-/// The "jan" provider entry is always overwritten with the current server-/// address and key. All other config values are preserved.-/// Also clears the session model override so the new default takes effect.-fn configure_openclaw(v1_url: &str, api_key: &str, model_id: &str) {- let home = dirs::home_dir().unwrap_or_default();- let config_path = home.join(".openclaw").join("openclaw.json");-- // Read existing config so we don't clobber other settings.- let mut config: serde_json::Value = config_path- .exists()- .then(|| std::fs::read_to_string(&config_path).ok())- .flatten()- .and_then(|s| serde_json::from_str(&s).ok())- .unwrap_or(serde_json::json!({}));-- // Inject (or overwrite) the jan provider.- config["models"]["providers"]["jan"] = serde_json::json!({- "baseUrl": v1_url,- "apiKey": api_key,- "api": "openai-completions",- "models": [{- "id": model_id,- "name": model_id,- "input": ["text"],- "reasoning": false,- "contextWindow": 131072,- "maxTokens": 16384,- "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 }- }]- });-- // Set jan/<model_id> as the primary default model.- config["agents"]["defaults"]["model"]["primary"] = serde_json::json!(format!("jan/{model_id}"));-- if let Some(parent) = config_path.parent() {- let _ = std::fs::create_dir_all(parent);- }- if let Ok(json) = serde_json::to_string_pretty(&config) {- let _ = std::fs::write(&config_path, json);- }-- // Clear any per-session model override so the new default is picked up.- let sessions_path = home- .join(".openclaw")- .join("agents")- .join("main")- .join("sessions")- .join("sessions.json");- if sessions_path.exists() {- let _ = std::fs::write(&sessions_path, "{}");- }-}--/// Start the model server and return `(pid, actual_port)`.-/// Resolves the engine automatically (LlamaCPP or MLX).-#[allow(clippy::too_many_arguments)]-async fn start_model_server(- model_id: &str,- bin: Option<String>,- port: u16,- api_key: String,- n_gpu_layers: i32,- ctx_size: i32,- fit: bool,- verbose: bool,-) -> (i32, u16) {- let (engine, model_path, mmproj) = match resolve_model_engine(model_id) {- Ok(r) => r,- Err(_) if looks_like_hf_repo(model_id) => {- auto_download_hf_model(model_id, false).await;- match resolve_model_engine(model_id) {- Ok(r) => r,- Err(e) => {- eprintln!("Error after download: {e}");- std::process::exit(1);- }- }- }- Err(e) => {- eprintln!("Error: {e}");- std::process::exit(1);- }- };- let model_path = model_path.to_string_lossy().into_owned();-- let pb = start_progress(verbose, format!("Loading {} ({engine})…", model_id));-- if engine == "mlx" {- #[cfg(not(target_os = "macos"))]- {- finish_progress(pb, "✗ MLX is only supported on macOS");- eprintln!(- "MLX models require macOS / Apple Silicon. Use a llama.cpp (GGUF) model instead."- );- std::process::exit(1)- }- #[cfg(target_os = "macos")]- {- use std::path::Path;- let bin_path = match bin- .or_else(|| discover_mlx_binary().map(|p| p.to_string_lossy().into_owned()))- {- Some(p) => p,- None => {- finish_progress(pb, "✗ mlx-server binary not found");- 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<String, String> = HashMap::new();- if !api_key.is_empty() {- envs.insert("MLX_API_KEY".to_string(), api_key.clone());- }- let effective_ctx_size = if fit { 0 } else { ctx_size };- let info = match load_mlx_model_impl(- mlx_state.mlx_server_process.clone(),- Path::new(&bin_path),- model_id.to_string(),- model_path,- port,- MlxConfig {- ctx_size: effective_ctx_size,- },- envs,- false,- 120,- )- .await- {- Ok(info) => info,- Err(e) => {- finish_progress(pb, 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);- finish_progress(pb, format!("✓ {model_id} ready · {url}"));- (info.pid, info.port as u16)- }- } else {- let bin_path = match bin- .or_else(|| discover_llamacpp_binary().map(|p| p.to_string_lossy().into_owned()))- {- Some(p) => p,- None => {- finish_progress(pb, "✗ llama-server binary not found");- eprintln!("Install a backend from Jan's settings or pass --bin <path>.");- std::process::exit(1);- }- };- let _ = (n_gpu_layers, ctx_size, fit, model_path, mmproj);- let llama_state = Arc::new(init_llamacpp_state());- let mut envs: HashMap<String, String> = HashMap::new();- if !api_key.is_empty() {- envs.insert("LLAMA_API_KEY".to_string(), api_key.clone());- }- let info = match ensure_router_and_load(- &llama_state,- &bin_path,- model_id,- port,- api_key,- false,- envs,- 120,- )- .await- {- Ok(info) => info,- Err(e) => {- finish_progress(pb, format!("✗ Failed to load {model_id}: {e}"));- std::process::exit(1);- }- };- let url = format!("http://127.0.0.1:{}", info.port);- finish_progress(pb, format!("✓ {model_id} ready · {url}"));- (info.pid, info.port)- }-}diff --git a/src-tauri/src/core/agent/project.rs b/src-tauri/src/core/agent/project.rsindex f9b3e92b4..81c15735f 100644--- a/src-tauri/src/core/agent/project.rs+++ b/src-tauri/src/core/agent/project.rs@@ -7,7 +7,7 @@ use serde::Deserialize;use crate::core::agent::permissions::{PermissionDefault, ToolPermissions};/// `[tools]` is always modeled. `[agent]` is only compiled for the CLI (its-/// sole consumer, via `jan agent run/step/status`); serde still ignores the+/// sole consumer, via `jan cli agent run/step/status`); serde still ignores the/// remaining deferred sections (`[budget]`/`[skills]`).#[derive(Debug, Clone, Default, Deserialize)]pub(crate) struct AgentToml {diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex 55cdd521b..c7869fdb7 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -27,11 +27,6 @@ use tauri_plugin_llamacpp::state::LlamacppState;#[cfg(target_os = "macos")]use tauri_plugin_mlx::state::MlxState;-#[cfg(target_os = "macos")]-pub use tauri_plugin_mlx::state::SessionInfo;-#[cfg(target_os = "macos")]-pub use tauri_plugin_mlx::{load_mlx_model_impl, MlxConfig};-// ── State constructors ─────────────────────────────────────────────────────pub fn init_llamacpp_state() -> LlamacppState {@@ -334,7 +329,7 @@ pub fn resolve_model_engine(model_id: &str) -> Result<(String, PathBuf, Option<P}Err(format!("Model '{}' not found for any engine. \- Run `jan models list` to see available models.",+ Run `jan cli models list` to see available models.",model_id))}@@ -359,7 +354,7 @@ pub fn resolve_model_by_id(if !yml_path.exists() {return Err(format!("Model '{}' not found for engine '{}'. \- Run `jan models list` to see available models.",+ Run `jan cli models list` to see available models.",model_id, engine));}@@ -445,220 +440,6 @@ pub fn discover_llamacpp_binary() -> Option<PathBuf> {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)-#[cfg(target_os = "macos")]-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('/').next_back().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 {@@ -707,7 +488,7 @@ fn resolve_project_root(project: &str) -> PathBuf {.unwrap_or_else(|_| PathBuf::from(project))}-/// Resolved-config + provider snapshot for `jan agent status`.+/// Resolved-config + provider snapshot for `jan cli agent status`.pub fn cli_agent_status(project: &str,overrides: &ProviderOverrides,@@ -773,7 +554,7 @@ pub fn cli_agent_config_unset(provider: &str) -> Result<bool, String> {}/// The global config file path, scaffolding a commented template if it doesn't-/// exist yet so `jan agent config path` always points at a real file.+/// exist yet so `jan config path` always points at a real file.pub fn cli_agent_config_path() -> Result<PathBuf, String> {crate::core::agent::global_config::ensure_global_config()}@@ -928,8 +709,8 @@ pub struct RouterServeInfo {}/// Start the llama-server router (if not already running) against the generated-/// preset, then POST `/models/load` for `model_id`. Shared by `jan serve` and-/// the agent path so a local model has a live upstream to talk to. The preset is+/// preset, then POST `/models/load` for `model_id`. Used by the agent path so a+/// local model has a live upstream to talk to. The preset is/// generated on demand (see [`preset::ensure_router_preset`]) when the desktop/// app hasn't produced one.#[allow(clippy::too_many_arguments)]@@ -1245,7 +1026,7 @@ async fn run_agent_loop(result.map(|_| ())}-/// Launch the interactive chat console (`jan agent ui`). An optional `task`+/// Launch the interactive chat console (bare `jan`). An optional `task`/// seeds the first turn; otherwise the user types the first message. Shares the/// engine with `run_agent_loop` via `AgentSession` — only presentation differs.pub async fn cli_agent_ui(@@ -1465,53 +1246,6 @@ mod tests {let _ = std::fs::remove_dir_all(&base);}- // ── looks_like_hf_repo ─────────────────────────────────────────────────-- #[test]- fn hf_repo_valid_basic() {- assert!(looks_like_hf_repo("janhq/Jan-code-4b-gguf"));- assert!(looks_like_hf_repo("openai/whisper"));- assert!(looks_like_hf_repo("a/b"));- }-- #[test]- fn hf_repo_valid_with_dots_dashes_underscores() {- assert!(looks_like_hf_repo("user.name/repo-name"));- assert!(looks_like_hf_repo("user_name/repo.v2"));- assert!(looks_like_hf_repo("Org-1/Model_2.gguf"));- }-- #[test]- fn hf_repo_rejects_paths() {- assert!(!looks_like_hf_repo("/abs/path"));- assert!(!looks_like_hf_repo("./relative"));- assert!(!looks_like_hf_repo("~/home"));- }-- #[test]- fn hf_repo_rejects_no_slash() {- assert!(!looks_like_hf_repo("noslashhere"));- }-- #[test]- fn hf_repo_rejects_empty_components() {- assert!(!looks_like_hf_repo("/repo"));- assert!(!looks_like_hf_repo("owner/"));- assert!(!looks_like_hf_repo("/"));- }-- #[test]- fn hf_repo_rejects_multiple_slashes() {- assert!(!looks_like_hf_repo("owner/repo/extra"));- }-- #[test]- fn hf_repo_rejects_invalid_chars() {- assert!(!looks_like_hf_repo("owner/repo name"));- assert!(!looks_like_hf_repo("own*er/repo"));- assert!(!looks_like_hf_repo("owner/re@po"));- }-// ── ModelYml deserialization ──────────────────────────────────────────#[test]@@ -1550,22 +1284,6 @@ mod tests {assert!(parsed.is_err());}- // ── HfFileInfo construction ───────────────────────────────────────────-- #[test]- fn hf_file_info_clone() {- let f = HfFileInfo {- filename: "x.gguf".into(),- size: 100,- sha256: Some("abc".into()),- download_url: "https://hf.co/x".into(),- };- let c = f.clone();- assert_eq!(c.filename, "x.gguf");- assert_eq!(c.size, 100);- assert_eq!(c.sha256.as_deref(), Some("abc"));- }-// ── State constructors ────────────────────────────────────────────────#[test]diff --git a/src-tauri/src/core/cli/providers.rs b/src-tauri/src/core/cli/providers.rsindex 4bbd5bc80..d6bd15800 100644--- a/src-tauri/src/core/cli/providers.rs+++ b/src-tauri/src/core/cli/providers.rs@@ -126,7 +126,7 @@ pub fn list_provider_models() -> Vec<(String, String)> {/// `[provider]` override -> `--provider`/`--api-key` CLI/env overrides.////// `project_root` is `None` when no project context is available (e.g.-/// `jan agent status` without `--project`); the local override is then+/// `jan cli agent status` without `--project`); the local override is then/// skipped. A missing/malformed Desktop store is not fatal: it's simply not/// layered in, since Global config alone is a valid standalone setup.pub fn load_provider_configs(diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex 9734486d9..8694e42aa 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -1,4 +1,4 @@-//! Interactive chat console over the agent loop (`jan agent ui`). A thin+//! Interactive chat console over the agent loop (bare `jan`). A thin//! renderer: the engine is shared with the plain CLI path, only the//! presentation differs. Maintains a running conversation — the user types//! messages into an input box, each submit spawns an agent run over the shared@@ -173,7 +173,7 @@ impl Picker {PickerKind::ToggleMcp => " ↑/↓ select Enter toggle Esc close",PickerKind::RewindMessage => " ↑/↓ select Enter choose Esc cancel",PickerKind::RewindScope => " ↑/↓ select Enter restore Esc cancel",- PickerKind::ViewConfig => " set via: jan agent config set --provider <id> ... Esc close",+ PickerKind::ViewConfig => " set via: jan config set --provider <id> ... Esc close",}}}@@ -3394,7 +3394,7 @@ fn open_mcp_picker(app: &mut App) {/// Open the `/config` screen: a read-only view of the providers configured in/// `~/.jan/config.toml` (the standalone-agent credential store), with API keys-/// redacted. Editing is headless via `jan agent config set/unset` (shown in the+/// redacted. Editing is headless via `jan config set/unset` (shown in the/// footer), since a TUI is not the safe place to type secrets.fn open_config_screen(app: &mut App) {let configs = match crate::core::agent::global_config::load_global_config() {@@ -3406,7 +3406,7 @@ fn open_config_screen(app: &mut App) {let items: Vec<PickerItem> = if providers.is_empty() {vec![PickerItem {- label: "no providers configured - run: jan agent config set --provider <id> --api-key <key>"+ label: "no providers configured - run: jan config set --provider <id> --api-key <key>".to_string(),value: String::new(),hint: None,