1use std::collections::BTreeMap;
19use std::time::Duration;
20
21use lean_ctx_protocol::cloud::usage::{CloudQuotaStateV1, CloudQuotaV1, CloudUsageV1};
22use lean_ctx_time::UtcDateTime;
23use serde::{Deserialize, Serialize};
24
25pub use lean_ctx_protocol::cloud::usage::FEATURE_USAGE;
26
27use crate::CloudError;
28use crate::auth::Session;
29use crate::config::CloudConfig;
30use crate::error::{NextStep, amount_text, quota_label};
31use crate::gateway::BALANCE_RESOURCE;
32use crate::state::{CloudStore, write_private};
33
34const USAGE_FILE: &str = "usage.json";
36
37pub const REFRESH_EVERY: Duration = Duration::from_mins(10);
39
40const ORDER: [&str; 7] = [
42 "storage_bytes",
43 "transfer_bytes",
44 "bus_messages",
45 BALANCE_RESOURCE,
46 "private_vaults",
47 "registered_instances",
48 "connected_instances",
49];
50
51const LABEL_WIDTH: usize = 22;
53
54#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
55#[serde(default)]
56struct Cache {
57 server: String,
59 fetched_at: Option<String>,
61 tried_at: Option<String>,
63 usage: Option<CloudUsageV1>,
64 logged: BTreeMap<String, CloudQuotaStateV1>,
66}
67
68fn load(store: &CloudStore) -> Cache {
69 std::fs::read(store.data_dir().join(USAGE_FILE))
70 .ok()
71 .and_then(|b| serde_json::from_slice(&b).ok())
72 .unwrap_or_default()
73}
74
75fn save(store: &CloudStore, cache: &Cache) {
76 if let Ok(bytes) = serde_json::to_vec_pretty(cache) {
77 let _ = write_private(store.data_dir(), USAGE_FILE, &bytes);
78 }
79}
80
81fn load_for(store: &CloudStore, server: &str) -> Cache {
83 let cache = load(store);
84 if cache.server == server {
85 cache
86 } else {
87 Cache {
88 server: server.to_string(),
89 ..Cache::default()
90 }
91 }
92}
93
94fn stamp(at: UtcDateTime) -> String {
95 at.to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true)
96}
97
98#[must_use]
100pub fn announced(store: &CloudStore) -> bool {
101 crate::session_ref::announced(store, FEATURE_USAGE)
102}
103
104pub fn fetch(session: &Session) -> Result<Option<CloudUsageV1>, CloudError> {
106 if !announced(&session.store) {
107 return Ok(None);
108 }
109 let answer = session.with_client(|client| client.get("/usage"))?;
110 decode(answer).map(Some)
111}
112
113fn decode(answer: serde_json::Value) -> Result<CloudUsageV1, CloudError> {
114 let usage: CloudUsageV1 =
115 serde_json::from_value(answer).map_err(|e| CloudError::Protocol(format!("usage: {e}")))?;
116 usage
117 .validate()
118 .map_err(|e| CloudError::Protocol(format!("usage: {e}")))?;
119 Ok(usage)
120}
121
122pub(crate) fn background(session: &Session, now: UtcDateTime) {
129 if !announced(&session.store) {
130 return;
131 }
132 let store = &session.store;
133 let mut cache = load_for(store, &session.instance.url);
134 if !due(cache.tried_at.as_deref(), now) {
135 return;
136 }
137 cache.tried_at = Some(stamp(now));
138 match fetch(session) {
139 Ok(Some(usage)) => {
140 for line in note(&mut cache, usage, now) {
141 tracing::warn!("{line}");
142 }
143 }
144 Ok(None) => {}
145 Err(error) => tracing::debug!("cloud: usage not read: {error}"),
146 }
147 save(store, &cache);
148}
149
150fn due(tried_at: Option<&str>, now: UtcDateTime) -> bool {
152 tried_at
153 .and_then(|t| UtcDateTime::parse_from_rfc3339(t).ok())
154 .is_none_or(|at| {
155 (now - at)
156 .to_std()
157 .map_or(true, |since| since >= REFRESH_EVERY)
158 })
159}
160
161fn note(cache: &mut Cache, usage: CloudUsageV1, now: UtcDateTime) -> Vec<String> {
166 let lines = rises(&cache.logged, &usage);
167 cache.logged = ordered(&usage)
168 .map(|(r, q)| (r.to_owned(), q.state))
169 .collect();
170 cache.usage = Some(usage);
171 cache.fetched_at = Some(stamp(now));
172 lines
173}
174
175#[must_use]
179pub fn rises(seen: &BTreeMap<String, CloudQuotaStateV1>, usage: &CloudUsageV1) -> Vec<String> {
180 ordered(usage)
181 .filter(|(r, q)| q.state.level() > seen.get(*r).map_or(0, |s| s.level()))
182 .map(|(r, q)| rise_line(r, q))
183 .collect()
184}
185
186#[must_use]
189pub fn rise_line(resource: &str, q: &CloudQuotaV1) -> String {
190 let what = quota_label(resource);
191 let amounts = format!(
192 "{} of {}",
193 amount_text(resource, q.used),
194 amount_text(resource, q.limit)
195 );
196 let mut line = if q.state == CloudQuotaStateV1::Full {
197 format!(
198 "LeanCTX Cloud: all of your {what} is used ({amounts}); nothing is charged for more"
199 )
200 } else {
201 format!(
202 "LeanCTX Cloud: {} % of your {what} is used ({amounts})",
203 percent(q)
204 )
205 };
206 if let Some(at) = reset_text(q) {
207 line.push_str(&format!("; it frees at {at}"));
208 }
209 if let Some(hint) = hint(q) {
210 line.push_str("; ");
211 line.push_str(hint);
212 }
213 line
214}
215
216pub fn status(store: &CloudStore, config: &CloudConfig, now: UtcDateTime) -> Vec<String> {
223 if !announced(store) || !matches!(store.instance(), Ok(Some(_))) {
224 return Vec::new();
225 }
226 match read(store, config, now) {
227 Ok(Some(r)) if r.live => status_lines(&r.usage, None),
228 Ok(Some(r)) => status_lines(&r.usage, r.as_of.as_deref()),
229 Ok(None) => Vec::new(),
230 Err(error) => vec![format!(
231 "Usage: not read now ({})",
232 why_not_read(&error)
233 )],
234 }
235}
236
237fn why_not_read(error: &CloudError) -> &'static str {
240 match error {
241 CloudError::Offline(_) => "LeanCTX Cloud did not answer",
242 CloudError::NotConnected => "this machine is not connected; run `lean-ctx cloud connect`",
243 CloudError::Unauthorized | CloudError::LeaseLapsed | CloudError::Revoked(_) => {
244 "LeanCTX Cloud no longer accepts this machine; run `lean-ctx cloud connect` again"
245 }
246 CloudError::Forbidden | CloudError::PlanRequired(_) => {
247 "your role or plan does not show usage"
248 }
249 _ if error.is_transient() => "LeanCTX Cloud is busy; try again shortly",
250 _ => "LeanCTX Cloud refused the request",
251 }
252}
253
254#[derive(Debug, Clone, PartialEq)]
256pub struct UsageRead {
257 pub usage: CloudUsageV1,
258 pub as_of: Option<String>,
260 pub live: bool,
262}
263
264pub fn read(
268 store: &CloudStore,
269 config: &CloudConfig,
270 now: UtcDateTime,
271) -> Result<Option<UsageRead>, CloudError> {
272 if !announced(store) {
273 return Ok(None);
274 }
275 let instance = store.instance()?.ok_or(CloudError::NotConnected)?;
276 let live = crate::scheduler::connected_session(store, config).and_then(|s| fetch(&s));
277 let mut cache = load_for(store, &instance.url);
278 match live {
279 Ok(Some(usage)) => {
280 cache.usage = Some(usage.clone());
282 cache.fetched_at = Some(stamp(now));
283 save(store, &cache);
284 Ok(Some(UsageRead {
285 usage,
286 as_of: cache.fetched_at,
287 live: true,
288 }))
289 }
290 Ok(None) => Ok(None),
291 Err(error) => match cache.usage {
292 Some(usage) => Ok(Some(UsageRead {
293 usage,
294 as_of: cache.fetched_at,
295 live: false,
296 })),
297 None => Err(error),
298 },
299 }
300}
301
302#[must_use]
305pub fn status_lines(usage: &CloudUsageV1, as_of: Option<&str>) -> Vec<String> {
306 let plan = match usage.plan.as_str() {
307 "personal" => "Personal",
308 "team" => "Team",
309 "enterprise" => "Enterprise",
310 _ => "no plan",
311 };
312 let mut head = format!("Usage: LeanCTX Cloud, {plan}");
313 if usage.read_only || usage.plan == "locked" {
314 head.push_str(" (read and export only)");
315 }
316 if let Some(at) = as_of {
317 head.push_str(&format!(" (as of {at})"));
318 }
319 let mut lines = vec![head];
320 lines.extend(ordered(usage).map(|(r, q)| quota_line(r, q)));
321 lines
322}
323
324#[must_use]
326pub fn quota_line(resource: &str, q: &CloudQuotaV1) -> String {
327 let mut line = format!(
328 " {:<LABEL_WIDTH$}{} of {}",
329 quota_label(resource),
330 amount_text(resource, q.used),
331 amount_text(resource, q.limit)
332 );
333 match q.state {
334 CloudQuotaStateV1::Full => {
335 line.push_str(" · FULL");
336 if let Some(at) = reset_text(q) {
337 line.push_str(&format!(" until {at}"));
338 }
339 }
340 CloudQuotaStateV1::Warn => line.push_str(&format!(" · warn ({} %)", percent(q))),
341 CloudQuotaStateV1::Ok | CloudQuotaStateV1::Unknown => return line,
342 }
343 if let Some(hint) = hint(q) {
344 line.push_str("; ");
345 line.push_str(hint);
346 }
347 line
348}
349
350fn ordered(usage: &CloudUsageV1) -> impl Iterator<Item = (&str, &CloudQuotaV1)> {
356 let known = ORDER.iter().filter_map(|r| usage.quotas.get_key_value(*r));
357 let rest = usage
358 .quotas
359 .iter()
360 .filter(|(r, _)| !ORDER.contains(&r.as_str()));
361 known
362 .chain(rest)
363 .map(|(r, q)| (r.as_str(), q))
364 .filter(|(r, q)| !(*r == BALANCE_RESOURCE && q.limit == 0))
365}
366
367fn percent(q: &CloudQuotaV1) -> u128 {
369 if q.limit == 0 {
370 return 100;
371 }
372 u128::from(q.used) * 100 / u128::from(q.limit)
373}
374
375fn hint(q: &CloudQuotaV1) -> Option<&'static str> {
377 NextStep::of_wire(q.next_step.as_deref()).and_then(NextStep::hint)
378}
379
380fn reset_text(q: &CloudQuotaV1) -> Option<String> {
382 let at = UtcDateTime::parse_from_rfc3339(q.reset_at.as_deref()?).ok()?;
383 Some(stamp(at))
384}
385
386#[cfg(test)]
387mod tests {
388 use super::*;
389 use serde_json::json;
390
391 #[test]
392 fn order_lists_the_balance_resource_from_the_gateway() {
393 assert!(ORDER.contains(&BALANCE_RESOURCE));
394 assert_eq!(BALANCE_RESOURCE, "model_credit_usd_micros");
395 }
396
397 fn fixture() -> serde_json::Value {
398 serde_json::from_str(include_str!(
399 "../../lean-ctx-protocol/tests/fixtures/cloud/usage.response.json"
400 ))
401 .unwrap()
402 }
403
404 fn usage() -> CloudUsageV1 {
405 decode(fixture()).unwrap()
406 }
407
408 fn now() -> UtcDateTime {
409 UtcDateTime::parse_from_rfc3339("2026-11-17T12:00:00Z").unwrap()
410 }
411
412 fn enrolled(dir: &std::path::Path, features: &[&str]) -> CloudStore {
413 let store = CloudStore::at(dir.join("config"), dir.join("cloud"));
414 let instance: crate::state::InstanceRecord = serde_json::from_value(json!({
415 "instance_id": "inst_1", "org_id": "org_acme", "org_name": "Platform",
416 "label": "laptop", "url": "https://cloud.example", "org_salt_id": "salt",
417 "enrolled_at": "2026-11-16T12:00:00Z"
418 }))
419 .unwrap();
420 store
421 .write_config(crate::state::INSTANCE_FILE, &instance)
422 .unwrap();
423 crate::session_ref::record(
424 &store,
425 "https://cloud.example",
426 features.iter().map(|f| (*f).to_string()).collect(),
427 )
428 .unwrap();
429 store
430 }
431
432 #[test]
433 fn status_shows_every_quota_in_its_unit_with_warn_and_full_marked() {
434 let lines = status_lines(&usage(), None);
435 assert_eq!(
436 lines,
437 [
438 "Usage: LeanCTX Cloud, Personal",
439 " storage 34 GiB of 40 GiB · warn (85 %); Team gives every seat its own allowance",
440 " monthly transfer 40 GiB of 40 GiB · FULL until 2026-12-01T00:00:00Z; Team gives every seat its own allowance",
441 " monthly bus messages 1200 of 200000",
442 " model credit $1.25 of $8.00",
443 " private vaults 3 of 20",
444 " instance slots 2 of 3",
445 " connected instances 1 of 2",
446 ]
447 );
448 for line in &lines {
449 for word in ["engine", "Queen", "workspace"] {
450 assert!(!line.contains(word), "{line}");
451 }
452 }
453 }
454
455 #[test]
456 fn a_model_credit_of_nothing_is_neither_shown_nor_warned() {
457 let mut raw = fixture();
458 raw["quotas"]["model_credit_usd_micros"] =
459 json!({"limit": 0, "used": 0, "state": "full", "next_step": "top_up"});
460 let usage = decode(raw).unwrap();
461 let lines = status_lines(&usage, None);
462 assert!(
463 lines.iter().all(|l| !l.contains("model credit")),
464 "{lines:?}"
465 );
466 assert_eq!(lines.len(), 7, "{lines:?}");
467 let rises = rises(&BTreeMap::new(), &usage);
468 assert!(
469 rises.iter().all(|l| !l.contains("model credit")),
470 "{rises:?}"
471 );
472 }
473
474 #[test]
475 fn a_model_credit_without_balance_stays_hidden_with_use_reported() {
476 let mut raw = fixture();
477 raw["quotas"]["model_credit_usd_micros"] =
478 json!({"limit": 0, "used": 1_250_000, "state": "full", "next_step": "top_up"});
479 let usage = decode(raw).unwrap();
480 let lines = status_lines(&usage, None);
481 assert!(
482 lines.iter().all(|l| !l.contains("model credit")),
483 "{lines:?}"
484 );
485 assert!(
486 rises(&BTreeMap::new(), &usage)
487 .iter()
488 .all(|l| !l.contains("model credit"))
489 );
490 }
491
492 #[test]
493 fn a_model_credit_that_gets_a_balance_and_runs_out_is_said_then() {
494 let mut cache = Cache::default();
495 let mut raw = fixture();
496 raw["quotas"]["model_credit_usd_micros"] =
497 json!({"limit": 0, "used": 0, "state": "full", "next_step": "top_up"});
498 let first = note(&mut cache, decode(raw.clone()).unwrap(), now());
499 assert!(
500 first.iter().all(|l| !l.contains("model credit")),
501 "{first:?}"
502 );
503 assert!(
504 !cache.logged.contains_key(BALANCE_RESOURCE),
505 "a hidden quota is no baseline"
506 );
507 raw["quotas"]["model_credit_usd_micros"] =
509 json!({"limit": 8_000_000, "used": 8_000_000, "state": "full", "next_step": "top_up"});
510 let topped = note(&mut cache, decode(raw).unwrap(), now());
511 assert_eq!(
512 topped
513 .iter()
514 .filter(|l| l.contains("all of your model credit is used ($8.00 of $8.00)"))
515 .count(),
516 1,
517 "{topped:?}"
518 );
519 }
520
521 #[test]
522 fn a_locked_or_cached_answer_says_so_and_unknown_resources_follow() {
523 let mut raw = fixture();
524 raw["plan"] = "locked".into();
525 raw["read_only"] = true.into();
526 raw["quotas"]["agent_seats"] = json!({"limit": 4, "used": 4, "state": "full",
527 "next_step": "contact", "reset_at": "soon"});
528 let lines = status_lines(&decode(raw).unwrap(), Some("2026-11-17T11:00:00Z"));
529 assert_eq!(
530 lines[0],
531 "Usage: LeanCTX Cloud, no plan (read and export only) (as of 2026-11-17T11:00:00Z)"
532 );
533 assert_eq!(
535 lines.last().unwrap(),
536 " agent_seats 4 of 4 · FULL; contact us to extend your Enterprise contract"
537 );
538 }
539
540 #[test]
541 fn a_rise_is_logged_once_and_again_only_after_falling_back() {
542 let mut cache = Cache::default();
543 let first = note(&mut cache, usage(), now());
544 assert_eq!(
545 first,
546 [
547 "LeanCTX Cloud: 85 % of your storage is used (34 GiB of 40 GiB); Team gives every seat its own allowance",
548 "LeanCTX Cloud: all of your monthly transfer is used (40 GiB of 40 GiB); nothing is charged for more; it frees at 2026-12-01T00:00:00Z; Team gives every seat its own allowance",
549 ]
550 );
551 for line in &first {
552 for word in ["workspace", "engine", "Queen"] {
553 assert!(!line.contains(word), "{word} in {line}");
554 }
555 }
556 assert!(note(&mut cache, usage(), now()).is_empty());
558 let mut raw = fixture();
560 raw["quotas"]["storage_bytes"]["used"] = (40_u64 << 30).into();
561 raw["quotas"]["storage_bytes"]["state"] = "full".into();
562 let full = note(&mut cache, decode(raw.clone()).unwrap(), now());
563 assert_eq!(
564 full,
565 [
566 "LeanCTX Cloud: all of your storage is used (40 GiB of 40 GiB); nothing is charged for more; Team gives every seat its own allowance"
567 ]
568 );
569 raw["quotas"]["storage_bytes"]["state"] = "ok".into();
571 raw["quotas"]["transfer_bytes"]["state"] = "ok".into();
572 assert!(note(&mut cache, decode(raw).unwrap(), now()).is_empty());
573 assert_eq!(note(&mut cache, usage(), now()).len(), 2);
574 }
575
576 #[test]
577 fn model_credit_and_counts_keep_their_units_in_a_rise() {
578 let credit = CloudQuotaV1 {
579 limit: 8_000_000,
580 used: 6_500_000,
581 reset_at: Some("2026-12-01T00:00:00Z".into()),
582 state: CloudQuotaStateV1::Warn,
583 next_step: Some("top_up".into()),
584 };
585 assert_eq!(
586 rise_line("model_credit_usd_micros", &credit),
587 "LeanCTX Cloud: 81 % of your model credit is used ($6.50 of $8.00); it frees at 2026-12-01T00:00:00Z; a top-up in LeanCTX Cloud adds more"
588 );
589 let seats = CloudQuotaV1 {
590 limit: 4,
591 used: 4,
592 reset_at: None,
593 state: CloudQuotaStateV1::Full,
594 next_step: Some("add_seats".into()),
595 };
596 assert_eq!(
597 quota_line("connected_instances", &seats),
598 " connected instances 4 of 4 · FULL; every seat you add in LeanCTX Cloud brings its own allowance"
599 );
600 }
601
602 #[test]
603 fn the_cache_survives_a_restart_and_another_server_starts_empty() {
604 let dir = tempfile::tempdir().unwrap();
605 let store = enrolled(dir.path(), &[FEATURE_USAGE]);
606 let mut cache = load_for(&store, "https://cloud.example");
607 assert!(!note(&mut cache, usage(), now()).is_empty());
608 save(&store, &cache);
609 let mut again = load_for(&store, "https://cloud.example");
610 assert!(
611 note(&mut again, usage(), now()).is_empty(),
612 "no repeat after a restart"
613 );
614 let other = load_for(&store, "https://other.example");
615 assert!(other.logged.is_empty() && other.usage.is_none());
616 }
617
618 #[test]
619 fn the_background_look_is_spaced() {
620 assert!(due(None, now()));
621 assert!(!due(Some("2026-11-17T11:55:00Z"), now()));
622 assert!(due(Some("2026-11-17T11:50:00Z"), now()));
623 assert!(due(Some("garbage"), now()));
624 }
625
626 #[test]
627 fn an_older_server_gets_no_request_and_no_status_lines() {
628 let dir = tempfile::tempdir().unwrap();
629 let store = enrolled(dir.path(), &["session_ref"]);
633 assert!(!announced(&store));
634 assert!(status(&store, &CloudConfig::default(), now()).is_empty());
635 assert!(!store.data_dir().join(USAGE_FILE).exists());
636 let store = enrolled(dir.path(), &[FEATURE_USAGE]);
638 assert!(announced(&store));
639 let lines = status(&store, &CloudConfig::default(), now());
640 assert_eq!(lines.len(), 1, "{lines:?}");
641 assert!(
642 lines[0].starts_with("Usage: not read now ("),
643 "{lines:?}"
644 );
645 }
646}