Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(agent-rpc): check a model's name without resolving its credential
thinhlpg544c738007d1
diff --git a/src-tauri/src/core/agent/upstream.rs b/src-tauri/src/core/agent/upstream.rsindex b1b6a27c3..2a8e94ac2 100644--- a/src-tauri/src/core/agent/upstream.rs+++ b/src-tauri/src/core/agent/upstream.rs@@ -587,6 +587,63 @@ pub(crate) async fn resolve_upstream_for_model(provider_configs: Arc<Mutex<HashMap<String, ProviderConfig>>>,#[cfg(not(feature = "cli"))] llama_state: Arc<LlamacppState>,#[cfg(not(feature = "cli"))] mlx_sessions: Arc<Mutex<HashMap<i32, MlxBackendSession>>>,+) -> Result<(String, Vec<String>), String> {+ upstream_for(+ model_id,+ provider_configs,+ Credentials::Fetch,+ #[cfg(not(feature = "cli"))]+ llama_state,+ #[cfg(not(feature = "cli"))]+ mlx_sessions,+ )+ .await+}++/// Why no upstream can serve `model_id`, or `None` when one can.+///+/// The servability half of [`resolve_upstream_for_model`], resolved without a+/// credential. Fetching one can mean an OAuth token refreshed over the network+/// for a registered account, and an auth failure is no statement about whether+/// a model's name is servable: a caller that only has to validate the name asks+/// this, and the request that follows resolves for real and reports a+/// credential failure as its own.+#[cfg(feature = "cli")]+pub(crate) async fn unservable_model(+ model_id: &str,+ provider_configs: Arc<Mutex<HashMap<String, ProviderConfig>>>,+ #[cfg(not(feature = "cli"))] llama_state: Arc<LlamacppState>,+ #[cfg(not(feature = "cli"))] mlx_sessions: Arc<Mutex<HashMap<i32, MlxBackendSession>>>,+) -> Option<String> {+ upstream_for(+ model_id,+ provider_configs,+ Credentials::Skip,+ #[cfg(not(feature = "cli"))]+ llama_state,+ #[cfg(not(feature = "cli"))]+ mlx_sessions,+ )+ .await+ .err()+}++/// Whether resolving an upstream fetches the credential the request will carry.+#[derive(Clone, Copy, PartialEq, Eq)]+enum Credentials {+ /// Fetch it, refreshing an account token that has expired.+ Fetch,+ /// Resolve the upstream without it, for a caller that only needs to know+ /// whether the model is servable.+ Skip,+}++async fn upstream_for(+ model_id: &str,+ provider_configs: Arc<Mutex<HashMap<String, ProviderConfig>>>,+ credentials: Credentials,+ #[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";@@ -611,22 +668,25 @@ pub(crate) async fn resolve_upstream_for_model(// concern; the desktop resolves credentials through its own// proxy path and falls back to the bearer key chain here.#[cfg(feature = "cli")]- let (api_url, api_keys) = {- let account_token =- crate::core::cli::auth::account::access_token(&provider_cfg.provider)- .await?;- let api_url = if provider_cfg.provider == "openai"- && account_token.is_some()- && api_url.trim_end_matches('/') == "https://api.openai.com/v1"- {- "https://chatgpt.com/backend-api".to_string()- } else {- api_url- };- let api_keys = account_token- .map(|token| vec![token])- .unwrap_or_else(|| provider_cfg.bearer_key_chain());- (api_url, api_keys)+ let (api_url, api_keys) = match credentials {+ Credentials::Fetch => {+ let account_token =+ crate::core::cli::auth::account::access_token(&provider_cfg.provider)+ .await?;+ let api_url = if provider_cfg.provider == "openai"+ && account_token.is_some()+ && api_url.trim_end_matches('/') == "https://api.openai.com/v1"+ {+ "https://chatgpt.com/backend-api".to_string()+ } else {+ api_url+ };+ let api_keys = account_token+ .map(|token| vec![token])+ .unwrap_or_else(|| provider_cfg.bearer_key_chain());+ (api_url, api_keys)+ }+ Credentials::Skip => (api_url, provider_cfg.bearer_key_chain()),};#[cfg(not(feature = "cli"))]let api_keys = provider_cfg.bearer_key_chain();@@ -2600,6 +2660,58 @@ mod tests {}}+ /// Whether a model is servable is decided without fetching a credential: a+ /// stored record nothing can read fails the request's own resolution, and+ /// must not decide this.+ #[cfg(feature = "cli")]+ #[tokio::test]+ async fn servability_is_decided_without_the_credential() {+ let _guard = crate::core::server::provider_secrets::SECRET_STORE_TEST_LOCK+ .lock()+ .unwrap_or_else(|error| error.into_inner());+ let dir = tempfile::tempdir().unwrap();+ let previous = std::env::var("JAN_DATA_FOLDER").ok();+ std::env::set_var("JAN_DATA_FOLDER", dir.path());+ crate::core::server::provider_secrets::force_file_secrets();+ // Unreadable on purpose: fetching it fails inside the store, before any+ // network call, which is what keeps this test offline.+ crate::core::server::provider_secrets::store_secret_record("auth:anthropic", "{ not json")+ .unwrap();++ let configs = Arc::new(Mutex::new(HashMap::from([(+ "anthropic".to_string(),+ ProviderConfig {+ provider: "anthropic".into(),+ base_url: Some("https://api.anthropic.com/v1".into()),+ models: vec!["claude-sonnet-5".into()],+ ..Default::default()+ },+ )])));++ // Servable: the name is served by a reachable provider, and nothing+ // about the credential took part in saying so.+ assert_eq!(+ unservable_model("claude-sonnet-5", Arc::clone(&configs)).await,+ None+ );+ // The request's own resolution does fetch it, and fails on it: the+ // failure the validation above must not turn into "invalid model".+ let failure = resolve_upstream_for_model("claude-sonnet-5", configs)+ .await+ .expect_err("the credential is unreadable");+ assert!(failure.contains("unreadable"), "{failure}");+ // A name no provider serves is still refused, credential or not.+ assert_eq!(+ unservable_model("claude-sonnet-99", Arc::new(Mutex::new(HashMap::new()))).await,+ Some("No upstream session found for model 'claude-sonnet-99'".to_string())+ );++ match previous {+ Some(value) => std::env::set_var("JAN_DATA_FOLDER", value),+ None => std::env::remove_var("JAN_DATA_FOLDER"),+ }+ }+/// 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 thediff --git a/src-tauri/src/core/cli/rpc.rs b/src-tauri/src/core/cli/rpc.rsindex 4ee7b91e1..60b601d72 100644--- a/src-tauri/src/core/cli/rpc.rs+++ b/src-tauri/src/core/cli/rpc.rs@@ -562,6 +562,12 @@ pub async fn serve() -> Result<(), String> {// session must not be left pinned to a model that// cannot serve it, which the next turn would report// as a failure of the client's own input.+ //+ // Servability, not the upstream itself: resolving+ // the upstream fetches its credential -- an OAuth+ // token, refreshed over the network when expired --+ // and an auth failure is not this method's to report+ // as `-32602`. The next turn resolves for real.let provider_configs = sessions.get(&set.session_id).expect("checked")@@ -569,14 +575,14 @@ pub async fn serve() -> Result<(), String> {.args.provider_configs.clone();- match crate::core::agent::upstream::resolve_upstream_for_model(+ match crate::core::agent::upstream::unservable_model(&set.model,provider_configs,).await{- Err(message) => error(&id, -32602, &message),- Ok(_) => {+ Some(message) => error(&id, -32602, &message),+ None => {let session = sessions.get_mut(&set.session_id).expect("checked");match rebuild_agent(session, Some(set.model)) {Ok(agent) => {