Skip to main content

lean_ctx_cloud/
usage.rs

1// SPDX-License-Identifier: Apache-2.0
2//! LeanCTX Cloud usage (`GET /v1/usage`): how far each quota of the
3//! workspace is used, so this machine warns at 80 % instead of meeting a
4//! refusal.
5//!
6//! Read only from a server that announced the `usage` capability
7//! ([`FEATURE_USAGE`], cached by [`crate::session_ref`]); an older server
8//! gets no request and nothing here prints anything.
9//!
10//! - `lean-ctx cloud status` shows every quota as "used of limit" (GiB for
11//!   bytes, $ for model credit, counts otherwise), `warn` and `full` marked
12//!   with the service's next step ([`status_lines`]).
13//! - The background sync reads it at most every [`REFRESH_EVERY`] and logs
14//!   one line when a quota rises to `warn` or `full` ([`rises`]); the states
15//!   it last logged are kept in `<data>/usage.json`, so neither the next
16//!   tick nor a restart repeats the line.
17
18use 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::{FREE_CONNECTED, FREE_REGISTERED, NextStep, amount_text, quota_label};
31use crate::gateway::BALANCE_RESOURCE;
32use crate::state::{CloudStore, write_private};
33
34/// The last answer and the states already logged.
35const USAGE_FILE: &str = "usage.json";
36
37/// How often the background sync asks (a status asks every time).
38pub const REFRESH_EVERY: Duration = Duration::from_mins(10);
39
40/// The quotas in the order the Plan page shows them; others follow by name.
41const 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
51/// Width of the label column of the status lines ("hosts connected at
52/// once" and a space).
53const LABEL_WIDTH: usize = 24;
54
55#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
56#[serde(default)]
57struct Cache {
58    /// The origin that answered; another enrolled server reads none of it.
59    server: String,
60    /// When [`Self::usage`] was read.
61    fetched_at: Option<String>,
62    /// When the background sync last asked, answered or not.
63    tried_at: Option<String>,
64    usage: Option<CloudUsageV1>,
65    /// Per resource, the state the background sync last saw.
66    logged: BTreeMap<String, CloudQuotaStateV1>,
67}
68
69fn load(store: &CloudStore) -> Cache {
70    std::fs::read(store.data_dir().join(USAGE_FILE))
71        .ok()
72        .and_then(|b| serde_json::from_slice(&b).ok())
73        .unwrap_or_default()
74}
75
76fn save(store: &CloudStore, cache: &Cache) {
77    if let Ok(bytes) = serde_json::to_vec_pretty(cache) {
78        let _ = write_private(store.data_dir(), USAGE_FILE, &bytes);
79    }
80}
81
82/// The cache of `server`; another server's starts empty.
83fn load_for(store: &CloudStore, server: &str) -> Cache {
84    let cache = load(store);
85    if cache.server == server {
86        cache
87    } else {
88        Cache {
89            server: server.to_string(),
90            ..Cache::default()
91        }
92    }
93}
94
95fn stamp(at: UtcDateTime) -> String {
96    at.to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true)
97}
98
99/// Whether the enrolled server announced `usage` when last asked.
100#[must_use]
101pub fn announced(store: &CloudStore) -> bool {
102    crate::session_ref::announced(store, FEATURE_USAGE)
103}
104
105/// Read `GET /v1/usage`; `None` without the capability (no request).
106pub fn fetch(session: &Session) -> Result<Option<CloudUsageV1>, CloudError> {
107    if !announced(&session.store) {
108        return Ok(None);
109    }
110    let answer = session.with_client(|client| client.get("/usage"))?;
111    decode(answer).map(Some)
112}
113
114fn decode(answer: serde_json::Value) -> Result<CloudUsageV1, CloudError> {
115    let usage: CloudUsageV1 =
116        serde_json::from_value(answer).map_err(|e| CloudError::Protocol(format!("usage: {e}")))?;
117    usage
118        .validate()
119        .map_err(|e| CloudError::Protocol(format!("usage: {e}")))?;
120    Ok(usage)
121}
122
123// ---------------------------------------------------------------------------
124// Background sync: one line per rise.
125
126/// The background sync's look at the usage: at most every
127/// [`REFRESH_EVERY`], only with the capability; logs each quota that rose to
128/// `warn` or `full` since the last look, once.
129pub(crate) fn background(session: &Session, now: UtcDateTime) {
130    if !announced(&session.store) {
131        return;
132    }
133    let store = &session.store;
134    let mut cache = load_for(store, &session.instance.url);
135    if !due(cache.tried_at.as_deref(), now) {
136        return;
137    }
138    cache.tried_at = Some(stamp(now));
139    match fetch(session) {
140        Ok(Some(usage)) => {
141            for line in note(&mut cache, usage, now) {
142                tracing::warn!("{line}");
143            }
144        }
145        Ok(None) => {}
146        Err(error) => tracing::debug!("cloud: usage not read: {error}"),
147    }
148    save(store, &cache);
149}
150
151/// Whether [`REFRESH_EVERY`] passed since `tried_at` (or it never ran).
152fn due(tried_at: Option<&str>, now: UtcDateTime) -> bool {
153    tried_at
154        .and_then(|t| UtcDateTime::parse_from_rfc3339(t).ok())
155        .is_none_or(|at| {
156            (now - at)
157                .to_std()
158                .map_or(true, |since| since >= REFRESH_EVERY)
159        })
160}
161
162/// Take a fresh answer into `cache`: the lines of the quotas that rose, and
163/// the states seen now as the new baseline. The baseline holds the quotas
164/// [`ordered`] shows, no others: a model credit hidden at $0 that later gets
165/// a balance and is used up is said then, not taken as already seen.
166fn note(cache: &mut Cache, usage: CloudUsageV1, now: UtcDateTime) -> Vec<String> {
167    let lines = rises(&cache.logged, &usage);
168    cache.logged = ordered(&usage)
169        .map(|(r, q)| (r.to_owned(), q.state))
170        .collect();
171    cache.usage = Some(usage);
172    cache.fetched_at = Some(stamp(now));
173    lines
174}
175
176/// One line per quota now at `warn` or `full` whose state was lower when
177/// last seen (`seen`): a state change, never a repeat. A quota that falls
178/// back and rises again is said again.
179#[must_use]
180pub fn rises(seen: &BTreeMap<String, CloudQuotaStateV1>, usage: &CloudUsageV1) -> Vec<String> {
181    ordered(usage)
182        .filter(|(r, q)| q.state.level() > seen.get(*r).map_or(0, |s| s.level()))
183        .map(|(r, q)| rise_line(r, q))
184        .collect()
185}
186
187/// The log line of a quota that reached `warn` or `full`, worded like the
188/// refusal it comes before.
189#[must_use]
190pub fn rise_line(resource: &str, q: &CloudQuotaV1) -> String {
191    let what = quota_label(resource);
192    if is_host_count(resource) {
193        return host_rise_line(what, resource, q);
194    }
195    let amounts = format!(
196        "{} of {}",
197        amount_text(resource, q.used),
198        amount_text(resource, q.limit)
199    );
200    let mut line = if q.state == CloudQuotaStateV1::Full {
201        format!(
202            "LeanCTX Cloud: all of your {what} is used ({amounts}); nothing is charged for more"
203        )
204    } else {
205        format!(
206            "LeanCTX Cloud: {} % of your {what} is used ({amounts})",
207            percent(q)
208        )
209    };
210    if let Some(at) = reset_text(q) {
211        line.push_str(&format!("; it frees at {at}"));
212    }
213    if let Some(hint) = hint(q) {
214        line.push_str("; ");
215        line.push_str(hint);
216    }
217    line
218}
219
220/// The two host counts (rc4-58): registered, and connected at once.
221fn is_host_count(resource: &str) -> bool {
222    matches!(resource, "registered_instances" | "connected_instances")
223}
224
225/// The rise of a host count, worded like the status line: "hosts
226/// registered 3 of 3: all in use; …".
227fn host_rise_line(what: &str, resource: &str, q: &CloudQuotaV1) -> String {
228    let head = format!("{what} {} of {}", q.used, q.limit);
229    if q.state == CloudQuotaStateV1::Full {
230        format!(
231            "{head}: all in use; nothing is charged for more{}",
232            host_full_tail(resource, q)
233        )
234    } else {
235        let mut line = format!("{head}: {} % in use", percent(q));
236        if let Some(hint) = hint(q) {
237            line.push_str("; ");
238            line.push_str(hint);
239        }
240        line
241    }
242}
243
244/// What a full host count says after "FULL" (rc4-62): when the next
245/// registration frees, how to free one now, and the service's next step.
246fn host_full_tail(resource: &str, q: &CloudQuotaV1) -> String {
247    let mut tail = String::new();
248    if resource == "registered_instances" {
249        if let Some(at) = reset_text(q) {
250            tail.push_str(&format!("; the next registration frees at {at}"));
251        }
252        tail.push_str("; ");
253        tail.push_str(FREE_REGISTERED);
254    } else {
255        tail.push_str("; ");
256        tail.push_str(FREE_CONNECTED);
257    }
258    if let Some(hint) = hint(q) {
259        tail.push_str("; ");
260        tail.push_str(hint);
261    }
262    tail
263}
264
265// ---------------------------------------------------------------------------
266// `lean-ctx cloud status`.
267
268/// The `Usage:` lines of `lean-ctx cloud status`: read now when the server
269/// announced `usage` (the last answer, dated, when that fails); nothing at
270/// all without the capability.
271pub fn status(store: &CloudStore, config: &CloudConfig, now: UtcDateTime) -> Vec<String> {
272    if !announced(store) || !matches!(store.instance(), Ok(Some(_))) {
273        return Vec::new();
274    }
275    match read(store, config, now) {
276        Ok(Some(r)) if r.live => status_lines(&r.usage, None),
277        Ok(Some(r)) => status_lines(&r.usage, r.as_of.as_deref()),
278        Ok(None) => Vec::new(),
279        Err(error) => vec![format!(
280            "Usage:        not read now ({})",
281            why_not_read(&error)
282        )],
283    }
284}
285
286/// Why usage could not be read, in the words of `cloud status` (the
287/// [`CloudError`] Display text names the service by its old name).
288fn why_not_read(error: &CloudError) -> &'static str {
289    match error {
290        CloudError::Offline(_) => "LeanCTX Cloud did not answer",
291        CloudError::NotConnected => "this machine is not connected; run `lean-ctx cloud connect`",
292        CloudError::Unauthorized | CloudError::LeaseLapsed | CloudError::Revoked(_) => {
293            "LeanCTX Cloud no longer accepts this machine; run `lean-ctx cloud connect` again"
294        }
295        CloudError::Forbidden | CloudError::PlanRequired(_) => {
296            "your role or plan does not show usage"
297        }
298        _ if error.is_transient() => "LeanCTX Cloud is busy; try again shortly",
299        _ => "LeanCTX Cloud refused the request",
300    }
301}
302
303/// A usage answer and when it was read.
304#[derive(Debug, Clone, PartialEq)]
305pub struct UsageRead {
306    pub usage: CloudUsageV1,
307    /// When the answer was read (RFC 3339).
308    pub as_of: Option<String>,
309    /// Read just now (`false`: the last answer; the server did not answer).
310    pub live: bool,
311}
312
313/// The usage for a reader (`lean-ctx cloud status`, `cloud usage --json`):
314/// read now, else the last answer of this server. `None` when the server
315/// did not announce `usage` (no request is sent).
316pub fn read(
317    store: &CloudStore,
318    config: &CloudConfig,
319    now: UtcDateTime,
320) -> Result<Option<UsageRead>, CloudError> {
321    if !announced(store) {
322        return Ok(None);
323    }
324    let instance = store.instance()?.ok_or(CloudError::NotConnected)?;
325    let live = crate::scheduler::connected_session(store, config).and_then(|s| fetch(&s));
326    let mut cache = load_for(store, &instance.url);
327    match live {
328        Ok(Some(usage)) => {
329            // The background sync's baseline (`logged`) stays its own.
330            cache.usage = Some(usage.clone());
331            cache.fetched_at = Some(stamp(now));
332            save(store, &cache);
333            Ok(Some(UsageRead {
334                usage,
335                as_of: cache.fetched_at,
336                live: true,
337            }))
338        }
339        Ok(None) => Ok(None),
340        Err(error) => match cache.usage {
341            Some(usage) => Ok(Some(UsageRead {
342                usage,
343                as_of: cache.fetched_at,
344                live: false,
345            })),
346            None => Err(error),
347        },
348    }
349}
350
351/// The status lines of `usage`; `as_of` dates an answer that was not read
352/// just now.
353#[must_use]
354pub fn status_lines(usage: &CloudUsageV1, as_of: Option<&str>) -> Vec<String> {
355    let plan = match usage.plan.as_str() {
356        "personal" => "Personal",
357        "team" => "Team",
358        "enterprise" => "Enterprise",
359        _ => "no plan",
360    };
361    let mut head = format!("Usage:        LeanCTX Cloud, {plan}");
362    if usage.read_only || usage.plan == "locked" {
363        head.push_str(" (read and export only)");
364    }
365    if let Some(at) = as_of {
366        head.push_str(&format!(" (as of {at})"));
367    }
368    let mut lines = vec![head];
369    lines.extend(ordered(usage).map(|(r, q)| quota_line(r, q)));
370    lines
371}
372
373/// One quota: `  storage   34 GiB of 40 GiB · warn (85 %); <next step>`.
374#[must_use]
375pub fn quota_line(resource: &str, q: &CloudQuotaV1) -> String {
376    let mut line = format!(
377        "  {:<LABEL_WIDTH$}{} of {}",
378        quota_label(resource),
379        amount_text(resource, q.used),
380        amount_text(resource, q.limit)
381    );
382    match q.state {
383        CloudQuotaStateV1::Full if is_host_count(resource) => {
384            line.push_str(" · FULL");
385            line.push_str(&host_full_tail(resource, q));
386            return line;
387        }
388        CloudQuotaStateV1::Full => {
389            line.push_str(" · FULL");
390            if let Some(at) = reset_text(q) {
391                line.push_str(&format!(" until {at}"));
392            }
393        }
394        CloudQuotaStateV1::Warn => line.push_str(&format!(" · warn ({} %)", percent(q))),
395        CloudQuotaStateV1::Ok | CloudQuotaStateV1::Unknown => return line,
396    }
397    if let Some(hint) = hint(q) {
398        line.push_str("; ");
399        line.push_str(hint);
400    }
401    line
402}
403
404/// The quotas in Plan page order, unknown resources after them by name.
405/// A model credit with limit $0 (no balance, e.g. a Personal trial that uses
406/// its own model access) is no quota to show or warn about: it would read as
407/// "$0.00 of $0.00 · FULL". That holds even when the answer reports use
408/// against it (`used > 0`): without a balance there is nothing to run out of.
409fn ordered(usage: &CloudUsageV1) -> impl Iterator<Item = (&str, &CloudQuotaV1)> {
410    let known = ORDER.iter().filter_map(|r| usage.quotas.get_key_value(*r));
411    let rest = usage
412        .quotas
413        .iter()
414        .filter(|(r, _)| !ORDER.contains(&r.as_str()));
415    known
416        .chain(rest)
417        .map(|(r, q)| (r.as_str(), q))
418        .filter(|(r, q)| !(*r == BALANCE_RESOURCE && q.limit == 0))
419}
420
421/// Used of limit in whole percent, rounded down (a zero limit is full).
422fn percent(q: &CloudQuotaV1) -> u128 {
423    if q.limit == 0 {
424        return 100;
425    }
426    u128::from(q.used) * 100 / u128::from(q.limit)
427}
428
429/// The service's next step as the refusal words it (`wait` adds none).
430fn hint(q: &CloudQuotaV1) -> Option<&'static str> {
431    NextStep::of_wire(q.next_step.as_deref()).and_then(NextStep::hint)
432}
433
434/// `reset_at` of a full or warned quota, when it is a timestamp.
435fn reset_text(q: &CloudQuotaV1) -> Option<String> {
436    let at = UtcDateTime::parse_from_rfc3339(q.reset_at.as_deref()?).ok()?;
437    Some(stamp(at))
438}
439
440#[cfg(test)]
441mod tests {
442    use super::*;
443    use serde_json::json;
444
445    #[test]
446    fn order_lists_the_balance_resource_from_the_gateway() {
447        assert!(ORDER.contains(&BALANCE_RESOURCE));
448        assert_eq!(BALANCE_RESOURCE, "model_credit_usd_micros");
449    }
450
451    fn fixture() -> serde_json::Value {
452        serde_json::from_str(include_str!(
453            "../../lean-ctx-protocol/tests/fixtures/cloud/usage.response.json"
454        ))
455        .unwrap()
456    }
457
458    fn usage() -> CloudUsageV1 {
459        decode(fixture()).unwrap()
460    }
461
462    fn now() -> UtcDateTime {
463        UtcDateTime::parse_from_rfc3339("2026-11-17T12:00:00Z").unwrap()
464    }
465
466    fn enrolled(dir: &std::path::Path, features: &[&str]) -> CloudStore {
467        let store = CloudStore::at(dir.join("config"), dir.join("cloud"));
468        let instance: crate::state::InstanceRecord = serde_json::from_value(json!({
469            "instance_id": "inst_1", "org_id": "org_acme", "org_name": "Platform",
470            "label": "laptop", "url": "https://cloud.example", "org_salt_id": "salt",
471            "enrolled_at": "2026-11-16T12:00:00Z"
472        }))
473        .unwrap();
474        store
475            .write_config(crate::state::INSTANCE_FILE, &instance)
476            .unwrap();
477        crate::session_ref::record(
478            &store,
479            "https://cloud.example",
480            features.iter().map(|f| (*f).to_string()).collect(),
481        )
482        .unwrap();
483        store
484    }
485
486    #[test]
487    fn status_shows_every_quota_in_its_unit_with_warn_and_full_marked() {
488        let lines = status_lines(&usage(), None);
489        assert_eq!(
490            lines,
491            [
492                "Usage:        LeanCTX Cloud, Personal",
493                "  storage                 34 GiB of 40 GiB · warn (85 %); Team gives every seat its own allowance",
494                "  monthly transfer        40 GiB of 40 GiB · FULL until 2026-12-01T00:00:00Z; Team gives every seat its own allowance",
495                "  monthly bus messages    1200 of 200000",
496                "  model credit            $1.25 of $8.00",
497                "  private vaults          3 of 20",
498                "  hosts registered        2 of 3",
499                "  hosts connected at once 1 of 2",
500            ]
501        );
502        for line in &lines {
503            for word in ["engine", "Queen", "workspace", "instance", "slot"] {
504                assert!(!line.contains(word), "{line}");
505            }
506        }
507    }
508
509    #[test]
510    fn a_model_credit_of_nothing_is_neither_shown_nor_warned() {
511        let mut raw = fixture();
512        raw["quotas"]["model_credit_usd_micros"] =
513            json!({"limit": 0, "used": 0, "state": "full", "next_step": "top_up"});
514        let usage = decode(raw).unwrap();
515        let lines = status_lines(&usage, None);
516        assert!(
517            lines.iter().all(|l| !l.contains("model credit")),
518            "{lines:?}"
519        );
520        assert_eq!(lines.len(), 7, "{lines:?}");
521        let rises = rises(&BTreeMap::new(), &usage);
522        assert!(
523            rises.iter().all(|l| !l.contains("model credit")),
524            "{rises:?}"
525        );
526    }
527
528    #[test]
529    fn a_model_credit_without_balance_stays_hidden_with_use_reported() {
530        let mut raw = fixture();
531        raw["quotas"]["model_credit_usd_micros"] =
532            json!({"limit": 0, "used": 1_250_000, "state": "full", "next_step": "top_up"});
533        let usage = decode(raw).unwrap();
534        let lines = status_lines(&usage, None);
535        assert!(
536            lines.iter().all(|l| !l.contains("model credit")),
537            "{lines:?}"
538        );
539        assert!(
540            rises(&BTreeMap::new(), &usage)
541                .iter()
542                .all(|l| !l.contains("model credit"))
543        );
544    }
545
546    #[test]
547    fn a_model_credit_that_gets_a_balance_and_runs_out_is_said_then() {
548        let mut cache = Cache::default();
549        let mut raw = fixture();
550        raw["quotas"]["model_credit_usd_micros"] =
551            json!({"limit": 0, "used": 0, "state": "full", "next_step": "top_up"});
552        let first = note(&mut cache, decode(raw.clone()).unwrap(), now());
553        assert!(
554            first.iter().all(|l| !l.contains("model credit")),
555            "{first:?}"
556        );
557        assert!(
558            !cache.logged.contains_key(BALANCE_RESOURCE),
559            "a hidden quota is no baseline"
560        );
561        // A top-up of $8.00, all used: the first time the credit can run out.
562        raw["quotas"]["model_credit_usd_micros"] =
563            json!({"limit": 8_000_000, "used": 8_000_000, "state": "full", "next_step": "top_up"});
564        let topped = note(&mut cache, decode(raw).unwrap(), now());
565        assert_eq!(
566            topped
567                .iter()
568                .filter(|l| l.contains("all of your model credit is used ($8.00 of $8.00)"))
569                .count(),
570            1,
571            "{topped:?}"
572        );
573    }
574
575    #[test]
576    fn a_locked_or_cached_answer_says_so_and_unknown_resources_follow() {
577        let mut raw = fixture();
578        raw["plan"] = "locked".into();
579        raw["read_only"] = true.into();
580        raw["quotas"]["agent_seats"] = json!({"limit": 4, "used": 4, "state": "full",
581                                              "next_step": "contact", "reset_at": "soon"});
582        let lines = status_lines(&decode(raw).unwrap(), Some("2026-11-17T11:00:00Z"));
583        assert_eq!(
584            lines[0],
585            "Usage:        LeanCTX Cloud, no plan (read and export only) (as of 2026-11-17T11:00:00Z)"
586        );
587        // A reset that is no timestamp is left out.
588        assert_eq!(
589            lines.last().unwrap(),
590            "  agent_seats             4 of 4 · FULL; contact us to extend your Enterprise contract"
591        );
592    }
593
594    #[test]
595    fn a_rise_is_logged_once_and_again_only_after_falling_back() {
596        let mut cache = Cache::default();
597        let first = note(&mut cache, usage(), now());
598        assert_eq!(
599            first,
600            [
601                "LeanCTX Cloud: 85 % of your storage is used (34 GiB of 40 GiB); Team gives every seat its own allowance",
602                "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",
603            ]
604        );
605        for line in &first {
606            for word in ["workspace", "engine", "Queen"] {
607                assert!(!line.contains(word), "{word} in {line}");
608            }
609        }
610        // The next tick with the same states: nothing.
611        assert!(note(&mut cache, usage(), now()).is_empty());
612        // Storage warn → full: one line; transfer stays full: none.
613        let mut raw = fixture();
614        raw["quotas"]["storage_bytes"]["used"] = (40_u64 << 30).into();
615        raw["quotas"]["storage_bytes"]["state"] = "full".into();
616        let full = note(&mut cache, decode(raw.clone()).unwrap(), now());
617        assert_eq!(
618            full,
619            [
620                "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"
621            ]
622        );
623        // Falling back says nothing; rising again says it again.
624        raw["quotas"]["storage_bytes"]["state"] = "ok".into();
625        raw["quotas"]["transfer_bytes"]["state"] = "ok".into();
626        assert!(note(&mut cache, decode(raw).unwrap(), now()).is_empty());
627        assert_eq!(note(&mut cache, usage(), now()).len(), 2);
628    }
629
630    #[test]
631    fn model_credit_and_counts_keep_their_units_in_a_rise() {
632        let credit = CloudQuotaV1 {
633            limit: 8_000_000,
634            used: 6_500_000,
635            reset_at: Some("2026-12-01T00:00:00Z".into()),
636            state: CloudQuotaStateV1::Warn,
637            next_step: Some("top_up".into()),
638        };
639        assert_eq!(
640            rise_line("model_credit_usd_micros", &credit),
641            "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"
642        );
643        let seats = CloudQuotaV1 {
644            limit: 4,
645            used: 4,
646            reset_at: None,
647            state: CloudQuotaStateV1::Full,
648            next_step: Some("add_seats".into()),
649        };
650        assert_eq!(
651            quota_line("connected_instances", &seats),
652            "  hosts connected at once 4 of 4 · FULL; to free one, disconnect a host (`lean-ctx cloud disconnect` on that machine); every seat you add in LeanCTX Cloud brings its own allowance"
653        );
654    }
655
656    /// rc4-58/rc4-62: the registered count says "hosts registered U of L",
657    /// when the next registration frees and how to free one, in the status
658    /// line and in the rise alike; no "instance" or "slot" count.
659    #[test]
660    fn host_counts_read_as_the_web_names_them() {
661        let registered = CloudQuotaV1 {
662            limit: 3,
663            used: 3,
664            reset_at: Some("2026-12-01T00:00:00Z".into()),
665            state: CloudQuotaStateV1::Full,
666            next_step: Some("upgrade_team".into()),
667        };
668        assert_eq!(
669            quota_line("registered_instances", &registered),
670            "  hosts registered        3 of 3 · FULL; the next registration frees at 2026-12-01T00:00:00Z; \
671             to free one, revoke a host you no longer use on the Hosts page; Team gives every seat its own allowance"
672        );
673        assert_eq!(
674            rise_line("registered_instances", &registered),
675            "hosts registered 3 of 3: all in use; nothing is charged for more; the next registration frees \
676             at 2026-12-01T00:00:00Z; to free one, revoke a host you no longer use on the Hosts page; \
677             Team gives every seat its own allowance"
678        );
679        let connected = CloudQuotaV1 {
680            limit: 2,
681            used: 2,
682            reset_at: None,
683            state: CloudQuotaStateV1::Full,
684            next_step: None,
685        };
686        assert_eq!(
687            rise_line("connected_instances", &connected),
688            "hosts connected at once 2 of 2: all in use; nothing is charged for more; \
689             to free one, disconnect a host (`lean-ctx cloud disconnect` on that machine)"
690        );
691        let warn = CloudQuotaV1 {
692            used: 1,
693            state: CloudQuotaStateV1::Warn,
694            ..connected
695        };
696        assert_eq!(
697            rise_line("connected_instances", &warn),
698            "hosts connected at once 1 of 2: 50 % in use"
699        );
700        for line in [
701            quota_line("registered_instances", &registered),
702            rise_line("registered_instances", &registered),
703            rise_line("connected_instances", &warn),
704        ] {
705            // Counts only: "slot" stays for the web's "Recover the slot now".
706            for word in ["instance", "slot", "seat is free"] {
707                assert!(!line.contains(word), "{word} in {line}");
708            }
709        }
710    }
711
712    #[test]
713    fn the_cache_survives_a_restart_and_another_server_starts_empty() {
714        let dir = tempfile::tempdir().unwrap();
715        let store = enrolled(dir.path(), &[FEATURE_USAGE]);
716        let mut cache = load_for(&store, "https://cloud.example");
717        assert!(!note(&mut cache, usage(), now()).is_empty());
718        save(&store, &cache);
719        let mut again = load_for(&store, "https://cloud.example");
720        assert!(
721            note(&mut again, usage(), now()).is_empty(),
722            "no repeat after a restart"
723        );
724        let other = load_for(&store, "https://other.example");
725        assert!(other.logged.is_empty() && other.usage.is_none());
726    }
727
728    #[test]
729    fn the_background_look_is_spaced() {
730        assert!(due(None, now()));
731        assert!(!due(Some("2026-11-17T11:55:00Z"), now()));
732        assert!(due(Some("2026-11-17T11:50:00Z"), now()));
733        assert!(due(Some("garbage"), now()));
734    }
735
736    #[test]
737    fn an_older_server_gets_no_request_and_no_status_lines() {
738        let dir = tempfile::tempdir().unwrap();
739        // Enrolled with a server that announced only `session_ref`: the
740        // status neither asks nor prints (a request would fail: there is no
741        // lease, so no session can be built at all).
742        let store = enrolled(dir.path(), &["session_ref"]);
743        assert!(!announced(&store));
744        assert!(status(&store, &CloudConfig::default(), now()).is_empty());
745        assert!(!store.data_dir().join(USAGE_FILE).exists());
746        // Announced but not reachable: one line that says why, no cache.
747        let store = enrolled(dir.path(), &[FEATURE_USAGE]);
748        assert!(announced(&store));
749        let lines = status(&store, &CloudConfig::default(), now());
750        assert_eq!(lines.len(), 1, "{lines:?}");
751        assert!(
752            lines[0].starts_with("Usage:        not read now ("),
753            "{lines:?}"
754        );
755    }
756}