1use crate::core::config::Config;
2
3pub fn cloud_background_tasks() {
4 let mut config = Config::load();
5 let today = chrono::Local::now().format("%Y-%m-%d").to_string();
6
7 let already_contributed = config
8 .cloud
9 .last_contribute
10 .as_deref()
11 .map(|d| d == today)
12 .unwrap_or(false);
13 let already_synced = config
14 .cloud
15 .last_sync
16 .as_deref()
17 .map(|d| d == today)
18 .unwrap_or(false);
19 let already_pulled = config
20 .cloud
21 .last_model_pull
22 .as_deref()
23 .map(|d| d == today)
24 .unwrap_or(false);
25
26 if config.cloud.contribute_enabled && !already_contributed {
27 let entries = collect_contribute_entries();
28 if !entries.is_empty() && crate::cloud_client::contribute(&entries).is_ok() {
29 config.cloud.last_contribute = Some(today.clone());
30 }
31 }
32
33 if crate::cloud_client::is_logged_in() {
34 if !already_synced {
35 let store = crate::core::stats::load();
36 let cep = &store.cep;
37 let entry = serde_json::json!({
38 "date": &today,
39 "tokens_original": cep.total_tokens_original,
40 "tokens_compressed": cep.total_tokens_compressed,
41 "tokens_saved": cep.total_tokens_original.saturating_sub(cep.total_tokens_compressed),
42 "tool_calls": store.total_commands,
43 "cache_hits": cep.total_cache_hits,
44 "cache_misses": cep.total_cache_reads.saturating_sub(cep.total_cache_hits),
45 });
46 if crate::cloud_client::sync_stats(&[entry]).is_ok() {
47 config.cloud.last_sync = Some(today.clone());
48 }
49 }
50
51 if !already_pulled {
52 if let Ok(data) = crate::cloud_client::pull_cloud_models() {
53 let _ = crate::cloud_client::save_cloud_models(&data);
54 config.cloud.last_model_pull = Some(today.clone());
55 }
56 }
57 }
58
59 let _ = config.save();
60}
61
62pub fn collect_contribute_entries() -> Vec<serde_json::Value> {
63 let mut entries = Vec::new();
64
65 if let Some(home) = dirs::home_dir() {
66 let mode_stats_path = home.join(".lean-ctx").join("mode_stats.json");
67 if let Ok(data) = std::fs::read_to_string(&mode_stats_path) {
68 if let Ok(predictor) = serde_json::from_str::<serde_json::Value>(&data) {
69 if let Some(history) = predictor["history"].as_object() {
70 for (_key, outcomes) in history {
71 if let Some(arr) = outcomes.as_array() {
72 for outcome in arr.iter().rev().take(3) {
73 let ext = outcome["ext"].as_str().unwrap_or("unknown");
74 let mode = outcome["mode"].as_str().unwrap_or("full");
75 let t_in = outcome["tokens_in"].as_u64().unwrap_or(0);
76 let t_out = outcome["tokens_out"].as_u64().unwrap_or(0);
77 let ratio = if t_in > 0 {
78 1.0 - t_out as f64 / t_in as f64
79 } else {
80 0.0
81 };
82 let bucket = match t_in {
83 0..=500 => "0-500",
84 501..=2000 => "500-2k",
85 2001..=10000 => "2k-10k",
86 _ => "10k+",
87 };
88 entries.push(serde_json::json!({
89 "file_ext": format!(".{ext}"),
90 "size_bucket": bucket,
91 "best_mode": mode,
92 "compression_ratio": (ratio * 100.0).round() / 100.0,
93 }));
94 if entries.len() >= 200 {
95 return entries;
96 }
97 }
98 }
99 }
100 }
101 }
102 }
103 }
104
105 if entries.is_empty() {
106 let stats_data = crate::core::stats::format_gain_json();
107 if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&stats_data) {
108 let original = parsed["cep"]["total_tokens_original"].as_u64().unwrap_or(0);
109 let compressed = parsed["cep"]["total_tokens_compressed"]
110 .as_u64()
111 .unwrap_or(0);
112 let ratio = if original > 0 {
113 1.0 - compressed as f64 / original as f64
114 } else {
115 0.0
116 };
117 if let Some(modes) = parsed["cep"]["modes"].as_object() {
118 let read_modes = ["full", "map", "signatures", "auto", "aggressive", "entropy"];
119 for (mode, count) in modes {
120 if !read_modes.contains(&mode.as_str()) || count.as_u64().unwrap_or(0) == 0 {
121 continue;
122 }
123 entries.push(serde_json::json!({
124 "file_ext": "mixed",
125 "size_bucket": "mixed",
126 "best_mode": mode,
127 "compression_ratio": (ratio * 100.0).round() / 100.0,
128 }));
129 }
130 }
131 }
132 }
133
134 entries
135}