1use std::fmt;
6
7use lean_ctx_protocol::cloud::lease::CloudPlan;
8use lean_ctx_protocol::cloud::{
9 CloudErrorBody, CloudErrorCode, CloudErrorDetailV1, CloudUploadKind,
10};
11
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub enum CloudError {
14 Offline(String),
16 NotConnected,
18 Unauthorized,
20 PlanRequired(Box<PlanNeed>),
23 InstanceLimit(Box<InstanceCap>),
26 QuotaExceeded(Box<Quota>),
30 StorageFull(Box<StorageFull>),
34 UploadRateLimited {
38 retry_after: Option<u64>,
39 per_hour: Option<u64>,
41 },
42 PolicyDenied(PolicyDenial),
45 LeaseLapsed,
47 Revoked(Revocation),
51 Forbidden,
53 Vetoed,
56 UploadDisabled(CloudUploadKind),
59 FeatureDisabled {
63 feature: Option<String>,
64 },
65 NotFound,
66 Conflict {
67 expected: Option<u64>,
68 actual: Option<u64>,
69 },
70 ScreeningBlocked,
71 UpgradeRequired {
72 min: Option<String>,
73 },
74 RateLimited {
75 retry_after: Option<u64>,
76 },
77 DeviceFlow(String),
79 TrialUnsupported {
83 origin: String,
85 },
86 Protocol(String),
89 Config(String),
91 Local(String),
93 Refused(String),
96 Task {
98 refusal: TaskRefusal,
99 number: Option<u64>,
100 detail: Option<String>,
102 },
103 Server {
105 status: u16,
106 code: String,
107 },
108}
109
110#[derive(Debug, Clone, PartialEq, Eq)]
112pub struct Quota {
113 pub status: u16,
115 pub resource: String,
118 pub limit: Option<u64>,
119 pub used: Option<u64>,
120 pub reset_at: Option<String>,
122 pub retry_after: Option<u64>,
124 pub cooldown_days: Option<u32>,
126 pub next_step: Option<NextStep>,
128}
129
130#[derive(Debug, Clone, PartialEq, Eq, Default)]
132pub struct InstanceCap {
133 pub resource: Option<String>,
136 pub limit: Option<u64>,
137 pub used: Option<u64>,
138 pub seats: Option<u64>,
140 pub per_seat: Option<u64>,
141 pub next_step: Option<NextStep>,
142}
143
144#[derive(Debug, Clone, PartialEq, Eq, Default)]
146pub struct StorageFull {
147 pub limit: Option<u64>,
148 pub used: Option<u64>,
149 pub next_step: Option<NextStep>,
150}
151
152#[derive(Debug, Clone, Copy, PartialEq, Eq)]
154pub enum NextStep {
155 Subscribe,
156 TopUp,
157 UpgradeTeam,
158 AddSeats,
159 Contact,
160 Wait,
161}
162
163impl NextStep {
164 #[must_use]
166 pub fn of_wire(value: Option<&str>) -> Option<Self> {
167 Some(match value? {
168 "subscribe" => Self::Subscribe,
169 "top_up" => Self::TopUp,
170 "upgrade_team" => Self::UpgradeTeam,
171 "add_seats" => Self::AddSeats,
172 "contact" => Self::Contact,
173 "wait" => Self::Wait,
174 _ => return None,
175 })
176 }
177
178 #[must_use]
181 pub fn hint(self) -> Option<&'static str> {
182 Some(match self {
183 Self::Subscribe => "choose a plan in LeanCTX Cloud",
184 Self::TopUp => "a top-up in LeanCTX Cloud adds more",
185 Self::UpgradeTeam => "Team gives every seat its own allowance",
186 Self::AddSeats => "every seat you add in LeanCTX Cloud brings its own allowance",
187 Self::Contact => "contact us to extend your Enterprise contract",
188 Self::Wait => return None,
189 })
190 }
191}
192
193fn write_hint(f: &mut fmt::Formatter<'_>, next: Option<NextStep>) -> fmt::Result {
195 match next.and_then(NextStep::hint) {
196 Some(hint) => write!(f, "; {hint}"),
197 None => Ok(()),
198 }
199}
200
201fn bytes_text(bytes: u64) -> String {
203 const UNITS: [(&str, u64); 4] = [
204 ("TiB", 1 << 40),
205 ("GiB", 1 << 30),
206 ("MiB", 1 << 20),
207 ("KiB", 1 << 10),
208 ];
209 for (unit, size) in UNITS {
210 if bytes >= size {
211 let tenths = u128::from(bytes) * 10 / u128::from(size);
212 return if tenths % 10 == 0 {
213 format!("{} {unit}", tenths / 10)
214 } else {
215 format!("{}.{} {unit}", tenths / 10, tenths % 10)
216 };
217 }
218 }
219 format!("{bytes} B")
220}
221
222#[must_use]
225pub fn amount_text(resource: &str, value: u64) -> String {
226 if resource.ends_with("_bytes") {
227 bytes_text(value)
228 } else if resource.ends_with("_usd_micros") {
229 format!("${}.{:02}", value / 1_000_000, value % 1_000_000 / 10_000)
230 } else {
231 value.to_string()
232 }
233}
234
235#[derive(Debug, Clone, PartialEq, Eq, Default)]
237pub struct PlanNeed {
238 pub feature: Option<String>,
241 pub plan_needed: Option<String>,
243 pub limit: Option<u64>,
245 pub used: Option<u64>,
246 pub message: Option<String>,
248 pub plan: Option<CloudPlan>,
251 pub reason: Option<String>,
255 pub next_step: Option<NextStep>,
257 pub plans_url: Option<String>,
260 pub trial_reason: Option<String>,
263}
264
265pub const LOCKED_MARK: &str = "this workspace is locked (read and export only)";
268
269pub const PLAN_LIMITS: &str = "Personal up to 3 hosts registered, up to 2 connected at once; Team and Enterprise up to 3 hosts registered, up to 2 connected at once per seat";
273
274pub const HOSTS_REGISTERED: &str = "hosts registered";
277
278pub const HOSTS_CONNECTED: &str = "hosts connected at once";
281
282pub const FREE_REGISTERED: &str = "to free one, revoke a host you no longer use on the Hosts page";
285
286pub const FREE_CONNECTED: &str =
288 "to free one, disconnect a host (`lean-ctx cloud disconnect` on that machine)";
289
290impl PlanNeed {
291 #[must_use]
293 pub fn locked(&self) -> Option<&str> {
294 self.reason
295 .as_deref()
296 .filter(|r| matches!(*r, "trial_ended" | "plan_ended"))
297 }
298
299 #[must_use]
301 pub fn trial_used(&self) -> bool {
302 self.reason.as_deref() == Some(TRIAL_USED)
303 }
304
305 fn plan_word(&self) -> &'static str {
307 let team = self.plan_needed.as_deref() == Some("team")
308 || matches!(self.plan, Some(CloudPlan::Team | CloudPlan::Enterprise));
309 if team { "Team" } else { "Personal" }
310 }
311}
312
313#[must_use]
315pub fn locked_line(reason: &str, plan_word: &str) -> String {
316 let what = if reason == "trial_ended" {
317 format!("Your {plan_word} trial has ended")
318 } else {
319 "Your plan has ended".to_string()
320 };
321 format!("{what}: {LOCKED_MARK}. Choose a plan in LeanCTX Cloud to sync again.")
322}
323
324fn plans_from(needed: &str) -> Option<&'static str> {
326 Some(match needed {
327 "personal" => "Personal, Team and Enterprise",
328 "team" => "Team and Enterprise",
329 "enterprise" => "Enterprise",
330 _ => return None,
331 })
332}
333
334fn write_plan_need(f: &mut fmt::Formatter<'_>, need: &PlanNeed) -> fmt::Result {
335 if need.trial_used() {
336 let plan = need.plan_word();
337 match need.trial_reason.as_deref() {
338 Some("trial_ended") => write!(
339 f,
340 "the {plan} trial of this address has ended; no second trial starts. Choose a plan"
341 )?,
342 Some("no_plan") => write!(
343 f,
344 "this address has no {plan} trial left and no plan; no second trial starts. Choose a plan"
345 )?,
346 _ => write!(
347 f,
348 "this address already had its {plan} trial; no second trial starts. Choose a plan"
349 )?,
350 }
351 return match need.plans_url.as_deref().filter(|u| u.starts_with("http")) {
352 Some(url) => write!(f, " at {url}, then run `lean-ctx cloud connect`"),
353 None => f.write_str(" in LeanCTX Cloud, then run `lean-ctx cloud connect`"),
354 };
355 }
356 if let Some(reason) = need.locked() {
358 return f.write_str(&locked_line(reason, need.plan_word()));
359 }
360 let Some(feature) = need.feature.as_deref() else {
361 return write!(
363 f,
364 "this workspace's plan does not include LeanCTX Cloud here ({PLAN_LIMITS})"
365 );
366 };
367 let plans = need.plan_needed.as_deref().and_then(plans_from);
368 let on = need
369 .plan
370 .filter(|p| *p != CloudPlan::Unknown)
371 .map(|p| match p {
372 CloudPlan::NoPlan => "; this workspace has no plan".to_string(),
373 p => format!("; this workspace is on {}", p.display_name()),
374 })
375 .unwrap_or_default();
376 match feature {
377 "repos" | "vaults" | "private_vaults" => {
378 f.write_str("this workspace has used all its vaults")?;
379 if let (Some(used), Some(limit)) = (need.used, need.limit) {
380 write!(f, " ({used} of {limit})")?;
381 }
382 if let Some(plans) = plans {
383 write!(f, "; more are included in {plans}")?;
384 }
385 write!(
386 f,
387 "{on}; remove or publish a vault in LeanCTX Cloud, or upgrade the plan"
388 )
389 }
390 other => {
391 match (&need.message, plans) {
392 (Some(message), _) => f.write_str(message.trim_end_matches('.'))?,
393 (None, Some(plans)) => {
394 write!(f, "{} is included in {plans}", other.replace('_', " "))?;
395 }
396 (None, None) => write!(
397 f,
398 "this workspace's plan does not include {}",
399 other.replace('_', " ")
400 )?,
401 }
402 f.write_str(&on)
403 }
404 }
405}
406
407pub const MONTHLY_RESOURCES: &[&str] =
409 &["transfer_bytes", "bus_messages", "model_credit_usd_micros"];
410
411impl Quota {
412 #[must_use]
414 pub fn waits(&self) -> bool {
415 self.status == 429 || MONTHLY_RESOURCES.contains(&self.resource.as_str())
416 }
417
418 #[must_use]
420 pub fn cooling_slot(&self) -> bool {
421 self.resource == "registered_instances"
422 && self.cooldown_days.is_some_and(|d| d > 0)
423 && self.reset_at.is_some()
424 }
425}
426
427#[derive(Debug, Clone, PartialEq, Eq, Default)]
429pub struct PolicyDenial {
430 pub member: Option<String>,
432 pub level: Option<String>,
434 pub action: Option<String>,
436}
437
438fn wire_token(value: Option<&str>, max: usize) -> Option<String> {
440 value
441 .filter(|s| {
442 (1..=max).contains(&s.len())
443 && s.bytes().all(|b| {
444 b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'_' | b'.' | b'-')
445 })
446 })
447 .map(str::to_string)
448}
449
450pub(crate) fn wire_time(value: Option<&str>) -> Option<String> {
452 let parsed = lean_ctx_time::OffsetDateTime::parse_from_rfc3339(value?).ok()?;
453 Some(
454 parsed
455 .to_utc()
456 .to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true),
457 )
458}
459
460pub const TRIAL_USED: &str = "trial_used";
462pub const NOT_READY: &str = "not_ready";
465pub const VAULT_CREATE_FORBIDDEN: &str = "vault_create_forbidden";
468
469fn web_url(value: Option<&str>) -> Option<String> {
475 value
476 .filter(|s| {
477 (s.starts_with("https://")
478 || s.starts_with("http://")
479 || (s.starts_with('/') && !s.starts_with("//")))
480 && s.len() <= 512
481 && !s.chars().any(hidden_in_url)
482 })
483 .map(str::to_string)
484}
485
486fn hidden_in_url(c: char) -> bool {
488 use unicode_general_category::{GeneralCategory, get_general_category};
489 c.is_control()
490 || c.is_whitespace()
491 || get_general_category(c) == GeneralCategory::Format
492 || lean_ctx_protocol::cloud::invisible(c)
493}
494
495fn same_origin(url: &str, base: &str) -> bool {
498 let Some(start) = url.find("://").map(|i| i + 3) else {
499 return false;
500 };
501 let end = url[start..]
502 .find(['/', '?', '#'])
503 .map_or(url.len(), |i| start + i);
504 url[..end].eq_ignore_ascii_case(base)
505}
506
507#[derive(Debug, Clone, PartialEq, Eq, Default)]
509pub struct Revocation {
510 pub workspace: Option<String>,
512 pub reason: Option<String>,
514 pub revoked_at: Option<u64>,
516 pub instance_id: Option<String>,
518}
519
520impl Revocation {
521 fn of_statement(statement: &serde_json::Value) -> Self {
524 let token = |v: &serde_json::Value, max: usize| {
525 v.as_str()
526 .filter(|s| {
527 (1..=max).contains(&s.len())
528 && s.bytes().all(|b| {
529 b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_' || b == b'-'
530 })
531 })
532 .map(str::to_string)
533 };
534 Self {
535 workspace: None,
536 reason: token(&statement["reason"], 32),
537 revoked_at: statement["revoked_at"].as_u64(),
538 instance_id: token(&statement["instance_id"], 36),
539 }
540 }
541}
542
543#[derive(Debug, Clone, Copy, PartialEq, Eq)]
545pub enum PermitCheck {
546 Presence,
548 Role,
550 Unknown,
552}
553
554#[derive(Debug, Clone, Copy, PartialEq, Eq)]
556pub enum TaskRefusal {
557 Claimed,
559 NotOpen,
561 StaleClaim,
563 Closed,
565 SelfVerify,
567 NotSubmitted,
569 NotPermitted(PermitCheck),
571 OptinScope,
574 OptinChanged,
577 OptinInactive,
580 DailyBudget { retry_after: Option<u64> },
583 StaleBase,
586 PersonUnproven,
589 SignatureExpired,
592}
593
594impl TaskRefusal {
595 fn from_reason(
596 code: CloudErrorCode,
597 reason: Option<&str>,
598 retry_after: Option<u64>,
599 check: Option<&str>,
600 ) -> Option<Self> {
601 Some(match (code, reason?) {
602 (CloudErrorCode::InvalidState, "task_claimed") => Self::Claimed,
603 (CloudErrorCode::InvalidState, "task_not_open") => Self::NotOpen,
604 (CloudErrorCode::InvalidState, "stale_claim") => Self::StaleClaim,
605 (CloudErrorCode::InvalidState, "task_closed") => Self::Closed,
606 (CloudErrorCode::ForbiddenRight, "self_verify") => Self::SelfVerify,
607 (CloudErrorCode::InvalidState, "not_submitted") => Self::NotSubmitted,
608 (CloudErrorCode::ForbiddenRight, "not_permitted") => Self::NotPermitted(match check {
609 Some("presence") => PermitCheck::Presence,
610 Some("role") => PermitCheck::Role,
611 _ => PermitCheck::Unknown,
612 }),
613 (CloudErrorCode::ForbiddenRight, "optin_scope") => Self::OptinScope,
614 (CloudErrorCode::ForbiddenRight, "person_unproven") => Self::PersonUnproven,
615 (CloudErrorCode::ForbiddenRight, "signature_expired") => Self::SignatureExpired,
616 (CloudErrorCode::InvalidState, "optin_changed") => Self::OptinChanged,
617 (CloudErrorCode::InvalidState, "optin_inactive") => Self::OptinInactive,
618 (CloudErrorCode::RateLimited, "daily_budget") => Self::DailyBudget { retry_after },
619 (CloudErrorCode::InvalidState | CloudErrorCode::RevisionConflict, "stale_base") => {
620 Self::StaleBase
621 }
622 _ => return None,
623 })
624 }
625
626 #[must_use]
629 pub fn ends_claim(self) -> bool {
630 matches!(self, Self::StaleClaim | Self::Closed | Self::OptinInactive)
631 }
632}
633
634impl fmt::Display for TaskRefusal {
635 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
636 match self {
637 Self::Claimed => f.write_str("another agent holds the task"),
638 Self::NotOpen => f.write_str("the task is not open"),
639 Self::StaleClaim => f.write_str("this claim is no longer the task's claim"),
640 Self::Closed => f.write_str("the task is closed"),
641 Self::SelfVerify => f.write_str(
642 "the agent that did the work does not check its own result; another agent verifies it",
643 ),
644 Self::NotSubmitted => f.write_str("the task has no result waiting for a check"),
645 Self::NotPermitted(PermitCheck::Presence) => f.write_str(
646 "this agent is not on the bus: its session (or the relay) must be running and announce it with the task's role",
647 ),
648 Self::NotPermitted(PermitCheck::Role) => {
649 f.write_str("this agent is on the bus in another role than the task needs")
650 }
651 Self::NotPermitted(PermitCheck::Unknown) => f.write_str(
652 "the task's role or the owner's worker consent does not allow this agent",
653 ),
654 Self::OptinScope => f.write_str("this instance's opt-in does not cover this vault"),
655 Self::OptinChanged => f.write_str("the opt-in changed; it is read again"),
656 Self::OptinInactive => f.write_str(
657 "this instance is not opted in (or the owner stopped worker mode on the web)",
658 ),
659 Self::StaleBase => f.write_str(
660 "the task's priority or labels changed meanwhile; read it again and retry",
661 ),
662 Self::PersonUnproven => f.write_str(
663 "the app's signature on this task did not check out; propose it again in the app",
664 ),
665 Self::SignatureExpired => f.write_str(
666 "the app's signature on this task is too old; propose it again in the app",
667 ),
668 Self::DailyBudget { retry_after } => match retry_after {
669 Some(s) => write!(f, "today's task budget is used up (resets in {s} s)"),
670 None => f.write_str("today's task budget is used up"),
671 },
672 }
673 }
674}
675
676fn bus_role(role: Option<&String>) -> Option<&str> {
679 role.map(String::as_str).filter(|r| {
680 (1..=64).contains(&r.len())
681 && r.bytes()
682 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
683 })
684}
685
686pub(crate) fn safe_message(message: &str) -> Option<String> {
689 let text: String = message
690 .chars()
691 .map(|c| if c.is_control() { ' ' } else { c })
692 .take(300)
693 .collect();
694 let text = text.trim();
695 (!text.is_empty()).then(|| text.to_string())
696}
697
698fn permit_line(refusal: TaskRefusal, detail: &CloudErrorDetailV1) -> Option<String> {
702 let TaskRefusal::NotPermitted(check) = refusal else {
703 return None;
704 };
705 let mut line =
706 safe_message(&detail.message).unwrap_or_else(|| match permit_roles(refusal, detail) {
707 Some(roles) => format!("{refusal} ({roles})"),
708 None => refusal.to_string(),
709 });
710 match check {
711 PermitCheck::Presence => line.push_str(
712 " [check: presence] Run `lean-ctx cloud bus relay --for 30`: it says who this machine announced, or why an agent is missing. LeanCTX Cloud keeps an agent present only while a relay stays connected (the daemon's), so claim while it runs.",
713 ),
714 PermitCheck::Role => line.push_str(" [check: role]"),
715 PermitCheck::Unknown => {}
716 }
717 Some(line)
718}
719
720fn permit_roles(refusal: TaskRefusal, detail: &CloudErrorDetailV1) -> Option<String> {
722 let role = bus_role(detail.role.as_ref())?;
723 match refusal {
724 TaskRefusal::NotPermitted(PermitCheck::Presence) => {
725 Some(format!("the task needs role {role}"))
726 }
727 TaskRefusal::NotPermitted(PermitCheck::Role) => {
728 Some(match bus_role(detail.agent_role.as_ref()) {
729 Some(agent_role) => {
730 format!("the agent works as {agent_role}, the task needs {role}")
731 }
732 None => format!("the task needs role {role}"),
733 })
734 }
735 _ => None,
736 }
737}
738
739fn lenient_u64(value: &serde_json::Value) -> Option<u64> {
741 value
742 .as_u64()
743 .or_else(|| value.as_str().and_then(|s| s.trim().parse().ok()))
744}
745
746fn lenient_detail(error: &serde_json::Value) -> Option<CloudErrorDetailV1> {
751 let object = error.as_object()?;
752 let code = object.get("code").filter(|c| c.is_string())?.clone();
753 let message = object
754 .get("message")
755 .filter(|m| m.is_string())
756 .cloned()
757 .unwrap_or_else(|| serde_json::Value::String(String::new()));
758 let base = || {
759 let mut kept = serde_json::Map::new();
760 kept.insert("code".into(), code.clone());
761 kept.insert("message".into(), message.clone());
762 kept
763 };
764 let decodes = |kept: &serde_json::Map<String, serde_json::Value>| {
765 serde_json::from_value::<CloudErrorDetailV1>(serde_json::Value::Object(kept.clone()))
766 .is_ok()
767 };
768 let mut kept = base();
769 for (name, value) in object {
770 if matches!(name.as_str(), "code" | "message") {
771 continue;
772 }
773 let candidates = [
774 Some(value.clone()),
775 lenient_u64(value).map(serde_json::Value::from),
776 ];
777 for candidate in candidates.into_iter().flatten() {
778 let mut probe = base();
779 probe.insert(name.clone(), candidate.clone());
780 if decodes(&probe) {
781 kept.insert(name.clone(), candidate);
782 break;
783 }
784 }
785 }
786 serde_json::from_value(serde_json::Value::Object(kept)).ok()
787}
788
789fn task_key_refusal(status: u16, body: &serde_json::Value) -> Option<String> {
793 let error = &body["error"];
794 let code = error["code"].as_str()?;
795 let reason = error["reason"].as_str();
796 match (status, code) {
797 (400, "invalid_field") if error["field"].as_str() == Some("task_propose_key") => {
798 Some(TASK_KEY_INVALID.into())
799 }
800 (409, "invalid_state") => reason
801 .filter(|r| matches!(*r, TASK_KEY_BOUND | TASK_KEY_CLEARED))
802 .map(str::to_owned),
803 _ => None,
804 }
805}
806
807fn optin_key_refusal(status: u16, body: &serde_json::Value) -> Option<String> {
811 let error = &body["error"];
812 let code = error["code"].as_str()?;
813 match (status, code) {
814 (400, "invalid_field")
815 if matches!(
816 error["field"].as_str(),
817 Some("optin_key" | "optin_key.bind_signature")
818 ) =>
819 {
820 Some(OPTIN_KEY_INVALID.into())
821 }
822 (409, _) => [code, error["reason"].as_str().unwrap_or_default()]
823 .into_iter()
824 .find(|name| matches!(*name, OPTIN_KEY_BOUND | OPTIN_KEY_CLEARED))
825 .map(str::to_owned),
826 _ => None,
827 }
828}
829
830pub const OPTIN_KEY_INVALID: &str = "optin_key_invalid";
832pub const OPTIN_KEY_BOUND: &str = "optin_key_bound";
834pub const OPTIN_KEY_CLEARED: &str = "optin_key_cleared";
836
837pub const APP_KEY_NOT_ANNOUNCED: &str = "app_key_not_announced";
840pub const APP_KEY_BIND_INVALID: &str = "app_key_bind_invalid";
843pub const APP_KEYS_INVALID: &str = "app_keys_invalid";
846pub const TASK_KEY_INVALID: &str = "task_propose_key_invalid";
848pub const TASK_KEY_BOUND: &str = "task_propose_key_bound";
850pub const TASK_KEY_CLEARED: &str = "task_propose_key_cleared";
852
853pub const RETRY_AFTER_CAP_S: u64 = 32 * 86_400;
856
857impl CloudError {
858 pub(crate) fn from_response(status: u16, body: &serde_json::Value) -> Self {
860 let value_reason = body["error"]["reason"].clone();
861 let revocation = body["error"]["revocation"].clone();
862 let trial_used = body["error"]["code"].as_str() == Some(TRIAL_USED);
863 let plans_url = web_url(body["error"]["plans_url"].as_str());
864 let decoded = serde_json::from_value::<CloudErrorBody>(body.clone())
865 .map(|body| body.error)
866 .ok()
867 .or_else(|| lenient_detail(&body["error"]));
868 if status == 400
872 && body["error"]["code"].as_str() == Some("invalid_field")
873 && let Some(reason @ (APP_KEY_NOT_ANNOUNCED | APP_KEY_BIND_INVALID)) =
874 body["error"]["reason"].as_str()
875 {
876 return Self::Server {
877 status,
878 code: reason.into(),
879 };
880 }
881 if status == 400
884 && body["error"]["code"].as_str() == Some("invalid_field")
885 && body["error"]["field"].as_str() == Some("app_keys")
886 {
887 return Self::Server {
888 status,
889 code: APP_KEYS_INVALID.into(),
890 };
891 }
892 if let Some(code) = task_key_refusal(status, body) {
897 return Self::Server { status, code };
898 }
899 if let Some(code) = optin_key_refusal(status, body) {
901 return Self::Server { status, code };
902 }
903 if matches!(status, 400 | 409)
906 && let Some(name) = [&body["error"]["reason"], &body["error"]["code"]]
907 .iter()
908 .filter_map(|v| v.as_str())
909 .find(|name| crate::auth::CHAT_KEY_REPAIR_REASONS.contains(name))
910 {
911 return Self::Server {
912 status,
913 code: name.to_owned(),
914 };
915 }
916 if status == 409 && body["error"]["code"].as_str() == Some(NOT_READY) {
919 return Self::Server {
920 status,
921 code: NOT_READY.into(),
922 };
923 }
924 if status == 403 && body["error"]["code"].as_str() == Some(VAULT_CREATE_FORBIDDEN) {
927 return Self::Forbidden;
928 }
929 let Some(mut detail) = decoded else {
930 return Self::of_status(status, lenient_u64(&body["error"]["retry_after_s"]));
931 };
932 detail.retry_after_s = detail.retry_after_s.map(|s| s.min(RETRY_AFTER_CAP_S));
935 if let Some(refusal) = TaskRefusal::from_reason(
936 detail.code,
937 detail.reason.as_deref(),
938 detail.retry_after_s,
939 detail.check.as_deref(),
940 ) {
941 return Self::Task {
942 refusal,
943 number: detail.number,
944 detail: permit_line(refusal, &detail),
945 };
946 }
947 let next_step = NextStep::of_wire(detail.next_step.as_deref());
948 if trial_used {
951 return Self::PlanRequired(Box::new(PlanNeed {
952 plan_needed: wire_token(detail.plan_needed.as_deref(), 32),
953 message: safe_message(&detail.message),
954 reason: Some(TRIAL_USED.into()),
955 next_step,
956 plans_url,
957 trial_reason: wire_token(detail.reason.as_deref(), 32),
958 ..PlanNeed::default()
959 }));
960 }
961 match detail.code {
962 CloudErrorCode::Unauthorized => Self::Unauthorized,
963 CloudErrorCode::LeaseExpired => Self::LeaseLapsed,
964 CloudErrorCode::InstanceRevoked => Self::Revoked(Revocation::of_statement(&revocation)),
965 CloudErrorCode::PlanRequired => Self::PlanRequired(Box::new(PlanNeed {
966 feature: wire_token(detail.feature.as_deref(), 64),
967 plan_needed: wire_token(detail.plan_needed.as_deref(), 32),
968 limit: detail.limit,
969 used: detail.used,
970 message: safe_message(&detail.message),
971 plan: None,
972 reason: wire_token(detail.reason.as_deref(), 32),
973 next_step,
974 plans_url: None,
975 trial_reason: None,
976 })),
977 CloudErrorCode::InstanceLimit => Self::InstanceLimit(Box::new(InstanceCap {
978 resource: wire_token(detail.resource.as_deref(), 64),
979 limit: detail.limit,
980 used: detail.used,
981 seats: detail.seats,
982 per_seat: detail.per_seat,
983 next_step,
984 })),
985 CloudErrorCode::QuotaExceeded => Self::QuotaExceeded(Box::new(Quota {
986 status,
987 resource: wire_token(detail.resource.as_deref(), 64)
988 .unwrap_or_else(|| "unknown".into()),
989 limit: detail.limit,
990 used: detail.used,
991 reset_at: wire_time(detail.reset_at.as_deref()),
992 retry_after: detail.retry_after_s,
993 cooldown_days: detail.cooldown_days,
994 next_step,
995 })),
996 CloudErrorCode::StorageQuotaExceeded => Self::StorageFull(Box::new(StorageFull {
997 limit: detail.limit_bytes.or(detail.limit),
998 used: detail.used_bytes.or(detail.used),
999 next_step,
1000 })),
1001 CloudErrorCode::UploadRateLimited => Self::UploadRateLimited {
1002 retry_after: detail.retry_after_s,
1003 per_hour: detail.limit_bytes_per_hour,
1004 },
1005 CloudErrorCode::PolicyDenied => Self::PolicyDenied(PolicyDenial {
1008 member: wire_token(detail.member.as_deref().or(detail.field.as_deref()), 80),
1009 level: wire_token(
1010 detail.level.as_deref().or(detail
1011 .reason
1012 .as_deref()
1013 .filter(|r| matches!(*r, "org" | "workspace" | "vault" | "instance"))),
1014 16,
1015 ),
1016 action: wire_token(detail.action.as_deref(), 64),
1017 }),
1018 CloudErrorCode::ForbiddenRight if value_reason.as_str() == Some("vetoed") => {
1019 Self::Vetoed
1020 }
1021 CloudErrorCode::ForbiddenRight => Self::Forbidden,
1022 CloudErrorCode::UploadDisabled => {
1023 Self::UploadDisabled(detail.kind.unwrap_or(CloudUploadKind::Unknown))
1024 }
1025 CloudErrorCode::NotFound => Self::NotFound,
1026 CloudErrorCode::FeatureDisabled => Self::FeatureDisabled {
1027 feature: wire_token(detail.feature.as_deref(), 64),
1028 },
1029 CloudErrorCode::RevisionConflict => Self::Conflict {
1030 expected: detail.expected,
1031 actual: detail.actual,
1032 },
1033 CloudErrorCode::ScreeningRequired => Self::ScreeningBlocked,
1034 CloudErrorCode::UpgradeRequired => Self::UpgradeRequired {
1035 min: detail.min_instance,
1036 },
1037 CloudErrorCode::RateLimited => Self::RateLimited {
1038 retry_after: detail.retry_after_s,
1039 },
1040 CloudErrorCode::ExpiredToken => Self::DeviceFlow(CODE_EXPIRED.into()),
1041 CloudErrorCode::AccessDenied => Self::DeviceFlow(CODE_DENIED.into()),
1042 _ if status == 429 => Self::RateLimited {
1045 retry_after: detail.retry_after_s,
1046 },
1047 CloudErrorCode::Unknown => Self::of_status(status, detail.retry_after_s),
1048 other => Self::Server {
1049 status,
1050 code: serde_json::to_value(other)
1051 .ok()
1052 .and_then(|v| v.as_str().map(str::to_string))
1053 .unwrap_or_else(|| "unknown".into()),
1054 },
1055 }
1056 }
1057
1058 #[must_use]
1064 pub fn with_origin(mut self, origin: &str) -> Self {
1065 if let Self::PlanRequired(need) = &mut self
1066 && let Some(url) = need.plans_url.take()
1067 {
1068 let base = origin.trim_end_matches('/');
1069 need.plans_url = if !(base.starts_with("https://") || base.starts_with("http://")) {
1070 None
1071 } else if url.starts_with('/') {
1072 Some(format!("{base}{url}"))
1073 } else if same_origin(&url, base) {
1074 Some(url)
1075 } else {
1076 None
1077 };
1078 }
1079 self
1080 }
1081
1082 #[must_use]
1086 pub fn for_trial(self) -> Self {
1087 match self {
1088 Self::DeviceFlow(why) if why == CODE_EXPIRED => {
1089 Self::DeviceFlow(TRIAL_CODE_EXPIRED.into())
1090 }
1091 other => other,
1092 }
1093 }
1094
1095 fn of_status(status: u16, retry_after: Option<u64>) -> Self {
1098 match status {
1099 429 => Self::RateLimited {
1100 retry_after: retry_after.map(|s| s.min(RETRY_AFTER_CAP_S)),
1101 },
1102 413 => Self::Server {
1103 status,
1104 code: "payload_too_large".into(),
1105 },
1106 _ => Self::Server {
1107 status,
1108 code: "unknown".into(),
1109 },
1110 }
1111 }
1112
1113 #[must_use]
1116 pub fn with_plan(mut self, plan: CloudPlan) -> Self {
1117 if let Self::PlanRequired(need) = &mut self
1118 && (need.feature.is_some() || need.locked().is_some())
1119 && plan != CloudPlan::Unknown
1120 {
1121 need.plan.get_or_insert(plan);
1122 }
1123 self
1124 }
1125
1126 pub fn is_transient(&self) -> bool {
1129 match self {
1130 Self::QuotaExceeded(q) => q.waits(),
1131 other => matches!(
1132 other,
1133 Self::Offline(_)
1134 | Self::RateLimited { .. }
1135 | Self::UploadRateLimited { .. }
1136 | Self::Server {
1137 status: 408 | 500..,
1138 ..
1139 }
1140 ),
1141 }
1142 }
1143
1144 pub fn retry_after_at(&self, now: lean_ctx_time::UtcDateTime) -> Option<u64> {
1148 match self {
1149 Self::RateLimited { retry_after } | Self::UploadRateLimited { retry_after, .. } => {
1150 *retry_after
1151 }
1152 Self::QuotaExceeded(q) if q.waits() => q.retry_after.or_else(|| {
1153 let reset =
1154 lean_ctx_time::OffsetDateTime::parse_from_rfc3339(q.reset_at.as_deref()?)
1155 .ok()?;
1156 u64::try_from((reset.to_utc() - now).num_seconds().max(1)).ok()
1157 }),
1158 _ => None,
1159 }
1160 }
1161}
1162
1163impl fmt::Display for CloudError {
1164 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1165 match self {
1166 Self::Offline(why) => write!(f, "LeanCTX Cloud is not reachable ({why})"),
1167 Self::NotConnected => f.write_str("not connected to LeanCTX Cloud (run `lean-ctx cloud connect`)"),
1168 Self::Unauthorized => f.write_str(
1169 "LeanCTX Cloud does not accept this instance any more (run `lean-ctx cloud connect` again)",
1170 ),
1171 Self::PlanRequired(need) => {
1172 write_plan_need(f, need)?;
1173 if need.locked().is_none() && !need.trial_used() {
1175 write_hint(f, need.next_step)?;
1176 }
1177 Ok(())
1178 }
1179 Self::InstanceLimit(cap) => write_instance_cap(f, cap),
1180 Self::QuotaExceeded(q) => write_quota(f, q),
1181 Self::StorageFull(s) => {
1182 f.write_str("this workspace's LeanCTX Cloud storage is full")?;
1183 if let (Some(used), Some(limit)) = (s.used, s.limit) {
1184 write!(f, " ({} of {})", bytes_text(used), bytes_text(limit))?;
1185 }
1186 f.write_str(
1187 "; nothing is charged for more; uploads stop until storage frees (remove vaults or files in LeanCTX Cloud)",
1188 )?;
1189 write_hint(f, s.next_step)
1190 }
1191 Self::UploadRateLimited {
1192 retry_after,
1193 per_hour,
1194 } => {
1195 f.write_str("LeanCTX Cloud's upload allowance for this hour is used up")?;
1196 if let Some(per_hour) = per_hour {
1197 write!(f, " ({} per hour)", bytes_text(*per_hour))?;
1198 }
1199 match retry_after {
1200 Some(s) => write!(f, "; the rest goes out in {s} s")?,
1201 None => f.write_str("; the rest goes out later")?,
1202 }
1203 f.write_str(" (a large first sync can take a few hours)")
1204 }
1205 Self::PolicyDenied(d) => {
1206 f.write_str("LeanCTX Cloud policy refuses this")?;
1207 if let Some(member) = &d.member {
1208 write!(f, " ({member}")?;
1209 if let Some(level) = &d.level {
1210 write!(f, ", set at the {level} level")?;
1211 }
1212 f.write_str(")")?;
1213 }
1214 match &d.action {
1215 Some(action) => write!(
1216 f,
1217 "; a person does this on the LeanCTX Cloud web ({})",
1218 action.replace('_', " ")
1219 ),
1220 None => f.write_str(
1221 "; it is not retried until an admin changes the policy in LeanCTX Cloud",
1222 ),
1223 }
1224 }
1225 Self::LeaseLapsed => {
1226 f.write_str("the LeanCTX Cloud lease has lapsed (run `lean-ctx cloud connect` again)")
1227 }
1228 Self::Revoked(r) => {
1229 f.write_str("this instance was revoked by ")?;
1230 match &r.workspace {
1231 Some(workspace) => f.write_str(workspace)?,
1232 None => f.write_str("its workspace")?,
1233 }
1234 if let Some(reason) = &r.reason {
1235 write!(f, " ({})", reason.replace('_', " "))?;
1236 }
1237 f.write_str("; reconnect with `lean-ctx cloud connect` after an admin allows it")
1238 }
1239 Self::Forbidden => f.write_str("LeanCTX Cloud does not allow this for your account"),
1240 Self::Vetoed => f.write_str("a workspace veto bars it until the veto is lifted"),
1241 Self::UploadDisabled(kind) => match kind {
1242 CloudUploadKind::Metrics => {
1243 f.write_str("the workspace has switched metrics upload off")
1244 }
1245 CloudUploadKind::Receipts => {
1246 f.write_str("the workspace has switched receipts upload off")
1247 }
1248 CloudUploadKind::Unknown => {
1249 f.write_str("the workspace has switched this upload off")
1250 }
1251 },
1252 Self::NotFound => f.write_str("LeanCTX Cloud does not know that item"),
1253 Self::FeatureDisabled { feature } => match feature.as_deref() {
1254 Some("instance_metrics") | None => f.write_str(
1255 "this LeanCTX Cloud server has switched off instance metrics; nothing was sent",
1256 ),
1257 Some(other) => write!(
1258 f,
1259 "this LeanCTX Cloud server has switched off {}; nothing was sent",
1260 other.replace('_', " ")
1261 ),
1262 },
1263 Self::Conflict { expected, actual } => match (expected, actual) {
1264 (Some(e), Some(a)) => {
1265 write!(f, "knowledge moved on (expected revision {e}, now {a})")
1266 }
1267 _ => f.write_str("knowledge moved on"),
1268 },
1269 Self::ScreeningBlocked => f.write_str("LeanCTX Cloud screening refused the content"),
1270 Self::UpgradeRequired { min } => match min {
1271 Some(min) => write!(f, "LeanCTX Cloud needs lean-ctx {min} or newer (run `lean-ctx update`)"),
1272 None => f.write_str("LeanCTX Cloud needs a newer lean-ctx (run `lean-ctx update`)"),
1273 },
1274 Self::RateLimited { retry_after } => match retry_after {
1275 Some(s) => write!(f, "LeanCTX Cloud asks to retry in {s} s"),
1276 None => f.write_str("LeanCTX Cloud asks to retry later"),
1277 },
1278 Self::DeviceFlow(why) => write!(f, "connection not approved: {why}"),
1279 Self::TrialUnsupported { origin } => write!(
1280 f,
1281 "LeanCTX does not offer the one-step trial here yet. Start the trial on {origin}, or sign in with `lean-ctx cloud connect`"
1282 ),
1283 Self::Protocol(why) => write!(f, "unexpected answer from Cloud: {why}"),
1284 Self::Config(why) => write!(f, "Cloud configuration: {why}"),
1285 Self::Local(why) => write!(f, "local Cloud state: {why}"),
1286 Self::Refused(why) => f.write_str(why),
1287 Self::Task {
1288 refusal,
1289 number,
1290 detail,
1291 } => {
1292 if let Some(number) = number {
1293 write!(f, "task #{number}: ")?;
1294 }
1295 match detail {
1296 Some(detail) if matches!(refusal, TaskRefusal::NotPermitted(_)) => {
1298 f.write_str(detail)
1299 }
1300 Some(detail) => write!(f, "{refusal} ({detail})"),
1301 None => write!(f, "{refusal}"),
1302 }
1303 }
1304 Self::Server { status, code } => write!(f, "LeanCTX Cloud answered {status} ({code})"),
1305 }
1306 }
1307}
1308
1309impl std::error::Error for CloudError {}
1310
1311pub const CODE_EXPIRED: &str =
1313 "the code expired before it was approved; run `lean-ctx cloud connect` again for a new one";
1314
1315pub const TRIAL_CODE_EXPIRED: &str = "the code expired before it was approved. If the browser said this address already had its trial, choose a plan in LeanCTX Cloud, then run `lean-ctx cloud connect`; otherwise run `lean-ctx cloud connect --trial` again for a new code";
1317
1318pub const CODE_DENIED: &str =
1320 "you chose \"Not mine\" in the browser; nothing changed on this machine";
1321
1322impl CloudError {
1323 #[must_use]
1329 pub fn event_code(&self) -> String {
1330 match self {
1331 Self::PlanRequired(need) if need.trial_used() => TRIAL_USED.into(),
1332 Self::PlanRequired(_) => "plan_required".into(),
1333 Self::TrialUnsupported { .. } => "trial_unsupported".into(),
1334 Self::DeviceFlow(why) if why == CODE_EXPIRED || why == TRIAL_CODE_EXPIRED => {
1335 "expired".into()
1336 }
1337 Self::DeviceFlow(why) if why == CODE_DENIED => "denied".into(),
1338 Self::DeviceFlow(why) if why == crate::auth::TASK_KEY_REFUSED => {
1340 TASK_KEY_INVALID.into()
1341 }
1342 Self::DeviceFlow(why) if why == crate::auth::TASK_KEY_ALREADY_BOUND => {
1343 TASK_KEY_BOUND.into()
1344 }
1345 Self::DeviceFlow(why) if why == crate::auth::TASK_KEY_WAS_REMOVED => {
1346 TASK_KEY_CLEARED.into()
1347 }
1348 Self::DeviceFlow(why) if why == crate::auth::OPTIN_KEY_REFUSED => {
1350 OPTIN_KEY_INVALID.into()
1351 }
1352 Self::DeviceFlow(why) if why == crate::auth::OPTIN_KEY_ALREADY_BOUND => {
1353 OPTIN_KEY_BOUND.into()
1354 }
1355 Self::DeviceFlow(why) if why == crate::auth::OPTIN_KEY_WAS_REMOVED => {
1356 OPTIN_KEY_CLEARED.into()
1357 }
1358 Self::DeviceFlow(why) if why == crate::auth::OPTIN_KEY_TOKEN_ENROLLMENT => {
1359 "token_enrollment".into()
1360 }
1361 Self::DeviceFlow(why) if why == crate::auth::APP_KEY_PAIRING_FAILED => {
1364 APP_KEY_NOT_ANNOUNCED.into()
1365 }
1366 Self::DeviceFlow(_) => "not_approved".into(),
1367 Self::InstanceLimit(_) => "instance_limit".into(),
1368 Self::QuotaExceeded(_) => "quota_exceeded".into(),
1369 Self::Offline(_) => "offline".into(),
1370 Self::Unauthorized => "unauthorized".into(),
1371 Self::Revoked(_) => "instance_revoked".into(),
1372 Self::RateLimited { .. } => "rate_limited".into(),
1373 Self::UpgradeRequired { .. } => "upgrade_required".into(),
1374 Self::Config(_) => "config".into(),
1375 Self::Protocol(_) => "protocol".into(),
1376 Self::Local(_) => "local".into(),
1377 Self::Server { code, .. } if wire_token(Some(code), 64).is_some() => code.clone(),
1378 _ => "error".into(),
1379 }
1380 }
1381}
1382
1383pub const RECOVER_HINT: &str = "for a lost or broken device, recover its slot now on the LeanCTX Cloud web (Hosts › Recover the slot now, with your second factor; once per 30 days)";
1387
1388fn host_cap_head(resource: &str) -> Option<&'static str> {
1390 match resource {
1391 "registered_instances" => Some("all hosts the plan includes are registered"),
1392 "connected_instances" => Some("all hosts that may be connected at once are connected"),
1393 _ => None,
1394 }
1395}
1396
1397fn write_instance_cap(f: &mut fmt::Formatter<'_>, cap: &InstanceCap) -> fmt::Result {
1400 let connected = cap.resource.as_deref() == Some("connected_instances");
1401 let resource = if connected {
1402 "connected_instances"
1403 } else {
1404 "registered_instances"
1405 };
1406 f.write_str(host_cap_head(resource).unwrap_or_default())?;
1407 if let (Some(used), Some(limit)) = (cap.used, cap.limit) {
1408 write!(f, " ({used} of {limit}")?;
1409 if let (Some(seats), Some(per_seat)) = (cap.seats, cap.per_seat) {
1410 write!(f, ": {seats} seats, {per_seat} per seat")?;
1411 }
1412 f.write_str(")")?;
1413 }
1414 if connected {
1415 write!(f, "; {FREE_CONNECTED}, or upgrade the plan")?;
1416 } else {
1417 write!(f, "; {FREE_REGISTERED}, or upgrade the plan")?;
1418 }
1419 write_hint(f, cap.next_step)
1420}
1421
1422#[must_use]
1424pub fn quota_label(resource: &str) -> &str {
1425 match resource {
1426 "transfer_bytes" => "monthly transfer",
1427 "bus_messages" => "monthly bus messages",
1428 "registered_instances" => HOSTS_REGISTERED,
1429 "private_vaults" => "private vaults",
1430 "connected_instances" => HOSTS_CONNECTED,
1431 "storage_bytes" => "storage",
1432 "model_credit_usd_micros" => "model credit",
1433 other => other,
1434 }
1435}
1436
1437fn write_quota(f: &mut fmt::Formatter<'_>, q: &Quota) -> fmt::Result {
1438 let what = quota_label(&q.resource);
1439 if let Some(head) = host_cap_head(&q.resource) {
1440 f.write_str(head)?;
1441 if let (Some(used), Some(limit)) = (q.used, q.limit) {
1442 write!(f, " ({used} of {limit})")?;
1443 }
1444 } else {
1445 write!(f, "this workspace has used all its {what}")?;
1446 if let (Some(used), Some(limit)) = (q.used, q.limit) {
1447 write!(
1448 f,
1449 " ({} of {})",
1450 amount_text(&q.resource, used),
1451 amount_text(&q.resource, limit)
1452 )?;
1453 }
1454 }
1455 f.write_str("; nothing is charged for more")?;
1456 match q.resource.as_str() {
1457 "registered_instances" if q.cooling_slot() => write!(
1458 f,
1459 "; a revoked host stays registered until {} ({}-day cool-down), or {RECOVER_HINT}",
1460 q.reset_at.as_deref().unwrap_or("?"),
1461 q.cooldown_days.unwrap_or(0)
1462 )?,
1463 "registered_instances" => write!(f, "; {FREE_REGISTERED}, or upgrade the plan")?,
1464 "connected_instances" => write!(f, "; {FREE_CONNECTED}")?,
1465 "private_vaults" => {
1466 f.write_str("; remove or publish a vault in LeanCTX Cloud, or upgrade the plan")?;
1467 }
1468 "model_credit_usd_micros" => {}
1470 _ if q.waits() => match &q.reset_at {
1471 Some(at) => write!(f, "; uploads wait in the local outbox until {at}")?,
1472 None => f.write_str("; uploads wait in the local outbox until it frees")?,
1473 },
1474 _ => {}
1475 }
1476 write_hint(f, q.next_step)
1477}
1478
1479#[cfg(test)]
1480mod tests {
1481 use super::*;
1482 use serde_json::json;
1483
1484 #[test]
1487 fn trial_used_refusal_names_the_used_trial_and_the_plans_page() {
1488 let body = json!({"error": {
1489 "code": "trial_used",
1490 "message": "This address already had a trial.",
1491 "plan_needed": "team",
1492 "next_step": "subscribe",
1493 "plans_url": "https://cloud.leanctx.com/app/plans"
1494 }});
1495 let error = CloudError::from_response(402, &body);
1496 let CloudError::PlanRequired(need) = &error else {
1497 panic!("{error:?}");
1498 };
1499 assert!(need.trial_used());
1500 assert_eq!(need.plan_needed.as_deref(), Some("team"));
1501 assert_eq!(
1502 need.plans_url.as_deref(),
1503 Some("https://cloud.leanctx.com/app/plans")
1504 );
1505 assert_eq!(error.event_code(), "trial_used");
1506 assert!(!error.is_transient());
1507 assert_eq!(
1508 error.to_string(),
1509 "this address already had its Team trial; no second trial starts. Choose a plan at https://cloud.leanctx.com/app/plans, then run `lean-ctx cloud connect`"
1510 );
1511 let ended = CloudError::from_response(
1513 402,
1514 &json!({"error": {"code": "trial_used", "reason": "trial_ended", "message": "",
1515 "plan_needed": "personal", "plans_url": "https://cloud.leanctx.com/app/plans"}}),
1516 );
1517 assert_eq!(ended.event_code(), "trial_used");
1518 assert_eq!(
1519 ended.to_string(),
1520 "the Personal trial of this address has ended; no second trial starts. Choose a plan at https://cloud.leanctx.com/app/plans, then run `lean-ctx cloud connect`"
1521 );
1522 let no_plan = CloudError::from_response(
1523 402,
1524 &json!({"error": {"code": "trial_used", "reason": "no_plan", "message": "",
1525 "plan_needed": "team"}}),
1526 );
1527 assert_eq!(no_plan.event_code(), "trial_used");
1528 assert!(no_plan.to_string().starts_with(
1529 "this address has no Team trial left and no plan; no second trial starts."
1530 ));
1531 let path = format!(
1534 "{}/crates/lean-ctx-protocol/tests/fixtures/cloud/error.trial_used.json",
1535 concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
1536 );
1537 let fixture: serde_json::Value =
1538 serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
1539 let refused = CloudError::from_response(402, &fixture);
1540 assert_eq!(refused.event_code(), "trial_used");
1541 assert_eq!(
1542 refused.to_string(),
1543 "this address already had its Personal trial; no second trial starts. Choose a plan in LeanCTX Cloud, then run `lean-ctx cloud connect`"
1544 );
1545 assert_eq!(
1546 refused
1547 .with_origin("https://cloud.leanctx.com/")
1548 .to_string(),
1549 "this address already had its Personal trial; no second trial starts. Choose a plan at https://cloud.leanctx.com/o/bob/billing/?plan=personal, then run `lean-ctx cloud connect`"
1550 );
1551 let hostile = CloudError::from_response(
1553 402,
1554 &json!({"error": {"code": "trial_used", "message": "", "plan_needed": "personal",
1555 "plans_url": "javascript:alert(1)"}}),
1556 );
1557 assert_eq!(
1558 hostile.to_string(),
1559 "this address already had its Personal trial; no second trial starts. Choose a plan in LeanCTX Cloud, then run `lean-ctx cloud connect`"
1560 );
1561 let plain = CloudError::from_response(
1563 402,
1564 &json!({"error": {"code": "plan_required", "message": "", "feature": "audit_export", "plan_needed": "team"}}),
1565 );
1566 assert_eq!(plain.event_code(), "plan_required");
1567 }
1568
1569 fn trial_used_with(plans_url: &str) -> CloudError {
1570 CloudError::from_response(
1571 402,
1572 &json!({"error": {"code": "trial_used", "message": "", "plan_needed": "personal",
1573 "plans_url": plans_url}}),
1574 )
1575 }
1576
1577 const NO_PAGE: &str = "this address already had its Personal trial; no second trial starts. Choose a plan in LeanCTX Cloud, then run `lean-ctx cloud connect`";
1578
1579 #[test]
1582 fn trial_plans_url_on_another_origin_is_not_shown() {
1583 let origin = "https://cloud.leanctx.com";
1584 assert_eq!(
1585 trial_used_with("https://Cloud.LeanCTX.com/app/plans?plan=personal")
1586 .with_origin(origin)
1587 .to_string(),
1588 "this address already had its Personal trial; no second trial starts. Choose a plan at https://Cloud.LeanCTX.com/app/plans?plan=personal, then run `lean-ctx cloud connect`"
1589 );
1590 for foreign in [
1591 "http://cloud.leanctx.com/app/plans",
1592 "https://evil.example/app/plans",
1593 "https://cloud.leanctx.com.evil.example/app/plans",
1594 "https://cloud.leanctx.com@evil.example/app/plans",
1595 "https://cloud.leanctx.com:8443/app/plans",
1596 "https://cloud.leanctx.com",
1597 ] {
1598 let shown = trial_used_with(foreign).with_origin(origin).to_string();
1599 let expected = if foreign == "https://cloud.leanctx.com" {
1600 "this address already had its Personal trial; no second trial starts. Choose a plan at https://cloud.leanctx.com, then run `lean-ctx cloud connect`"
1601 } else {
1602 NO_PAGE
1603 };
1604 assert_eq!(shown, expected, "{foreign}");
1605 }
1606 assert_eq!(
1608 trial_used_with("https://cloud.leanctx.com/app/plans")
1609 .with_origin("file:///tmp")
1610 .to_string(),
1611 NO_PAGE
1612 );
1613 }
1614
1615 #[test]
1618 fn trial_plans_url_with_format_characters_is_not_shown() {
1619 for c in [
1620 '\u{202E}',
1621 '\u{202A}',
1622 '\u{2066}',
1623 '\u{2069}',
1624 '\u{200B}',
1625 '\u{200D}',
1626 '\u{200E}',
1627 '\u{061C}',
1628 '\u{00AD}',
1629 '\u{FEFF}',
1630 '\u{E0041}',
1631 '\u{3164}',
1632 ] {
1633 let url = format!("/o/bob/billing/{c}?plan=personal");
1634 assert_eq!(
1635 trial_used_with(&url)
1636 .with_origin("https://cloud.leanctx.com")
1637 .to_string(),
1638 NO_PAGE,
1639 "U+{:04X}",
1640 c as u32
1641 );
1642 }
1643 assert_eq!(
1644 trial_used_with("/o/bob/billing/?plan=personal")
1645 .with_origin("https://cloud.leanctx.com")
1646 .to_string(),
1647 "this address already had its Personal trial; no second trial starts. Choose a plan at https://cloud.leanctx.com/o/bob/billing/?plan=personal, then run `lean-ctx cloud connect`"
1648 );
1649 }
1650
1651 #[test]
1655 fn trial_code_expiry_points_to_the_plans_page() {
1656 let expired = CloudError::DeviceFlow(CODE_EXPIRED.into()).for_trial();
1657 assert_eq!(expired, CloudError::DeviceFlow(TRIAL_CODE_EXPIRED.into()));
1658 assert_eq!(expired.event_code(), "expired");
1659 assert!(
1660 expired
1661 .to_string()
1662 .contains("choose a plan in LeanCTX Cloud")
1663 );
1664 assert!(
1665 !expired
1666 .to_string()
1667 .contains("run `lean-ctx cloud connect` again")
1668 );
1669 let denied = CloudError::DeviceFlow(CODE_DENIED.into());
1670 assert_eq!(denied.clone().for_trial(), denied);
1671 assert_eq!(
1672 CloudError::Offline("reset".into()).for_trial(),
1673 CloudError::Offline("reset".into())
1674 );
1675 }
1676
1677 #[test]
1678 fn trial_event_codes_name_the_device_flow_outcomes() {
1679 assert_eq!(
1680 CloudError::DeviceFlow(CODE_EXPIRED.into()).event_code(),
1681 "expired"
1682 );
1683 assert_eq!(
1684 CloudError::from_response(
1685 400,
1686 &json!({"error": {"code": "access_denied", "message": ""}})
1687 )
1688 .event_code(),
1689 "denied"
1690 );
1691 assert_eq!(
1692 CloudError::Server {
1693 status: 400,
1694 code: "invalid_request".into()
1695 }
1696 .event_code(),
1697 "invalid_request"
1698 );
1699 assert_eq!(
1700 CloudError::Server {
1701 status: 500,
1702 code: "Bad Code\n".into()
1703 }
1704 .event_code(),
1705 "error"
1706 );
1707 assert_eq!(CloudError::Offline("reset".into()).event_code(), "offline");
1708 assert_eq!(
1710 CloudError::DeviceFlow(crate::auth::APP_KEY_PAIRING_FAILED.into()).event_code(),
1711 APP_KEY_NOT_ANNOUNCED
1712 );
1713 assert_eq!(APP_KEY_NOT_ANNOUNCED, "app_key_not_announced");
1714 for reason in [APP_KEY_NOT_ANNOUNCED, APP_KEY_BIND_INVALID] {
1716 let body = serde_json::json!({"error": {"code": "invalid_field",
1717 "field": "app_keys_bind_signature", "reason": reason, "message": "x"}});
1718 assert!(matches!(
1719 CloudError::from_response(400, &body),
1720 CloudError::Server { status: 400, code } if code == reason
1721 ));
1722 }
1723 }
1724
1725 #[test]
1728 fn invalid_field_keeps_its_code() {
1729 assert_eq!(
1730 CloudError::from_response(
1731 400,
1732 &json!({"error": {"code": "invalid_field", "message": "x",
1733 "field": "chat_key.bind_signature"}}),
1734 ),
1735 CloudError::Server {
1736 status: 400,
1737 code: "invalid_field".into()
1738 }
1739 );
1740 }
1741
1742 #[test]
1745 fn a_detail_with_a_mistyped_member_keeps_its_code_and_retry() {
1746 let limited = CloudError::from_response(
1747 429,
1748 &json!({"error": {"code": "rate_limited", "message": "slow down",
1749 "retry_after_s": 12, "number": "seventeen"}}),
1750 );
1751 assert_eq!(
1752 limited,
1753 CloudError::RateLimited {
1754 retry_after: Some(12)
1755 }
1756 );
1757 let claimed = CloudError::from_response(
1759 409,
1760 &json!({"error": {"code": "invalid_state", "message": "x",
1761 "reason": "task_claimed", "number": "17", "limit": {"odd": true}}}),
1762 );
1763 assert!(
1764 matches!(
1765 claimed,
1766 CloudError::Task {
1767 refusal: TaskRefusal::Claimed,
1768 number: Some(17),
1769 ..
1770 }
1771 ),
1772 "{claimed:?}"
1773 );
1774 let quota = CloudError::from_response(
1775 429,
1776 &json!({"error": {"code": "quota_exceeded", "message": "x",
1777 "resource": "bus_messages", "retry_after_s": "60", "used": -1}}),
1778 );
1779 let CloudError::QuotaExceeded(quota) = quota else {
1780 panic!("{quota:?}");
1781 };
1782 assert_eq!(
1783 (quota.resource.as_str(), quota.retry_after, quota.used),
1784 ("bus_messages", Some(60), None)
1785 );
1786 assert_eq!(
1788 CloudError::from_response(400, &json!({"error": {"code": 7}})),
1789 CloudError::Server {
1790 status: 400,
1791 code: "unknown".into()
1792 }
1793 );
1794 }
1795
1796 #[test]
1799 fn edge_answers_are_classified_by_status() {
1800 let busy = CloudError::from_response(
1801 429,
1802 &json!({"error": {"code": "server_busy", "message": "x", "retry_after_s": 5}}),
1803 );
1804 assert_eq!(
1805 busy,
1806 CloudError::RateLimited {
1807 retry_after: Some(5)
1808 }
1809 );
1810 let header_only = CloudError::from_response(429, &json!({"error": {"retry_after_s": 9}}));
1812 assert_eq!(
1813 header_only,
1814 CloudError::RateLimited {
1815 retry_after: Some(9)
1816 }
1817 );
1818 assert_eq!(
1819 CloudError::from_response(429, &serde_json::Value::Null),
1820 CloudError::RateLimited { retry_after: None }
1821 );
1822 for status in [408, 500, 502, 503, 504] {
1824 let down = CloudError::from_response(status, &serde_json::Value::Null);
1825 assert!(down.is_transient(), "{status}: {down:?}");
1826 }
1827 let too_large = CloudError::from_response(413, &serde_json::Value::Null);
1828 assert_eq!(
1829 too_large,
1830 CloudError::Server {
1831 status: 413,
1832 code: "payload_too_large".into()
1833 }
1834 );
1835 assert!(!too_large.is_transient());
1836 }
1837
1838 #[test]
1839 fn instance_limit_carries_the_seat_numbers() {
1840 let error = CloudError::from_response(
1841 409,
1842 &json!({"error": {"code": "instance_limit", "message": "x", "limit": 2, "used": 2}}),
1843 );
1844 assert_eq!(
1845 error,
1846 CloudError::InstanceLimit(Box::new(InstanceCap {
1847 limit: Some(2),
1848 used: Some(2),
1849 ..InstanceCap::default()
1850 }))
1851 );
1852 assert_eq!(
1853 error.to_string(),
1854 "all hosts the plan includes are registered (2 of 2); to free one, revoke a host you no longer use on the Hosts page, or upgrade the plan"
1855 );
1856 }
1857
1858 #[test]
1861 fn a_connected_limit_says_disconnect_and_names_the_seats() {
1862 let error = CloudError::from_response(
1863 409,
1864 &json!({"error": {"code": "instance_limit", "message": "x", "resource": "connected_instances",
1865 "limit": 4, "used": 4, "plan": "team", "next_step": "add_seats",
1866 "seats": 2, "per_seat": 2}}),
1867 );
1868 assert_eq!(
1869 error,
1870 CloudError::InstanceLimit(Box::new(InstanceCap {
1871 resource: Some("connected_instances".into()),
1872 limit: Some(4),
1873 used: Some(4),
1874 seats: Some(2),
1875 per_seat: Some(2),
1876 next_step: Some(NextStep::AddSeats),
1877 }))
1878 );
1879 assert_eq!(
1880 error.to_string(),
1881 "all hosts that may be connected at once are connected (4 of 4: 2 seats, 2 per seat); to free one, disconnect a host (`lean-ctx cloud disconnect` on that machine), or upgrade the plan; every seat you add in LeanCTX Cloud brings its own allowance"
1882 );
1883 assert!(!error.is_transient());
1884 let personal = CloudError::from_response(
1885 409,
1886 &json!({"error": {"code": "instance_limit", "message": "x", "resource": "connected_instances",
1887 "limit": 2, "used": 2, "plan": "personal", "next_step": "upgrade_team"}}),
1888 );
1889 assert!(
1890 personal
1891 .to_string()
1892 .ends_with("; Team gives every seat its own allowance"),
1893 "{personal}"
1894 );
1895 }
1896
1897 #[test]
1898 fn storage_full_decodes_with_bytes_and_is_not_retried() {
1899 let error = CloudError::from_response(
1900 403,
1901 &json!({"error": {"code": "storage_quota_exceeded", "message": "x", "resource": "storage_bytes",
1902 "limit": 1_073_741_824_u64, "used": 1_073_741_824_u64,
1903 "limit_bytes": 1_073_741_824_u64, "used_bytes": 1_073_741_824_u64,
1904 "plan": "personal", "next_step": "upgrade_team"}}),
1905 );
1906 assert_eq!(
1907 error,
1908 CloudError::StorageFull(Box::new(StorageFull {
1909 limit: Some(1 << 30),
1910 used: Some(1 << 30),
1911 next_step: Some(NextStep::UpgradeTeam),
1912 }))
1913 );
1914 assert!(!error.is_transient(), "waiting does not free storage");
1915 assert_eq!(
1916 error.retry_after_at(lean_ctx_time::UtcDateTime::now()),
1917 None
1918 );
1919 assert_eq!(
1920 error.to_string(),
1921 "this workspace's LeanCTX Cloud storage is full (1 GiB of 1 GiB); nothing is charged for more; uploads stop until storage frees (remove vaults or files in LeanCTX Cloud); Team gives every seat its own allowance"
1922 );
1923 assert!(!error.to_string().contains("unknown"));
1924 let bare = CloudError::from_response(
1927 403,
1928 &json!({"error": {"code": "storage_quota_exceeded", "message": "x", "limit": 1536, "used": 2048,
1929 "next_step": "something_new"}}),
1930 );
1931 assert_eq!(
1932 bare,
1933 CloudError::StorageFull(Box::new(StorageFull {
1934 limit: Some(1536),
1935 used: Some(2048),
1936 next_step: None,
1937 }))
1938 );
1939 assert!(bare.to_string().contains("(2 KiB of 1.5 KiB)"), "{bare}");
1940 }
1941
1942 #[test]
1943 fn upload_rate_limited_is_transient_and_honours_retry_after() {
1944 let error = CloudError::from_response(
1945 429,
1946 &json!({"error": {"code": "upload_rate_limited", "message": "x",
1947 "limit_bytes_per_hour": 268_435_456_u64, "plan": "personal",
1948 "next_step": "wait", "retry_after_s": 1200}}),
1949 );
1950 assert_eq!(
1951 error,
1952 CloudError::UploadRateLimited {
1953 retry_after: Some(1200),
1954 per_hour: Some(256 << 20),
1955 }
1956 );
1957 assert!(error.is_transient());
1958 assert_eq!(
1959 error.retry_after_at(lean_ctx_time::UtcDateTime::now()),
1960 Some(1200)
1961 );
1962 assert_eq!(
1963 error.to_string(),
1964 "LeanCTX Cloud's upload allowance for this hour is used up (256 MiB per hour); the rest goes out in 1200 s (a large first sync can take a few hours)"
1965 );
1966 let huge = CloudError::from_response(
1968 429,
1969 &json!({"error": {"code": "upload_rate_limited", "message": "x", "retry_after_s": u64::MAX}}),
1970 );
1971 assert_eq!(
1972 huge.retry_after_at(lean_ctx_time::UtcDateTime::now()),
1973 Some(RETRY_AFTER_CAP_S)
1974 );
1975 }
1976
1977 #[test]
1978 fn quota_hints_and_new_resource_labels() {
1979 let quota = |resource: &str, limit: u64, next: &str| {
1980 CloudError::from_response(
1981 409,
1982 &json!({"error": {"code": "quota_exceeded", "message": "x", "resource": resource,
1983 "limit": limit, "used": limit, "plan": "personal", "next_step": next}}),
1984 )
1985 .to_string()
1986 };
1987 assert_eq!(
1988 quota("storage_bytes", 1 << 30, "upgrade_team"),
1989 "this workspace has used all its storage (1 GiB of 1 GiB); nothing is charged for more; Team gives every seat its own allowance"
1990 );
1991 assert_eq!(
1992 quota("model_credit_usd_micros", 8_000_000, "top_up"),
1993 "this workspace has used all its model credit ($8.00 of $8.00); nothing is charged for more; a top-up in LeanCTX Cloud adds more"
1994 );
1995 assert!(
1996 quota("registered_instances", 3, "contact")
1997 .ends_with("; contact us to extend your Enterprise contract")
1998 );
1999 assert_eq!(
2001 quota("registered_instances", 3, "upgrade_team"),
2002 "all hosts the plan includes are registered (3 of 3); nothing is charged for more; \
2003 to free one, revoke a host you no longer use on the Hosts page, or upgrade the plan; \
2004 Team gives every seat its own allowance"
2005 );
2006 assert_eq!(
2007 quota("connected_instances", 2, "wait"),
2008 "all hosts that may be connected at once are connected (2 of 2); \
2009 nothing is charged for more; to free one, disconnect a host (`lean-ctx cloud disconnect` on that machine)"
2010 );
2011 for resource in ["registered_instances", "connected_instances"] {
2014 let line = quota(resource, 2, "upgrade_team");
2015 for word in ["instance", "slot", "workspace"] {
2016 assert!(!line.contains(word), "{word} in {line}");
2017 }
2018 }
2019 let monthly = CloudError::from_response(
2021 429,
2022 &json!({"error": {"code": "quota_exceeded", "message": "x", "resource": "bus_messages",
2023 "limit": 200_000, "used": 200_000, "next_step": "wait",
2024 "reset_at": "2026-12-01T00:00:00Z", "retry_after_s": 60}}),
2025 );
2026 assert_eq!(
2027 monthly.to_string(),
2028 "this workspace has used all its monthly bus messages (200000 of 200000); nothing is charged for more; uploads wait in the local outbox until 2026-12-01T00:00:00Z"
2029 );
2030 let feature = CloudError::from_response(
2032 402,
2033 &json!({"error": {"code": "plan_required", "message": "", "feature": "audit_export",
2034 "plan_needed": "team", "next_step": "upgrade_team"}}),
2035 );
2036 assert_eq!(
2037 feature.to_string(),
2038 "audit export is included in Team and Enterprise; Team gives every seat its own allowance"
2039 );
2040 let locked = CloudError::from_response(
2041 402,
2042 &json!({"error": {"code": "plan_required", "message": "x", "feature": "read_only",
2043 "reason": "trial_ended", "plan": "locked", "next_step": "subscribe",
2044 "plan_needed": "personal"}}),
2045 );
2046 assert_eq!(
2047 locked.to_string(),
2048 "Your Personal trial has ended: this workspace is locked (read and export only). Choose a plan in LeanCTX Cloud to sync again."
2049 );
2050 }
2051
2052 #[test]
2053 fn bytes_are_worded_in_binary_units() {
2054 assert_eq!(bytes_text(0), "0 B");
2055 assert_eq!(bytes_text(1023), "1023 B");
2056 assert_eq!(bytes_text(256 << 20), "256 MiB");
2057 assert_eq!(bytes_text(40 << 30), "40 GiB");
2058 assert_eq!(bytes_text(3 << 29), "1.5 GiB");
2059 assert_eq!(bytes_text(u64::MAX), "16777215.9 TiB");
2060 }
2061
2062 #[test]
2063 fn a_huge_retry_after_is_capped_on_the_way_in() {
2064 for huge in [u64::MAX, i64::MAX.unsigned_abs(), RETRY_AFTER_CAP_S + 1] {
2065 let error = CloudError::from_response(
2066 429,
2067 &json!({"error": {"code": "rate_limited", "message": "x", "retry_after_s": huge}}),
2068 );
2069 assert_eq!(
2070 error,
2071 CloudError::RateLimited {
2072 retry_after: Some(RETRY_AFTER_CAP_S)
2073 }
2074 );
2075 }
2076 let small = CloudError::from_response(
2077 429,
2078 &json!({"error": {"code": "rate_limited", "message": "x", "retry_after_s": 90}}),
2079 );
2080 assert_eq!(
2081 small,
2082 CloudError::RateLimited {
2083 retry_after: Some(90)
2084 }
2085 );
2086 }
2087
2088 #[test]
2089 fn upload_disabled_names_the_kind_and_is_not_retried() {
2090 let error = CloudError::from_response(
2091 403,
2092 &json!({"error": {"code": "upload_disabled", "message": "x", "kind": "metrics"}}),
2093 );
2094 assert_eq!(error, CloudError::UploadDisabled(CloudUploadKind::Metrics));
2095 assert!(!error.is_transient());
2096 assert!(error.to_string().contains("metrics upload off"));
2097 }
2098
2099 #[test]
2100 fn task_reasons_become_task_refusals_and_others_stay() {
2101 let refusal = |status, code: &str, reason: &str| {
2102 CloudError::from_response(
2103 status,
2104 &json!({"error": {"code": code, "message": "x", "reason": reason, "number": 7, "retry_after_s": 60}}),
2105 )
2106 };
2107 assert_eq!(
2108 refusal(409, "invalid_state", "stale_claim"),
2109 CloudError::Task {
2110 refusal: TaskRefusal::StaleClaim,
2111 number: Some(7),
2112 detail: None
2113 }
2114 );
2115 assert_eq!(
2116 refusal(403, "forbidden_right", "optin_scope"),
2117 CloudError::Task {
2118 refusal: TaskRefusal::OptinScope,
2119 number: Some(7),
2120 detail: None
2121 }
2122 );
2123 let permit_said = |check: &str, agent_role: Option<&str>, message: &str| {
2125 let mut e = json!({"error": {"code": "forbidden_right", "message": message,
2126 "reason": "not_permitted", "number": 7, "check": check,
2127 "role": "backend"}});
2128 if let Some(r) = agent_role {
2129 e["error"]["agent_role"] = r.into();
2130 }
2131 CloudError::from_response(403, &e).to_string()
2132 };
2133 let permit = |check: &str, agent_role: Option<&str>| permit_said(check, agent_role, "");
2134 assert_eq!(
2135 permit("presence", None),
2136 "task #7: this agent is not on the bus: its session (or the relay) must be running and announce it with the task's role (the task needs role backend) [check: presence] Run `lean-ctx cloud bus relay --for 30`: it says who this machine announced, or why an agent is missing. LeanCTX Cloud keeps an agent present only while a relay stays connected (the daemon's), so claim while it runs."
2137 );
2138 assert_eq!(
2139 permit("role", Some("web")),
2140 "task #7: this agent is on the bus in another role than the task needs (the agent works as web, the task needs backend) [check: role]"
2141 );
2142 assert!(
2143 permit("role", Some("web\u{1b}[31m"))
2144 .ends_with("(the task needs role backend) [check: role]"),
2145 "a role that is not a bus identifier is not printed"
2146 );
2147 assert_eq!(
2149 permit_said(
2150 "presence",
2151 None,
2152 "Agent coder-1 is not on the bus: this task needs it present with role backend. Start its session (or the relay) and claim again."
2153 ),
2154 "task #7: Agent coder-1 is not on the bus: this task needs it present with role backend. Start its session (or the relay) and claim again. [check: presence] Run `lean-ctx cloud bus relay --for 30`: it says who this machine announced, or why an agent is missing. LeanCTX Cloud keeps an agent present only while a relay stays connected (the daemon's), so claim while it runs."
2155 );
2156 assert_eq!(
2157 permit_said(
2158 "role",
2159 Some("web"),
2160 "Agent coder-1 works as role web;\u{1b}[31m this task needs role backend."
2161 ),
2162 "task #7: Agent coder-1 works as role web; [31m this task needs role backend. [check: role]",
2163 "control characters of the service's message never reach the terminal"
2164 );
2165 assert_eq!(
2167 permit_said("", None, "Agent coder-1 may not take this task."),
2168 "task #7: Agent coder-1 may not take this task."
2169 );
2170 let inactive = refusal(409, "invalid_state", "optin_inactive");
2171 assert!(matches!(inactive, CloudError::Task { refusal, .. } if refusal.ends_claim()));
2172 assert!(matches!(
2173 refusal(409, "invalid_state", "optin_changed"),
2174 CloudError::Task {
2175 refusal: TaskRefusal::OptinChanged,
2176 ..
2177 }
2178 ));
2179 let budget = refusal(429, "rate_limited", "daily_budget");
2180 assert_eq!(
2181 budget,
2182 CloudError::Task {
2183 refusal: TaskRefusal::DailyBudget {
2184 retry_after: Some(60)
2185 },
2186 number: Some(7),
2187 detail: None
2188 }
2189 );
2190 assert!(!budget.is_transient(), "a used-up budget is not retried");
2191 assert!(
2192 budget
2193 .to_string()
2194 .starts_with("task #7: today's task budget")
2195 );
2196 for (fixture, expected) in [
2198 ("error.optin_scope.json", TaskRefusal::OptinScope),
2199 ("error.optin_changed.json", TaskRefusal::OptinChanged),
2200 ("error.optin_inactive.json", TaskRefusal::OptinInactive),
2201 (
2202 "error.daily_budget.json",
2203 TaskRefusal::DailyBudget {
2204 retry_after: Some(43200),
2205 },
2206 ),
2207 ("error.task_claimed.json", TaskRefusal::Claimed),
2208 (
2209 "error.task_not_permitted.json",
2210 TaskRefusal::NotPermitted(PermitCheck::Unknown),
2211 ),
2212 (
2213 "error.task_not_permitted_role.json",
2214 TaskRefusal::NotPermitted(PermitCheck::Role),
2215 ),
2216 ] {
2217 let path = format!(
2218 "{}/crates/lean-ctx-protocol/tests/fixtures/cloud/{fixture}",
2219 concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
2220 );
2221 let body: serde_json::Value =
2222 serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
2223 let code: CloudErrorCode =
2224 serde_json::from_value(body["error"]["code"].clone()).unwrap();
2225 assert!(
2226 matches!(
2227 CloudError::from_response(code.http_status(), &body),
2228 CloudError::Task { refusal, .. } if refusal == expected
2229 ),
2230 "{fixture}"
2231 );
2232 }
2233 for (fixture, expected) in [
2235 (
2236 "task_verify.error.self_verify.json",
2237 TaskRefusal::SelfVerify,
2238 ),
2239 (
2240 "task_verify.error.not_submitted.json",
2241 TaskRefusal::NotSubmitted,
2242 ),
2243 ] {
2244 let path = format!(
2245 "{}/crates/lean-ctx-protocol/tests/fixtures/cloud-v2/routes/{fixture}",
2246 concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
2247 );
2248 let body: serde_json::Value =
2249 serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
2250 let code: CloudErrorCode =
2251 serde_json::from_value(body["error"]["code"].clone()).unwrap();
2252 assert!(
2253 matches!(
2254 CloudError::from_response(code.http_status(), &body),
2255 CloudError::Task { refusal, .. } if refusal == expected
2256 ),
2257 "{fixture}"
2258 );
2259 }
2260 assert_eq!(
2261 refusal(403, "forbidden_right", "vetoed"),
2262 CloudError::Vetoed
2263 );
2264 assert_eq!(
2265 refusal(409, "invalid_state", "code_graph_disabled"),
2266 CloudError::Server {
2267 status: 409,
2268 code: "invalid_state".into()
2269 },
2270 "a reason of another section keeps its old meaning"
2271 );
2272 }
2273
2274 fn plan_required_example(file: &str, feature: &str) -> (u16, serde_json::Value) {
2276 let path = format!(
2277 "{}/crates/lean-ctx-protocol/tests/fixtures/cloud-v2/web/{file}",
2278 concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
2279 );
2280 let fixture: serde_json::Value =
2281 serde_json::from_slice(&std::fs::read(&path).expect(&path)).expect(&path);
2282 let example = fixture["errors"]
2283 .as_array()
2284 .expect("errors")
2285 .iter()
2286 .find(|e| {
2287 e["body"]["error"]["code"] == "plan_required"
2288 && e["body"]["error"]["feature"] == feature
2289 })
2290 .unwrap_or_else(|| panic!("{file}: no plan_required {feature}"));
2291 (
2292 u16::try_from(example["status"].as_u64().unwrap()).unwrap(),
2293 example["body"].clone(),
2294 )
2295 }
2296
2297 #[test]
2298 fn plan_required_keeps_the_feature_and_words_it() {
2299 let (status, body) = plan_required_example("vault-transfer.json", "repos");
2301 assert_eq!(status, 402);
2302 let error = CloudError::from_response(status, &body);
2303 assert!(
2304 matches!(&error, CloudError::PlanRequired(need) if need.feature.as_deref() == Some("repos"))
2305 );
2306 assert_eq!(
2307 error.clone().with_plan(CloudPlan::Unknown),
2308 error,
2309 "an unknown plan is not named"
2310 );
2311 assert!(!error.is_transient());
2312 let repos = error.with_plan(CloudPlan::NoPlan);
2313 assert!(!repos.to_string().contains("engine"));
2314 assert_eq!(
2315 repos.to_string(),
2316 "this workspace has used all its vaults (3 of 3); more are included in Personal, Team and Enterprise; this workspace has no plan; remove or publish a vault in LeanCTX Cloud, or upgrade the plan"
2317 );
2318
2319 let (status, body) = plan_required_example("organisation-create.json", "company");
2321 let org = CloudError::from_response(status, &body).with_plan(CloudPlan::Team);
2322 assert_eq!(
2323 org.to_string(),
2324 "A company comes with Enterprise, on request: send a request and we set it up with you; this workspace is on Team"
2325 );
2326 let unnamed = CloudError::from_response(
2327 402,
2328 &json!({"error": {"code": "plan_required", "message": "", "feature": "audit_export", "plan_needed": "team"}}),
2329 );
2330 assert_eq!(
2331 unnamed.to_string(),
2332 "audit export is included in Team and Enterprise"
2333 );
2334 let hostile = CloudError::from_response(
2335 402,
2336 &json!({"error": {"code": "plan_required", "message": "x\u{1b}[2J", "feature": "Comp\u{1b}"}}),
2337 );
2338 assert_eq!(
2339 hostile,
2340 CloudError::PlanRequired(Box::new(PlanNeed {
2341 message: Some("x [2J".into()),
2342 ..PlanNeed::default()
2343 })),
2344 "a feature that is not a wire token is dropped, the message is terminal-safe"
2345 );
2346 }
2347
2348 #[test]
2349 fn plan_required_without_a_feature_keeps_the_1x_seat_text() {
2350 let path = format!(
2351 "{}/crates/lean-ctx-protocol/tests/fixtures/cloud/error.plan_required.json",
2352 concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
2353 );
2354 let body: serde_json::Value =
2355 serde_json::from_slice(&std::fs::read(&path).expect(&path)).expect(&path);
2356 let error = CloudError::from_response(402, &body).with_plan(CloudPlan::NoPlan);
2357 assert_eq!(
2358 error.to_string(),
2359 "this workspace's plan does not include LeanCTX Cloud here (Personal up to 3 hosts registered, up to 2 connected at once; Team and Enterprise up to 3 hosts registered, up to 2 connected at once per seat)"
2360 );
2361 assert!(
2362 matches!(&error, CloudError::PlanRequired(need) if need.plan.is_none()),
2363 "a 1.x refusal is about LeanCTX Cloud itself, not a feature of the plan"
2364 );
2365 }
2366
2367 #[test]
2368 fn a_locked_workspace_is_one_line_whatever_the_feature() {
2369 let locked = |reason: &str, feature: Option<&str>, needed: &str| {
2370 let mut body = json!({"error": {"code": "plan_required", "message": "Your trial has ended: this workspace is locked.",
2371 "plan_needed": needed, "reason": reason}});
2372 if let Some(f) = feature {
2373 body["error"]["feature"] = f.into();
2374 }
2375 CloudError::from_response(402, &body)
2376 };
2377 let trial = "Your Personal trial has ended: this workspace is locked (read and export only). Choose a plan in LeanCTX Cloud to sync again.";
2378 for feature in [None, Some("read_only")] {
2379 let e = locked("trial_ended", feature, "personal");
2380 assert_eq!(e.to_string(), trial);
2381 assert!(matches!(&e, CloudError::PlanRequired(n) if n.locked() == Some("trial_ended")));
2382 assert_eq!(
2383 e.with_plan(CloudPlan::Personal).to_string(),
2384 trial,
2385 "the lease's plan adds nothing to the line"
2386 );
2387 }
2388 assert_eq!(
2389 locked("plan_ended", Some("read_only"), "team").to_string(),
2390 "Your plan has ended: this workspace is locked (read and export only). Choose a plan in LeanCTX Cloud to sync again."
2391 );
2392 assert_eq!(
2393 locked("trial_ended", None, "team").to_string(),
2394 "Your Team trial has ended: this workspace is locked (read and export only). Choose a plan in LeanCTX Cloud to sync again."
2395 );
2396 let no_plan = locked("no_plan", None, "personal");
2398 assert!(
2399 no_plan.to_string().contains("2 connected at once"),
2400 "{no_plan}"
2401 );
2402 assert!(!no_plan.to_string().contains(LOCKED_MARK));
2403 }
2404
2405 #[test]
2406 fn non_contract_bodies_become_server_errors() {
2407 assert_eq!(
2408 CloudError::from_response(502, &json!("<html>")),
2409 CloudError::Server {
2410 status: 502,
2411 code: "unknown".into()
2412 }
2413 );
2414 assert!(
2415 CloudError::Server {
2416 status: 502,
2417 code: "unknown".into()
2418 }
2419 .is_transient()
2420 );
2421 }
2422
2423 #[test]
2424 fn a_role_that_may_not_add_a_vault_is_forbidden() {
2425 let body = json!({"error": {
2426 "code": "vault_create_forbidden",
2427 "message": "Only an owner, admin or maintainer of this team can add a new vault.",
2428 "role_needed": "maintainer",
2429 }});
2430 assert_eq!(CloudError::from_response(403, &body), CloudError::Forbidden);
2431 assert_ne!(CloudError::from_response(500, &body), CloudError::Forbidden);
2433 }
2434}