Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(cli): send an anonymous usage ping from the headless jan CLI (#8580)
Akarshan Biswasdc7cf43f9b30
diff --git a/src-tauri/src/bin/jan.rs b/src-tauri/src/bin/jan.rsindex 7a7efa89f..609c9b3b2 100644--- a/src-tauri/src/bin/jan.rs+++ b/src-tauri/src/bin/jan.rs@@ -28,7 +28,10 @@ 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 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.",+(see `jan config set`), a project's agent.toml, or the Jan desktop app.\n\n\+Once every 24h this sends an anonymous usage ping (version, OS/arch, a random\n\+install id) to the same endpoint as the update check. Set JAN_CLI_NO_UPDATE_CHECK\n\+to opt out of both.",after_help = "Examples:\n \jan # open the interactive agent console (TUI)\n \jan --safe # TUI that asks before writes and commands\n \@@ -358,6 +361,7 @@ async fn main() {// No stderr notice on this path: the TUI's alternate screen would wipe// it, and blocking on the check here would delay the first frame. The// TUI runs the same check itself and notes it in the transcript.+ // The usage ping is likewise deferred to the TUI's own background task.let overrides = cli.providers.into_overrides();if let Err(e) = cli_agent_ui(&cli.project,@@ -381,6 +385,10 @@ async fn main() {if !matches!(command, Commands::Update { .. }) {app_lib::core::cli::updater::print_update_notice_if_available().await;}+ // Awaited (not spawned): a short-lived `jan cli ...` invocation can exit+ // before a detached background task gets to run. See `telemetry::ping_if_due`+ // for what this sends and `JAN_CLI_NO_UPDATE_CHECK` to opt out.+ app_lib::core::cli::telemetry::ping_if_due().await;match command {Commands::Cli { cmd } => handle_cli(cmd).await,diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex 7f52171a4..7b156e8c1 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -10,6 +10,7 @@ pub mod providers;mod path_refs;pub mod run_report;mod secret_input;+pub mod telemetry;pub mod tokamak;mod tui;pub mod updater;diff --git a/src-tauri/src/core/cli/telemetry.rs b/src-tauri/src/core/cli/telemetry.rsnew file mode 100644index 000000000..5abf68315--- /dev/null+++ b/src-tauri/src/core/cli/telemetry.rs@@ -0,0 +1,159 @@+//! Anonymous usage ping for the headless `jan` CLI.+//!+//! Reuses the desktop's HMAC-signed update-check endpoint purely as a usage+//! counter: once per 24h, fires a signed request carrying the CLI version,+//! OS/arch, and a persisted anonymous install id (analogous to the desktop's+//! `nonce_seed` session, see `core::updater::session`). The `User-Agent` is+//! `Jan-Agent/...`, not `Jan/...`, so this is distinguishable server-side from+//! a desktop update check. Shares the update check's opt-out+//! (`JAN_CLI_NO_UPDATE_CHECK`) and its silent-failure philosophy: a dropped+//! ping must never print anything or affect startup.++use std::path::{Path, PathBuf};+use std::time::{Duration, SystemTime, UNIX_EPOCH};++use serde::{Deserialize, Serialize};+use uuid::Uuid;++use crate::core::updater::custom_updater::SECRET_KEY;+use crate::core::updater::hmac_client::SignedRequestHeaders;++const PING_ENDPOINT: &str = "https://apps.jan.ai/update-check";+const PING_INTERVAL_SECS: u64 = 24 * 60 * 60;+const PING_TIMEOUT: Duration = Duration::from_millis(1500);++#[derive(Debug, Default, Deserialize, Serialize)]+struct TelemetryState {+ #[serde(default)]+ install_id: Option<String>,+ #[serde(default)]+ last_ping_unix: Option<u64>,+}++fn state_path() -> Option<PathBuf> {+ Some(dirs::home_dir()?.join(".jan").join("cli_telemetry.json"))+}++fn load_state(path: &Path) -> TelemetryState {+ std::fs::read_to_string(path)+ .ok()+ .and_then(|raw| serde_json::from_str(&raw).ok())+ .unwrap_or_default()+}++fn save_state(path: &Path, state: &TelemetryState) {+ if let Some(dir) = path.parent() {+ let _ = std::fs::create_dir_all(dir);+ }+ if let Ok(raw) = serde_json::to_string_pretty(state) {+ let _ = std::fs::write(path, raw);+ }+}++fn unix_now() -> u64 {+ SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .map(|d| d.as_secs())+ .unwrap_or(0)+}++// "Jan Agent", not "Jan": lets the analytics backend tell this ping apart+// from a desktop client, which sends "Jan/{version} (...)" (see+// `custom_updater::build_user_agent`) -- both share the same version number,+// so the client name is the only distinguishing signal in the request.+fn build_user_agent(version: &str) -> String {+ format!(+ "Jan-Agent/{} ({}; {})",+ version,+ std::env::consts::OS,+ std::env::consts::ARCH+ )+}++/// Send the anonymous usage ping if 24h have elapsed since the last one (or+/// none was ever sent). Best-effort by design: a missing home directory, an+/// unreachable endpoint, or an unwritable state file all silently no-op, the+/// same as `updater::available_update`.+pub async fn ping_if_due() {+ if std::env::var_os("JAN_CLI_NO_UPDATE_CHECK").is_some() {+ return;+ }+ let Some(path) = state_path() else {+ return;+ };+ let mut state = load_state(&path);+ let now = unix_now();+ if state+ .last_ping_unix+ .is_some_and(|last| now.saturating_sub(last) < PING_INTERVAL_SECS)+ {+ return;+ }++ let install_id = state+ .install_id+ .clone()+ .unwrap_or_else(|| Uuid::new_v4().to_string());+ state.install_id = Some(install_id.clone());++ let version = env!("CARGO_PKG_VERSION");+ let headers = SignedRequestHeaders::new(SECRET_KEY, &install_id, version);+ if let Ok(client) = reqwest::Client::builder().timeout(PING_TIMEOUT).build() {+ let mut request = client.get(PING_ENDPOINT);+ for (key, value) in headers.to_header_pairs() {+ request = request.header(key, value);+ }+ request = request+ .header("Accept", "application/json")+ .header("User-Agent", build_user_agent(version));+ let _ = tokio::time::timeout(PING_TIMEOUT, request.send()).await;+ }++ // Recorded regardless of the request's outcome: a down endpoint must not+ // turn into a retry storm on every subsequent invocation.+ state.last_ping_unix = Some(now);+ save_state(&path, &state);+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn first_run_has_no_state() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("cli_telemetry.json");+ let state = load_state(&path);+ assert!(state.install_id.is_none());+ assert!(state.last_ping_unix.is_none());+ }++ #[test]+ fn state_roundtrips_through_save_and_load() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("cli_telemetry.json");+ let state = TelemetryState {+ install_id: Some("abc-123".to_string()),+ last_ping_unix: Some(42),+ };+ save_state(&path, &state);+ let loaded = load_state(&path);+ assert_eq!(loaded.install_id.as_deref(), Some("abc-123"));+ assert_eq!(loaded.last_ping_unix, Some(42));+ }++ #[test]+ fn opt_out_env_var_skips_everything() {+ // Guard against parallel test races on the process-wide env var.+ static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());+ let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());++ std::env::set_var("JAN_CLI_NO_UPDATE_CHECK", "1");+ tokio::runtime::Builder::new_current_thread()+ .enable_all()+ .build()+ .unwrap()+ .block_on(ping_if_due());+ std::env::remove_var("JAN_CLI_NO_UPDATE_CHECK");+ }+}diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex c8517c978..6eeab4f16 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -4584,6 +4584,11 @@ async fn chat_loop<B: Backend>(// and notes itself whenever it lands rather than delaying the first frame.let mut update_task = Some(tokio::spawn(super::updater::available_update()));+ // Anonymous usage ping (see `telemetry::ping_if_due`), same reasoning:+ // detached so it never delays the first frame. Nothing is noted for it --+ // it has no user-visible outcome.+ tokio::spawn(super::telemetry::ping_if_due());+// `/update` downloads tens of megabytes and rewrites the binary; off the// render loop for the same reason, and one at a time.let mut update_install_task: Option<diff --git a/src-tauri/src/core/mod.rs b/src-tauri/src/core/mod.rsindex 2139ae94a..ebf4cbed8 100644--- a/src-tauri/src/core/mod.rs+++ b/src-tauri/src/core/mod.rs@@ -20,5 +20,9 @@ pub mod state;pub mod system;pub mod threads;-#[cfg(all(not(any(target_os = "android", target_os = "ios")), not(feature = "cli")))]+// `custom_updater`/`hmac_client` (the HMAC-signed request-signing bits) are+// also used by the headless CLI's usage ping (`cli::telemetry`); only+// `commands`/`session` are Tauri-specific and stay desktop-only, see+// `updater::mod`.+#[cfg(not(any(target_os = "android", target_os = "ios")))]pub mod updater;diff --git a/src-tauri/src/core/updater/custom_updater.rs b/src-tauri/src/core/updater/custom_updater.rsindex 62b40b9fb..43a57851b 100644--- a/src-tauri/src/core/updater/custom_updater.rs+++ b/src-tauri/src/core/updater/custom_updater.rs@@ -18,7 +18,7 @@ use thiserror::Error;/// Secret key for HMAC signature/// - In CI: Set JAN_SIGNING_KEY environment variable at build time/// - In local dev: Falls back to a test key-const SECRET_KEY: &str = match option_env!("JAN_SIGNING_KEY") {+pub(crate) const SECRET_KEY: &str = match option_env!("JAN_SIGNING_KEY") {Some(key) => key,None => "local-dev-test-key-not-for-production",};diff --git a/src-tauri/src/core/updater/mod.rs b/src-tauri/src/core/updater/mod.rsindex 8a352fb4e..73bd092c2 100644--- a/src-tauri/src/core/updater/mod.rs+++ b/src-tauri/src/core/updater/mod.rs@@ -1,7 +1,10 @@-// Desktop-only Tauri commands (AppHandle<Wry>); the headless `jan` CLI build-// still uses the sibling `hmac_client`/`session` modules via `downloads`.+// Desktop-only Tauri commands (AppHandle<Wry>) and session store+// (tauri-plugin-store); the headless `jan` CLI build reuses the sibling+// `custom_updater`/`hmac_client` modules for its own usage ping instead+// (`cli::telemetry`), which needs neither.#[cfg(not(feature = "cli"))]pub mod commands;pub mod custom_updater;pub mod hmac_client;+#[cfg(not(feature = "cli"))]pub mod session;