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.

feat(agent-cli): count update checks instead of pinging separately

Minh141120682d0fca2867
diff --git a/src-tauri/src/bin/jan.rs b/src-tauri/src/bin/jan.rs
index fbf799b8c..4a828244f 100644
--- a/src-tauri/src/bin/jan.rs
+++ b/src-tauri/src/bin/jan.rs
@@ -548,14 +548,12 @@ async fn main() {
return;
};
- // `jan update` reports the same thing itself, in more detail.
+ // `jan update` reports the same thing itself, in more detail. The check
+ // doubles as the usage record (see `updater::fetch_manifest`), so there is
+ // no separate ping to fire here; `JAN_CLI_NO_UPDATE_CHECK` opts out of both.
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/telemetry.rs b/src-tauri/src/core/cli/telemetry.rs
index 5abf68315..6352b955b 100644
--- a/src-tauri/src/core/cli/telemetry.rs
+++ b/src-tauri/src/core/cli/telemetry.rs
@@ -1,33 +1,24 @@
-//! Anonymous usage ping for the headless `jan` CLI.
+//! Analytics identity 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.
+//! Holds the persisted anonymous install id (analogous to the desktop's
+//! `nonce_seed` session, see `core::updater::session`) and the `Jan-Agent/...`
+//! user agent. Both are consumed by `updater::fetch_manifest`, which checks for
+//! updates through the analytics proxy so that the check itself is the usage
+//! record -- the same way a desktop update check is recorded. Nothing here
+//! sends a request of its own.
+//!
+//! `JAN_CLI_NO_UPDATE_CHECK` opts out: `updater` then skips the proxy entirely
+//! and reads the manifest straight from the CDN, so no identity is sent.
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> {
@@ -50,18 +41,28 @@ fn save_state(path: &Path, state: &TelemetryState) {
}
}
-fn unix_now() -> u64 {
- SystemTime::now()
- .duration_since(UNIX_EPOCH)
- .map(|d| d.as_secs())
- .unwrap_or(0)
+/// The stable per-install id used as the analytics distinct id, generated on
+/// first use and persisted to `~/.jan/cli_telemetry.json`. `None` when there is
+/// no home directory to persist to -- the caller then skips the proxy rather
+/// than inventing a fresh id per run, which would count one install as many.
+pub(super) fn install_id() -> Option<String> {
+ let path = state_path()?;
+ let mut state = load_state(&path);
+ if let Some(id) = state.install_id.clone() {
+ return Some(id);
+ }
+
+ let id = Uuid::new_v4().to_string();
+ state.install_id = Some(id.clone());
+ save_state(&path, &state);
+ Some(id)
}
-// "Jan Agent", not "Jan": lets the analytics backend tell this ping apart
-// from a desktop client, which sends "Jan/{version} (...)" (see
+// "Jan Agent", not "Jan": lets the analytics backend tell this 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 {
+pub(super) fn user_agent(version: &str) -> String {
format!(
"Jan-Agent/{} ({}; {})",
version,
@@ -70,51 +71,6 @@ fn build_user_agent(version: &str) -> String {
)
}
-/// 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::*;
@@ -125,7 +81,6 @@ mod tests {
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]
@@ -134,26 +89,29 @@ mod tests {
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));
+ assert_eq!(load_state(&path).install_id.as_deref(), Some("abc-123"));
}
#[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());
+ fn existing_install_ids_survive_the_ping_field_going_away() {
+ // Files written by the previous ping-based telemetry carry an extra
+ // `last_ping_unix`. Dropping the field must not orphan the install id,
+ // or every existing install would be counted as new.
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("cli_telemetry.json");
+ std::fs::write(
+ &path,
+ r#"{"install_id":"legacy-id","last_ping_unix":1787720989}"#,
+ )
+ .unwrap();
+ assert_eq!(load_state(&path).install_id.as_deref(), Some("legacy-id"));
+ }
- 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");
+ #[test]
+ fn user_agent_names_the_agent_not_the_desktop() {
+ let ua = user_agent("0.8.4-37");
+ assert!(ua.starts_with("Jan-Agent/0.8.4-37 ("), "{ua}");
}
}
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index b4e2fd0e8..0af62da06 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -6555,10 +6555,6 @@ 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.
diff --git a/src-tauri/src/core/cli/updater.rs b/src-tauri/src/core/cli/updater.rs
index 8e89adc31..1eb6d62c2 100644
--- a/src-tauri/src/core/cli/updater.rs
+++ b/src-tauri/src/core/cli/updater.rs
@@ -5,6 +5,13 @@
//! `JAN_CLI_BUILD_VERSION` (the actual nightly version, since `Cargo.toml`'s
//! `version` stays pinned). A local `cargo build --features cli` has neither,
//! so both the check and `jan update` are no-ops there.
+//!
+//! The check is routed through the analytics proxy
+//! (`apps-nightly.jan.ai/agent/update-check`), which serves the same manifest
+//! as the CDN and records the request -- so usage is counted by the update
+//! check itself, exactly as it is for the desktop app, rather than by a
+//! separate ping. The CDN stays as an unsigned fallback, so analytics being
+//! down, misconfigured, or rejecting our signature can never block an update.
use std::cmp::Ordering;
use std::fs::{self, File};
@@ -15,6 +22,9 @@ use std::time::Duration;
use serde::Deserialize;
use sha2::{Digest, Sha256};
+use crate::core::updater::custom_updater::SECRET_KEY;
+use crate::core::updater::hmac_client::SignedRequestHeaders;
+
const CHECK_TIMEOUT: Duration = Duration::from_millis(1500);
const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(300);
const BINARY_NAME: &str = if cfg!(windows) { "jan.exe" } else { "jan" };
@@ -103,14 +113,80 @@ fn compare_versions(a: &str, b: &str) -> Ordering {
Ordering::Equal
}
+/// The analytics-proxied manifest for this build's channel: same content as
+/// the CDN, but the request is recorded. `None` for a local build (no channel)
+/// or when the user opted out, in which case the CDN is read directly and
+/// nothing identifying is sent anywhere.
+fn tracked_manifest_url() -> Option<&'static str> {
+ if std::env::var_os("JAN_CLI_NO_UPDATE_CHECK").is_some() {
+ return None;
+ }
+ tracked_url_for(update_channel())
+}
+
+/// Channel -> proxy URL, split out from `tracked_manifest_url` because the
+/// channel is a compile-time `option_env!` and so is always `None` under
+/// `cargo test`, which would make the mapping untestable in place.
+fn tracked_url_for(channel: Option<&str>) -> Option<&'static str> {
+ match channel {
+ Some("agent-nightly") => Some("https://apps-nightly.jan.ai/agent/update-check"),
+ _ => None,
+ }
+}
+
+/// Fetch the manifest, preferring the proxy so the check is counted against
+/// this install rather than an IP hash. Any proxy failure -- unreachable, 403
+/// on a signing-key mismatch, garbled body -- silently falls through to the
+/// CDN, so update checks are never gated on analytics being healthy.
async fn fetch_manifest(channel: &str, timeout: Duration) -> Result<UpdateManifest, String> {
- let url = format!("https://delta.jan.ai/{channel}/manifest.json");
+ let tracked = tracked_manifest_url();
+
+ // `check_for_update` caps the whole call at `timeout`, so a fallback only
+ // gets a turn if the first attempt is bounded to a share of it.
+ let attempts = if tracked.is_some() { 2 } else { 1 };
let client = reqwest::Client::builder()
- .timeout(timeout)
+ .timeout(timeout / attempts)
.build()
.map_err(|e| e.to_string())?;
- client
+
+ if let Some(url) = tracked {
+ if let Ok(manifest) = fetch_one(&client, url, true).await {
+ return Ok(manifest);
+ }
+ }
+
+ fetch_one(
+ &client,
+ &format!("https://delta.jan.ai/{channel}/manifest.json"),
+ false,
+ )
+ .await
+}
+
+/// One manifest GET. `signed` attaches the HMAC headers the analytics service
+/// verifies (`hmac_client::SignedRequestHeaders`) plus the `Jan-Agent` user
+/// agent, which is what lets the backend attribute the request to this install
+/// instead of falling back to hashing the source IP.
+async fn fetch_one(
+ client: &reqwest::Client,
+ url: &str,
+ signed: bool,
+) -> Result<UpdateManifest, String> {
+ let mut request = client
.get(url)
+ .header("Accept", "application/json")
+ .header("User-Agent", super::telemetry::user_agent(build_version()));
+
+ if signed {
+ let install_id =
+ super::telemetry::install_id().ok_or("no home directory to persist an install id")?;
+ let headers = SignedRequestHeaders::new(SECRET_KEY, &install_id, build_version());
+ for (key, value) in headers.to_header_pairs() {
+ request = request.header(key, value);
+ }
+ }
+
+ request
.send()
.await
.map_err(|e| e.to_string())?
@@ -147,7 +223,7 @@ pub async fn check_for_update(timeout: Duration) -> Result<AvailableUpdate, Stri
})?;
let manifest = tokio::time::timeout(timeout, fetch_manifest(channel, timeout))
.await
- .map_err(|_| format!("timed out contacting https://delta.jan.ai/{channel}"))??;
+ .map_err(|_| format!("timed out fetching the {channel} manifest"))??;
Ok(read_update(&manifest, channel))
}
@@ -461,6 +537,19 @@ fn archive_suffix(url: &str) -> &'static str {
#[cfg(test)]
mod tests {
use super::*;
+
+ #[test]
+ fn only_known_channels_are_routed_through_the_proxy() {
+ // The nightly channel is proxied so the check is counted...
+ assert_eq!(
+ tracked_url_for(Some("agent-nightly")),
+ Some("https://apps-nightly.jan.ai/agent/update-check")
+ );
+ // ...and anything else reads the CDN directly rather than guessing a
+ // host, which would 404 every update check on that channel.
+ assert_eq!(tracked_url_for(Some("agent-stable")), None);
+ assert_eq!(tracked_url_for(None), None);
+ }
use std::io::Cursor;
#[test]