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.

fix(agent): satisfy clippy on the cli and desktop feature sets

thinhlpgdc5476dd6b4f
diff --git a/src-tauri/src/core/agent/upstream.rs b/src-tauri/src/core/agent/upstream.rs
index 73a1bc39a..dba56b397 100644
--- a/src-tauri/src/core/agent/upstream.rs
+++ b/src-tauri/src/core/agent/upstream.rs
@@ -4,6 +4,7 @@
//! `core/server/proxy.rs` (no behavior change) so both the server path and
//! `core/agent/loop.rs` consume one implementation.
+#[cfg(feature = "cli")]
use std::cmp::Reverse;
use std::collections::HashMap;
use std::fs;
@@ -246,6 +247,8 @@ fn mcp_call_result_to_string(result: &CallToolResult) -> String {
/// True when the provider carries a credential (an API key or key chain),
/// so a model id offered by several providers can prefer the signed-in one.
+/// Only the `cli` build ranks providers this way.
+#[cfg(feature = "cli")]
fn credentialed(config: &ProviderConfig) -> bool {
config.api_key.is_some() || !config.api_keys.is_empty()
}
@@ -1808,17 +1811,50 @@ mod tests {
assert_eq!(keys, vec!["sk-opencode"]);
}
+ /// Holds the secret-store serialization guard, the temp data folder and the
+ /// `JAN_DATA_FOLDER` restore together, so an async test can keep all three
+ /// alive across `.await` without holding a bare lock guard over it.
+ #[cfg(feature = "cli")]
+ struct TempSecretStore {
+ _guard: std::sync::MutexGuard<'static, ()>,
+ previous: Option<String>,
+ _dir: tempfile::TempDir,
+ }
+
+ #[cfg(feature = "cli")]
+ impl TempSecretStore {
+ fn new() -> Self {
+ let guard = crate::core::server::provider_secrets::SECRET_STORE_TEST_LOCK
+ .lock()
+ .unwrap_or_else(|e| e.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();
+ Self {
+ _guard: guard,
+ previous,
+ _dir: dir,
+ }
+ }
+ }
+
+ #[cfg(feature = "cli")]
+ impl Drop for TempSecretStore {
+ fn drop(&mut self) {
+ match &self.previous {
+ Some(value) => std::env::set_var("JAN_DATA_FOLDER", value),
+ None => std::env::remove_var("JAN_DATA_FOLDER"),
+ }
+ }
+ }
+
#[cfg(feature = "cli")]
#[tokio::test]
async fn account_credentials_override_the_api_key_chain() {
use crate::core::cli::auth::{Credential, CredentialStore, OAuthToken};
- use crate::core::server::provider_secrets::SECRET_STORE_TEST_LOCK;
- let _guard = SECRET_STORE_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
- let directory = tempfile::tempdir().unwrap();
- let previous = std::env::var("JAN_DATA_FOLDER").ok();
- std::env::set_var("JAN_DATA_FOLDER", directory.path());
- crate::core::server::provider_secrets::force_file_secrets();
+ let _secrets = TempSecretStore::new();
CredentialStore::store(
"openai",
&Credential::OAuthToken(OAuthToken {
@@ -1850,11 +1886,6 @@ mod tests {
.unwrap();
assert_eq!(url, "https://chatgpt.com/backend-api/chat/completions");
assert_eq!(keys, vec!["account-access"]);
-
- match previous {
- Some(value) => std::env::set_var("JAN_DATA_FOLDER", value),
- None => std::env::remove_var("JAN_DATA_FOLDER"),
- }
}
#[test]
diff --git a/src-tauri/src/core/cli/auth/account.rs b/src-tauri/src/core/cli/auth/account.rs
index 229783ac6..fafe41ef5 100644
--- a/src-tauri/src/core/cli/auth/account.rs
+++ b/src-tauri/src/core/cli/auth/account.rs
@@ -898,10 +898,10 @@ pub async fn claude_plan_summary(fallback: &str) -> String {
.json(&body)
.send()
.await;
- if matches!(&probe, Ok(response) if response.status().is_success()) {
- if model == "claude-sonnet-5" {
- heavy_ok = true;
- }
+ if model == "claude-sonnet-5"
+ && matches!(&probe, Ok(response) if response.status().is_success())
+ {
+ heavy_ok = true;
}
}
let tier = claude_code_subscription_type();
@@ -1081,14 +1081,15 @@ mod tests {
use crate::core::server::provider_secrets::SECRET_STORE_TEST_LOCK;
use std::io::{Read, Write};
use std::net::TcpListener;
- use std::sync::{mpsc, Mutex, MutexGuard};
+ use std::sync::{mpsc, MutexGuard};
- /// Serializes the two tests that mutate the process-global Claude alias
- /// latch, which cargo runs in parallel threads.
- static ALIAS_TEST_LOCK: Mutex<()> = Mutex::new(());
+ /// Serializes the tests that mutate the process-global Claude alias latch,
+ /// which cargo runs in parallel threads. A tokio mutex, not a std one:
+ /// these tests hold the guard across `.await`.
+ static ALIAS_TEST_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
- fn alias_test_lock() -> MutexGuard<'static, ()> {
- ALIAS_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner())
+ async fn alias_test_lock() -> tokio::sync::MutexGuard<'static, ()> {
+ ALIAS_TEST_LOCK.lock().await
}
struct TempSecrets {
@@ -1152,24 +1153,6 @@ mod tests {
format!("http://{addr}/v1")
}
- fn token_server() -> String {
- let listener = TcpListener::bind("127.0.0.1:0").unwrap();
- let endpoint = format!("http://{}/token", listener.local_addr().unwrap());
- std::thread::spawn(move || {
- let (mut stream, _) = listener.accept().unwrap();
- let mut request = [0; 4096];
- let _ = stream.read(&mut request).unwrap();
- let body = r#"{"access_token":"exchanged-account-token","refresh_token":"refresh","expires_in":3600,"token_type":"Bearer","scope":"profile offline_access"}"#;
- write!(
- stream,
- "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
- body.len(),
- body
- )
- .unwrap();
- });
- endpoint
- }
/// Build a signed-shape Codex OAuth access token (a JWT) carrying the
/// `https://api.openai.com/auth` -> `chatgpt_account_id` claim that jan
/// uses to verify a Codex account. The signature is a dummy; `codex_chatgpt_account_id`
@@ -1548,7 +1531,7 @@ mod tests {
fields.get("redirect_uri"),
Some(&login.redirect_uri.to_string())
);
- assert!(fields.get("client_id").is_some());
+ assert!(fields.contains_key("client_id"));
// Anthropic's token endpoint expects `state` echoed back on exchange;
// OpenAI's rejects the extra field, so it must stay Claude-only.
assert_eq!(fields.get("state"), Some(&login.state));
@@ -1636,7 +1619,7 @@ mod tests {
}
let request = String::from_utf8_lossy(&request);
assert!(
- request.starts_with(&format!("POST /token HTTP/1.1\r\n")),
+ request.starts_with("POST /token HTTP/1.1\r\n"),
"{request}"
);
let lower = request.to_ascii_lowercase();
@@ -1729,7 +1712,7 @@ mod tests {
);
let token = OAuthToken {
- access_token: codex_jwt("account-321").into(),
+ access_token: codex_jwt("account-321"),
refresh_token: Some("refresh".into()),
expires_at: CredentialStore::load("openai")
.unwrap()
@@ -1799,7 +1782,7 @@ mod tests {
);
let token = OAuthToken {
- access_token: codex_jwt("account-321").into(),
+ access_token: codex_jwt("account-321"),
refresh_token: Some("refresh".into()),
expires_at: CredentialStore::load("openai")
.unwrap()
@@ -1839,10 +1822,7 @@ mod tests {
assert!(CredentialStore::load(AccountProvider::Claude.credential_provider())
.unwrap()
.is_none());
- assert!(load_global_config()
- .unwrap()
- .get("anthropic")
- .is_none());
+ assert!(!load_global_config().unwrap().contains_key("anthropic"));
});
}
@@ -1860,10 +1840,7 @@ mod tests {
assert!(CredentialStore::load(AccountProvider::Claude.credential_provider())
.unwrap()
.is_none());
- assert!(load_global_config()
- .unwrap()
- .get("anthropic")
- .is_none());
+ assert!(!load_global_config().unwrap().contains_key("anthropic"));
});
}
@@ -1878,10 +1855,7 @@ mod tests {
assert!(CredentialStore::load(AccountProvider::Claude.credential_provider())
.unwrap()
.is_none());
- assert!(load_global_config()
- .unwrap()
- .get("anthropic")
- .is_none());
+ assert!(!load_global_config().unwrap().contains_key("anthropic"));
});
}
@@ -1977,7 +1951,7 @@ mod tests {
#[tokio::test(flavor = "current_thread")]
async fn claude_plan_summary_falls_back_when_no_credential() {
- let _alias = alias_test_lock();
+ let _alias = alias_test_lock().await;
set_claude_alias(false);
let _temp = TempSecrets::new();
// No Claude credential is stored in the fresh temp home, and the alias
@@ -2054,7 +2028,7 @@ mod tests {
#[tokio::test(flavor = "current_thread")]
async fn claude_alias_is_off_by_default_in_tests() {
- let _guard = alias_test_lock();
+ let _guard = alias_test_lock().await;
set_claude_alias(false);
assert!(!claude_alias_enabled());
assert_eq!(claude_code_access_token().await, None);
@@ -2062,7 +2036,7 @@ mod tests {
#[tokio::test(flavor = "current_thread")]
async fn claude_alias_toggle_controls_the_lookup_gate() {
- let _guard = alias_test_lock();
+ let _guard = alias_test_lock().await;
set_claude_alias(false);
// Off: the keychain is never touched, so this is deterministic None
// even on a machine with Claude Code / omp installed.
diff --git a/src-tauri/src/core/cli/auth/providers.rs b/src-tauri/src/core/cli/auth/providers.rs
index e0f8dbb9b..93245ae08 100644
--- a/src-tauri/src/core/cli/auth/providers.rs
+++ b/src-tauri/src/core/cli/auth/providers.rs
@@ -236,7 +236,7 @@ fn parse_codex_models(value: &serde_json::Value) -> Vec<String> {
.collect();
// Rolling ChatGPT codenames carry a user-scoped suffix (e.g.
// `gpt-5.6-luna-wm`); they are not stable Codex models, so drop them.
- ids.retain(|id| !matches!(id.split('-').last(), Some("wm")));
+ ids.retain(|id| !id.ends_with("-wm"));
ids.sort();
ids.dedup();
ids
@@ -493,7 +493,7 @@ mod tests {
let result = login_for_test(&deepseek_at(endpoint), "bad");
assert!(matches!(result, Err(LoginError::Unauthorized)));
assert!(CredentialStore::load("deepseek").unwrap().is_none());
- assert!(load_global_config().unwrap().get("deepseek").is_none());
+ assert!(!load_global_config().unwrap().contains_key("deepseek"));
});
}
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index 0d1d671b3..4b8084540 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -10300,7 +10300,7 @@ fn open_login_picker_at(app: &mut App, selected_provider: Option<&str>) {
providers.sort_by(|a, b| match (a.id == "tokamak", b.id == "tokamak") {
(true, false) => std::cmp::Ordering::Less,
(false, true) => std::cmp::Ordering::Greater,
- _ => a.name.cmp(&b.name),
+ _ => a.name.cmp(b.name),
});
let items = providers
.into_iter()
@@ -11983,9 +11983,6 @@ fn login_prompt_lines(prompt: &LoginPrompt, width: u16) -> Vec<Line<'static>> {
let dim = Style::new().dark_gray();
let max = width.max(1) as usize;
let definition = crate::core::cli::auth::provider_by_id(&prompt.provider);
- let name = definition
- .as_ref()
- .map_or("provider", |provider| provider.name);
let keys_url = definition
.as_ref()
.map_or("", |provider| provider.api_key.keys_url);
@@ -12985,7 +12982,7 @@ fn provider_label_for_model(
let reachable = pc
.iter()
.filter(|(_, c)| is_cli_reachable(c) && offers(c))
- .min_by_key(|(name, c)| (std::cmp::Reverse(c.api_key.is_some()), name.clone()))
+ .min_by_key(|(name, c)| (std::cmp::Reverse(c.api_key.is_some()), (*name).clone()))
.or_else(|| pc.iter().find(|(_, c)| offers(c)));
match reachable {
Some((name, _)) if name != model => format!("{name}/{model}"),
@@ -13647,7 +13644,7 @@ mod tests {
compact_tokens, finish_account_login, finish_compaction, finish_login, finish_update_install,
image_mime_of, load_first_file_image, load_image_file, MAX_IMAGE_BYTES,
message_text, CompactKind, MAX_OVERFLOW_RETRIES,
- estimate_token_count, header_spans, status_panel, SubagentPanel,
+ estimate_token_count, header_spans,
provider_label_for_model,
note_update, open_config_screen, spawn_branch_poll, await_branch_poll,
parse_command, partial_json_field, restore_goal, restore_run_mode, restore_todos,
@@ -16681,7 +16678,7 @@ mod tests {
providers.sort_by(|a, b| match (a.id == "tokamak", b.id == "tokamak") {
(true, false) => std::cmp::Ordering::Less,
(false, true) => std::cmp::Ordering::Greater,
- _ => a.name.cmp(&b.name),
+ _ => a.name.cmp(b.name),
});
providers
};
diff --git a/src-tauri/src/core/server/provider_secrets.rs b/src-tauri/src/core/server/provider_secrets.rs
index 76a97fe06..471dff1a4 100644
--- a/src-tauri/src/core/server/provider_secrets.rs
+++ b/src-tauri/src/core/server/provider_secrets.rs
@@ -255,8 +255,9 @@ pub fn delete_secret_record(key: &str) -> Result<(), String> {
/// Force the encrypted-file fallback for the rest of the process. Test-only:
/// lets unit tests exercise the file path without touching the developer's
-/// keychain.
-#[cfg(test)]
+/// keychain. Every caller is a `cli`-feature test, so the desktop build would
+/// otherwise carry it unused.
+#[cfg(all(test, feature = "cli"))]
pub(crate) fn force_file_secrets() {
KEYRING_DOWN.store(true, Ordering::Relaxed);
}