Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(agent-cli): run local llamacpp models in the agent loop
Akarshan Biswasb1c9d0dd9736
diff --git a/src-tauri/src/bin/jan-cli.rs b/src-tauri/src/bin/jan-cli.rsindex 2c1012a66..ebb23eec6 100644--- a/src-tauri/src/bin/jan-cli.rs+++ b/src-tauri/src/bin/jan-cli.rs@@ -16,8 +16,8 @@ use app_lib::core::cli::providers::ProviderOverrides;use app_lib::core::cli::{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, fetch_hf_gguf_files, init_llamacpp_state,- list_models, looks_like_hf_repo, resolve_model_engine, HfFileInfo,+ 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")]@@ -25,8 +25,6 @@ use app_lib::core::cli::{discover_mlx_binary, init_mlx_state, load_mlx_model_impl, resolve_model_by_id, MlxConfig,};use std::path::PathBuf;-use tauri_plugin_llamacpp::router as llamacpp_router;-use tauri_plugin_llamacpp::state::LlamacppState;// ── Top-level CLI ──────────────────────────────────────────────────────────@@ -1195,102 +1193,6 @@ async fn handle_serve(args: ServeArgs) {}}-struct RouterServeInfo {- pid: i32,- port: u16,- #[allow(dead_code)]- api_key: String,-}--#[allow(clippy::too_many_arguments)]-async fn ensure_router_and_load(- llama_state: &std::sync::Arc<LlamacppState>,- bin_path: &str,- model_id: &str,- port: u16,- api_key: String,- is_embedding: bool,- envs: HashMap<String, String>,- timeout: u64,-) -> Result<RouterServeInfo, String> {- if is_embedding {- return Err(- "--embedding on the llamacpp engine requires router preset support; \- use the desktop UI to load embedding models for now."- .to_string(),- );- }-- let preset_path = cli_get_data_folder()- .join("llamacpp")- .join("router.preset.ini");- if !preset_path.exists() {- return Err(format!(- "Router preset not found at {}; run the desktop app once to generate it, \- or implement a Rust preset generator.",- preset_path.display()- ));- }-- let already_running = { llama_state.router.lock().await.is_some() };- if !already_running {- let router_api_key = if api_key.is_empty() {- uuid::Uuid::new_v4().to_string()- } else {- api_key.clone()- };- let mut router_envs = envs.clone();- router_envs- .entry("LLAMA_ARG_TIMEOUT".to_string())- .or_insert_with(|| timeout.to_string());-- let log_dir = cli_get_data_folder().join("logs");-- let handle = llamacpp_router::start_router(- std::path::PathBuf::from(bin_path),- preset_path,- log_dir,- port,- router_api_key,- 0,- Vec::new(),- router_envs,- None,- )- .await- .map_err(|e| format!("{e:?}"))?;- let mut guard = llama_state.router.lock().await;- *guard = Some(handle);- }-- let (router_port, router_key, router_pid) = {- let guard = llama_state.router.lock().await;- let h = guard- .as_ref()- .ok_or_else(|| "Router unexpectedly missing after start".to_string())?;- (h.port, h.api_key.clone(), h.pid)- };-- let url = format!("http://127.0.0.1:{router_port}/models/load");- let resp = reqwest::Client::new()- .post(&url)- .header("Authorization", format!("Bearer {router_key}"))- .json(&serde_json::json!({ "model": model_id }))- .send()- .await- .map_err(|e| format!("Failed to POST {url}: {e}"))?;- let status = resp.status();- if !status.is_success() {- let body = resp.text().await.unwrap_or_default();- return Err(format!("Router /models/load returned {status}: {body}"));- }-- Ok(RouterServeInfo {- pid: router_pid as i32,- port: router_port,- api_key: router_key,- })-}/// Block until Ctrl+C, then terminate the child process.async fn wait_for_shutdown(pid: i32) {diff --git a/src-tauri/src/core/agent/upstream.rs b/src-tauri/src/core/agent/upstream.rsindex e137d73f7..7c88b22bf 100644--- a/src-tauri/src/core/agent/upstream.rs+++ b/src-tauri/src/core/agent/upstream.rs@@ -160,12 +160,14 @@ pub(crate) async fn resolve_upstream_for_model(if let Some(provider) = provider_name {let pc2 = provider_configs.lock().await;if let Some(provider_cfg) = pc2.get(provider.as_str()).cloned() {- let api_url = provider_cfg- .base_url- .clone()- .ok_or_else(|| format!("Missing base_url for provider '{provider}'"))?;- let url = format!("{}{}", api_url, destination_path);- return Ok((url, provider_cfg.bearer_key_chain()));+ // A populated base_url means an HTTP upstream (cloud, or a local+ // engine whose live endpoint was registered at runtime). A local+ // engine loaded from persisted settings has none -- fall through to+ // the MLX session / llama-server router resolution below.+ if let Some(api_url) = provider_cfg.base_url.clone().filter(|u| !u.is_empty()) {+ let url = format!("{}{}", api_url, destination_path);+ return Ok((url, provider_cfg.bearer_key_chain()));+ }}}diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex 4cfa7987f..f47fd2f94 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -2,6 +2,7 @@//!//! This module is only compiled when the `cli` feature is enabled.+pub mod preset;pub mod providers;mod tui;@@ -19,6 +20,7 @@ use crate::core::threads::{get_thread_metadata_path,},};+use tauri_plugin_llamacpp::router as llamacpp_router;use tauri_plugin_llamacpp::state::LlamacppState;#[cfg(target_os = "macos")]use tauri_plugin_mlx::state::MlxState;@@ -732,12 +734,13 @@ fn build_cli_orchestration_args(project_root: PathBuf,permissions: crate::core::agent::permissions::ToolPermissions,provider_configs: HashMap<String, crate::core::state::ProviderConfig>,+ llama_state: Arc<LlamacppState>,permission_requests: PermissionRegistry,) -> OrchestrationArgs {OrchestrationArgs {client: reqwest::Client::new(),provider_configs: Arc::new(Mutex::new(provider_configs)),- llama_state: Arc::new(init_llamacpp_state()),+ llama_state,mlx_sessions: Arc::new(Mutex::new(HashMap::new())),mcp_servers: Arc::new(Mutex::new(HashMap::new())),mcp_settings: Arc::new(Mutex::new(McpSettings::default())),@@ -748,6 +751,164 @@ fn build_cli_orchestration_args(}}+/// Model-load readiness timeout (seconds) for the router started on the agent+/// path. Generous: a cold local model can take a while to memory-map + warm up.+const AGENT_ROUTER_TIMEOUT_SECS: u64 = 300;++/// Pick a free TCP port on the loopback interface. The port is released+/// immediately; the router binds it moments later (standard, benign race).+fn pick_free_port() -> Result<u16, String> {+ let listener =+ std::net::TcpListener::bind(("127.0.0.1", 0)).map_err(|e| e.to_string())?;+ listener+ .local_addr()+ .map(|a| a.port())+ .map_err(|e| e.to_string())+}++/// When `model_id` resolves to a local llamacpp model, spawn a background task+/// that starts the router and loads the model into `llama_state`. Returns the+/// task handle so the caller can await readiness before the first turn without+/// blocking setup/render. Cloud (and MLX) models return `None` -- they either+/// hit an HTTP provider or a separately-managed session.+fn spawn_local_router_if_needed(+ model_id: &str,+ llama_state: &Arc<LlamacppState>,+) -> Option<tokio::task::JoinHandle<Result<(), String>>> {+ match resolve_model_engine(model_id) {+ Ok((engine, _, _)) if engine == "llamacpp" => {}+ _ => return None,+ }++ let llama_state = llama_state.clone();+ let model_id = model_id.to_string();+ Some(tokio::spawn(async move {+ let bin_path = discover_llamacpp_binary()+ .ok_or_else(|| {+ "llama-server binary not found; install a backend in the Jan desktop app".to_string()+ })?+ .to_string_lossy()+ .into_owned();+ let port = pick_free_port()?;+ ensure_router_and_load(+ &llama_state,+ &bin_path,+ &model_id,+ port,+ String::new(),+ false,+ HashMap::new(),+ AGENT_ROUTER_TIMEOUT_SECS,+ )+ .await+ .map(|_| ())+ }))+}++/// Await a spawned router-start task, flattening the join + inner errors.+async fn await_router_task(+ task: Option<tokio::task::JoinHandle<Result<(), String>>>,+) -> Result<(), String> {+ match task {+ Some(h) => h+ .await+ .map_err(|e| format!("router task failed: {e}"))?+ .map_err(|e| format!("failed to start local model: {e}")),+ None => Ok(()),+ }+}++/// Router endpoint + pid after [`ensure_router_and_load`].+pub struct RouterServeInfo {+ pub pid: i32,+ pub port: u16,+ #[allow(dead_code)]+ pub api_key: String,+}++/// 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+/// generated on demand (see [`preset::ensure_router_preset`]) when the desktop+/// app hasn't produced one.+#[allow(clippy::too_many_arguments)]+pub async fn ensure_router_and_load(+ llama_state: &Arc<LlamacppState>,+ bin_path: &str,+ model_id: &str,+ port: u16,+ api_key: String,+ is_embedding: bool,+ envs: HashMap<String, String>,+ timeout: u64,+) -> Result<RouterServeInfo, String> {+ if is_embedding {+ return Err(+ "--embedding on the llamacpp engine requires router preset support; \+ use the desktop UI to load embedding models for now."+ .to_string(),+ );+ }++ let preset_path = preset::ensure_router_preset()?;++ let already_running = { llama_state.router.lock().await.is_some() };+ if !already_running {+ let router_api_key = if api_key.is_empty() {+ uuid::Uuid::new_v4().to_string()+ } else {+ api_key.clone()+ };+ let mut router_envs = envs.clone();+ router_envs+ .entry("LLAMA_ARG_TIMEOUT".to_string())+ .or_insert_with(|| timeout.to_string());++ let handle = llamacpp_router::start_router(+ PathBuf::from(bin_path),+ preset_path,+ port,+ router_api_key,+ 0,+ Vec::new(),+ router_envs,+ None,+ )+ .await+ .map_err(|e| format!("{e:?}"))?;+ let mut guard = llama_state.router.lock().await;+ *guard = Some(handle);+ }++ let (router_port, router_key, router_pid) = {+ let guard = llama_state.router.lock().await;+ let h = guard+ .as_ref()+ .ok_or_else(|| "Router unexpectedly missing after start".to_string())?;+ (h.port, h.api_key.clone(), h.pid)+ };++ let url = format!("http://127.0.0.1:{router_port}/models/load");+ let resp = reqwest::Client::new()+ .post(&url)+ .header("Authorization", format!("Bearer {router_key}"))+ .json(&serde_json::json!({ "model": model_id }))+ .send()+ .await+ .map_err(|e| format!("Failed to POST {url}: {e}"))?;+ let status = resp.status();+ if !status.is_success() {+ let body = resp.text().await.unwrap_or_default();+ return Err(format!("Router /models/load returned {status}: {body}"));+ }++ Ok(RouterServeInfo {+ pid: router_pid as i32,+ port: router_port,+ api_key: router_key,+ })+}+/// Everything needed to drive one agent run: the engine handle, request body,/// and the shared permission registry. Built once and consumed by either the/// plain CLI printer or the TUI renderer.@@ -755,6 +916,9 @@ pub(crate) struct PreparedRun {pub args: OrchestrationArgs,pub body: serde_json::Value,pub permission_requests: PermissionRegistry,+ /// Background local-router startup, awaited before the first turn. `None`+ /// for cloud models.+ pub router_task: Option<tokio::task::JoinHandle<Result<(), String>>>,}/// Resolved engine handle for a chat session: the args are built once and the@@ -765,6 +929,9 @@ pub(crate) struct AgentSession {pub permission_requests: PermissionRegistry,pub model: String,pub max_turns: u32,+ /// Background local-router startup, awaited before the first turn. `None`+ /// for cloud models.+ pub router_task: Option<tokio::task::JoinHandle<Result<(), String>>>,}impl AgentSession {@@ -807,11 +974,18 @@ fn prepare_agent_session(let provider_configs = load_provider_configs(&overrides)?;+ // A local llamacpp model needs its router started; cloud models are plain+ // HTTP upstreams. Start it off-thread so setup/render isn't blocked on the+ // model load; the caller awaits `router_task` before the first turn.+ let llama_state = Arc::new(init_llamacpp_state());+ let router_task = spawn_local_router_if_needed(&model, &llama_state);+let permission_requests: PermissionRegistry = Arc::new(Mutex::new(HashMap::new()));let args = build_cli_orchestration_args(project_root,permissions,provider_configs,+ llama_state,permission_requests.clone(),);@@ -820,6 +994,7 @@ fn prepare_agent_session(permission_requests,model,max_turns,+ router_task,})}@@ -836,6 +1011,7 @@ fn prepare_agent_run(args: session.args,body,permission_requests: session.permission_requests,+ router_task: session.router_task,})}@@ -850,8 +1026,12 @@ async fn run_agent_loop(args,body,permission_requests,+ router_task,} = prepare_agent_run(project, task, model_override, max_turns_override, overrides)?;+ // Block until the local model is loaded (no-op for cloud models).+ await_router_task(router_task).await?;+let (tx, mut rx) = mpsc::unbounded_channel::<StreamEvent>();let printer = tokio::spawn(async move {while let Some(ev) = rx.recv().await {diff --git a/src-tauri/src/core/cli/preset.rs b/src-tauri/src/core/cli/preset.rsnew file mode 100644index 000000000..67e13472f--- /dev/null+++ b/src-tauri/src/core/cli/preset.rs@@ -0,0 +1,216 @@+//! CLI port of the desktop llamacpp `router.preset.ini` generator.+//!+//! The desktop app builds this file in `extensions/llamacpp-extension/src/preset.ts`+//! from its live provider config plus every model's `model.yml`. The CLI has no+//! live provider store, so this port emits a focused, always-loadable subset:+//! per-model sections resolved from each `model.yml` (compiled llama.cpp defaults+//! apply for the engine-wide `[*]` section). Global tuning knobs, MTP speculative+//! decoding, and sampling defaults are intentionally omitted here (they require+//! the provider config / a backend-build probe the CLI doesn't have); a preset+//! generated by the desktop app is always preferred and never overwritten.++use std::path::PathBuf;++use serde_yaml::Value;++use crate::core::app::commands::resolve_jan_data_folder;++const DEFAULT_EMBEDDING_UBATCH: i64 = 2048;++/// Ensure `<jan_data>/llamacpp/router.preset.ini` exists, generating it from the+/// installed models when absent. Never overwrites an existing preset (the+/// desktop-generated one carries richer engine-wide tuning). Returns its path.+pub fn ensure_router_preset() -> Result<PathBuf, String> {+ let data_folder = resolve_jan_data_folder();+ let preset_path = data_folder.join("llamacpp").join("router.preset.ini");+ if preset_path.exists() {+ return Ok(preset_path);+ }++ let content = generate_preset()?;+ let parent = preset_path+ .parent()+ .ok_or_else(|| "invalid preset path".to_string())?;+ std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;++ // Atomic write (tmp + rename) so a partial file is never read by the router.+ let tmp = preset_path.with_extension("ini.tmp");+ std::fs::write(&tmp, content).map_err(|e| e.to_string())?;+ std::fs::rename(&tmp, &preset_path).map_err(|e| e.to_string())?;+ Ok(preset_path)+}++/// Build the full preset body from every discovered llamacpp model.+fn generate_preset() -> Result<String, String> {+ let data_folder = resolve_jan_data_folder();+ let models_root = data_folder.join("llamacpp").join("models");++ let mut sections: Vec<String> = Vec::new();+ for (model_id, _) in super::list_models("llamacpp") {+ let yml_path = models_root.join(&model_id).join("model.yml");+ let raw = match std::fs::read_to_string(&yml_path) {+ Ok(r) => r,+ Err(_) => continue,+ };+ let yml: Value = match serde_yaml::from_str(&raw) {+ Ok(v) => v,+ Err(_) => continue,+ };+ if let Some(section) = model_section(&model_id, &yml) {+ sections.push(section);+ }+ }++ if sections.is_empty() {+ return Err(format!(+ "no llamacpp models found under {}; download a model with `jan pull <repo>` first",+ models_root.display()+ ));+ }++ Ok(sections.join("\n"))+}++/// Render one `[<model_id>]` section, or `None` when the yml has no `model_path`.+fn model_section(model_id: &str, yml: &Value) -> Option<String> {+ let model_path = str_field(yml, "model_path").filter(|s| !s.is_empty())?;++ let mut lines = vec![format!("[{model_id}]")];+ lines.push(format!("model = {}", resolve_path(&model_path)));++ if let Some(mmproj) = str_field(yml, "mmproj_path").filter(|s| !s.is_empty()) {+ lines.push(format!("mmproj = {}", resolve_path(&mmproj)));+ }+ if let Some(tpl) = str_field(yml, "chat_template").filter(|s| !s.is_empty()) {+ lines.push(format!("chat-template = {}", escape_ini_value(&tpl)));+ }+ if let Some(ngl) = int_field(yml, "n_gpu_layers").filter(|&n| n >= 0) {+ lines.push(format!("n-gpu-layers = {ngl}"));+ }++ if bool_field(yml, "embedding") {+ lines.push("embeddings = true".to_string());+ lines.push("ctx-size = 0".to_string());+ let pooling = str_field(yml, "pooling")+ .filter(|s| !s.is_empty())+ .unwrap_or_else(|| "mean".to_string());+ lines.push(format!("pooling = {}", escape_ini_value(&pooling)));+ let ubatch = int_field(yml, "ubatch_size")+ .filter(|&n| n > 0)+ .unwrap_or(DEFAULT_EMBEDDING_UBATCH);+ let batch = int_field(yml, "batch_size").unwrap_or(0).max(ubatch);+ lines.push(format!("ubatch-size = {ubatch}"));+ lines.push(format!("batch-size = {batch}"));+ }++ lines.push("load-on-startup = false".to_string());+ lines.push(String::new());+ Some(lines.join("\n"))+}++/// Resolve a `model.yml` path: absolute used verbatim, relative joined with the+/// Jan data folder (mirrors `resolve_model_by_id`).+fn resolve_path(p: &str) -> String {+ let pb = PathBuf::from(p);+ if pb.is_absolute() {+ pb.to_string_lossy().into_owned()+ } else {+ resolve_jan_data_folder()+ .join(p)+ .to_string_lossy()+ .into_owned()+ }+}++/// Collapse newlines to a single space and trim (mirrors `escapeIniValue`).+fn escape_ini_value(v: &str) -> String {+ let mut out = String::with_capacity(v.len());+ let mut prev_space = false;+ for ch in v.chars() {+ if ch == '\r' || ch == '\n' {+ if !prev_space {+ out.push(' ');+ prev_space = true;+ }+ } else {+ out.push(ch);+ prev_space = false;+ }+ }+ out.trim().to_string()+}++fn str_field(yml: &Value, key: &str) -> Option<String> {+ yml.get(key).and_then(|v| v.as_str()).map(str::to_owned)+}++fn int_field(yml: &Value, key: &str) -> Option<i64> {+ yml.get(key).and_then(|v| v.as_i64())+}++fn bool_field(yml: &Value, key: &str) -> bool {+ yml.get(key).and_then(|v| v.as_bool()).unwrap_or(false)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn yml(s: &str) -> Value {+ serde_yaml::from_str(s).unwrap()+ }++ #[test]+ fn chat_model_section_has_model_and_startup() {+ let v = yml("model_path: /abs/model.gguf\nname: Foo\n");+ let section = model_section("foo", &v).unwrap();+ assert!(section.starts_with("[foo]\n"));+ assert!(section.contains("model = /abs/model.gguf"));+ assert!(section.contains("load-on-startup = false"));+ assert!(!section.contains("embeddings"));+ }++ #[test]+ fn absolute_model_path_used_verbatim() {+ assert_eq!(resolve_path("/abs/x.gguf"), "/abs/x.gguf");+ }++ #[test]+ fn relative_model_path_joined_with_data_folder() {+ let resolved = resolve_path("llamacpp/models/foo/model.gguf");+ assert!(resolved.ends_with("llamacpp/models/foo/model.gguf"));+ assert!(PathBuf::from(&resolved).is_absolute());+ }++ #[test]+ fn vision_model_emits_mmproj() {+ let v = yml("model_path: /abs/m.gguf\nmmproj_path: /abs/mmproj.gguf\n");+ let section = model_section("v", &v).unwrap();+ assert!(section.contains("mmproj = /abs/mmproj.gguf"));+ }++ #[test]+ fn embedding_model_emits_embedding_block() {+ let v = yml(+ "model_path: /abs/e.gguf\nembedding: true\npooling: mean\nubatch_size: 2048\nbatch_size: 1024\n",+ );+ let section = model_section("e", &v).unwrap();+ assert!(section.contains("embeddings = true"));+ assert!(section.contains("ctx-size = 0"));+ assert!(section.contains("pooling = mean"));+ assert!(section.contains("ubatch-size = 2048"));+ // batch-size is floored to ubatch-size.+ assert!(section.contains("batch-size = 2048"));+ }++ #[test]+ fn missing_model_path_yields_no_section() {+ let v = yml("name: Foo\n");+ assert!(model_section("foo", &v).is_none());+ }++ #[test]+ fn escape_collapses_newlines() {+ assert_eq!(escape_ini_value("a\n b \r\n c "), "a b c");+ }+}diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex 47f915181..7b6409c61 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -979,6 +979,26 @@ async fn next_event(current: &mut Option<CurrentRun>) -> Option<StreamEvent> {}}+/// Await the background router-start task once, then never resolve again (so the+/// select arm stays quiet after the model is ready). `None` -> pends forever.+///+/// The handle is borrowed, not taken: this future is rebuilt (and dropped) every+/// select iteration, so taking it would discard the still-running task the first+/// time another branch wins the race. The slot is cleared only on completion.+async fn await_router(+ task: &mut Option<tokio::task::JoinHandle<Result<(), String>>>,+) -> Result<(), String> {+ let joined = match task.as_mut() {+ Some(h) => h.await,+ None => return pending().await,+ };+ *task = None;+ match joined {+ Ok(inner) => inner.map_err(|e| format!("failed to start local model: {e}")),+ Err(e) => Err(format!("router task failed: {e}")),+ }+}+pub async fn run(session: AgentSession,agent_dir: std::path::PathBuf,@@ -989,6 +1009,7 @@ pub async fn run(permission_requests,model,max_turns,+ router_task,} = session;let args = Arc::new(args);@@ -999,7 +1020,15 @@ pub async fn run(let mut terminal = Terminal::new(backend).map_err(|e| e.to_string())?;let mut app = App::new(model, max_turns, agent_dir);- let res = chat_loop(&mut terminal, &args, &permission_requests, &mut app, initial_task).await;+ let res = chat_loop(+ &mut terminal,+ &args,+ &permission_requests,+ &mut app,+ initial_task,+ router_task,+ )+ .await;let _ = disable_raw_mode();let _ = execute!(terminal.backend_mut(), LeaveAlternateScreen);@@ -1013,21 +1042,32 @@ async fn chat_loop<B: Backend>(registry: &PermissionRegistry,app: &mut App,initial_task: Option<String>,+ mut router_task: Option<tokio::task::JoinHandle<Result<(), String>>>,) -> Result<(), String> {let mut current: Option<CurrentRun> = None;let mut ticker = tokio::time::interval(Duration::from_millis(50));+ // A local model loads in the background; gate the first run on it.+ let mut router_ready = router_task.is_none();+ let mut loading_noted = false;+match initial_task {Some(task) if !task.trim().is_empty() => app.submit_user(task.trim().to_string()),_ => app.note("type a message to start, or /help for commands"),}while !app.should_quit {- // Kick off a queued run once the previous one has cleared. `submit_user`- // already flipped status to Running and reset the turn counter.+ // Kick off a queued run once the previous one has cleared and the local+ // model (if any) is loaded. `submit_user` already flipped status to+ // Running and reset the turn counter.if app.want_start && current.is_none() {- app.want_start = false;- current = Some(spawn_run(args, app.body()));+ if router_ready {+ app.want_start = false;+ current = Some(spawn_run(args, app.body()));+ } else if !loading_noted {+ loading_noted = true;+ app.note("loading local model...");+ }}terminal@@ -1042,6 +1082,13 @@ async fn chat_loop<B: Backend>(}}}+ router_res = await_router(&mut router_task) => {+ router_ready = true;+ if let Err(e) = router_res {+ app.want_start = false;+ app.on_error(String::new(), e);+ }+ }ev = next_event(&mut current) => match ev {Some(StreamEvent::Done { stop_reason, usage }) => {app.on_done(stop_reason, usage);