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.

refactor(cli): make jan agent remote-only and free of Tauri/GTK dependencies

Akarshan Biswas0f541638ec96
diff --git a/.github/workflows/jan-linter-and-test.yml b/.github/workflows/jan-linter-and-test.yml
index c6b9e9ccd..86bdfe7f3 100644
--- a/.github/workflows/jan-linter-and-test.yml
+++ b/.github/workflows/jan-linter-and-test.yml
@@ -109,6 +109,9 @@ jobs:
run: |
cargo llvm-cov clean --workspace --manifest-path src-tauri/Cargo.toml
cargo llvm-cov --no-report --manifest-path src-tauri/Cargo.toml --no-default-features --features test-tauri -- --test-threads=1
+ # The headless CLI is a separate, mutually-exclusive feature config
+ # (no Tauri); its modules are compiled out of the run above.
+ cargo llvm-cov --no-report --manifest-path src-tauri/Cargo.toml --no-default-features --features cli --lib -- --test-threads=1
cargo llvm-cov --no-report --manifest-path src-tauri/plugins/tauri-plugin-hardware/Cargo.toml
cargo llvm-cov --no-report --manifest-path src-tauri/plugins/tauri-plugin-llamacpp/Cargo.toml
cargo llvm-cov --no-report --manifest-path src-tauri/utils/Cargo.toml
diff --git a/.github/workflows/template-cli-build-linux-x64.yml b/.github/workflows/template-cli-build-linux-x64.yml
index 689c4c4c0..87853c9b7 100644
--- a/.github/workflows/template-cli-build-linux-x64.yml
+++ b/.github/workflows/template-cli-build-linux-x64.yml
@@ -48,26 +48,20 @@ jobs:
with:
toolchain: stable
- - name: Install system dependencies
- run: |
- sudo apt-get update
- sudo apt-get install -y libdbus-1-dev pkg-config
-
- name: Cache cargo
uses: Swatinem/rust-cache@v2
- - name: Assert no GUI crates
+ # The CLI must stay free of Tauri/GTK: this runner has no libwebkit2gtk,
+ # so a regression here would surface as a confusing linker error later.
+ - name: Assert no GUI crates in the CLI dependency graph
run: |
cd src-tauri
- if cargo tree --no-default-features --features cli -i tauri >/dev/null 2>&1 || \
- cargo tree --no-default-features --features cli -i gtk >/dev/null 2>&1 || \
- cargo tree --no-default-features --features cli -i gdk >/dev/null 2>&1 || \
- cargo tree --no-default-features --features cli -i muda >/dev/null 2>&1 || \
- cargo tree --no-default-features --features cli -i wry >/dev/null 2>&1 || \
- cargo tree --no-default-features --features cli -i webkit2gtk >/dev/null 2>&1; then
- echo "GUI crate leaked into the CLI dependency graph" >&2
- exit 1
- fi
+ for crate in tauri gtk gdk muda wry webkit2gtk; do
+ if cargo tree --no-default-features --features cli -e normal -i "$crate" >/dev/null 2>&1; then
+ echo "::error::$crate is back in the jan CLI dependency graph"
+ exit 1
+ fi
+ done
- name: Build CLI binary
env:
diff --git a/AGENT-TUI.md b/AGENT-TUI.md
index 222b05df1..089aa3648 100644
--- a/AGENT-TUI.md
+++ b/AGENT-TUI.md
@@ -45,7 +45,7 @@ rustc --version # 1.77.2+ (minimum)
```bash
# Quick check (no binary produced):
-cd src-tauri && cargo check --features cli --lib
+cd src-tauri && cargo check --no-default-features --features cli --lib
# Debug build + install to ~/.local/bin:
cd /Users/alandao/Documents/codes/jan-agent
@@ -53,7 +53,7 @@ cd /Users/alandao/Documents/codes/jan-agent
./build-tui.sh release # release (optimized, slower build)
# Release build (optimized, smaller binary):
-cd src-tauri && cargo build --features cli --bin jan --release
+cd src-tauri && cargo build --no-default-features --features cli --bin jan --release
```
### Using the Build Script
@@ -72,30 +72,32 @@ The script installs the binary to `~/.local/bin/jan-agent`. Make sure `~/.local/
### Binary vs Library
-- The **library** (`app_lib`) is what you build in CI/CD for both desktop and CLI.
-- The **CLI binary** (`jan`) needs `--features cli` to include TUI dependencies.
+- The **library** (`app_lib`) is what you build in CI/CD for both desktop and CLI,
+ but the two are mutually exclusive feature configs: `cli` compiles out every
+ Tauri-dependent module, and the Tauri/GTK crates are not even dependencies.
+- The **CLI binary** (`jan`) needs `--no-default-features --features cli` to include TUI dependencies.
- The **desktop binary** (`jan-desktop`) uses the `desktop` feature (Tauri).
-When developing TUI features, use `cargo check --features cli --lib` for the fast inner loop (checks only the library, not binary linking).
+When developing TUI features, use `cargo check --no-default-features --features cli --lib` for the fast inner loop (checks only the library, not binary linking).
## Testing
### Run All TUI Tests
```bash
-cd src-tauri && cargo test --features cli --lib -- core::cli::tui
+cd src-tauri && cargo test --no-default-features --features cli --lib -- core::cli::tui
```
### Run a Specific Test
```bash
-cd src-tauri && cargo test --features cli --lib -- core::cli::tui::tests::submit_user_attaches_pending_images_and_renders_label
+cd src-tauri && cargo test --no-default-features --features cli --lib -- core::cli::tui::tests::submit_user_attaches_pending_images_and_renders_label
```
### Watch Mode (auto-re-run on changes)
```bash
-cd src-tauri && cargo watch -x "test --features cli --lib -- core::cli::tui"
+cd src-tauri && cargo watch -x "test --no-default-features --features cli --lib -- core::cli::tui"
```
*(Requires `cargo watch`: `cargo install cargo-watch`)*
@@ -238,7 +240,7 @@ The TUI supports Tab-based slash command completion:
jan-agent tui
# Or from the project:
-cd src-tauri && cargo run --features cli --bin jan -- tui
+cd src-tauri && cargo run --no-default-features --features cli --bin jan -- tui
# With a specific model:
jan-agent tui --model my-model
@@ -304,12 +306,13 @@ fn my_new_test() {
export PATH="$HOME/.local/bin:$PATH"
```
-### "error: could not compile `Jan`"
+### "features `cli` and `tauri-app`/`desktop` are mutually exclusive"
-Desktop features are required for some dependencies. When building CLI-only, use `--features cli`:
+`--features cli` on its own still enables the crate's `default` features (which
+include `desktop`). The CLI is a Tauri-free build, so it must opt out of them:
```bash
-cd src-tauri && cargo check --features cli --lib
+cd src-tauri && cargo check --no-default-features --features cli --lib
```
### "signal: 9" (SIGKILL) during build
@@ -318,7 +321,7 @@ The Rust compiler may run out of memory on large builds. Try:
```bash
# Limit parallel codegen units
-cd src-tauri && CARGO_BUILD_JOBS=2 cargo build --features cli --bin jan
+cd src-tauri && CARGO_BUILD_JOBS=2 cargo build --no-default-features --features cli --bin jan
```
### TUI rendering artifacts
diff --git a/Makefile b/Makefile
index 1d6d50ad9..64a358d81 100644
--- a/Makefile
+++ b/Makefile
@@ -234,8 +234,8 @@ endif
# Build jan CLI (release, platform-aware) → src-tauri/resources/bin/jan[.exe]
build-cli:
ifeq ($(DETECTED_OS),Darwin)
- cd src-tauri && cargo build --release --features cli --bin jan --target aarch64-apple-darwin
- cd src-tauri && cargo build --release --features cli --bin jan --target x86_64-apple-darwin
+ cd src-tauri && cargo build --release --no-default-features --features cli --bin jan --target aarch64-apple-darwin
+ cd src-tauri && cargo build --release --no-default-features --features cli --bin jan --target x86_64-apple-darwin
lipo -create \
src-tauri/target/aarch64-apple-darwin/release/jan \
src-tauri/target/x86_64-apple-darwin/release/jan \
@@ -255,17 +255,17 @@ ifeq ($(DETECTED_OS),Darwin)
cp src-tauri/resources/bin/jan src-tauri/target/universal-apple-darwin/release/jan
else ifeq ($(DETECTED_OS),Windows)
- cd src-tauri && cargo build --release --features cli --bin jan
+ cd src-tauri && cargo build --release --no-default-features --features cli --bin jan
cp src-tauri/target/release/jan.exe src-tauri/resources/bin/jan.exe
else
- cd src-tauri && cargo build --release --features cli --bin jan
+ cd src-tauri && cargo build --release --no-default-features --features cli --bin jan
cp src-tauri/target/release/jan src-tauri/resources/bin/jan
endif
# Debug build for local dev (faster, native arch only)
build-cli-dev:
$(call MKDIR,'src-tauri/resources/bin')
- cd src-tauri && cargo build --features cli --bin jan
+ cd src-tauri && cargo build --no-default-features --features cli --bin jan
ifeq ($(DETECTED_OS),Windows)
copy src-tauri\target\debug\jan.exe src-tauri\resources\bin\jan.exe
else
@@ -283,13 +283,13 @@ agent: build-agent
# and then installed to src-tauri/resources/bin/jan[.exe] for bundling.
build-agent:
ifeq ($(DETECTED_OS),Windows)
- cd src-tauri && cargo build --release --features cli --bin jan
+ cd src-tauri && cargo build --release --no-default-features --features cli --bin jan
copy src-tauri\target\release\jan.exe src-tauri\resources\bin\jan.exe
@echo "Jan agent built at:"
@echo " src-tauri/resources/bin/jan.exe"
@echo " src-tauri/target/release/jan.exe"
else
- cd src-tauri && cargo build --release --features cli --bin jan
+ cd src-tauri && cargo build --release --no-default-features --features cli --bin jan
install -m755 src-tauri/target/release/jan src-tauri/resources/bin/jan
@echo "Jan agent built at:"
@echo " src-tauri/resources/bin/jan"
diff --git a/build-tui.sh b/build-tui.sh
index 95ce9bd1b..3ca7d4ebf 100755
--- a/build-tui.sh
+++ b/build-tui.sh
@@ -32,7 +32,7 @@ build() {
fi
echo "==> Building CLI binary (${profile})..."
- (cd "$CRATE_DIR" && cargo build $flag --features cli --bin jan)
+ (cd "$CRATE_DIR" && cargo build $flag --no-default-features --features cli --bin jan)
local artifact="$CRATE_DIR/target/$target_dir/jan"
if [ ! -f "$artifact" ]; then
@@ -51,12 +51,12 @@ build() {
case "${1:-debug}" in
check)
echo "==> cargo check (no binary produced)..."
- (cd "$CRATE_DIR" && cargo check --features cli --lib)
+ (cd "$CRATE_DIR" && cargo check --no-default-features --features cli --lib)
echo "==> OK"
;;
test)
echo "==> Running TUI tests..."
- (cd "$CRATE_DIR" && cargo test --features cli --lib -- core::cli::tui)
+ (cd "$CRATE_DIR" && cargo test --no-default-features --features cli --lib -- core::cli::tui)
echo "==> All TUI tests passed"
;;
release)
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 97b866a53..e60cf130f 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -43,14 +43,44 @@ deep-link = ["dep:tauri-plugin-deep-link"]
desktop = [
"deep-link",
"hardware",
+ "tauri-app",
+]
+# Everything that makes this crate a Tauri application: the framework, its
+# plugins, and the native GUI helpers (file dialogs, GTK, D-Bus). The headless
+# `jan` CLI builds without this feature and links no GUI crate -- gtk/gdk enter
+# the graph through `tauri` itself (via muda), so the dependency must be absent,
+# not merely unused.
+tauri-app = [
+ "dep:tauri",
+ "dep:tauri-build",
+ "dep:tauri-plugin-http",
+ "dep:tauri-plugin-llamacpp",
+ "dep:tauri-plugin-log",
+ "dep:tauri-plugin-opener",
+ "dep:tauri-plugin-os",
+ "dep:tauri-plugin-rag",
+ "dep:tauri-plugin-shell",
+ "dep:tauri-plugin-store",
+ "dep:tauri-plugin-mlx",
+ "dep:tauri-plugin-updater",
+ "dep:tauri-plugin-single-instance",
+ "dep:tauri-plugin-dialog",
+ "dep:fix-path-env",
+ "dep:rfd",
+ "dep:gtk",
+ "dep:zbus",
+ "tauri-plugin-vector-db/tauri",
+ "tauri-plugin-websearch/tauri",
]
mobile = [
"tauri/protocol-asset",
"tauri/test",
"tauri/wry",
"dep:sqlx",
+ "tauri-app",
]
test-tauri = [
+ "tauri-app",
"tauri/wry",
"tauri/x11",
"tauri/protocol-asset",
@@ -63,14 +93,14 @@ test-tauri = [
cli = ["dep:env_logger", "dep:dialoguer", "dep:indicatif", "dep:console", "dep:ratatui", "dep:tui-markdown", "dep:comfy-table", "dep:arboard", "dep:png"]
[build-dependencies]
-tauri-build = { version = "2.0.2", features = [] }
+tauri-build = { version = "2.0.2", features = [], optional = true }
serde_json = "1.0"
[dependencies]
dirs = "6.0.0"
async-trait = "0.1"
env = "1.0.1"
-fix-path-env = { git = "https://github.com/tauri-apps/fix-path-env-rs" }
+fix-path-env = { git = "https://github.com/tauri-apps/fix-path-env-rs", optional = true }
flate2 = "1.0"
futures-util = "0.3.31"
hex = "0.4"
@@ -103,16 +133,18 @@ tar = "0.4"
zip = "0.6"
tauri-plugin-deep-link = { version = "2", optional = true }
tauri-plugin-hardware = { path = "./plugins/tauri-plugin-hardware", optional = true }
-tauri-plugin-llamacpp = { path = "./plugins/tauri-plugin-llamacpp" }
-tauri-plugin-vector-db = { path = "./plugins/tauri-plugin-vector-db" }
-tauri-plugin-rag = { path = "./plugins/tauri-plugin-rag" }
-tauri-plugin-websearch = { path = "./plugins/tauri-plugin-websearch" }
+tauri-plugin-llamacpp = { path = "./plugins/tauri-plugin-llamacpp", optional = true }
+# The CLI consumes only these two plugins' tauri-free cores (`db`, `provider`);
+# the desktop feature turns their Tauri command surface back on.
+tauri-plugin-vector-db = { path = "./plugins/tauri-plugin-vector-db", default-features = false }
+tauri-plugin-rag = { path = "./plugins/tauri-plugin-rag", optional = true }
+tauri-plugin-websearch = { path = "./plugins/tauri-plugin-websearch", default-features = false }
# `default-features = false` drops the plugin's default `rustls-tls` (bundled
# Mozilla roots) so `native-tls` reads the OS trust store instead. Other
# features re-list the plugin's defaults so behaviour is otherwise unchanged.
# `macos-system-configuration` is reqwest's legacy alias for `system-proxy` —
# cross-platform-safe; native deps are target-gated by Cargo.
-tauri-plugin-http = { version = "2", default-features = false, features = [
+tauri-plugin-http = { version = "2", optional = true, default-features = false, features = [
"native-tls",
"http2",
"charset",
@@ -120,18 +152,18 @@ tauri-plugin-http = { version = "2", default-features = false, features = [
"cookies",
"unsafe-headers",
] }
-tauri-plugin-log = "2.0.0-rc"
-tauri-plugin-opener = "2.2.7"
-tauri-plugin-os = "2.2.1"
-tauri-plugin-shell = "2.2.0"
-tauri-plugin-store = "2"
+tauri-plugin-log = { version = "2.0.0-rc", optional = true }
+tauri-plugin-opener = { version = "2.2.7", optional = true }
+tauri-plugin-os = { version = "2.2.1", optional = true }
+tauri-plugin-shell = { version = "2.2.0", optional = true }
+tauri-plugin-store = { version = "2", optional = true }
sqlx = { version = "0.8", features = ["runtime-tokio", "sqlite"], optional = true }
thiserror = "2.0.12"
tokio = { version = "1", features = ["full"] }
tokio-util = "0.7.14"
url = "2.5"
uuid = { version = "1.7", features = ["v4"] }
-rfd = { version = "0.15.4", default-features = false, features = [
+rfd = { version = "0.15.4", optional = true, default-features = false, features = [
"tokio",
"xdg-portal",
"common-controls-v6",
@@ -165,6 +197,7 @@ png = { version = "0.17", optional = true }
[dependencies.tauri]
version = "2.8.5"
+optional = true
default-features = false
features = ["protocol-asset", "macos-private-api", "test"]
@@ -176,8 +209,8 @@ nix = { version = "=0.30.1", features = ["signal", "process", "resource"] }
libc = "0.2"
[target.'cfg(target_os = "linux")'.dependencies]
-zbus = { version = "5", default-features = false, features = ["tokio"] }
-gtk = "0.18"
+zbus = { version = "5", default-features = false, features = ["tokio"], optional = true }
+gtk = { version = "0.18", optional = true }
[target.'cfg(windows)'.dependencies]
libc = "0.2.172"
@@ -185,23 +218,23 @@ windows-sys = { version = "0.60.2", features = ["Win32_Storage_FileSystem"] }
# MLX runs only on Apple Silicon, so the plugin is built solely for macOS.
[target.'cfg(target_os = "macos")'.dependencies]
-tauri-plugin-mlx = { path = "./plugins/tauri-plugin-mlx" }
+tauri-plugin-mlx = { path = "./plugins/tauri-plugin-mlx", optional = true }
[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
reqwest = { version = "0.12", features = ["json", "blocking", "stream", "native-tls"] }
-tauri-plugin-updater = "2"
+tauri-plugin-updater = { version = "2", optional = true }
once_cell = "1.18"
-tauri-plugin-single-instance = { version = "2", features = ["deep-link"] }
+tauri-plugin-single-instance = { version = "2", features = ["deep-link"], optional = true }
[target.'cfg(any(target_os = "android", target_os = "ios"))'.dependencies]
reqwest = { version = "0.12", features = ["json", "blocking", "stream", "rustls-tls"], default-features = false }
-tauri-plugin-dialog = { version = "2.2.1", default-features = false }
-tauri-plugin-http = { version = "2", default-features = false }
-tauri-plugin-log = { version = "2.0.0-rc", default-features = false }
-tauri-plugin-opener = { version = "2.2.7", default-features = false }
-tauri-plugin-os = { version = "2.2.1", default-features = false }
-tauri-plugin-shell = { version = "2.2.0", default-features = false }
-tauri-plugin-store = { version = "2", default-features = false }
+tauri-plugin-dialog = { version = "2.2.1", default-features = false, optional = true }
+tauri-plugin-http = { version = "2", default-features = false, optional = true }
+tauri-plugin-log = { version = "2.0.0-rc", default-features = false, optional = true }
+tauri-plugin-opener = { version = "2.2.7", default-features = false, optional = true }
+tauri-plugin-os = { version = "2.2.1", default-features = false, optional = true }
+tauri-plugin-shell = { version = "2.2.0", default-features = false, optional = true }
+tauri-plugin-store = { version = "2", default-features = false, optional = true }
# Release profile optimizations for minimal binary size
[profile.release]
diff --git a/src-tauri/build.rs b/src-tauri/build.rs
index 7f512be51..4aff91b66 100644
--- a/src-tauri/build.rs
+++ b/src-tauri/build.rs
@@ -1,5 +1,5 @@
fn main() {
- #[cfg(not(feature = "cli"))]
+ #[cfg(feature = "tauri-app")]
{
tauri_build::build();
}
diff --git a/src-tauri/plugins/tauri-plugin-vector-db/Cargo.toml b/src-tauri/plugins/tauri-plugin-vector-db/Cargo.toml
index c178aaf51..179027523 100644
--- a/src-tauri/plugins/tauri-plugin-vector-db/Cargo.toml
+++ b/src-tauri/plugins/tauri-plugin-vector-db/Cargo.toml
@@ -10,8 +10,14 @@ rust-version = "1.77.2"
exclude = ["/examples", "/dist-js", "/guest-js", "/node_modules"]
links = "tauri-plugin-vector-db"
+[features]
+default = ["tauri"]
+# The Tauri command/plugin surface. Disabled by the headless `jan` CLI, which
+# consumes `db` directly and must not link any GUI crate.
+tauri = ["dep:tauri"]
+
[dependencies]
-tauri = { version = "2.8.5", default-features = false }
+tauri = { version = "2.8.5", default-features = false, optional = true }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
thiserror = "2.0"
diff --git a/src-tauri/plugins/tauri-plugin-vector-db/src/lib.rs b/src-tauri/plugins/tauri-plugin-vector-db/src/lib.rs
index 7a1ee0e1d..f58ee1520 100644
--- a/src-tauri/plugins/tauri-plugin-vector-db/src/lib.rs
+++ b/src-tauri/plugins/tauri-plugin-vector-db/src/lib.rs
@@ -1,9 +1,4 @@
-use tauri::{
- plugin::{Builder, TauriPlugin},
- Runtime,
- Manager,
-};
-
+#[cfg(feature = "tauri")]
mod commands;
pub mod db;
mod error;
@@ -13,8 +8,11 @@ mod utils;
pub use error::VectorDBError;
pub use state::VectorDBState;
-pub fn init<R: Runtime>() -> TauriPlugin<R> {
- Builder::new("vector-db")
+#[cfg(feature = "tauri")]
+pub fn init<R: tauri::Runtime>() -> tauri::plugin::TauriPlugin<R> {
+ use tauri::Manager;
+
+ tauri::plugin::Builder::new("vector-db")
.invoke_handler(tauri::generate_handler![
commands::create_collection,
commands::insert_chunks,
diff --git a/src-tauri/plugins/tauri-plugin-websearch/Cargo.toml b/src-tauri/plugins/tauri-plugin-websearch/Cargo.toml
index 2e40ac199..a8cf1cefe 100644
--- a/src-tauri/plugins/tauri-plugin-websearch/Cargo.toml
+++ b/src-tauri/plugins/tauri-plugin-websearch/Cargo.toml
@@ -10,12 +10,18 @@ rust-version = "1.77.2"
exclude = ["/examples", "/dist-js", "/guest-js", "/node_modules"]
links = "tauri-plugin-websearch"
+[features]
+default = ["tauri"]
+# The Tauri command/plugin surface. Disabled by the headless `jan` CLI, which
+# consumes `provider` directly and must not link any GUI crate.
+tauri = ["dep:tauri"]
+
[dependencies]
async-trait = "0.1"
log = "0.4"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
-tauri = { version = "2.5.0", default-features = false, features = [] }
+tauri = { version = "2.5.0", default-features = false, features = [], optional = true }
thiserror = "2.0.12"
tokio = { version = "1", features = ["full"] }
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
diff --git a/src-tauri/plugins/tauri-plugin-websearch/src/lib.rs b/src-tauri/plugins/tauri-plugin-websearch/src/lib.rs
index a1bad8928..373834a82 100644
--- a/src-tauri/plugins/tauri-plugin-websearch/src/lib.rs
+++ b/src-tauri/plugins/tauri-plugin-websearch/src/lib.rs
@@ -1,17 +1,15 @@
-use tauri::{
- plugin::{Builder, TauriPlugin},
- Runtime,
-};
-
+#[cfg(feature = "tauri")]
mod commands;
pub mod provider;
+#[cfg(feature = "tauri")]
pub use commands::{web_fetch, web_search, WebSearchError};
pub use provider::{FetchedPage, SearchResult};
/// Initializes the web search plugin.
-pub fn init<R: Runtime>() -> TauriPlugin<R> {
- Builder::new("websearch")
+#[cfg(feature = "tauri")]
+pub fn init<R: tauri::Runtime>() -> tauri::plugin::TauriPlugin<R> {
+ tauri::plugin::Builder::new("websearch")
.invoke_handler(tauri::generate_handler![
commands::web_search,
commands::web_fetch
diff --git a/src-tauri/src/bin/jan.rs b/src-tauri/src/bin/jan.rs
index f4e1406e4..720f4e16b 100644
--- a/src-tauri/src/bin/jan.rs
+++ b/src-tauri/src/bin/jan.rs
@@ -1,18 +1,19 @@
//! jan — headless CLI for Jan.
//!
-//! Shares all core logic with the Jan desktop app.
-//! Build with: cargo build --features cli --bin jan
+//! Shares the Tauri-free core logic with the Jan desktop app; talks only to
+//! remote providers (no local inference, no GUI dependencies).
+//! Build with: cargo build --no-default-features --features cli --bin jan
use clap::{Args, CommandFactory, FromArgMatches, Parser, Subcommand};
use console::Style;
// 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::providers::ProviderOverrides;
+use app_lib::core::cli::providers::{load_provider_configs, 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_thread, cli_list_messages, cli_list_threads, list_models,
+ cli_get_thread, cli_list_messages, cli_list_threads,
};
// ── Top-level CLI ──────────────────────────────────────────────────────────
@@ -20,18 +21,19 @@ use app_lib::core::cli::{
#[derive(Parser)]
#[command(
name = "jan",
- about = "Chat with local AI models in an interactive agent console — no cloud required",
+ about = "Chat with AI models in an interactive agent console",
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\
+where you chat with a 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.",
+agents headlessly and manage threads and providers.\n\n\
+Models are served by remote providers configured in ~/.jan/config.toml\n\
+(see `jan config set`), a project's agent.toml, or the Jan desktop app.",
after_help = "Examples:\n \
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 models list # show every configured provider model\n \
jan cli threads list # list saved conversation threads",
version
)]
@@ -88,13 +90,13 @@ enum CliCommands {
#[command(subcommand)]
cmd: ThreadsCommands,
},
- /// List models installed in the Jan data folder
+ /// List the models exposed by the configured providers
#[command(display_order = 11)]
Models {
#[command(subcommand)]
cmd: ModelsCommands,
},
- /// Run folder-based agents against local or cloud models
+ /// Run folder-based agents against a configured provider's models
#[command(display_order = 12)]
Agent {
#[command(subcommand)]
@@ -240,11 +242,14 @@ enum ThreadsCommands {
#[derive(Subcommand)]
enum ModelsCommands {
- /// Print all installed models as JSON (from the Jan data folder)
+ /// Print every configured provider's models as JSON (API keys redacted)
List {
- /// Filter by engine: llamacpp, mlx, or all
- #[arg(long, default_value = "all")]
- engine: String,
+ /// Only show models from this provider (e.g. anthropic)
+ #[arg(long)]
+ provider: Option<String>,
+ /// Project root whose agent.toml [provider] override is applied
+ #[arg(long, default_value = ".")]
+ project: String,
},
}
@@ -467,26 +472,37 @@ async fn handle_threads(cmd: ThreadsCommands) {
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,
- }));
+ ModelsCommands::List { provider, project } => {
+ let configs = match load_provider_configs(
+ Some(std::path::Path::new(&project)),
+ &ProviderOverrides::default().with_env(),
+ ) {
+ Ok(c) => c,
+ Err(e) => {
+ eprintln!("Error: {e}");
+ std::process::exit(1);
}
- }
+ };
+ let mut output: Vec<serde_json::Value> = configs
+ .values()
+ .filter(|c| app_lib::core::cli::providers::is_cli_reachable(c))
+ .filter(|c| provider.as_ref().map_or(true, |p| &c.provider == p))
+ .flat_map(|c| {
+ c.models.iter().map(move |m| {
+ serde_json::json!({
+ "id": m,
+ "provider": c.provider,
+ "base_url": c.base_url,
+ "api_type": c.api_type,
+ "has_api_key": !c.bearer_key_chain().is_empty(),
+ })
+ })
+ })
+ .collect();
+ output.sort_by(|a, b| {
+ (a["provider"].as_str(), a["id"].as_str())
+ .cmp(&(b["provider"].as_str(), b["id"].as_str()))
+ });
println!("{}", serde_json::to_string_pretty(&output).unwrap());
}
}
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rs
index f1a7f97e3..6c11e6014 100644
--- a/src-tauri/src/core/agent/loop.rs
+++ b/src-tauri/src/core/agent/loop.rs
@@ -9,6 +9,7 @@ use std::sync::Arc;
use async_trait::async_trait;
use reqwest::Client;
+#[cfg(not(feature = "cli"))]
use tauri_plugin_llamacpp::state::LlamacppState;
use tokio::sync::{mpsc, Mutex};
@@ -20,7 +21,9 @@ use crate::core::agent::upstream::{
extract_choice_message, extract_tool_calls, load_assistant_config, parse_openai_messages,
resolve_upstream_for_model, set_system_prompt, stream_openai_chat_completions,
};
+#[cfg(not(feature = "cli"))]
use crate::core::server::proxy::router_first_model;
+#[cfg(not(feature = "cli"))]
use crate::core::server::MlxBackendSession;
use crate::core::{
mcp::models::McpSettings,
@@ -49,7 +52,10 @@ fn next_permission_id() -> String {
pub(crate) struct OrchestrationArgs {
pub client: Client,
pub provider_configs: Arc<Mutex<HashMap<String, ProviderConfig>>>,
+ /// Local engine handles. Absent in the `cli` build, which is remote-only.
+ #[cfg(not(feature = "cli"))]
pub llama_state: Arc<LlamacppState>,
+ #[cfg(not(feature = "cli"))]
pub mlx_sessions: Arc<Mutex<HashMap<i32, MlxBackendSession>>>,
pub mcp_servers: SharedMcpServers,
pub mcp_settings: Arc<Mutex<McpSettings>>,
@@ -522,7 +528,9 @@ impl ToolInvoker for CompositeToolInvoker {
}
/// API-server entry point. Preserves the original single-final-JSON contract by
-/// running the streamed loop with a discarded event sink.
+/// running the streamed loop with a discarded event sink. Desktop-only: the
+/// `cli` build has no proxy server.
+#[cfg(not(feature = "cli"))]
#[allow(clippy::too_many_arguments)]
pub(crate) async fn run_server_side_openai_orchestration(
json_body: &serde_json::Value,
@@ -657,7 +665,9 @@ async fn orchestrate_inner(
let OrchestrationArgs {
client,
provider_configs,
+ #[cfg(not(feature = "cli"))]
llama_state,
+ #[cfg(not(feature = "cli"))]
mlx_sessions,
mcp_servers,
mcp_settings,
@@ -723,14 +733,17 @@ async fn orchestrate_inner(
}
}
}
- if model_id.is_none() {
- if let Some(first) = router_first_model(llama_state, client).await {
- model_id = Some(first);
+ #[cfg(not(feature = "cli"))]
+ {
+ if model_id.is_none() {
+ if let Some(first) = router_first_model(llama_state, client).await {
+ model_id = Some(first);
+ }
+ }
+ if model_id.is_none() {
+ let mlx_guard = mlx_sessions.lock().await;
+ model_id = mlx_guard.values().next().map(|s| s.info.model_id.clone());
}
- }
- if model_id.is_none() {
- let mlx_guard = mlx_sessions.lock().await;
- model_id = mlx_guard.values().next().map(|s| s.info.model_id.clone());
}
let model_id = model_id.ok_or("No running model sessions available")?;
@@ -802,7 +815,9 @@ async fn orchestrate_inner(
let (upstream_url, session_api_keys) = resolve_upstream_for_model(
&model_id,
provider_configs.clone(),
+ #[cfg(not(feature = "cli"))]
llama_state.clone(),
+ #[cfg(not(feature = "cli"))]
mlx_sessions.clone(),
)
.await?;
@@ -944,7 +959,9 @@ pub(crate) async fn compact_history(
let (upstream_url, api_keys) = resolve_upstream_for_model(
model_id,
args.provider_configs.clone(),
+ #[cfg(not(feature = "cli"))]
args.llama_state.clone(),
+ #[cfg(not(feature = "cli"))]
args.mlx_sessions.clone(),
)
.await?;
@@ -976,7 +993,9 @@ pub(crate) async fn evaluate_goal(
let (upstream_url, api_keys) = resolve_upstream_for_model(
smol_model_id,
args.provider_configs.clone(),
+ #[cfg(not(feature = "cli"))]
args.llama_state.clone(),
+ #[cfg(not(feature = "cli"))]
args.mlx_sessions.clone(),
)
.await?;
diff --git a/src-tauri/src/core/agent/mod.rs b/src-tauri/src/core/agent/mod.rs
index 1f8532b03..b0c2295d7 100644
--- a/src-tauri/src/core/agent/mod.rs
+++ b/src-tauri/src/core/agent/mod.rs
@@ -1,6 +1,8 @@
//! Shared agent orchestration: the server-side loop and its upstream/provider
//! plumbing, consumed by both the API-server proxy and `tauri-plugin-agent`.
+// Tauri IPC surface for the desktop agent; the CLI drives the loop directly.
+#[cfg(not(feature = "cli"))]
pub mod commands;
pub mod compaction;
pub mod context;
diff --git a/src-tauri/src/core/agent/project.rs b/src-tauri/src/core/agent/project.rs
index 81c15735f..ea4556909 100644
--- a/src-tauri/src/core/agent/project.rs
+++ b/src-tauri/src/core/agent/project.rs
@@ -209,6 +209,7 @@ pub(crate) fn set_model_in_agent_toml(path: &Path, model: &str) -> Result<(), St
/// Persist `[skills].enabled` into the agent.toml at `path`, format-preserving
/// (comments kept). An empty list clears the whitelist (= all skills enabled).
+#[cfg(any(not(feature = "cli"), test))]
pub(crate) fn set_skills_enabled_in_agent_toml(
path: &Path,
enabled: &[String],
diff --git a/src-tauri/src/core/agent/skills.rs b/src-tauri/src/core/agent/skills.rs
index b4734bdd5..48d1f3d55 100644
--- a/src-tauri/src/core/agent/skills.rs
+++ b/src-tauri/src/core/agent/skills.rs
@@ -196,6 +196,7 @@ fn describe(parsed: &ParsedSkill) -> String {
/// Metadata for every discovered skill (name + description) — for the UI list.
/// Keeps empty stubs so the user can see and edit them.
+#[cfg(any(not(feature = "cli"), test))]
pub(crate) fn list_meta(root: &Path) -> Vec<SkillMeta> {
discover(root)
.into_iter()
@@ -268,6 +269,7 @@ pub(crate) fn write(root: &Path, name: &str, content: &str) -> Result<(), String
}
/// Delete a skill (folder or flat form). Idempotent: a missing skill is Ok.
+#[cfg(any(not(feature = "cli"), test))]
pub(crate) fn delete(root: &Path, name: &str) -> Result<(), String> {
let stem = safe_stem(name)?;
let dir = skills_dir(root);
diff --git a/src-tauri/src/core/agent/upstream.rs b/src-tauri/src/core/agent/upstream.rs
index b99ea58f6..15bdd6229 100644
--- a/src-tauri/src/core/agent/upstream.rs
+++ b/src-tauri/src/core/agent/upstream.rs
@@ -12,13 +12,17 @@ use std::sync::Arc;
use futures_util::StreamExt;
use reqwest::Client;
use rmcp::model::{CallToolRequestParam, CallToolResult};
+#[cfg(not(feature = "cli"))]
use tauri_plugin_llamacpp::state::LlamacppState;
use tokio::sync::{mpsc, Mutex};
use crate::core::agent::events::StreamEvent;
-use crate::core::server::proxy::{
- http_status_indicates_api_key_retry, normalize_openai_tool_parameters_schema, router_upstream,
+use crate::core::openai_schema::{
+ http_status_indicates_api_key_retry, normalize_openai_tool_parameters_schema,
};
+#[cfg(not(feature = "cli"))]
+use crate::core::server::proxy::router_upstream;
+#[cfg(not(feature = "cli"))]
use crate::core::server::MlxBackendSession;
use crate::core::{
mcp::models::McpSettings,
@@ -162,18 +166,38 @@ fn mcp_call_result_to_string(result: &CallToolResult) -> String {
}
}
+/// Resolve `model_id` to an upstream URL + key chain. The desktop build also
+/// resolves local engines (MLX session, llama-server router); the `cli` build is
+/// remote-only, so a model with no provider entry is unresolvable.
pub(crate) async fn resolve_upstream_for_model(
model_id: &str,
provider_configs: Arc<Mutex<HashMap<String, ProviderConfig>>>,
- llama_state: Arc<LlamacppState>,
- mlx_sessions: Arc<Mutex<HashMap<i32, MlxBackendSession>>>,
+ #[cfg(not(feature = "cli"))] llama_state: Arc<LlamacppState>,
+ #[cfg(not(feature = "cli"))] mlx_sessions: Arc<Mutex<HashMap<i32, MlxBackendSession>>>,
) -> Result<(String, Vec<String>), String> {
let destination_path = "/chat/completions";
let pc = provider_configs.lock().await;
- let provider_name = pc
+ let offers = |config: &ProviderConfig| config.models.iter().any(|m| m == model_id);
+
+ // The same model id can be listed by several providers -- typically a local
+ // engine descriptor (no base_url) plus a Jan desktop API server exposing the
+ // same model over HTTP. `HashMap` iteration order is randomized, so pick the
+ // usable one deterministically instead of whichever hashes first. Only the
+ // CLI needs this: the desktop resolves base_url-less providers through its
+ // in-process engine branches below.
+ #[cfg(feature = "cli")]
+ let first_match = pc
.iter()
- .find(|(_, config)| config.models.iter().any(|m| m == model_id))
+ .filter(|(_, config)| {
+ config.base_url.as_deref().is_some_and(|u| !u.is_empty()) && offers(config)
+ })
+ .min_by_key(|(name, _)| name.to_string())
+ .or_else(|| pc.iter().find(|(_, config)| offers(config)));
+ #[cfg(not(feature = "cli"))]
+ let first_match = pc.iter().find(|(_, config)| offers(config));
+
+ let provider_name = first_match
.map(|(_, config)| config.provider.clone())
.or_else(|| {
if let Some(sep_pos) = model_id.find('/') {
@@ -200,18 +224,21 @@ pub(crate) async fn resolve_upstream_for_model(
}
}
- let mlx_guard = mlx_sessions.lock().await;
- if let Some(info) = mlx_guard.values().find(|s| s.info.model_id == model_id) {
- let target_port = info.info.port;
- return Ok((
- format!("http://127.0.0.1:{target_port}/v1{destination_path}"),
- vec![info.info.api_key.clone()],
- ));
- }
- drop(mlx_guard);
+ #[cfg(not(feature = "cli"))]
+ {
+ let mlx_guard = mlx_sessions.lock().await;
+ if let Some(info) = mlx_guard.values().find(|s| s.info.model_id == model_id) {
+ let target_port = info.info.port;
+ return Ok((
+ format!("http://127.0.0.1:{target_port}/v1{destination_path}"),
+ vec![info.info.api_key.clone()],
+ ));
+ }
+ drop(mlx_guard);
- if let Some((url, key)) = router_upstream(&llama_state, destination_path).await {
- return Ok((url, vec![key]));
+ if let Some((url, key)) = router_upstream(&llama_state, destination_path).await {
+ return Ok((url, vec![key]));
+ }
}
Err(format!("No upstream session found for model '{model_id}'"))
@@ -383,6 +410,7 @@ pub(crate) async fn execute_mcp_tool_calls(
results
}
+#[cfg(not(feature = "cli"))]
pub(crate) async fn call_openai_chat_completions(
client: &Client,
upstream_url: &str,
@@ -801,6 +829,44 @@ mod tests {
mpsc::unbounded_channel()
}
+ /// A model served both by a Jan desktop API server (reachable over HTTP) and
+ /// by local engine descriptors (no base_url) must always resolve to the
+ /// server. `HashMap` order is randomized, so the local entries outnumber the
+ /// remote one here: without a deterministic preference this fails most runs.
+ #[cfg(feature = "cli")]
+ #[tokio::test]
+ async fn shared_model_id_resolves_to_the_reachable_provider() {
+ let mut configs = HashMap::new();
+ for local in ["llamacpp", "llamacpp-rs", "mlx", "engine-d", "engine-e"] {
+ configs.insert(
+ local.to_string(),
+ ProviderConfig {
+ provider: local.into(),
+ base_url: None,
+ models: vec!["sentence-transformer-mini".into()],
+ ..Default::default()
+ },
+ );
+ }
+ configs.insert(
+ "JanServer".to_string(),
+ ProviderConfig {
+ provider: "JanServer".into(),
+ base_url: Some("http://127.0.0.1:1337/v1".into()),
+ models: vec!["sentence-transformer-mini".into()],
+ ..Default::default()
+ },
+ );
+
+ let (url, _keys) = resolve_upstream_for_model(
+ "sentence-transformer-mini",
+ Arc::new(Mutex::new(configs)),
+ )
+ .await
+ .expect("the API server provider is reachable");
+ assert_eq!(url, "http://127.0.0.1:1337/v1/chat/completions");
+ }
+
#[test]
fn parse_messages_passes_multimodal_content_array_through() {
let messages = json!([{
diff --git a/src-tauri/src/core/app/commands.rs b/src-tauri/src/core/app/commands.rs
index de396b491..a1db403a1 100644
--- a/src-tauri/src/core/app/commands.rs
+++ b/src-tauri/src/core/app/commands.rs
@@ -2,13 +2,14 @@ use std::{
fs,
path::{Path, PathBuf},
};
+#[cfg(not(feature = "cli"))]
use tauri::{AppHandle, Manager, Runtime, State};
-use super::{
- constants::{CONFIGURATION_FILE_NAME, TAURI_BUNDLE_IDENTIFIER},
- helpers::copy_dir_recursive,
- models::AppConfiguration,
-};
+use super::constants::{CONFIGURATION_FILE_NAME, TAURI_BUNDLE_IDENTIFIER};
+use super::models::AppConfiguration;
+#[cfg(not(feature = "cli"))]
+use super::helpers::copy_dir_recursive;
+#[cfg(not(feature = "cli"))]
use crate::core::state::AppState;
/// Canonical Jan app support directory (`%APPDATA%/Jan` on Windows).
@@ -78,6 +79,7 @@ fn legacy_app_config_candidate_paths(app_data_dir: &Path) -> Vec<PathBuf> {
paths
}
+#[cfg(not(feature = "cli"))]
fn app_data_dir_with_fallback<R: Runtime>(app_handle: &tauri::AppHandle<R>) -> PathBuf {
let package_name = env!("CARGO_PKG_NAME");
app_handle
@@ -150,6 +152,7 @@ pub fn resolve_jan_data_folder() -> PathBuf {
PathBuf::from(home).join(&app_name).join("data")
}
+#[cfg(not(feature = "cli"))]
#[tauri::command]
pub fn get_app_configurations<R: Runtime>(app_handle: tauri::AppHandle<R>) -> AppConfiguration {
let mut app_default_configuration = AppConfiguration::default();
@@ -205,6 +208,7 @@ pub fn get_app_configurations<R: Runtime>(app_handle: tauri::AppHandle<R>) -> Ap
}
}
+#[cfg(not(feature = "cli"))]
#[tauri::command]
pub fn update_app_configuration<R: Runtime>(
app_handle: tauri::AppHandle<R>,
@@ -220,6 +224,7 @@ pub fn update_app_configuration<R: Runtime>(
.map_err(|e| e.to_string())
}
+#[cfg(not(feature = "cli"))]
#[tauri::command]
pub fn get_jan_data_folder_path<R: Runtime>(app_handle: tauri::AppHandle<R>) -> PathBuf {
if cfg!(test) {
@@ -250,6 +255,7 @@ pub fn get_jan_data_folder_path<R: Runtime>(app_handle: tauri::AppHandle<R>) ->
PathBuf::from(app_configurations.data_folder)
}
+#[cfg(not(feature = "cli"))]
#[tauri::command]
pub fn get_configuration_file_path<R: Runtime>(app_handle: tauri::AppHandle<R>) -> PathBuf {
let app_path = app_data_dir_with_fallback(&app_handle);
@@ -259,6 +265,7 @@ pub fn get_configuration_file_path<R: Runtime>(app_handle: tauri::AppHandle<R>)
app_path.join(CONFIGURATION_FILE_NAME)
}
+#[cfg(not(feature = "cli"))]
#[tauri::command]
pub fn default_data_folder_path<R: Runtime>(app_handle: tauri::AppHandle<R>) -> String {
let mut path = app_handle.path().data_dir().unwrap_or_else(|err| {
@@ -286,11 +293,13 @@ pub fn default_data_folder_path<R: Runtime>(app_handle: tauri::AppHandle<R>) ->
path_str
}
+#[cfg(not(feature = "cli"))]
#[tauri::command]
pub fn get_user_home_path<R: Runtime>(app: AppHandle<R>) -> String {
get_app_configurations(app.clone()).data_folder
}
+#[cfg(not(feature = "cli"))]
#[tauri::command]
pub fn change_app_data_folder<R: Runtime>(
app_handle: tauri::AppHandle<R>,
@@ -334,6 +343,7 @@ pub fn change_app_data_folder<R: Runtime>(
update_app_configuration(app_handle, configuration)
}
+#[cfg(not(feature = "cli"))]
#[tauri::command]
pub fn app_token(state: State<'_, AppState>) -> Option<String> {
state.app_token.clone()
diff --git a/src-tauri/src/core/app/mod.rs b/src-tauri/src/core/app/mod.rs
index ebcc21278..2dc65d6b3 100644
--- a/src-tauri/src/core/app/mod.rs
+++ b/src-tauri/src/core/app/mod.rs
@@ -1,5 +1,8 @@
pub mod commands;
pub mod constants;
+#[cfg(not(feature = "cli"))]
pub mod helpers;
pub mod models;
+// Desktop settings.json store, driven by Tauri commands + a flush thread.
+#[cfg(not(feature = "cli"))]
pub mod settings_store;
diff --git a/src-tauri/src/core/cli/mcp.rs b/src-tauri/src/core/cli/mcp.rs
index 7029563ca..00fa0747b 100644
--- a/src-tauri/src/core/cli/mcp.rs
+++ b/src-tauri/src/core/cli/mcp.rs
@@ -21,11 +21,10 @@ use rmcp::{
ServiceExt,
};
use serde_json::Value;
-use tauri_plugin_http::reqwest;
use tokio::process::Command;
use crate::core::app::commands::resolve_jan_data_folder;
-use crate::core::mcp::helpers::{extract_active_status, extract_command_args};
+use crate::core::mcp::models::{extract_active_status, extract_command_args};
use crate::core::mcp::models::McpSettings;
use crate::core::state::{RunningServiceEnum, SharedMcpServers};
diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rs
index c7869fdb7..f44756856 100644
--- a/src-tauri/src/core/cli/mod.rs
+++ b/src-tauri/src/core/cli/mod.rs
@@ -3,7 +3,6 @@
//! This module is only compiled when the `cli` feature is enabled.
pub mod mcp;
-pub mod preset;
pub mod providers;
mod path_refs;
mod tui;
@@ -12,8 +11,6 @@ use std::path::PathBuf;
use std::sync::Arc;
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, update_thread_metadata, write_messages_to_file},
@@ -22,21 +19,6 @@ 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;
-
-// ── State constructors ─────────────────────────────────────────────────────
-
-pub fn init_llamacpp_state() -> LlamacppState {
- LlamacppState::new()
-}
-
-#[cfg(target_os = "macos")]
-pub fn init_mlx_state() -> MlxState {
- MlxState::new()
-}
// ── Thread operations ──────────────────────────────────────────────────────
@@ -232,214 +214,6 @@ fn default_thread_title(history: &[serde_json::Value]) -> String {
}
}
-// ── Server operations ──────────────────────────────────────────────────────
-
-/// 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` 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_key(|b| std::cmp::Reverse(b.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_key(|a| a.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
-}
-
// ── App config ────────────────────────────────────────────────────────────
pub fn cli_get_data_folder() -> PathBuf {
@@ -498,8 +272,11 @@ pub fn cli_agent_status(
let cfg = load_agent_config(&project_root)?;
let provider_configs = load_provider_configs(Some(&project_root), overrides)?;
+ // Only providers this build can reach: local-engine entries inherited from
+ // the desktop store have no upstream here (see `is_cli_reachable`).
let mut providers: Vec<serde_json::Value> = provider_configs
.values()
+ .filter(|c| crate::core::cli::providers::is_cli_reachable(c))
.map(|c| {
serde_json::json!({
"provider": c.provider,
@@ -610,7 +387,6 @@ 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>,
mcp_servers: crate::core::state::SharedMcpServers,
mcp_settings: McpSettings,
permission_requests: PermissionRegistry,
@@ -619,8 +395,6 @@ fn build_cli_orchestration_args(
OrchestrationArgs {
client: reqwest::Client::new(),
provider_configs: Arc::new(Mutex::new(provider_configs)),
- llama_state,
- mlx_sessions: Arc::new(Mutex::new(HashMap::new())),
mcp_servers,
mcp_settings: Arc::new(Mutex::new(mcp_settings)),
jan_data_folder: resolve_jan_data_folder().to_string_lossy().into_owned(),
@@ -633,164 +407,6 @@ 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`. 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)]
-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.
@@ -798,9 +414,6 @@ 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>>>,
/// Background connect of `active` MCP servers, awaited before the first turn.
pub mcp_task: Option<tokio::task::JoinHandle<Vec<String>>>,
}
@@ -824,9 +437,6 @@ pub(crate) struct AgentSession {
/// Per-request output cap forwarded to the model as OpenAI `max_tokens`.
/// `None` omits the field (model default).
pub max_tokens: Option<u64>,
- /// Background local-router startup, awaited before the first turn. `None`
- /// for cloud models.
- pub router_task: Option<tokio::task::JoinHandle<Result<(), String>>>,
/// Shared MCP connection map (same Arc held by `args`), so the TUI can
/// connect/disconnect servers live via `/mcp` and later turns pick them up.
pub mcp_servers: crate::core::state::SharedMcpServers,
@@ -902,11 +512,22 @@ fn prepare_agent_session(
let provider_configs = load_provider_configs(Some(&project_root), &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);
+ // Reject a model whose only provider is a local engine descriptor before any
+ // setup work: the CLI cannot start an engine itself, so this would otherwise
+ // fail mid-run with a far vaguer message. Local models are still runnable
+ // over HTTP -- via the desktop app's API server -- which is what the hint
+ // points at; a provider entry with a base_url never reaches this branch.
+ if let Some(local) =
+ crate::core::cli::providers::unreachable_local_provider(&provider_configs, &model)
+ {
+ return Err(format!(
+ "model '{model}' is only offered by '{local}', a local engine the Jan CLI cannot \
+ start itself. To use it, run the model in the Jan desktop app with its API server \
+ enabled and point a provider at it:\n \
+ jan config set --provider jan --base-url http://localhost:1337/v1 --model {model}\n\
+ Or pick a model from `jan cli models list`."
+ ));
+ }
// MCP servers marked `active` in mcp_config.json connect off-thread so setup/
// render isn't blocked on a cold stdio spawn. The caller awaits `mcp_task`
@@ -930,7 +551,6 @@ fn prepare_agent_session(
project_root,
permissions,
provider_configs,
- llama_state,
mcp_servers.clone(),
mcp_settings,
permission_requests.clone(),
@@ -946,7 +566,6 @@ fn prepare_agent_session(
context_window: cfg.agent.context_window.unwrap_or(128_000),
reserve_tokens: cfg.agent.compaction_reserve_tokens.unwrap_or(16_384),
max_tokens: cfg.agent.max_tokens,
- router_task,
mcp_servers,
mcp_task,
})
@@ -978,7 +597,6 @@ fn prepare_agent_run(
args: session.args,
body,
permission_requests: session.permission_requests,
- router_task: session.router_task,
mcp_task: session.mcp_task,
})
}
@@ -995,12 +613,9 @@ async fn run_agent_loop(
args,
body,
permission_requests,
- router_task,
mcp_task,
} = prepare_agent_run(project, task, model_override, max_turns_override, overrides, yolo)?;
- // Block until the local model is loaded (no-op for cloud models).
- await_router_task(router_task).await?;
// Block until active MCP servers connect, so tools (collected once per run)
// are present on the first turn.
if let Some(task) = mcp_task {
@@ -1246,53 +861,6 @@ mod tests {
let _ = std::fs::remove_dir_all(&base);
}
- // ── ModelYml deserialization ──────────────────────────────────────────
-
- #[test]
- fn model_yml_minimal_required_field() {
- let yml = "model_path: /tmp/x.gguf\n";
- let parsed: ModelYml = serde_yaml::from_str(yml).unwrap();
- assert_eq!(parsed.model_path, "/tmp/x.gguf");
- assert_eq!(parsed.size_bytes, 0);
- assert!(!parsed.embedding);
- assert!(parsed.name.is_none());
- assert!(parsed.mmproj_path.is_none());
- assert!(parsed.capabilities.is_empty());
- }
-
- #[test]
- fn model_yml_full() {
- let yml = "model_path: relative/model.gguf\n\
- name: My Model\n\
- size_bytes: 1024\n\
- embedding: true\n\
- mmproj_path: relative/mmproj.gguf\n\
- capabilities:\n - vision\n - tools\n";
- let parsed: ModelYml = serde_yaml::from_str(yml).unwrap();
- assert_eq!(parsed.model_path, "relative/model.gguf");
- assert_eq!(parsed.name.as_deref(), Some("My Model"));
- assert_eq!(parsed.size_bytes, 1024);
- assert!(parsed.embedding);
- assert_eq!(parsed.mmproj_path.as_deref(), Some("relative/mmproj.gguf"));
- assert_eq!(parsed.capabilities, vec!["vision", "tools"]);
- }
-
- #[test]
- fn model_yml_missing_model_path_errors() {
- let yml = "name: bad\n";
- let parsed: Result<ModelYml, _> = serde_yaml::from_str(yml);
- assert!(parsed.is_err());
- }
-
- // ── State constructors ────────────────────────────────────────────────
-
- #[test]
- fn state_constructors_do_not_panic() {
- let _ = init_llamacpp_state();
- #[cfg(target_os = "macos")]
- let _ = init_mlx_state();
- }
-
// ── cli_get_data_folder returns a path ────────────────────────────────
#[test]
diff --git a/src-tauri/src/core/cli/preset.rs b/src-tauri/src/core/cli/preset.rs
deleted file mode 100644
index 67e13472f..000000000
--- a/src-tauri/src/core/cli/preset.rs
+++ /dev/null
@@ -1,216 +0,0 @@
-//! 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/providers.rs b/src-tauri/src/core/cli/providers.rs
index d6bd15800..154e5c722 100644
--- a/src-tauri/src/core/cli/providers.rs
+++ b/src-tauri/src/core/cli/providers.rs
@@ -104,22 +104,70 @@ fn parse_selection(raw: &str) -> DesktopSelection {
}
}
-/// Enumerate `(provider, model_id)` pairs from the persisted desktop store,
-/// sorted by provider then model. Used to populate the TUI `/model` selector.
-pub fn list_provider_models() -> Vec<(String, String)> {
- let path = resolve_jan_data_folder().join("settings.json");
- let configs = match std::fs::read_to_string(&path) {
- Ok(raw) => parse_provider_store(&raw),
- Err(_) => return Vec::new(),
- };
+/// Whether the CLI can actually reach this provider. A populated `base_url` is
+/// an HTTP upstream; an empty one means a local engine (llamacpp, llamacpp-rs,
+/// mlx) whose endpoint only exists after the desktop app spawns it. The CLI is
+/// remote-only, so those entries are dead options and must not be offered.
+/// Mirrors the resolution rule in `agent::upstream::resolve_upstream_for_model`,
+/// whose local-engine branches are compiled out of this build.
+pub fn is_cli_reachable(config: &ProviderConfig) -> bool {
+ config.base_url.as_deref().is_some_and(|u| !u.is_empty())
+}
+
+/// `(provider, model_id)` pairs the CLI can actually run, sorted by provider
+/// then model.
+pub fn reachable_models(configs: &HashMap<String, ProviderConfig>) -> Vec<(String, String)> {
let mut out: Vec<(String, String)> = configs
.values()
+ .filter(|c| is_cli_reachable(c))
.flat_map(|c| c.models.iter().map(|m| (c.provider.clone(), m.clone())))
.collect();
out.sort();
out
}
+/// Name of the local-engine provider serving `model_id` when **no** reachable
+/// provider offers it, so the caller can reject the run up front instead of
+/// failing at upstream resolution. Lookup mirrors
+/// `agent::upstream::resolve_upstream_for_model`: an exact hit in a provider's
+/// `models` list, or a `<provider>/<model>` prefix.
+///
+/// `None` for a model nobody claims: provider `models` lists are routinely
+/// incomplete (custom deployments, freshly released ids), so an unknown id must
+/// still fall through to normal resolution rather than be rejected here.
+pub fn unreachable_local_provider(
+ configs: &HashMap<String, ProviderConfig>,
+ model_id: &str,
+) -> Option<String> {
+ let offering = |c: &&ProviderConfig| c.models.iter().any(|m| m == model_id);
+ if configs.values().filter(offering).any(is_cli_reachable) {
+ return None;
+ }
+ if let Some(local) = configs.values().find(|c| offering(c)) {
+ return Some(local.provider.clone());
+ }
+
+ let prefix = model_id.split_once('/')?.0;
+ configs
+ .get(prefix)
+ .filter(|c| !is_cli_reachable(c))
+ .map(|c| c.provider.clone())
+}
+
+/// Runnable `(provider, model_id)` pairs for the TUI `/model` selector, taken
+/// from the same layered resolution the agent uses -- so the picker offers
+/// exactly what a run can reach, including `~/.jan/config.toml` providers the
+/// desktop store knows nothing about.
+pub fn list_provider_models(project_root: Option<&std::path::Path>) -> Vec<(String, String)> {
+ match load_provider_configs(project_root, &ProviderOverrides::default().with_env()) {
+ Ok(configs) => reachable_models(&configs),
+ Err(e) => {
+ log::warn!("could not load provider configs for the model picker: {e}");
+ Vec::new()
+ }
+ }
+}
+
/// Load provider configs by layering the four `.jan`-based scopes (see module
/// docs for the priority order): Global `~/.jan/config.toml` -> Desktop
/// `settings.json` (inherit-only, additive) -> project `agent.toml`
@@ -477,6 +525,132 @@ mod tests {
assert_eq!(parse_selection(blank), DesktopSelection::default());
}
+ #[test]
+ fn only_providers_with_a_base_url_are_cli_reachable() {
+ let remote = ProviderConfig {
+ provider: "anthropic".into(),
+ base_url: Some("https://api.anthropic.com/v1".into()),
+ ..Default::default()
+ };
+ // Local engines (llamacpp, llamacpp-rs, mlx) are stored by the desktop
+ // app without a base_url: their upstream only exists once the desktop
+ // has spawned the engine, which the CLI never does.
+ let local = ProviderConfig {
+ provider: "llamacpp".into(),
+ base_url: None,
+ ..Default::default()
+ };
+ let blank = ProviderConfig {
+ provider: "mlx".into(),
+ base_url: Some(String::new()),
+ ..Default::default()
+ };
+ assert!(is_cli_reachable(&remote));
+ assert!(!is_cli_reachable(&local));
+ assert!(!is_cli_reachable(&blank));
+ }
+
+ #[test]
+ fn reachable_models_skips_local_engine_providers() {
+ let mut configs = HashMap::new();
+ configs.insert(
+ "llamacpp".to_string(),
+ ProviderConfig {
+ provider: "llamacpp".into(),
+ base_url: None,
+ models: vec!["gemma-4-E2B-it-IQ4_XS".into()],
+ ..Default::default()
+ },
+ );
+ configs.insert(
+ "anthropic".to_string(),
+ ProviderConfig {
+ provider: "anthropic".into(),
+ base_url: Some("https://api.anthropic.com/v1".into()),
+ models: vec!["claude-sonnet-5".into(), "claude-opus-5".into()],
+ ..Default::default()
+ },
+ );
+ let pairs = reachable_models(&configs);
+ assert_eq!(
+ pairs,
+ vec![
+ ("anthropic".to_string(), "claude-opus-5".to_string()),
+ ("anthropic".to_string(), "claude-sonnet-5".to_string()),
+ ]
+ );
+ }
+
+ fn cfg(provider: &str, base_url: Option<&str>, models: &[&str]) -> ProviderConfig {
+ ProviderConfig {
+ provider: provider.into(),
+ base_url: base_url.map(String::from),
+ models: models.iter().map(|m| m.to_string()).collect(),
+ ..Default::default()
+ }
+ }
+
+ fn two_provider_store() -> HashMap<String, ProviderConfig> {
+ let mut c = HashMap::new();
+ c.insert(
+ "llamacpp".into(),
+ cfg("llamacpp", None, &["gemma-4-E2B-it-IQ4_XS", "shared-id"]),
+ );
+ c.insert(
+ "anthropic".into(),
+ cfg(
+ "anthropic",
+ Some("https://api.anthropic.com/v1"),
+ &["claude-sonnet-5", "shared-id"],
+ ),
+ );
+ c
+ }
+
+ #[test]
+ fn local_only_model_is_reported_with_its_provider() {
+ assert_eq!(
+ unreachable_local_provider(&two_provider_store(), "gemma-4-E2B-it-IQ4_XS"),
+ Some("llamacpp".to_string())
+ );
+ }
+
+ #[test]
+ fn remote_model_is_not_flagged() {
+ assert_eq!(
+ unreachable_local_provider(&two_provider_store(), "claude-sonnet-5"),
+ None
+ );
+ }
+
+ #[test]
+ fn model_offered_by_both_local_and_remote_is_not_flagged() {
+ // A reachable provider also serves it, so the run can proceed.
+ assert_eq!(
+ unreachable_local_provider(&two_provider_store(), "shared-id"),
+ None
+ );
+ }
+
+ #[test]
+ fn unknown_model_is_not_flagged() {
+ // Provider `models` lists are often incomplete (custom deployments), so
+ // an id nobody claims must fall through to normal upstream resolution
+ // rather than being rejected here.
+ assert_eq!(
+ unreachable_local_provider(&two_provider_store(), "some-custom-model"),
+ None
+ );
+ }
+
+ #[test]
+ fn provider_prefixed_local_model_is_flagged() {
+ assert_eq!(
+ unreachable_local_provider(&two_provider_store(), "llamacpp/whatever"),
+ Some("llamacpp".to_string())
+ );
+ }
+
#[test]
fn no_override_is_noop() {
let mut configs = parse_provider_store(STORE);
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index ad09fc71b..b537ae8ab 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -473,6 +473,7 @@ enum SnapshotJob {
type SnapshotInputs = (PathBuf, Option<String>, String, String, Vec<PathBuf>);
impl App {
+ #[allow(clippy::too_many_arguments)]
fn new(
model: String,
max_turns: u32,
@@ -2243,29 +2244,12 @@ 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.
+/// Await the background MCP-connect task once, returning the connected server
+/// names (empty if none / on task failure).
///
/// 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}")),
- }
-}
-
-/// Await the background MCP-connect task once, returning the connected server
-/// names (empty if none / on task failure). Same cancel-safe borrow as
-/// `await_router`: the slot is cleared only on completion.
async fn await_mcp(task: &mut Option<tokio::task::JoinHandle<Vec<String>>>) -> Vec<String> {
let joined = match task.as_mut() {
Some(h) => h.await,
@@ -2294,7 +2278,7 @@ fn spawn_snapshot(
}
/// Await the in-flight snapshot task once, clearing the slot. Same cancel-safe
-/// borrow as `await_router`; pends forever when idle.
+/// borrow as `await_mcp`; pends forever when idle.
async fn await_snapshot(
task: &mut Option<tokio::task::JoinHandle<Result<String, String>>>,
) -> Result<String, String> {
@@ -2325,7 +2309,6 @@ pub async fn run(
context_window,
reserve_tokens,
max_tokens,
- router_task,
mcp_servers,
mcp_task,
} = session;
@@ -2359,7 +2342,6 @@ pub async fn run(
&permission_requests,
&mut app,
initial_task,
- router_task,
mcp_task,
&mcp_servers,
)
@@ -2383,7 +2365,6 @@ async fn chat_loop<B: Backend>(
registry: &PermissionRegistry,
app: &mut App,
initial_task: Option<String>,
- mut router_task: Option<tokio::task::JoinHandle<Result<(), String>>>,
mut mcp_task: Option<tokio::task::JoinHandle<Vec<String>>>,
mcp_servers: &crate::core::state::SharedMcpServers,
) -> Result<(), String> {
@@ -2393,9 +2374,8 @@ async fn chat_loop<B: Backend>(
// before this loop starts, so both start in sync.
let mut mouse_capture_active = true;
- // A local model and active MCP servers load in the background; gate the first
- // run on both so the model's tools (collected once per run) are ready.
- let mut router_ready = router_task.is_none();
+ // Active MCP servers connect in the background; gate the first run on them
+ // so the model's tools (collected once per run) are ready.
let mut mcp_ready = mcp_task.is_none();
let mut loading_noted = false;
@@ -2430,22 +2410,19 @@ async fn chat_loop<B: Backend>(
app.run_goal_evaluation().await;
}
- // Kick off a queued run once the previous one has cleared, the local
- // model (if any) is loaded, and the base snapshot (if any) is captured.
- // `submit_user` already flipped status to Running and reset the counter.
+ // Kick off a queued run once the previous one has cleared, the MCP
+ // servers (if any) are connected, and the base snapshot (if any) is
+ // captured. `submit_user` already flipped status to Running and reset
+ // the counter.
if app.want_start && current.is_none() {
let base_ready = app.repo_root.is_none() || app.base_snapshot.is_some();
- if router_ready && mcp_ready && base_ready {
+ if mcp_ready && base_ready {
app.want_start = false;
current = Some(spawn_run(args, app.body()));
- } else if !loading_noted && (!router_ready || !mcp_ready) {
- // The base snapshot gates silently; only model/MCP loads note.
+ } else if !loading_noted && !mcp_ready {
+ // The base snapshot gates silently; only the MCP connect notes.
loading_noted = true;
- app.note(if !router_ready {
- "loading local model..."
- } else {
- "connecting MCP servers..."
- });
+ app.note("connecting MCP servers...");
}
}
@@ -2484,13 +2461,6 @@ 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);
- }
- }
connected = await_mcp(&mut mcp_task) => {
mcp_ready = true;
match connected.as_slice() {
@@ -3345,12 +3315,14 @@ fn open_thread_picker(app: &mut App) {
}
}
-/// Open the `/model` selector listing `provider / model` pairs from the desktop
-/// store, with the current model pre-highlighted.
+/// Open the `/model` selector listing the `provider / model` pairs this build
+/// can actually run, with the current model pre-highlighted.
fn open_model_picker(app: &mut App) {
- let pairs = super::providers::list_provider_models();
+ let pairs = super::providers::list_provider_models(Some(&app.project_root));
if pairs.is_empty() {
- return app.note("no models available (configure a provider in the desktop app)");
+ return app.note(
+ "no models available (add a provider with `jan config set`, or configure one in the desktop app)",
+ );
}
let selected = pairs.iter().position(|(_, m)| *m == app.model).unwrap_or(0);
let items = pairs
diff --git a/src-tauri/src/core/mcp/helpers.rs b/src-tauri/src/core/mcp/helpers.rs
index 7bfd77920..b0bcbdf3b 100644
--- a/src-tauri/src/core/mcp/helpers.rs
+++ b/src-tauri/src/core/mcp/helpers.rs
@@ -9,7 +9,6 @@ use rmcp::{
use serde_json::Value;
use std::{collections::HashMap, env, process::Stdio, sync::Arc, time::Duration};
use tauri::{AppHandle, Emitter, Manager, Runtime, State};
-use tauri_plugin_http::reqwest;
use tokio::{
io::AsyncReadExt,
process::Command,
@@ -19,7 +18,7 @@ use tokio::{
use crate::core::{
app::commands::get_jan_data_folder_path,
- mcp::models::{McpServerConfig, McpSettings},
+ mcp::models::{extract_active_status, extract_command_args, McpSettings},
mcp::progress::JanClientHandler,
state::{AppState, RunningMcpService, SharedMcpServers},
};
@@ -846,43 +845,6 @@ fn emit_mcp_update_event<R: Runtime>(app: &AppHandle<R>, name: &str) {
}
}
-pub fn extract_command_args(config: &Value) -> Option<McpServerConfig> {
- let obj = config.as_object()?;
- let command = obj.get("command")?.as_str()?.to_string();
- let args = obj.get("args")?.as_array()?.clone();
- let url = obj.get("url").and_then(|u| u.as_str()).map(String::from);
- let transport_type = obj.get("type").and_then(|t| t.as_str()).map(String::from);
- let timeout = obj
- .get("timeout")
- .and_then(|t| t.as_u64())
- .map(Duration::from_secs);
- let headers = obj
- .get("headers")
- .unwrap_or(&Value::Object(serde_json::Map::new()))
- .as_object()?
- .clone();
- let envs = obj
- .get("env")
- .unwrap_or(&Value::Object(serde_json::Map::new()))
- .as_object()?
- .clone();
- Some(McpServerConfig {
- timeout,
- transport_type,
- url,
- command,
- args,
- envs,
- headers,
- })
-}
-
-pub fn extract_active_status(config: &Value) -> Option<bool> {
- let obj = config.as_object()?;
- let active = obj.get("active")?.as_bool()?;
- Some(active)
-}
-
/// Restart only servers that were previously active (like cortex restart behavior)
pub async fn restart_active_mcp_servers<R: Runtime>(
app: &AppHandle<R>,
diff --git a/src-tauri/src/core/mcp/mod.rs b/src-tauri/src/core/mcp/mod.rs
index 1cbd96886..0fd6438e7 100644
--- a/src-tauri/src/core/mcp/mod.rs
+++ b/src-tauri/src/core/mcp/mod.rs
@@ -1,9 +1,16 @@
+// Tauri command surface + the AppHandle-driven server lifecycle are
+// desktop-only; the CLI drives MCP through `core::cli::mcp`.
+#[cfg(not(feature = "cli"))]
pub mod commands;
pub mod constants;
+#[cfg(not(feature = "cli"))]
pub mod helpers;
+#[cfg(not(feature = "cli"))]
pub mod lockfile;
pub mod models;
+#[cfg(not(feature = "cli"))]
pub mod progress;
#[cfg(test)]
+#[cfg(not(feature = "cli"))]
mod tests;
diff --git a/src-tauri/src/core/mcp/models.rs b/src-tauri/src/core/mcp/models.rs
index 5b12bed96..2326b2b2c 100644
--- a/src-tauri/src/core/mcp/models.rs
+++ b/src-tauri/src/core/mcp/models.rs
@@ -15,6 +15,44 @@ pub struct McpServerConfig {
pub headers: serde_json::Map<String, Value>,
}
+/// Parse a raw `mcp_config.json` server entry into typed connection params.
+pub fn extract_command_args(config: &Value) -> Option<McpServerConfig> {
+ let obj = config.as_object()?;
+ let command = obj.get("command")?.as_str()?.to_string();
+ let args = obj.get("args")?.as_array()?.clone();
+ let url = obj.get("url").and_then(|u| u.as_str()).map(String::from);
+ let transport_type = obj.get("type").and_then(|t| t.as_str()).map(String::from);
+ let timeout = obj
+ .get("timeout")
+ .and_then(|t| t.as_u64())
+ .map(Duration::from_secs);
+ let headers = obj
+ .get("headers")
+ .unwrap_or(&Value::Object(serde_json::Map::new()))
+ .as_object()?
+ .clone();
+ let envs = obj
+ .get("env")
+ .unwrap_or(&Value::Object(serde_json::Map::new()))
+ .as_object()?
+ .clone();
+ Some(McpServerConfig {
+ timeout,
+ transport_type,
+ url,
+ command,
+ args,
+ envs,
+ headers,
+ })
+}
+
+pub fn extract_active_status(config: &Value) -> Option<bool> {
+ let obj = config.as_object()?;
+ let active = obj.get("active")?.as_bool()?;
+ Some(active)
+}
+
fn default_tool_call_timeout_seconds() -> u64 {
super::constants::DEFAULT_MCP_TOOL_CALL_TIMEOUT_SECS
}
@@ -108,3 +146,110 @@ pub struct ServerSummary {
pub capabilities: Vec<String>,
pub description: String,
}
+
+#[cfg(test)]
+mod tests {
+ use super::{extract_active_status, extract_command_args};
+ use std::time::Duration;
+
+ #[test]
+ fn test_extract_command_args_minimal_config() {
+ let cfg = serde_json::json!({
+ "command": "npx",
+ "args": ["-y", "server"]
+ });
+ let parsed = extract_command_args(&cfg).expect("should parse");
+ assert_eq!(parsed.command, "npx");
+ assert_eq!(parsed.args.len(), 2);
+ assert_eq!(parsed.args[0], "-y");
+ assert!(parsed.url.is_none());
+ assert!(parsed.transport_type.is_none());
+ assert!(parsed.timeout.is_none());
+ assert!(parsed.envs.is_empty());
+ assert!(parsed.headers.is_empty());
+ }
+
+ #[test]
+ fn test_extract_command_args_full_config() {
+ let cfg = serde_json::json!({
+ "command": "",
+ "args": [],
+ "type": "http",
+ "url": "https://mcp.example.com/mcp",
+ "timeout": 45,
+ "env": {"API_KEY": "abc", "DEBUG": "1"},
+ "headers": {"Authorization": "Bearer xyz"}
+ });
+ let parsed = extract_command_args(&cfg).expect("should parse");
+ assert_eq!(parsed.command, "");
+ assert_eq!(parsed.transport_type.as_deref(), Some("http"));
+ assert_eq!(parsed.url.as_deref(), Some("https://mcp.example.com/mcp"));
+ assert_eq!(parsed.timeout, Some(Duration::from_secs(45)));
+ assert_eq!(
+ parsed.envs.get("API_KEY").and_then(|v| v.as_str()),
+ Some("abc")
+ );
+ assert_eq!(parsed.envs.get("DEBUG").and_then(|v| v.as_str()), Some("1"));
+ assert_eq!(
+ parsed.headers.get("Authorization").and_then(|v| v.as_str()),
+ Some("Bearer xyz")
+ );
+ }
+
+ #[test]
+ fn test_extract_command_args_returns_none_when_required_fields_missing() {
+ // Missing command
+ let cfg = serde_json::json!({"args": []});
+ assert!(extract_command_args(&cfg).is_none());
+ // Missing args
+ let cfg = serde_json::json!({"command": "npx"});
+ assert!(extract_command_args(&cfg).is_none());
+ // Not an object
+ let cfg = serde_json::json!(["a", "b"]);
+ assert!(extract_command_args(&cfg).is_none());
+ // command not a string
+ let cfg = serde_json::json!({"command": 123, "args": []});
+ assert!(extract_command_args(&cfg).is_none());
+ // args not an array
+ let cfg = serde_json::json!({"command": "npx", "args": "oops"});
+ assert!(extract_command_args(&cfg).is_none());
+ }
+
+ #[test]
+ fn test_extract_command_args_parses_default_mcp_config_servers() {
+ use crate::core::mcp::constants::DEFAULT_MCP_CONFIG;
+ let value: serde_json::Value = serde_json::from_str(DEFAULT_MCP_CONFIG).unwrap();
+ for (name, cfg) in value["mcpServers"].as_object().unwrap() {
+ let parsed = extract_command_args(cfg)
+ .unwrap_or_else(|| panic!("default config server '{name}' should parse"));
+ // command may be empty for HTTP transports
+ if name == "exa" {
+ assert_eq!(parsed.transport_type.as_deref(), Some("http"));
+ assert!(parsed.url.is_some());
+ } else {
+ assert!(!parsed.command.is_empty(), "{name} should have a command");
+ }
+ }
+ }
+
+ #[test]
+ fn test_extract_active_status_variants() {
+ assert_eq!(
+ extract_active_status(&serde_json::json!({"active": true})),
+ Some(true)
+ );
+ assert_eq!(
+ extract_active_status(&serde_json::json!({"active": false})),
+ Some(false)
+ );
+ // Missing
+ assert_eq!(extract_active_status(&serde_json::json!({})), None);
+ // Wrong type
+ assert_eq!(
+ extract_active_status(&serde_json::json!({"active": "yes"})),
+ None
+ );
+ // Not an object
+ assert_eq!(extract_active_status(&serde_json::json!(true)), None);
+ }
+}
diff --git a/src-tauri/src/core/mcp/tests.rs b/src-tauri/src/core/mcp/tests.rs
index f683dbcde..c1f72d5ea 100644
--- a/src-tauri/src/core/mcp/tests.rs
+++ b/src-tauri/src/core/mcp/tests.rs
@@ -762,116 +762,6 @@ fn test_server_summary_round_trip() {
assert_eq!(parsed.description, "Read files");
}
-// ============================================================================
-// helpers.rs pure-function tests: extract_command_args / extract_active_status
-// ============================================================================
-
-#[test]
-fn test_extract_command_args_minimal_config() {
- use super::helpers::extract_command_args;
- let cfg = serde_json::json!({
- "command": "npx",
- "args": ["-y", "server"]
- });
- let parsed = extract_command_args(&cfg).expect("should parse");
- assert_eq!(parsed.command, "npx");
- assert_eq!(parsed.args.len(), 2);
- assert_eq!(parsed.args[0], "-y");
- assert!(parsed.url.is_none());
- assert!(parsed.transport_type.is_none());
- assert!(parsed.timeout.is_none());
- assert!(parsed.envs.is_empty());
- assert!(parsed.headers.is_empty());
-}
-
-#[test]
-fn test_extract_command_args_full_config() {
- use super::helpers::extract_command_args;
- let cfg = serde_json::json!({
- "command": "",
- "args": [],
- "type": "http",
- "url": "https://mcp.example.com/mcp",
- "timeout": 45,
- "env": {"API_KEY": "abc", "DEBUG": "1"},
- "headers": {"Authorization": "Bearer xyz"}
- });
- let parsed = extract_command_args(&cfg).expect("should parse");
- assert_eq!(parsed.command, "");
- assert_eq!(parsed.transport_type.as_deref(), Some("http"));
- assert_eq!(parsed.url.as_deref(), Some("https://mcp.example.com/mcp"));
- assert_eq!(parsed.timeout, Some(Duration::from_secs(45)));
- assert_eq!(
- parsed.envs.get("API_KEY").and_then(|v| v.as_str()),
- Some("abc")
- );
- assert_eq!(parsed.envs.get("DEBUG").and_then(|v| v.as_str()), Some("1"));
- assert_eq!(
- parsed.headers.get("Authorization").and_then(|v| v.as_str()),
- Some("Bearer xyz")
- );
-}
-
-#[test]
-fn test_extract_command_args_returns_none_when_required_fields_missing() {
- use super::helpers::extract_command_args;
- // Missing command
- let cfg = serde_json::json!({"args": []});
- assert!(extract_command_args(&cfg).is_none());
- // Missing args
- let cfg = serde_json::json!({"command": "npx"});
- assert!(extract_command_args(&cfg).is_none());
- // Not an object
- let cfg = serde_json::json!(["a", "b"]);
- assert!(extract_command_args(&cfg).is_none());
- // command not a string
- let cfg = serde_json::json!({"command": 123, "args": []});
- assert!(extract_command_args(&cfg).is_none());
- // args not an array
- let cfg = serde_json::json!({"command": "npx", "args": "oops"});
- assert!(extract_command_args(&cfg).is_none());
-}
-
-#[test]
-fn test_extract_command_args_parses_default_mcp_config_servers() {
- use super::constants::DEFAULT_MCP_CONFIG;
- use super::helpers::extract_command_args;
- let value: serde_json::Value = serde_json::from_str(DEFAULT_MCP_CONFIG).unwrap();
- for (name, cfg) in value["mcpServers"].as_object().unwrap() {
- let parsed = extract_command_args(cfg)
- .unwrap_or_else(|| panic!("default config server '{name}' should parse"));
- // command may be empty for HTTP transports
- if name == "exa" {
- assert_eq!(parsed.transport_type.as_deref(), Some("http"));
- assert!(parsed.url.is_some());
- } else {
- assert!(!parsed.command.is_empty(), "{name} should have a command");
- }
- }
-}
-
-#[test]
-fn test_extract_active_status_variants() {
- use super::helpers::extract_active_status;
- assert_eq!(
- extract_active_status(&serde_json::json!({"active": true})),
- Some(true)
- );
- assert_eq!(
- extract_active_status(&serde_json::json!({"active": false})),
- Some(false)
- );
- // Missing
- assert_eq!(extract_active_status(&serde_json::json!({})), None);
- // Wrong type
- assert_eq!(
- extract_active_status(&serde_json::json!({"active": "yes"})),
- None
- );
- // Not an object
- assert_eq!(extract_active_status(&serde_json::json!(true)), None);
-}
-
// ============================================================================
// lockfile.rs Tests
// ============================================================================
diff --git a/src-tauri/src/core/mod.rs b/src-tauri/src/core/mod.rs
index 88cd8c19b..2139ae94a 100644
--- a/src-tauri/src/core/mod.rs
+++ b/src-tauri/src/core/mod.rs
@@ -2,17 +2,23 @@ pub mod agent;
pub mod app;
#[cfg(feature = "cli")]
pub mod cli;
+// Download manager, native file dialogs/IO commands, and the system/tray
+// command surface are desktop-only; the CLI uses std::fs and its own tools.
+#[cfg(not(feature = "cli"))]
pub mod downloads;
+#[cfg(not(feature = "cli"))]
pub mod filesystem;
pub mod mcp;
+pub mod openai_schema;
pub mod server;
// Desktop-only app setup (tray, theme, window wiring); pulls in Tauri GUI types
// (Wry/AppHandle) the headless `jan` CLI build does not link.
#[cfg(not(feature = "cli"))]
pub mod setup;
pub mod state;
+#[cfg(not(feature = "cli"))]
pub mod system;
pub mod threads;
-#[cfg(not(any(target_os = "android", target_os = "ios")))]
+#[cfg(all(not(any(target_os = "android", target_os = "ios")), not(feature = "cli")))]
pub mod updater;
diff --git a/src-tauri/src/core/openai_schema.rs b/src-tauri/src/core/openai_schema.rs
new file mode 100644
index 000000000..b3ef4fbfb
--- /dev/null
+++ b/src-tauri/src/core/openai_schema.rs
@@ -0,0 +1,173 @@
+//! OpenAI wire-format helpers shared by the proxy server and the agent's
+//! upstream layer: tool-schema normalization and key-rotation status checks.
+//! Tauri-free so the headless CLI build can use it without the proxy.
+
+use reqwest::StatusCode;
+
+const SCHEMA_PRIMITIVE_TYPES: &[&str] = &[
+ "string", "number", "integer", "boolean", "null", "array", "object",
+];
+
+// llama.cpp's json-schema-to-grammar emits PCRE `\d` for these formats,
+// which GBNF rejects; the failed grammar silently disables tool-call JSON.
+const LLAMACPP_BROKEN_STRING_FORMATS: &[&str] = &["date", "time", "date-time"];
+
+fn pattern_has_pcre_shorthand(pattern: &str) -> bool {
+ let bytes = pattern.as_bytes();
+ let mut i = 0;
+ while i + 1 < bytes.len() {
+ if bytes[i] == b'\\' && matches!(bytes[i + 1], b'd' | b'D' | b'w' | b'W' | b's' | b'S') {
+ return true;
+ }
+ i += 1;
+ }
+ false
+}
+
+/// If `value` is a bare string naming a JSON-schema primitive type (e.g.
+/// `"string"`), expand it to `{ "type": <that> }`. Some tool generators emit
+/// shorthand like `{ "properties": { "foo": "string" } }`; llama.cpp's
+/// json-schema-to-grammar rejects that with `Unrecognized schema: "string"`.
+fn coerce_schema_node(value: &mut serde_json::Value) {
+ if let serde_json::Value::String(s) = value {
+ if SCHEMA_PRIMITIVE_TYPES.contains(&s.as_str()) {
+ let mut obj = serde_json::Map::new();
+ obj.insert(
+ "type".to_string(),
+ serde_json::Value::String(std::mem::take(s)),
+ );
+ *value = serde_json::Value::Object(obj);
+ }
+ }
+ normalize_openai_tool_parameters_schema(value);
+}
+
+/// Some OpenAI tool schema generators (and some MCP servers) may emit schemas where
+/// a property schema only contains `description` but omits `type`, or where a
+/// schema-node slot holds a bare type-name string instead of a sub-schema object.
+///
+/// A strict JSON schema converter inside the upstream server rejects those schemas.
+/// To be robust, we default `type` to `"string"` for description-only leaf schemas
+/// and expand bare-string sub-schemas to `{ "type": <name> }`.
+/// Keep this behavior aligned with `normalizeToolInputSchema` in the frontend.
+pub(crate) fn normalize_openai_tool_parameters_schema(schema: &mut serde_json::Value) {
+ match schema {
+ serde_json::Value::Object(map) => {
+ let has_description = map.contains_key("description");
+ let has_type = map.contains_key("type");
+ let is_object_type = map.get("type").and_then(|v| v.as_str()) == Some("object");
+ let has_nested_schema_keywords = map.contains_key("properties")
+ || map.contains_key("items")
+ || map.contains_key("anyOf")
+ || map.contains_key("oneOf")
+ || map.contains_key("allOf")
+ || map.contains_key("$ref");
+
+ if is_object_type && !map.contains_key("properties") {
+ map.insert(
+ "properties".to_string(),
+ serde_json::Value::Object(serde_json::Map::new()),
+ );
+ }
+
+ // Only patch leaf nodes (description without `type` AND without nested schema keywords).
+ if has_description && !has_type && !has_nested_schema_keywords {
+ map.insert(
+ "type".to_string(),
+ serde_json::Value::String("string".to_string()),
+ );
+ }
+
+ let drop_format = map
+ .get("format")
+ .and_then(|v| v.as_str())
+ .map(|f| LLAMACPP_BROKEN_STRING_FORMATS.contains(&f))
+ .unwrap_or(false);
+ if drop_format {
+ map.remove("format");
+ }
+
+ let drop_pattern = map
+ .get("pattern")
+ .and_then(|v| v.as_str())
+ .map(pattern_has_pcre_shorthand)
+ .unwrap_or(false);
+ if drop_pattern {
+ map.remove("pattern");
+ }
+
+ // Recurse, with shorthand expansion for keys whose direct children
+ // are schema nodes.
+ for (key, v) in map.iter_mut() {
+ match key.as_str() {
+ "properties" | "patternProperties" | "definitions" | "$defs" => {
+ if let serde_json::Value::Object(inner) = v {
+ for (_, child) in inner.iter_mut() {
+ coerce_schema_node(child);
+ }
+ } else {
+ normalize_openai_tool_parameters_schema(v);
+ }
+ }
+ "anyOf" | "oneOf" | "allOf" | "prefixItems" => {
+ if let serde_json::Value::Array(arr) = v {
+ for child in arr.iter_mut() {
+ coerce_schema_node(child);
+ }
+ } else {
+ normalize_openai_tool_parameters_schema(v);
+ }
+ }
+ "items" => match v {
+ serde_json::Value::Array(arr) => {
+ for child in arr.iter_mut() {
+ coerce_schema_node(child);
+ }
+ }
+ _ => coerce_schema_node(v),
+ },
+ _ => normalize_openai_tool_parameters_schema(v),
+ }
+ }
+ }
+ serde_json::Value::Array(arr) => {
+ for v in arr.iter_mut() {
+ normalize_openai_tool_parameters_schema(v);
+ }
+ }
+ _ => {}
+ }
+}
+
+#[cfg(any(not(feature = "cli"), test))]
+pub(crate) fn normalize_openai_tools_in_chat_body(body: &mut serde_json::Value) {
+ let tools = match body.get_mut("tools") {
+ Some(t) => t,
+ None => return,
+ };
+
+ let tools_arr = match tools.as_array_mut() {
+ Some(a) => a,
+ None => return,
+ };
+
+ for tool in tools_arr.iter_mut() {
+ let function = match tool.get_mut("function") {
+ Some(f) => f,
+ None => continue,
+ };
+ let parameters = match function.get_mut("parameters") {
+ Some(p) => p,
+ None => continue,
+ };
+
+ normalize_openai_tool_parameters_schema(parameters);
+ }
+}
+
+pub(crate) fn http_status_indicates_api_key_retry(status: StatusCode) -> bool {
+ matches!(
+ status,
+ StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN | StatusCode::TOO_MANY_REQUESTS
+ )
+}
diff --git a/src-tauri/src/core/server/mod.rs b/src-tauri/src/core/server/mod.rs
index 46f448c9b..8db09125d 100644
--- a/src-tauri/src/core/server/mod.rs
+++ b/src-tauri/src/core/server/mod.rs
@@ -1,18 +1,25 @@
+// The proxy server and its Tauri command surface are desktop-only; the `jan`
+// CLI is a headless agent client with no local API server.
+#[cfg(not(feature = "cli"))]
pub mod commands;
+#[cfg(not(feature = "cli"))]
pub mod converters;
pub mod provider_secrets;
+#[cfg(not(feature = "cli"))]
pub mod proxy;
+#[cfg(not(feature = "cli"))]
pub mod remote_provider_commands;
#[cfg(test)]
+#[cfg(not(feature = "cli"))]
pub mod tests;
// MLX session types used by the proxy. MLX is macOS-only, so on other platforms
// we expose a field-compatible stub: the session map is always empty there, so
// the proxy's MLX branches are dead but still compile.
-#[cfg(target_os = "macos")]
+#[cfg(all(target_os = "macos", not(feature = "cli")))]
pub use tauri_plugin_mlx::state::{MlxBackendSession, SessionInfo};
-#[cfg(not(target_os = "macos"))]
+#[cfg(all(not(target_os = "macos"), not(feature = "cli")))]
mod mlx_stub {
#[derive(Debug, Clone)]
pub struct SessionInfo {
@@ -29,5 +36,5 @@ mod mlx_stub {
}
}
-#[cfg(not(target_os = "macos"))]
+#[cfg(all(not(target_os = "macos"), not(feature = "cli")))]
pub use mlx_stub::{MlxBackendSession, SessionInfo};
diff --git a/src-tauri/src/core/server/provider_secrets.rs b/src-tauri/src/core/server/provider_secrets.rs
index cb078e2dc..3439f5275 100644
--- a/src-tauri/src/core/server/provider_secrets.rs
+++ b/src-tauri/src/core/server/provider_secrets.rs
@@ -217,6 +217,7 @@ pub fn load_provider_keys(provider: &str) -> Vec<String> {
/// Store a single generic secret (e.g. the Hugging Face token) under `key`.
/// Empty value deletes it. Backed by the same keyring/encrypted-file store.
+#[cfg(not(feature = "cli"))]
#[tauri::command]
pub async fn set_secret(key: String, value: String) -> Result<(), String> {
// Keyring/file access is blocking; keep it off the main (UI) thread.
@@ -232,6 +233,7 @@ pub async fn set_secret(key: String, value: String) -> Result<(), String> {
}
/// Read a single generic secret stored via `set_secret`. None when absent.
+#[cfg(not(feature = "cli"))]
#[tauri::command]
pub async fn get_secret(key: String) -> Option<String> {
tauri::async_runtime::spawn_blocking(move || load_provider_keys(&key).into_iter().next())
diff --git a/src-tauri/src/core/server/proxy.rs b/src-tauri/src/core/server/proxy.rs
index da899dc63..9ee7df86b 100644
--- a/src-tauri/src/core/server/proxy.rs
+++ b/src-tauri/src/core/server/proxy.rs
@@ -32,6 +32,9 @@ pub(crate) use crate::core::agent::upstream::{
execute_mcp_tool_calls, extract_choice_message, extract_tool_calls, load_assistant_config,
parse_openai_messages, resolve_upstream_for_model, set_system_prompt,
};
+use crate::core::openai_schema::{
+ http_status_indicates_api_key_retry, normalize_openai_tools_in_chat_body,
+};
type ResBody = BoxBody<Bytes, Infallible>;
@@ -62,173 +65,6 @@ fn body_channel() -> (BodySender, ResBody) {
(BodySender(tx), body)
}
-const SCHEMA_PRIMITIVE_TYPES: &[&str] = &[
- "string", "number", "integer", "boolean", "null", "array", "object",
-];
-
-// llama.cpp's json-schema-to-grammar emits PCRE `\d` for these formats,
-// which GBNF rejects; the failed grammar silently disables tool-call JSON.
-const LLAMACPP_BROKEN_STRING_FORMATS: &[&str] = &["date", "time", "date-time"];
-
-fn pattern_has_pcre_shorthand(pattern: &str) -> bool {
- let bytes = pattern.as_bytes();
- let mut i = 0;
- while i + 1 < bytes.len() {
- if bytes[i] == b'\\' && matches!(bytes[i + 1], b'd' | b'D' | b'w' | b'W' | b's' | b'S') {
- return true;
- }
- i += 1;
- }
- false
-}
-
-/// If `value` is a bare string naming a JSON-schema primitive type (e.g.
-/// `"string"`), expand it to `{ "type": <that> }`. Some tool generators emit
-/// shorthand like `{ "properties": { "foo": "string" } }`; llama.cpp's
-/// json-schema-to-grammar rejects that with `Unrecognized schema: "string"`.
-fn coerce_schema_node(value: &mut serde_json::Value) {
- if let serde_json::Value::String(s) = value {
- if SCHEMA_PRIMITIVE_TYPES.contains(&s.as_str()) {
- let mut obj = serde_json::Map::new();
- obj.insert(
- "type".to_string(),
- serde_json::Value::String(std::mem::take(s)),
- );
- *value = serde_json::Value::Object(obj);
- }
- }
- normalize_openai_tool_parameters_schema(value);
-}
-
-/// Some OpenAI tool schema generators (and some MCP servers) may emit schemas where
-/// a property schema only contains `description` but omits `type`, or where a
-/// schema-node slot holds a bare type-name string instead of a sub-schema object.
-///
-/// A strict JSON schema converter inside the upstream server rejects those schemas.
-/// To be robust, we default `type` to `"string"` for description-only leaf schemas
-/// and expand bare-string sub-schemas to `{ "type": <name> }`.
-/// Keep this behavior aligned with `normalizeToolInputSchema` in the frontend.
-pub(crate) fn normalize_openai_tool_parameters_schema(schema: &mut serde_json::Value) {
- match schema {
- serde_json::Value::Object(map) => {
- let has_description = map.contains_key("description");
- let has_type = map.contains_key("type");
- let is_object_type = map.get("type").and_then(|v| v.as_str()) == Some("object");
- let has_nested_schema_keywords = map.contains_key("properties")
- || map.contains_key("items")
- || map.contains_key("anyOf")
- || map.contains_key("oneOf")
- || map.contains_key("allOf")
- || map.contains_key("$ref");
-
- if is_object_type && !map.contains_key("properties") {
- map.insert(
- "properties".to_string(),
- serde_json::Value::Object(serde_json::Map::new()),
- );
- }
-
- // Only patch leaf nodes (description without `type` AND without nested schema keywords).
- if has_description && !has_type && !has_nested_schema_keywords {
- map.insert(
- "type".to_string(),
- serde_json::Value::String("string".to_string()),
- );
- }
-
- let drop_format = map
- .get("format")
- .and_then(|v| v.as_str())
- .map(|f| LLAMACPP_BROKEN_STRING_FORMATS.contains(&f))
- .unwrap_or(false);
- if drop_format {
- map.remove("format");
- }
-
- let drop_pattern = map
- .get("pattern")
- .and_then(|v| v.as_str())
- .map(pattern_has_pcre_shorthand)
- .unwrap_or(false);
- if drop_pattern {
- map.remove("pattern");
- }
-
- // Recurse, with shorthand expansion for keys whose direct children
- // are schema nodes.
- for (key, v) in map.iter_mut() {
- match key.as_str() {
- "properties" | "patternProperties" | "definitions" | "$defs" => {
- if let serde_json::Value::Object(inner) = v {
- for (_, child) in inner.iter_mut() {
- coerce_schema_node(child);
- }
- } else {
- normalize_openai_tool_parameters_schema(v);
- }
- }
- "anyOf" | "oneOf" | "allOf" | "prefixItems" => {
- if let serde_json::Value::Array(arr) = v {
- for child in arr.iter_mut() {
- coerce_schema_node(child);
- }
- } else {
- normalize_openai_tool_parameters_schema(v);
- }
- }
- "items" => match v {
- serde_json::Value::Array(arr) => {
- for child in arr.iter_mut() {
- coerce_schema_node(child);
- }
- }
- _ => coerce_schema_node(v),
- },
- _ => normalize_openai_tool_parameters_schema(v),
- }
- }
- }
- serde_json::Value::Array(arr) => {
- for v in arr.iter_mut() {
- normalize_openai_tool_parameters_schema(v);
- }
- }
- _ => {}
- }
-}
-
-pub(crate) fn normalize_openai_tools_in_chat_body(body: &mut serde_json::Value) {
- let tools = match body.get_mut("tools") {
- Some(t) => t,
- None => return,
- };
-
- let tools_arr = match tools.as_array_mut() {
- Some(a) => a,
- None => return,
- };
-
- for tool in tools_arr.iter_mut() {
- let function = match tool.get_mut("function") {
- Some(f) => f,
- None => continue,
- };
- let parameters = match function.get_mut("parameters") {
- Some(p) => p,
- None => continue,
- };
-
- normalize_openai_tool_parameters_schema(parameters);
- }
-}
-
-pub(crate) fn http_status_indicates_api_key_retry(status: StatusCode) -> bool {
- matches!(
- status,
- StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN | StatusCode::TOO_MANY_REQUESTS
- )
-}
-
/// Transform Anthropic /messages API body to OpenAI /chat/completions body
pub(crate) fn transform_anthropic_to_openai(body: &serde_json::Value) -> Option<serde_json::Value> {
let model = body.get("model")?.as_str()?;
diff --git a/src-tauri/src/core/server/tests.rs b/src-tauri/src/core/server/tests.rs
index d73432908..90ee20dfa 100644
--- a/src-tauri/src/core/server/tests.rs
+++ b/src-tauri/src/core/server/tests.rs
@@ -308,7 +308,7 @@ mod server_tests {
}
});
- proxy::normalize_openai_tool_parameters_schema(&mut schema);
+ crate::core::openai_schema::normalize_openai_tool_parameters_schema(&mut schema);
assert_eq!(schema["properties"]["url"]["type"], json!("string"));
}
@@ -319,7 +319,7 @@ mod server_tests {
"type": "object"
});
- proxy::normalize_openai_tool_parameters_schema(&mut schema);
+ crate::core::openai_schema::normalize_openai_tool_parameters_schema(&mut schema);
assert_eq!(schema["properties"], json!({}));
}
@@ -349,7 +349,7 @@ mod server_tests {
}
});
- proxy::normalize_openai_tool_parameters_schema(&mut schema);
+ crate::core::openai_schema::normalize_openai_tool_parameters_schema(&mut schema);
assert_eq!(
schema["properties"]["payload"]["properties"]["title"]["type"],
@@ -382,7 +382,7 @@ mod server_tests {
}
});
- proxy::normalize_openai_tool_parameters_schema(&mut schema);
+ crate::core::openai_schema::normalize_openai_tool_parameters_schema(&mut schema);
assert_eq!(schema["properties"]["name"]["type"], json!("integer"));
assert!(schema["properties"]["container"].get("type").is_none());
@@ -402,7 +402,7 @@ mod server_tests {
}
});
- proxy::normalize_openai_tool_parameters_schema(&mut schema);
+ crate::core::openai_schema::normalize_openai_tool_parameters_schema(&mut schema);
assert_eq!(schema["properties"]["name"], json!({"type": "string"}));
assert_eq!(schema["properties"]["count"], json!({"type": "integer"}));
@@ -417,7 +417,7 @@ mod server_tests {
}
});
- proxy::normalize_openai_tool_parameters_schema(&mut schema);
+ crate::core::openai_schema::normalize_openai_tool_parameters_schema(&mut schema);
assert_eq!(
schema["properties"]["tags"]["items"],
@@ -434,7 +434,7 @@ mod server_tests {
}
});
- proxy::normalize_openai_tool_parameters_schema(&mut schema);
+ crate::core::openai_schema::normalize_openai_tool_parameters_schema(&mut schema);
assert_eq!(
schema["properties"]["value"]["anyOf"],
@@ -451,7 +451,7 @@ mod server_tests {
}
});
- proxy::normalize_openai_tool_parameters_schema(&mut schema);
+ crate::core::openai_schema::normalize_openai_tool_parameters_schema(&mut schema);
assert_eq!(
schema["properties"]["mode"]["enum"],
@@ -477,7 +477,7 @@ mod server_tests {
});
let original = schema.clone();
- proxy::normalize_openai_tool_parameters_schema(&mut schema);
+ crate::core::openai_schema::normalize_openai_tool_parameters_schema(&mut schema);
assert_eq!(schema, original);
}
@@ -500,7 +500,7 @@ mod server_tests {
}
});
- proxy::normalize_openai_tool_parameters_schema(&mut schema);
+ crate::core::openai_schema::normalize_openai_tool_parameters_schema(&mut schema);
assert_eq!(schema["properties"]["count"]["type"], json!("integer"));
assert_eq!(schema["properties"]["title"]["type"], json!("string"));
@@ -522,7 +522,7 @@ mod server_tests {
}
});
- proxy::normalize_openai_tool_parameters_schema(&mut schema);
+ crate::core::openai_schema::normalize_openai_tool_parameters_schema(&mut schema);
assert!(schema["properties"]["start"].get("format").is_none());
assert!(schema["properties"]["stop"].get("format").is_none());
@@ -540,7 +540,7 @@ mod server_tests {
}
});
- proxy::normalize_openai_tool_parameters_schema(&mut schema);
+ crate::core::openai_schema::normalize_openai_tool_parameters_schema(&mut schema);
assert_eq!(schema["properties"]["id"]["format"], json!("uuid"));
assert_eq!(schema["properties"]["url"]["format"], json!("uri"));
@@ -556,7 +556,7 @@ mod server_tests {
}
});
- proxy::normalize_openai_tool_parameters_schema(&mut schema);
+ crate::core::openai_schema::normalize_openai_tool_parameters_schema(&mut schema);
assert!(schema["properties"]["when"].get("pattern").is_none());
assert_eq!(schema["properties"]["alpha"]["pattern"], json!("^[A-Z]+$"));
@@ -572,7 +572,7 @@ mod server_tests {
}
});
- proxy::normalize_openai_tool_parameters_schema(&mut schema);
+ crate::core::openai_schema::normalize_openai_tool_parameters_schema(&mut schema);
assert!(schema["properties"]["until"].get("format").is_none());
assert_eq!(schema["properties"]["until"]["type"], json!("string"));
@@ -584,20 +584,20 @@ mod server_tests {
#[test]
fn http_status_indicates_api_key_retry_matrix() {
use hyper::StatusCode;
- assert!(proxy::http_status_indicates_api_key_retry(
+ assert!(crate::core::openai_schema::http_status_indicates_api_key_retry(
StatusCode::UNAUTHORIZED
));
- assert!(proxy::http_status_indicates_api_key_retry(
+ assert!(crate::core::openai_schema::http_status_indicates_api_key_retry(
StatusCode::FORBIDDEN
));
- assert!(proxy::http_status_indicates_api_key_retry(
+ assert!(crate::core::openai_schema::http_status_indicates_api_key_retry(
StatusCode::TOO_MANY_REQUESTS
));
- assert!(!proxy::http_status_indicates_api_key_retry(StatusCode::OK));
- assert!(!proxy::http_status_indicates_api_key_retry(
+ assert!(!crate::core::openai_schema::http_status_indicates_api_key_retry(StatusCode::OK));
+ assert!(!crate::core::openai_schema::http_status_indicates_api_key_retry(
StatusCode::BAD_REQUEST
));
- assert!(!proxy::http_status_indicates_api_key_retry(
+ assert!(!crate::core::openai_schema::http_status_indicates_api_key_retry(
StatusCode::INTERNAL_SERVER_ERROR
));
}
@@ -1022,7 +1022,7 @@ mod server_tests {
}
}]
});
- proxy::normalize_openai_tools_in_chat_body(&mut body);
+ crate::core::openai_schema::normalize_openai_tools_in_chat_body(&mut body);
assert_eq!(
body["tools"][0]["function"]["parameters"]["properties"]["url"]["type"],
json!("string")
@@ -1033,7 +1033,7 @@ mod server_tests {
fn normalize_openai_tools_in_chat_body_no_tools_is_noop() {
let mut body = json!({"messages": []});
let original = body.clone();
- proxy::normalize_openai_tools_in_chat_body(&mut body);
+ crate::core::openai_schema::normalize_openai_tools_in_chat_body(&mut body);
assert_eq!(body, original);
}
@@ -1139,7 +1139,7 @@ mod server_tests {
]
});
- proxy::normalize_openai_tool_parameters_schema(&mut schema);
+ crate::core::openai_schema::normalize_openai_tool_parameters_schema(&mut schema);
assert_eq!(schema["anyOf"][0]["properties"], json!({}));
assert_eq!(schema["anyOf"][1]["type"], json!("string"));
diff --git a/src-tauri/src/core/state.rs b/src-tauri/src/core/state.rs
index 4d3eac6fc..292fd3d11 100644
--- a/src-tauri/src/core/state.rs
+++ b/src-tauri/src/core/state.rs
@@ -1,17 +1,25 @@
-use std::{
- collections::{HashMap, HashSet},
- sync::Arc,
-};
+use std::collections::HashMap;
+#[cfg(not(feature = "cli"))]
+use std::collections::HashSet;
+use std::sync::Arc;
-use crate::core::{
- downloads::models::DownloadManagerState,
- mcp::models::{McpSettings, ToolWithServer},
- mcp::progress::JanClientHandler,
-};
+#[cfg(not(feature = "cli"))]
+use crate::core::downloads::models::DownloadManagerState;
+#[cfg(not(feature = "cli"))]
+use crate::core::mcp::models::{McpSettings, ToolWithServer};
+#[cfg(not(feature = "cli"))]
+use crate::core::mcp::progress::JanClientHandler;
+#[cfg(feature = "cli")]
+use rmcp::model::{CallToolRequestParam, CallToolResult, InitializeRequestParam, Tool};
+#[cfg(feature = "cli")]
+use rmcp::ServiceError;
use rmcp::{service::RunningService, RoleClient};
-use tokio::sync::{oneshot, Mutex, Notify};
+use tokio::sync::Mutex;
+#[cfg(not(feature = "cli"))]
+use tokio::sync::{oneshot, Notify};
/// Server handle type for managing the proxy server lifecycle
+#[cfg(not(feature = "cli"))]
pub type ServerHandle =
tokio::task::JoinHandle<Result<(), Box<dyn std::error::Error + Send + Sync>>>;
@@ -52,10 +60,45 @@ pub struct ProviderCustomHeader {
}
/// Every connection uses the same handler, so that progress notifications are
-/// observed at all -- rmcp drops them on the `()` handler.
+/// observed at all -- rmcp drops them on the `()` handler. Desktop-only: the
+/// handler emits through a Tauri `AppHandle`, which the CLI build doesn't have.
+#[cfg(not(feature = "cli"))]
pub type RunningMcpService = RunningService<RoleClient, JanClientHandler>;
+#[cfg(not(feature = "cli"))]
pub type SharedMcpServers = Arc<Mutex<HashMap<String, RunningMcpService>>>;
+/// CLI's MCP client has no progress-notification sink, so it can use either
+/// the plain handler or one seeded with an `initialize` response.
+#[cfg(feature = "cli")]
+pub enum RunningServiceEnum {
+ NoInit(RunningService<RoleClient, ()>),
+ WithInit(RunningService<RoleClient, InitializeRequestParam>),
+}
+#[cfg(feature = "cli")]
+pub type SharedMcpServers = Arc<Mutex<HashMap<String, RunningServiceEnum>>>;
+
+#[cfg(feature = "cli")]
+impl RunningServiceEnum {
+ pub async fn list_all_tools(&self) -> Result<Vec<Tool>, ServiceError> {
+ match self {
+ Self::NoInit(s) => s.list_all_tools().await,
+ Self::WithInit(s) => s.list_all_tools().await,
+ }
+ }
+ pub async fn call_tool(
+ &self,
+ params: CallToolRequestParam,
+ ) -> Result<CallToolResult, ServiceError> {
+ match self {
+ Self::NoInit(s) => s.call_tool(params).await,
+ Self::WithInit(s) => s.call_tool(params).await,
+ }
+ }
+}
+
+/// Shared desktop application state owned by Tauri. The CLI builds its
+/// subsystems (MCP map, provider configs) directly instead.
+#[cfg(not(feature = "cli"))]
pub struct AppState {
pub app_token: Option<String>,
pub mcp_servers: SharedMcpServers,
@@ -88,6 +131,7 @@ pub struct AppState {
pub mcp_last_known_tools: Arc<Mutex<HashMap<String, Vec<ToolWithServer>>>>,
}
+#[cfg(not(feature = "cli"))]
impl Default for AppState {
fn default() -> Self {
Self {
diff --git a/src-tauri/src/core/threads/mod.rs b/src-tauri/src/core/threads/mod.rs
index 094503b68..5575c9aff 100644
--- a/src-tauri/src/core/threads/mod.rs
+++ b/src-tauri/src/core/threads/mod.rs
@@ -10,6 +10,7 @@
- As a result, the messages.jsonl file for each thread is always consistent and never corrupted, even under concurrent access.
*/
+#[cfg(not(feature = "cli"))]
pub mod commands;
pub mod constants;
#[cfg(any(target_os = "android", target_os = "ios"))]
@@ -18,4 +19,5 @@ pub mod helpers;
pub mod utils;
#[cfg(test)]
+#[cfg(not(feature = "cli"))]
mod tests;
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 370d8f3e8..5496d1629 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -1,3 +1,14 @@
+// The headless `jan` CLI and the desktop app are mutually exclusive builds: the
+// `cli` feature gates off every Tauri-dependent module, so pairing it with the
+// Tauri stack leaves the desktop entry points without their subsystems. Note
+// that `--features cli` alone still implies `default` (and therefore
+// `desktop`); the CLI must be built with `--no-default-features`.
+#[cfg(all(feature = "cli", feature = "tauri-app"))]
+compile_error!(
+ "features `cli` and `tauri-app`/`desktop` are mutually exclusive; \
+ build the CLI with `cargo build --no-default-features --features cli --bin jan`"
+);
+
pub mod core;
#[cfg(not(feature = "cli"))]