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 3 instances, 2 connected at once; Team and Enterprise 3 per seat, 2 connected at once per seat";
272
273impl PlanNeed {
274 #[must_use]
276 pub fn locked(&self) -> Option<&str> {
277 self.reason
278 .as_deref()
279 .filter(|r| matches!(*r, "trial_ended" | "plan_ended"))
280 }
281
282 #[must_use]
284 pub fn trial_used(&self) -> bool {
285 self.reason.as_deref() == Some(TRIAL_USED)
286 }
287
288 fn plan_word(&self) -> &'static str {
290 let team = self.plan_needed.as_deref() == Some("team")
291 || matches!(self.plan, Some(CloudPlan::Team | CloudPlan::Enterprise));
292 if team { "Team" } else { "Personal" }
293 }
294}
295
296#[must_use]
298pub fn locked_line(reason: &str, plan_word: &str) -> String {
299 let what = if reason == "trial_ended" {
300 format!("Your {plan_word} trial has ended")
301 } else {
302 "Your plan has ended".to_string()
303 };
304 format!("{what}: {LOCKED_MARK}. Choose a plan in LeanCTX Cloud to sync again.")
305}
306
307fn plans_from(needed: &str) -> Option<&'static str> {
309 Some(match needed {
310 "personal" => "Personal, Team and Enterprise",
311 "team" => "Team and Enterprise",
312 "enterprise" => "Enterprise",
313 _ => return None,
314 })
315}
316
317fn write_plan_need(f: &mut fmt::Formatter<'_>, need: &PlanNeed) -> fmt::Result {
318 if need.trial_used() {
319 let plan = need.plan_word();
320 match need.trial_reason.as_deref() {
321 Some("trial_ended") => write!(
322 f,
323 "the {plan} trial of this address has ended; no second trial starts. Choose a plan"
324 )?,
325 Some("no_plan") => write!(
326 f,
327 "this address has no {plan} trial left and no plan; no second trial starts. Choose a plan"
328 )?,
329 _ => write!(
330 f,
331 "this address already had its {plan} trial; no second trial starts. Choose a plan"
332 )?,
333 }
334 return match need.plans_url.as_deref().filter(|u| u.starts_with("http")) {
335 Some(url) => write!(f, " at {url}, then run `lean-ctx cloud connect`"),
336 None => f.write_str(" in LeanCTX Cloud, then run `lean-ctx cloud connect`"),
337 };
338 }
339 if let Some(reason) = need.locked() {
341 return f.write_str(&locked_line(reason, need.plan_word()));
342 }
343 let Some(feature) = need.feature.as_deref() else {
344 return write!(
346 f,
347 "this workspace's plan does not include LeanCTX Cloud here ({PLAN_LIMITS})"
348 );
349 };
350 let plans = need.plan_needed.as_deref().and_then(plans_from);
351 let on = need
352 .plan
353 .filter(|p| *p != CloudPlan::Unknown)
354 .map(|p| match p {
355 CloudPlan::NoPlan => "; this workspace has no plan".to_string(),
356 p => format!("; this workspace is on {}", p.display_name()),
357 })
358 .unwrap_or_default();
359 match feature {
360 "repos" | "vaults" | "private_vaults" => {
361 f.write_str("this workspace has used all its vaults")?;
362 if let (Some(used), Some(limit)) = (need.used, need.limit) {
363 write!(f, " ({used} of {limit})")?;
364 }
365 if let Some(plans) = plans {
366 write!(f, "; more are included in {plans}")?;
367 }
368 write!(
369 f,
370 "{on}; remove or publish a vault in LeanCTX Cloud, or upgrade the plan"
371 )
372 }
373 other => {
374 match (&need.message, plans) {
375 (Some(message), _) => f.write_str(message.trim_end_matches('.'))?,
376 (None, Some(plans)) => {
377 write!(f, "{} is included in {plans}", other.replace('_', " "))?;
378 }
379 (None, None) => write!(
380 f,
381 "this workspace's plan does not include {}",
382 other.replace('_', " ")
383 )?,
384 }
385 f.write_str(&on)
386 }
387 }
388}
389
390pub const MONTHLY_RESOURCES: &[&str] =
392 &["transfer_bytes", "bus_messages", "model_credit_usd_micros"];
393
394impl Quota {
395 #[must_use]
397 pub fn waits(&self) -> bool {
398 self.status == 429 || MONTHLY_RESOURCES.contains(&self.resource.as_str())
399 }
400
401 #[must_use]
403 pub fn cooling_slot(&self) -> bool {
404 self.resource == "registered_instances"
405 && self.cooldown_days.is_some_and(|d| d > 0)
406 && self.reset_at.is_some()
407 }
408}
409
410#[derive(Debug, Clone, PartialEq, Eq, Default)]
412pub struct PolicyDenial {
413 pub member: Option<String>,
415 pub level: Option<String>,
417 pub action: Option<String>,
419}
420
421fn wire_token(value: Option<&str>, max: usize) -> Option<String> {
423 value
424 .filter(|s| {
425 (1..=max).contains(&s.len())
426 && s.bytes().all(|b| {
427 b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'_' | b'.' | b'-')
428 })
429 })
430 .map(str::to_string)
431}
432
433pub(crate) fn wire_time(value: Option<&str>) -> Option<String> {
435 let parsed = lean_ctx_time::OffsetDateTime::parse_from_rfc3339(value?).ok()?;
436 Some(
437 parsed
438 .to_utc()
439 .to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true),
440 )
441}
442
443pub const TRIAL_USED: &str = "trial_used";
445pub const NOT_READY: &str = "not_ready";
448
449fn web_url(value: Option<&str>) -> Option<String> {
455 value
456 .filter(|s| {
457 (s.starts_with("https://")
458 || s.starts_with("http://")
459 || (s.starts_with('/') && !s.starts_with("//")))
460 && s.len() <= 512
461 && !s.chars().any(hidden_in_url)
462 })
463 .map(str::to_string)
464}
465
466fn hidden_in_url(c: char) -> bool {
468 use unicode_general_category::{GeneralCategory, get_general_category};
469 c.is_control()
470 || c.is_whitespace()
471 || get_general_category(c) == GeneralCategory::Format
472 || lean_ctx_protocol::cloud::invisible(c)
473}
474
475fn same_origin(url: &str, base: &str) -> bool {
478 let Some(start) = url.find("://").map(|i| i + 3) else {
479 return false;
480 };
481 let end = url[start..]
482 .find(['/', '?', '#'])
483 .map_or(url.len(), |i| start + i);
484 url[..end].eq_ignore_ascii_case(base)
485}
486
487#[derive(Debug, Clone, PartialEq, Eq, Default)]
489pub struct Revocation {
490 pub workspace: Option<String>,
492 pub reason: Option<String>,
494 pub revoked_at: Option<u64>,
496 pub instance_id: Option<String>,
498}
499
500impl Revocation {
501 fn of_statement(statement: &serde_json::Value) -> Self {
504 let token = |v: &serde_json::Value, max: usize| {
505 v.as_str()
506 .filter(|s| {
507 (1..=max).contains(&s.len())
508 && s.bytes().all(|b| {
509 b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_' || b == b'-'
510 })
511 })
512 .map(str::to_string)
513 };
514 Self {
515 workspace: None,
516 reason: token(&statement["reason"], 32),
517 revoked_at: statement["revoked_at"].as_u64(),
518 instance_id: token(&statement["instance_id"], 36),
519 }
520 }
521}
522
523#[derive(Debug, Clone, Copy, PartialEq, Eq)]
525pub enum PermitCheck {
526 Presence,
528 Role,
530 Unknown,
532}
533
534#[derive(Debug, Clone, Copy, PartialEq, Eq)]
536pub enum TaskRefusal {
537 Claimed,
539 NotOpen,
541 StaleClaim,
543 Closed,
545 SelfVerify,
547 NotSubmitted,
549 NotPermitted(PermitCheck),
551 OptinScope,
554 OptinChanged,
557 OptinInactive,
560 DailyBudget { retry_after: Option<u64> },
563 StaleBase,
566}
567
568impl TaskRefusal {
569 fn from_reason(
570 code: CloudErrorCode,
571 reason: Option<&str>,
572 retry_after: Option<u64>,
573 check: Option<&str>,
574 ) -> Option<Self> {
575 Some(match (code, reason?) {
576 (CloudErrorCode::InvalidState, "task_claimed") => Self::Claimed,
577 (CloudErrorCode::InvalidState, "task_not_open") => Self::NotOpen,
578 (CloudErrorCode::InvalidState, "stale_claim") => Self::StaleClaim,
579 (CloudErrorCode::InvalidState, "task_closed") => Self::Closed,
580 (CloudErrorCode::ForbiddenRight, "self_verify") => Self::SelfVerify,
581 (CloudErrorCode::InvalidState, "not_submitted") => Self::NotSubmitted,
582 (CloudErrorCode::ForbiddenRight, "not_permitted") => Self::NotPermitted(match check {
583 Some("presence") => PermitCheck::Presence,
584 Some("role") => PermitCheck::Role,
585 _ => PermitCheck::Unknown,
586 }),
587 (CloudErrorCode::ForbiddenRight, "optin_scope") => Self::OptinScope,
588 (CloudErrorCode::InvalidState, "optin_changed") => Self::OptinChanged,
589 (CloudErrorCode::InvalidState, "optin_inactive") => Self::OptinInactive,
590 (CloudErrorCode::RateLimited, "daily_budget") => Self::DailyBudget { retry_after },
591 (CloudErrorCode::InvalidState | CloudErrorCode::RevisionConflict, "stale_base") => {
592 Self::StaleBase
593 }
594 _ => return None,
595 })
596 }
597
598 #[must_use]
601 pub fn ends_claim(self) -> bool {
602 matches!(self, Self::StaleClaim | Self::Closed | Self::OptinInactive)
603 }
604}
605
606impl fmt::Display for TaskRefusal {
607 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
608 match self {
609 Self::Claimed => f.write_str("another agent holds the task"),
610 Self::NotOpen => f.write_str("the task is not open"),
611 Self::StaleClaim => f.write_str("this claim is no longer the task's claim"),
612 Self::Closed => f.write_str("the task is closed"),
613 Self::SelfVerify => f.write_str(
614 "the agent that did the work does not check its own result; another agent verifies it",
615 ),
616 Self::NotSubmitted => f.write_str("the task has no result waiting for a check"),
617 Self::NotPermitted(PermitCheck::Presence) => f.write_str(
618 "this agent is not on the bus: its session (or the relay) must be running and announce it with the task's role",
619 ),
620 Self::NotPermitted(PermitCheck::Role) => {
621 f.write_str("this agent is on the bus in another role than the task needs")
622 }
623 Self::NotPermitted(PermitCheck::Unknown) => f.write_str(
624 "the task's role or the owner's worker consent does not allow this agent",
625 ),
626 Self::OptinScope => f.write_str("this instance's opt-in does not cover this vault"),
627 Self::OptinChanged => f.write_str("the opt-in changed; it is read again"),
628 Self::OptinInactive => f.write_str(
629 "this instance is not opted in (or the owner stopped worker mode on the web)",
630 ),
631 Self::StaleBase => f.write_str(
632 "the task's priority or labels changed meanwhile; read it again and retry",
633 ),
634 Self::DailyBudget { retry_after } => match retry_after {
635 Some(s) => write!(f, "today's task budget is used up (resets in {s} s)"),
636 None => f.write_str("today's task budget is used up"),
637 },
638 }
639 }
640}
641
642fn bus_role(role: Option<&String>) -> Option<&str> {
645 role.map(String::as_str).filter(|r| {
646 (1..=64).contains(&r.len())
647 && r.bytes()
648 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
649 })
650}
651
652pub(crate) fn safe_message(message: &str) -> Option<String> {
655 let text: String = message
656 .chars()
657 .map(|c| if c.is_control() { ' ' } else { c })
658 .take(300)
659 .collect();
660 let text = text.trim();
661 (!text.is_empty()).then(|| text.to_string())
662}
663
664fn permit_line(refusal: TaskRefusal, detail: &CloudErrorDetailV1) -> Option<String> {
668 let TaskRefusal::NotPermitted(check) = refusal else {
669 return None;
670 };
671 let mut line =
672 safe_message(&detail.message).unwrap_or_else(|| match permit_roles(refusal, detail) {
673 Some(roles) => format!("{refusal} ({roles})"),
674 None => refusal.to_string(),
675 });
676 match check {
677 PermitCheck::Presence => line.push_str(
678 " [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.",
679 ),
680 PermitCheck::Role => line.push_str(" [check: role]"),
681 PermitCheck::Unknown => {}
682 }
683 Some(line)
684}
685
686fn permit_roles(refusal: TaskRefusal, detail: &CloudErrorDetailV1) -> Option<String> {
688 let role = bus_role(detail.role.as_ref())?;
689 match refusal {
690 TaskRefusal::NotPermitted(PermitCheck::Presence) => {
691 Some(format!("the task needs role {role}"))
692 }
693 TaskRefusal::NotPermitted(PermitCheck::Role) => {
694 Some(match bus_role(detail.agent_role.as_ref()) {
695 Some(agent_role) => {
696 format!("the agent works as {agent_role}, the task needs {role}")
697 }
698 None => format!("the task needs role {role}"),
699 })
700 }
701 _ => None,
702 }
703}
704
705fn lenient_u64(value: &serde_json::Value) -> Option<u64> {
707 value
708 .as_u64()
709 .or_else(|| value.as_str().and_then(|s| s.trim().parse().ok()))
710}
711
712fn lenient_detail(error: &serde_json::Value) -> Option<CloudErrorDetailV1> {
717 let object = error.as_object()?;
718 let code = object.get("code").filter(|c| c.is_string())?.clone();
719 let message = object
720 .get("message")
721 .filter(|m| m.is_string())
722 .cloned()
723 .unwrap_or_else(|| serde_json::Value::String(String::new()));
724 let base = || {
725 let mut kept = serde_json::Map::new();
726 kept.insert("code".into(), code.clone());
727 kept.insert("message".into(), message.clone());
728 kept
729 };
730 let decodes = |kept: &serde_json::Map<String, serde_json::Value>| {
731 serde_json::from_value::<CloudErrorDetailV1>(serde_json::Value::Object(kept.clone()))
732 .is_ok()
733 };
734 let mut kept = base();
735 for (name, value) in object {
736 if matches!(name.as_str(), "code" | "message") {
737 continue;
738 }
739 let candidates = [
740 Some(value.clone()),
741 lenient_u64(value).map(serde_json::Value::from),
742 ];
743 for candidate in candidates.into_iter().flatten() {
744 let mut probe = base();
745 probe.insert(name.clone(), candidate.clone());
746 if decodes(&probe) {
747 kept.insert(name.clone(), candidate);
748 break;
749 }
750 }
751 }
752 serde_json::from_value(serde_json::Value::Object(kept)).ok()
753}
754
755pub const RETRY_AFTER_CAP_S: u64 = 32 * 86_400;
758
759impl CloudError {
760 pub(crate) fn from_response(status: u16, body: &serde_json::Value) -> Self {
762 let value_reason = body["error"]["reason"].clone();
763 let revocation = body["error"]["revocation"].clone();
764 let trial_used = body["error"]["code"].as_str() == Some(TRIAL_USED);
765 let plans_url = web_url(body["error"]["plans_url"].as_str());
766 let decoded = serde_json::from_value::<CloudErrorBody>(body.clone())
767 .map(|body| body.error)
768 .ok()
769 .or_else(|| lenient_detail(&body["error"]));
770 if status == 409 && body["error"]["code"].as_str() == Some(NOT_READY) {
773 return Self::Server {
774 status,
775 code: NOT_READY.into(),
776 };
777 }
778 let Some(mut detail) = decoded else {
779 return Self::of_status(status, lenient_u64(&body["error"]["retry_after_s"]));
780 };
781 detail.retry_after_s = detail.retry_after_s.map(|s| s.min(RETRY_AFTER_CAP_S));
784 if let Some(refusal) = TaskRefusal::from_reason(
785 detail.code,
786 detail.reason.as_deref(),
787 detail.retry_after_s,
788 detail.check.as_deref(),
789 ) {
790 return Self::Task {
791 refusal,
792 number: detail.number,
793 detail: permit_line(refusal, &detail),
794 };
795 }
796 let next_step = NextStep::of_wire(detail.next_step.as_deref());
797 if trial_used {
800 return Self::PlanRequired(Box::new(PlanNeed {
801 plan_needed: wire_token(detail.plan_needed.as_deref(), 32),
802 message: safe_message(&detail.message),
803 reason: Some(TRIAL_USED.into()),
804 next_step,
805 plans_url,
806 trial_reason: wire_token(detail.reason.as_deref(), 32),
807 ..PlanNeed::default()
808 }));
809 }
810 match detail.code {
811 CloudErrorCode::Unauthorized => Self::Unauthorized,
812 CloudErrorCode::LeaseExpired => Self::LeaseLapsed,
813 CloudErrorCode::InstanceRevoked => Self::Revoked(Revocation::of_statement(&revocation)),
814 CloudErrorCode::PlanRequired => Self::PlanRequired(Box::new(PlanNeed {
815 feature: wire_token(detail.feature.as_deref(), 64),
816 plan_needed: wire_token(detail.plan_needed.as_deref(), 32),
817 limit: detail.limit,
818 used: detail.used,
819 message: safe_message(&detail.message),
820 plan: None,
821 reason: wire_token(detail.reason.as_deref(), 32),
822 next_step,
823 plans_url: None,
824 trial_reason: None,
825 })),
826 CloudErrorCode::InstanceLimit => Self::InstanceLimit(Box::new(InstanceCap {
827 resource: wire_token(detail.resource.as_deref(), 64),
828 limit: detail.limit,
829 used: detail.used,
830 seats: detail.seats,
831 per_seat: detail.per_seat,
832 next_step,
833 })),
834 CloudErrorCode::QuotaExceeded => Self::QuotaExceeded(Box::new(Quota {
835 status,
836 resource: wire_token(detail.resource.as_deref(), 64)
837 .unwrap_or_else(|| "unknown".into()),
838 limit: detail.limit,
839 used: detail.used,
840 reset_at: wire_time(detail.reset_at.as_deref()),
841 retry_after: detail.retry_after_s,
842 cooldown_days: detail.cooldown_days,
843 next_step,
844 })),
845 CloudErrorCode::StorageQuotaExceeded => Self::StorageFull(Box::new(StorageFull {
846 limit: detail.limit_bytes.or(detail.limit),
847 used: detail.used_bytes.or(detail.used),
848 next_step,
849 })),
850 CloudErrorCode::UploadRateLimited => Self::UploadRateLimited {
851 retry_after: detail.retry_after_s,
852 per_hour: detail.limit_bytes_per_hour,
853 },
854 CloudErrorCode::PolicyDenied => Self::PolicyDenied(PolicyDenial {
857 member: wire_token(detail.member.as_deref().or(detail.field.as_deref()), 80),
858 level: wire_token(
859 detail.level.as_deref().or(detail
860 .reason
861 .as_deref()
862 .filter(|r| matches!(*r, "org" | "workspace" | "vault" | "instance"))),
863 16,
864 ),
865 action: wire_token(detail.action.as_deref(), 64),
866 }),
867 CloudErrorCode::ForbiddenRight if value_reason.as_str() == Some("vetoed") => {
868 Self::Vetoed
869 }
870 CloudErrorCode::ForbiddenRight => Self::Forbidden,
871 CloudErrorCode::UploadDisabled => {
872 Self::UploadDisabled(detail.kind.unwrap_or(CloudUploadKind::Unknown))
873 }
874 CloudErrorCode::NotFound => Self::NotFound,
875 CloudErrorCode::FeatureDisabled => Self::FeatureDisabled {
876 feature: wire_token(detail.feature.as_deref(), 64),
877 },
878 CloudErrorCode::RevisionConflict => Self::Conflict {
879 expected: detail.expected,
880 actual: detail.actual,
881 },
882 CloudErrorCode::ScreeningRequired => Self::ScreeningBlocked,
883 CloudErrorCode::UpgradeRequired => Self::UpgradeRequired {
884 min: detail.min_instance,
885 },
886 CloudErrorCode::RateLimited => Self::RateLimited {
887 retry_after: detail.retry_after_s,
888 },
889 CloudErrorCode::ExpiredToken => Self::DeviceFlow(CODE_EXPIRED.into()),
890 CloudErrorCode::AccessDenied => Self::DeviceFlow(CODE_DENIED.into()),
891 _ if status == 429 => Self::RateLimited {
894 retry_after: detail.retry_after_s,
895 },
896 CloudErrorCode::Unknown => Self::of_status(status, detail.retry_after_s),
897 other => Self::Server {
898 status,
899 code: serde_json::to_value(other)
900 .ok()
901 .and_then(|v| v.as_str().map(str::to_string))
902 .unwrap_or_else(|| "unknown".into()),
903 },
904 }
905 }
906
907 #[must_use]
913 pub fn with_origin(mut self, origin: &str) -> Self {
914 if let Self::PlanRequired(need) = &mut self
915 && let Some(url) = need.plans_url.take()
916 {
917 let base = origin.trim_end_matches('/');
918 need.plans_url = if !(base.starts_with("https://") || base.starts_with("http://")) {
919 None
920 } else if url.starts_with('/') {
921 Some(format!("{base}{url}"))
922 } else if same_origin(&url, base) {
923 Some(url)
924 } else {
925 None
926 };
927 }
928 self
929 }
930
931 #[must_use]
935 pub fn for_trial(self) -> Self {
936 match self {
937 Self::DeviceFlow(why) if why == CODE_EXPIRED => {
938 Self::DeviceFlow(TRIAL_CODE_EXPIRED.into())
939 }
940 other => other,
941 }
942 }
943
944 fn of_status(status: u16, retry_after: Option<u64>) -> Self {
947 match status {
948 429 => Self::RateLimited {
949 retry_after: retry_after.map(|s| s.min(RETRY_AFTER_CAP_S)),
950 },
951 413 => Self::Server {
952 status,
953 code: "payload_too_large".into(),
954 },
955 _ => Self::Server {
956 status,
957 code: "unknown".into(),
958 },
959 }
960 }
961
962 #[must_use]
965 pub fn with_plan(mut self, plan: CloudPlan) -> Self {
966 if let Self::PlanRequired(need) = &mut self
967 && (need.feature.is_some() || need.locked().is_some())
968 && plan != CloudPlan::Unknown
969 {
970 need.plan.get_or_insert(plan);
971 }
972 self
973 }
974
975 pub fn is_transient(&self) -> bool {
978 match self {
979 Self::QuotaExceeded(q) => q.waits(),
980 other => matches!(
981 other,
982 Self::Offline(_)
983 | Self::RateLimited { .. }
984 | Self::UploadRateLimited { .. }
985 | Self::Server {
986 status: 408 | 500..,
987 ..
988 }
989 ),
990 }
991 }
992
993 pub fn retry_after_at(&self, now: lean_ctx_time::UtcDateTime) -> Option<u64> {
997 match self {
998 Self::RateLimited { retry_after } | Self::UploadRateLimited { retry_after, .. } => {
999 *retry_after
1000 }
1001 Self::QuotaExceeded(q) if q.waits() => q.retry_after.or_else(|| {
1002 let reset =
1003 lean_ctx_time::OffsetDateTime::parse_from_rfc3339(q.reset_at.as_deref()?)
1004 .ok()?;
1005 u64::try_from((reset.to_utc() - now).num_seconds().max(1)).ok()
1006 }),
1007 _ => None,
1008 }
1009 }
1010}
1011
1012impl fmt::Display for CloudError {
1013 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1014 match self {
1015 Self::Offline(why) => write!(f, "LeanCTX Cloud is not reachable ({why})"),
1016 Self::NotConnected => f.write_str("not connected to LeanCTX Cloud (run `lean-ctx cloud connect`)"),
1017 Self::Unauthorized => f.write_str(
1018 "LeanCTX Cloud does not accept this instance any more (run `lean-ctx cloud connect` again)",
1019 ),
1020 Self::PlanRequired(need) => {
1021 write_plan_need(f, need)?;
1022 if need.locked().is_none() && !need.trial_used() {
1024 write_hint(f, need.next_step)?;
1025 }
1026 Ok(())
1027 }
1028 Self::InstanceLimit(cap) => write_instance_cap(f, cap),
1029 Self::QuotaExceeded(q) => write_quota(f, q),
1030 Self::StorageFull(s) => {
1031 f.write_str("this workspace's LeanCTX Cloud storage is full")?;
1032 if let (Some(used), Some(limit)) = (s.used, s.limit) {
1033 write!(f, " ({} of {})", bytes_text(used), bytes_text(limit))?;
1034 }
1035 f.write_str(
1036 "; nothing is charged for more; uploads stop until storage frees (remove vaults or files in LeanCTX Cloud)",
1037 )?;
1038 write_hint(f, s.next_step)
1039 }
1040 Self::UploadRateLimited {
1041 retry_after,
1042 per_hour,
1043 } => {
1044 f.write_str("LeanCTX Cloud's upload allowance for this hour is used up")?;
1045 if let Some(per_hour) = per_hour {
1046 write!(f, " ({} per hour)", bytes_text(*per_hour))?;
1047 }
1048 match retry_after {
1049 Some(s) => write!(f, "; the rest goes out in {s} s")?,
1050 None => f.write_str("; the rest goes out later")?,
1051 }
1052 f.write_str(" (a large first sync can take a few hours)")
1053 }
1054 Self::PolicyDenied(d) => {
1055 f.write_str("LeanCTX Cloud policy refuses this")?;
1056 if let Some(member) = &d.member {
1057 write!(f, " ({member}")?;
1058 if let Some(level) = &d.level {
1059 write!(f, ", set at the {level} level")?;
1060 }
1061 f.write_str(")")?;
1062 }
1063 match &d.action {
1064 Some(action) => write!(
1065 f,
1066 "; a person does this on the LeanCTX Cloud web ({})",
1067 action.replace('_', " ")
1068 ),
1069 None => f.write_str(
1070 "; it is not retried until an admin changes the policy in LeanCTX Cloud",
1071 ),
1072 }
1073 }
1074 Self::LeaseLapsed => {
1075 f.write_str("the LeanCTX Cloud lease has lapsed (run `lean-ctx cloud connect` again)")
1076 }
1077 Self::Revoked(r) => {
1078 f.write_str("this instance was revoked by ")?;
1079 match &r.workspace {
1080 Some(workspace) => f.write_str(workspace)?,
1081 None => f.write_str("its workspace")?,
1082 }
1083 if let Some(reason) = &r.reason {
1084 write!(f, " ({})", reason.replace('_', " "))?;
1085 }
1086 f.write_str("; reconnect with `lean-ctx cloud connect` after an admin allows it")
1087 }
1088 Self::Forbidden => f.write_str("this instance's lease does not allow that"),
1089 Self::Vetoed => f.write_str("a workspace veto bars it until the veto is lifted"),
1090 Self::UploadDisabled(kind) => match kind {
1091 CloudUploadKind::Metrics => {
1092 f.write_str("the workspace has switched metrics upload off")
1093 }
1094 CloudUploadKind::Receipts => {
1095 f.write_str("the workspace has switched receipts upload off")
1096 }
1097 CloudUploadKind::Unknown => {
1098 f.write_str("the workspace has switched this upload off")
1099 }
1100 },
1101 Self::NotFound => f.write_str("LeanCTX Cloud does not know that item"),
1102 Self::FeatureDisabled { feature } => match feature.as_deref() {
1103 Some("instance_metrics") | None => f.write_str(
1104 "this LeanCTX Cloud server has switched off instance metrics; nothing was sent",
1105 ),
1106 Some(other) => write!(
1107 f,
1108 "this LeanCTX Cloud server has switched off {}; nothing was sent",
1109 other.replace('_', " ")
1110 ),
1111 },
1112 Self::Conflict { expected, actual } => match (expected, actual) {
1113 (Some(e), Some(a)) => {
1114 write!(f, "knowledge moved on (expected revision {e}, now {a})")
1115 }
1116 _ => f.write_str("knowledge moved on"),
1117 },
1118 Self::ScreeningBlocked => f.write_str("LeanCTX Cloud screening refused the content"),
1119 Self::UpgradeRequired { min } => match min {
1120 Some(min) => write!(f, "LeanCTX Cloud needs lean-ctx {min} or newer (run `lean-ctx update`)"),
1121 None => f.write_str("LeanCTX Cloud needs a newer lean-ctx (run `lean-ctx update`)"),
1122 },
1123 Self::RateLimited { retry_after } => match retry_after {
1124 Some(s) => write!(f, "LeanCTX Cloud asks to retry in {s} s"),
1125 None => f.write_str("LeanCTX Cloud asks to retry later"),
1126 },
1127 Self::DeviceFlow(why) => write!(f, "connection not approved: {why}"),
1128 Self::TrialUnsupported { origin } => write!(
1129 f,
1130 "LeanCTX does not offer the one-step trial here yet. Start the trial on {origin}, or sign in with `lean-ctx cloud connect`"
1131 ),
1132 Self::Protocol(why) => write!(f, "unexpected answer from Cloud: {why}"),
1133 Self::Config(why) => write!(f, "Cloud configuration: {why}"),
1134 Self::Local(why) => write!(f, "local Cloud state: {why}"),
1135 Self::Refused(why) => f.write_str(why),
1136 Self::Task {
1137 refusal,
1138 number,
1139 detail,
1140 } => {
1141 if let Some(number) = number {
1142 write!(f, "task #{number}: ")?;
1143 }
1144 match detail {
1145 Some(detail) if matches!(refusal, TaskRefusal::NotPermitted(_)) => {
1147 f.write_str(detail)
1148 }
1149 Some(detail) => write!(f, "{refusal} ({detail})"),
1150 None => write!(f, "{refusal}"),
1151 }
1152 }
1153 Self::Server { status, code } => write!(f, "LeanCTX Cloud answered {status} ({code})"),
1154 }
1155 }
1156}
1157
1158impl std::error::Error for CloudError {}
1159
1160pub const CODE_EXPIRED: &str =
1162 "the code expired before it was approved; run `lean-ctx cloud connect` again for a new one";
1163
1164pub 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";
1166
1167pub const CODE_DENIED: &str =
1169 "you chose \"Not mine\" in the browser; nothing changed on this machine";
1170
1171impl CloudError {
1172 #[must_use]
1178 pub fn event_code(&self) -> String {
1179 match self {
1180 Self::PlanRequired(need) if need.trial_used() => TRIAL_USED.into(),
1181 Self::PlanRequired(_) => "plan_required".into(),
1182 Self::TrialUnsupported { .. } => "trial_unsupported".into(),
1183 Self::DeviceFlow(why) if why == CODE_EXPIRED || why == TRIAL_CODE_EXPIRED => {
1184 "expired".into()
1185 }
1186 Self::DeviceFlow(why) if why == CODE_DENIED => "denied".into(),
1187 Self::DeviceFlow(_) => "not_approved".into(),
1188 Self::InstanceLimit(_) => "instance_limit".into(),
1189 Self::QuotaExceeded(_) => "quota_exceeded".into(),
1190 Self::Offline(_) => "offline".into(),
1191 Self::Unauthorized => "unauthorized".into(),
1192 Self::Revoked(_) => "instance_revoked".into(),
1193 Self::RateLimited { .. } => "rate_limited".into(),
1194 Self::UpgradeRequired { .. } => "upgrade_required".into(),
1195 Self::Config(_) => "config".into(),
1196 Self::Protocol(_) => "protocol".into(),
1197 Self::Local(_) => "local".into(),
1198 Self::Server { code, .. } if wire_token(Some(code), 64).is_some() => code.clone(),
1199 _ => "error".into(),
1200 }
1201 }
1202}
1203
1204pub const RECOVER_HINT: &str = "for a lost or broken device, recover its slot now on the LeanCTX Cloud web (Settings › Connected instances › Recover, with your second factor; once per 30 days)";
1208
1209fn write_instance_cap(f: &mut fmt::Formatter<'_>, cap: &InstanceCap) -> fmt::Result {
1212 let connected = cap.resource.as_deref() == Some("connected_instances");
1213 if connected {
1214 f.write_str("all instances this workspace may connect at once are connected")?;
1215 } else {
1216 f.write_str("all instances of the workspace are in use")?;
1217 }
1218 if let (Some(used), Some(limit)) = (cap.used, cap.limit) {
1219 write!(f, " ({used} of {limit}")?;
1220 if let (Some(seats), Some(per_seat)) = (cap.seats, cap.per_seat) {
1221 write!(f, ": {seats} seats, {per_seat} per seat")?;
1222 }
1223 f.write_str(")")?;
1224 }
1225 if connected {
1226 f.write_str(
1227 "; disconnect one (`lean-ctx cloud disconnect` on that machine, or in LeanCTX Cloud) or upgrade the plan",
1228 )?;
1229 } else {
1230 f.write_str("; remove one in LeanCTX Cloud or upgrade the plan")?;
1231 }
1232 write_hint(f, cap.next_step)
1233}
1234
1235#[must_use]
1237pub fn quota_label(resource: &str) -> &str {
1238 match resource {
1239 "transfer_bytes" => "monthly transfer",
1240 "bus_messages" => "monthly bus messages",
1241 "registered_instances" => "instance slots",
1242 "private_vaults" => "private vaults",
1243 "connected_instances" => "connected instances",
1244 "storage_bytes" => "storage",
1245 "model_credit_usd_micros" => "model credit",
1246 other => other,
1247 }
1248}
1249
1250fn write_quota(f: &mut fmt::Formatter<'_>, q: &Quota) -> fmt::Result {
1251 let what = quota_label(&q.resource);
1252 write!(f, "this workspace has used all its {what}")?;
1253 if let (Some(used), Some(limit)) = (q.used, q.limit) {
1254 write!(
1255 f,
1256 " ({} of {})",
1257 amount_text(&q.resource, used),
1258 amount_text(&q.resource, limit)
1259 )?;
1260 }
1261 f.write_str("; nothing is charged for more")?;
1262 match q.resource.as_str() {
1263 "registered_instances" if q.cooling_slot() => write!(
1264 f,
1265 "; a revoked instance's slot frees at {} ({}-day cool-down), or {RECOVER_HINT}",
1266 q.reset_at.as_deref().unwrap_or("?"),
1267 q.cooldown_days.unwrap_or(0)
1268 )?,
1269 "registered_instances" => f.write_str(
1270 "; revoke an instance you no longer use in LeanCTX Cloud (Settings › Connected instances), or upgrade the plan",
1271 )?,
1272 "private_vaults" => {
1273 f.write_str("; remove or publish a vault in LeanCTX Cloud, or upgrade the plan")?;
1274 }
1275 "model_credit_usd_micros" => {}
1277 _ if q.waits() => match &q.reset_at {
1278 Some(at) => write!(f, "; uploads wait in the local outbox until {at}")?,
1279 None => f.write_str("; uploads wait in the local outbox until it frees")?,
1280 },
1281 _ => {}
1282 }
1283 write_hint(f, q.next_step)
1284}
1285
1286#[cfg(test)]
1287mod tests {
1288 use super::*;
1289 use serde_json::json;
1290
1291 #[test]
1294 fn trial_used_refusal_names_the_used_trial_and_the_plans_page() {
1295 let body = json!({"error": {
1296 "code": "trial_used",
1297 "message": "This address already had a trial.",
1298 "plan_needed": "team",
1299 "next_step": "subscribe",
1300 "plans_url": "https://cloud.leanctx.com/app/plans"
1301 }});
1302 let error = CloudError::from_response(402, &body);
1303 let CloudError::PlanRequired(need) = &error else {
1304 panic!("{error:?}");
1305 };
1306 assert!(need.trial_used());
1307 assert_eq!(need.plan_needed.as_deref(), Some("team"));
1308 assert_eq!(
1309 need.plans_url.as_deref(),
1310 Some("https://cloud.leanctx.com/app/plans")
1311 );
1312 assert_eq!(error.event_code(), "trial_used");
1313 assert!(!error.is_transient());
1314 assert_eq!(
1315 error.to_string(),
1316 "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`"
1317 );
1318 let ended = CloudError::from_response(
1320 402,
1321 &json!({"error": {"code": "trial_used", "reason": "trial_ended", "message": "",
1322 "plan_needed": "personal", "plans_url": "https://cloud.leanctx.com/app/plans"}}),
1323 );
1324 assert_eq!(ended.event_code(), "trial_used");
1325 assert_eq!(
1326 ended.to_string(),
1327 "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`"
1328 );
1329 let no_plan = CloudError::from_response(
1330 402,
1331 &json!({"error": {"code": "trial_used", "reason": "no_plan", "message": "",
1332 "plan_needed": "team"}}),
1333 );
1334 assert_eq!(no_plan.event_code(), "trial_used");
1335 assert!(no_plan.to_string().starts_with(
1336 "this address has no Team trial left and no plan; no second trial starts."
1337 ));
1338 let path = format!(
1341 "{}/crates/lean-ctx-protocol/tests/fixtures/cloud/error.trial_used.json",
1342 concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
1343 );
1344 let fixture: serde_json::Value =
1345 serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
1346 let refused = CloudError::from_response(402, &fixture);
1347 assert_eq!(refused.event_code(), "trial_used");
1348 assert_eq!(
1349 refused.to_string(),
1350 "this address already had its Personal trial; no second trial starts. Choose a plan in LeanCTX Cloud, then run `lean-ctx cloud connect`"
1351 );
1352 assert_eq!(
1353 refused
1354 .with_origin("https://cloud.leanctx.com/")
1355 .to_string(),
1356 "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`"
1357 );
1358 let hostile = CloudError::from_response(
1360 402,
1361 &json!({"error": {"code": "trial_used", "message": "", "plan_needed": "personal",
1362 "plans_url": "javascript:alert(1)"}}),
1363 );
1364 assert_eq!(
1365 hostile.to_string(),
1366 "this address already had its Personal trial; no second trial starts. Choose a plan in LeanCTX Cloud, then run `lean-ctx cloud connect`"
1367 );
1368 let plain = CloudError::from_response(
1370 402,
1371 &json!({"error": {"code": "plan_required", "message": "", "feature": "audit_export", "plan_needed": "team"}}),
1372 );
1373 assert_eq!(plain.event_code(), "plan_required");
1374 }
1375
1376 fn trial_used_with(plans_url: &str) -> CloudError {
1377 CloudError::from_response(
1378 402,
1379 &json!({"error": {"code": "trial_used", "message": "", "plan_needed": "personal",
1380 "plans_url": plans_url}}),
1381 )
1382 }
1383
1384 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`";
1385
1386 #[test]
1389 fn trial_plans_url_on_another_origin_is_not_shown() {
1390 let origin = "https://cloud.leanctx.com";
1391 assert_eq!(
1392 trial_used_with("https://Cloud.LeanCTX.com/app/plans?plan=personal")
1393 .with_origin(origin)
1394 .to_string(),
1395 "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`"
1396 );
1397 for foreign in [
1398 "http://cloud.leanctx.com/app/plans",
1399 "https://evil.example/app/plans",
1400 "https://cloud.leanctx.com.evil.example/app/plans",
1401 "https://cloud.leanctx.com@evil.example/app/plans",
1402 "https://cloud.leanctx.com:8443/app/plans",
1403 "https://cloud.leanctx.com",
1404 ] {
1405 let shown = trial_used_with(foreign).with_origin(origin).to_string();
1406 let expected = if foreign == "https://cloud.leanctx.com" {
1407 "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`"
1408 } else {
1409 NO_PAGE
1410 };
1411 assert_eq!(shown, expected, "{foreign}");
1412 }
1413 assert_eq!(
1415 trial_used_with("https://cloud.leanctx.com/app/plans")
1416 .with_origin("file:///tmp")
1417 .to_string(),
1418 NO_PAGE
1419 );
1420 }
1421
1422 #[test]
1425 fn trial_plans_url_with_format_characters_is_not_shown() {
1426 for c in [
1427 '\u{202E}',
1428 '\u{202A}',
1429 '\u{2066}',
1430 '\u{2069}',
1431 '\u{200B}',
1432 '\u{200D}',
1433 '\u{200E}',
1434 '\u{061C}',
1435 '\u{00AD}',
1436 '\u{FEFF}',
1437 '\u{E0041}',
1438 '\u{3164}',
1439 ] {
1440 let url = format!("/o/bob/billing/{c}?plan=personal");
1441 assert_eq!(
1442 trial_used_with(&url)
1443 .with_origin("https://cloud.leanctx.com")
1444 .to_string(),
1445 NO_PAGE,
1446 "U+{:04X}",
1447 c as u32
1448 );
1449 }
1450 assert_eq!(
1451 trial_used_with("/o/bob/billing/?plan=personal")
1452 .with_origin("https://cloud.leanctx.com")
1453 .to_string(),
1454 "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`"
1455 );
1456 }
1457
1458 #[test]
1462 fn trial_code_expiry_points_to_the_plans_page() {
1463 let expired = CloudError::DeviceFlow(CODE_EXPIRED.into()).for_trial();
1464 assert_eq!(expired, CloudError::DeviceFlow(TRIAL_CODE_EXPIRED.into()));
1465 assert_eq!(expired.event_code(), "expired");
1466 assert!(
1467 expired
1468 .to_string()
1469 .contains("choose a plan in LeanCTX Cloud")
1470 );
1471 assert!(
1472 !expired
1473 .to_string()
1474 .contains("run `lean-ctx cloud connect` again")
1475 );
1476 let denied = CloudError::DeviceFlow(CODE_DENIED.into());
1477 assert_eq!(denied.clone().for_trial(), denied);
1478 assert_eq!(
1479 CloudError::Offline("reset".into()).for_trial(),
1480 CloudError::Offline("reset".into())
1481 );
1482 }
1483
1484 #[test]
1485 fn trial_event_codes_name_the_device_flow_outcomes() {
1486 assert_eq!(
1487 CloudError::DeviceFlow(CODE_EXPIRED.into()).event_code(),
1488 "expired"
1489 );
1490 assert_eq!(
1491 CloudError::from_response(
1492 400,
1493 &json!({"error": {"code": "access_denied", "message": ""}})
1494 )
1495 .event_code(),
1496 "denied"
1497 );
1498 assert_eq!(
1499 CloudError::Server {
1500 status: 400,
1501 code: "invalid_request".into()
1502 }
1503 .event_code(),
1504 "invalid_request"
1505 );
1506 assert_eq!(
1507 CloudError::Server {
1508 status: 500,
1509 code: "Bad Code\n".into()
1510 }
1511 .event_code(),
1512 "error"
1513 );
1514 assert_eq!(CloudError::Offline("reset".into()).event_code(), "offline");
1515 }
1516
1517 #[test]
1520 fn a_detail_with_a_mistyped_member_keeps_its_code_and_retry() {
1521 let limited = CloudError::from_response(
1522 429,
1523 &json!({"error": {"code": "rate_limited", "message": "slow down",
1524 "retry_after_s": 12, "number": "seventeen"}}),
1525 );
1526 assert_eq!(
1527 limited,
1528 CloudError::RateLimited {
1529 retry_after: Some(12)
1530 }
1531 );
1532 let claimed = CloudError::from_response(
1534 409,
1535 &json!({"error": {"code": "invalid_state", "message": "x",
1536 "reason": "task_claimed", "number": "17", "limit": {"odd": true}}}),
1537 );
1538 assert!(
1539 matches!(
1540 claimed,
1541 CloudError::Task {
1542 refusal: TaskRefusal::Claimed,
1543 number: Some(17),
1544 ..
1545 }
1546 ),
1547 "{claimed:?}"
1548 );
1549 let quota = CloudError::from_response(
1550 429,
1551 &json!({"error": {"code": "quota_exceeded", "message": "x",
1552 "resource": "bus_messages", "retry_after_s": "60", "used": -1}}),
1553 );
1554 let CloudError::QuotaExceeded(quota) = quota else {
1555 panic!("{quota:?}");
1556 };
1557 assert_eq!(
1558 (quota.resource.as_str(), quota.retry_after, quota.used),
1559 ("bus_messages", Some(60), None)
1560 );
1561 assert_eq!(
1563 CloudError::from_response(400, &json!({"error": {"code": 7}})),
1564 CloudError::Server {
1565 status: 400,
1566 code: "unknown".into()
1567 }
1568 );
1569 }
1570
1571 #[test]
1574 fn edge_answers_are_classified_by_status() {
1575 let busy = CloudError::from_response(
1576 429,
1577 &json!({"error": {"code": "server_busy", "message": "x", "retry_after_s": 5}}),
1578 );
1579 assert_eq!(
1580 busy,
1581 CloudError::RateLimited {
1582 retry_after: Some(5)
1583 }
1584 );
1585 let header_only = CloudError::from_response(429, &json!({"error": {"retry_after_s": 9}}));
1587 assert_eq!(
1588 header_only,
1589 CloudError::RateLimited {
1590 retry_after: Some(9)
1591 }
1592 );
1593 assert_eq!(
1594 CloudError::from_response(429, &serde_json::Value::Null),
1595 CloudError::RateLimited { retry_after: None }
1596 );
1597 for status in [408, 500, 502, 503, 504] {
1599 let down = CloudError::from_response(status, &serde_json::Value::Null);
1600 assert!(down.is_transient(), "{status}: {down:?}");
1601 }
1602 let too_large = CloudError::from_response(413, &serde_json::Value::Null);
1603 assert_eq!(
1604 too_large,
1605 CloudError::Server {
1606 status: 413,
1607 code: "payload_too_large".into()
1608 }
1609 );
1610 assert!(!too_large.is_transient());
1611 }
1612
1613 #[test]
1614 fn instance_limit_carries_the_seat_numbers() {
1615 let error = CloudError::from_response(
1616 409,
1617 &json!({"error": {"code": "instance_limit", "message": "x", "limit": 2, "used": 2}}),
1618 );
1619 assert_eq!(
1620 error,
1621 CloudError::InstanceLimit(Box::new(InstanceCap {
1622 limit: Some(2),
1623 used: Some(2),
1624 ..InstanceCap::default()
1625 }))
1626 );
1627 assert_eq!(
1628 error.to_string(),
1629 "all instances of the workspace are in use (2 of 2); remove one in LeanCTX Cloud or upgrade the plan"
1630 );
1631 }
1632
1633 #[test]
1636 fn a_connected_limit_says_disconnect_and_names_the_seats() {
1637 let error = CloudError::from_response(
1638 409,
1639 &json!({"error": {"code": "instance_limit", "message": "x", "resource": "connected_instances",
1640 "limit": 4, "used": 4, "plan": "team", "next_step": "add_seats",
1641 "seats": 2, "per_seat": 2}}),
1642 );
1643 assert_eq!(
1644 error,
1645 CloudError::InstanceLimit(Box::new(InstanceCap {
1646 resource: Some("connected_instances".into()),
1647 limit: Some(4),
1648 used: Some(4),
1649 seats: Some(2),
1650 per_seat: Some(2),
1651 next_step: Some(NextStep::AddSeats),
1652 }))
1653 );
1654 assert_eq!(
1655 error.to_string(),
1656 "all instances this workspace may connect at once are connected (4 of 4: 2 seats, 2 per seat); disconnect one (`lean-ctx cloud disconnect` on that machine, or in LeanCTX Cloud) or upgrade the plan; every seat you add in LeanCTX Cloud brings its own allowance"
1657 );
1658 assert!(!error.is_transient());
1659 let personal = CloudError::from_response(
1660 409,
1661 &json!({"error": {"code": "instance_limit", "message": "x", "resource": "connected_instances",
1662 "limit": 2, "used": 2, "plan": "personal", "next_step": "upgrade_team"}}),
1663 );
1664 assert!(
1665 personal
1666 .to_string()
1667 .ends_with("; Team gives every seat its own allowance"),
1668 "{personal}"
1669 );
1670 }
1671
1672 #[test]
1673 fn storage_full_decodes_with_bytes_and_is_not_retried() {
1674 let error = CloudError::from_response(
1675 403,
1676 &json!({"error": {"code": "storage_quota_exceeded", "message": "x", "resource": "storage_bytes",
1677 "limit": 1_073_741_824_u64, "used": 1_073_741_824_u64,
1678 "limit_bytes": 1_073_741_824_u64, "used_bytes": 1_073_741_824_u64,
1679 "plan": "personal", "next_step": "upgrade_team"}}),
1680 );
1681 assert_eq!(
1682 error,
1683 CloudError::StorageFull(Box::new(StorageFull {
1684 limit: Some(1 << 30),
1685 used: Some(1 << 30),
1686 next_step: Some(NextStep::UpgradeTeam),
1687 }))
1688 );
1689 assert!(!error.is_transient(), "waiting does not free storage");
1690 assert_eq!(
1691 error.retry_after_at(lean_ctx_time::UtcDateTime::now()),
1692 None
1693 );
1694 assert_eq!(
1695 error.to_string(),
1696 "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"
1697 );
1698 assert!(!error.to_string().contains("unknown"));
1699 let bare = CloudError::from_response(
1702 403,
1703 &json!({"error": {"code": "storage_quota_exceeded", "message": "x", "limit": 1536, "used": 2048,
1704 "next_step": "something_new"}}),
1705 );
1706 assert_eq!(
1707 bare,
1708 CloudError::StorageFull(Box::new(StorageFull {
1709 limit: Some(1536),
1710 used: Some(2048),
1711 next_step: None,
1712 }))
1713 );
1714 assert!(bare.to_string().contains("(2 KiB of 1.5 KiB)"), "{bare}");
1715 }
1716
1717 #[test]
1718 fn upload_rate_limited_is_transient_and_honours_retry_after() {
1719 let error = CloudError::from_response(
1720 429,
1721 &json!({"error": {"code": "upload_rate_limited", "message": "x",
1722 "limit_bytes_per_hour": 268_435_456_u64, "plan": "personal",
1723 "next_step": "wait", "retry_after_s": 1200}}),
1724 );
1725 assert_eq!(
1726 error,
1727 CloudError::UploadRateLimited {
1728 retry_after: Some(1200),
1729 per_hour: Some(256 << 20),
1730 }
1731 );
1732 assert!(error.is_transient());
1733 assert_eq!(
1734 error.retry_after_at(lean_ctx_time::UtcDateTime::now()),
1735 Some(1200)
1736 );
1737 assert_eq!(
1738 error.to_string(),
1739 "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)"
1740 );
1741 let huge = CloudError::from_response(
1743 429,
1744 &json!({"error": {"code": "upload_rate_limited", "message": "x", "retry_after_s": u64::MAX}}),
1745 );
1746 assert_eq!(
1747 huge.retry_after_at(lean_ctx_time::UtcDateTime::now()),
1748 Some(RETRY_AFTER_CAP_S)
1749 );
1750 }
1751
1752 #[test]
1753 fn quota_hints_and_new_resource_labels() {
1754 let quota = |resource: &str, limit: u64, next: &str| {
1755 CloudError::from_response(
1756 409,
1757 &json!({"error": {"code": "quota_exceeded", "message": "x", "resource": resource,
1758 "limit": limit, "used": limit, "plan": "personal", "next_step": next}}),
1759 )
1760 .to_string()
1761 };
1762 assert_eq!(
1763 quota("storage_bytes", 1 << 30, "upgrade_team"),
1764 "this workspace has used all its storage (1 GiB of 1 GiB); nothing is charged for more; Team gives every seat its own allowance"
1765 );
1766 assert_eq!(
1767 quota("model_credit_usd_micros", 8_000_000, "top_up"),
1768 "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"
1769 );
1770 assert!(
1771 quota("registered_instances", 3, "contact")
1772 .ends_with("; contact us to extend your Enterprise contract")
1773 );
1774 let monthly = CloudError::from_response(
1776 429,
1777 &json!({"error": {"code": "quota_exceeded", "message": "x", "resource": "bus_messages",
1778 "limit": 200_000, "used": 200_000, "next_step": "wait",
1779 "reset_at": "2026-12-01T00:00:00Z", "retry_after_s": 60}}),
1780 );
1781 assert_eq!(
1782 monthly.to_string(),
1783 "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"
1784 );
1785 let feature = CloudError::from_response(
1787 402,
1788 &json!({"error": {"code": "plan_required", "message": "", "feature": "audit_export",
1789 "plan_needed": "team", "next_step": "upgrade_team"}}),
1790 );
1791 assert_eq!(
1792 feature.to_string(),
1793 "audit export is included in Team and Enterprise; Team gives every seat its own allowance"
1794 );
1795 let locked = CloudError::from_response(
1796 402,
1797 &json!({"error": {"code": "plan_required", "message": "x", "feature": "read_only",
1798 "reason": "trial_ended", "plan": "locked", "next_step": "subscribe",
1799 "plan_needed": "personal"}}),
1800 );
1801 assert_eq!(
1802 locked.to_string(),
1803 "Your Personal trial has ended: this workspace is locked (read and export only). Choose a plan in LeanCTX Cloud to sync again."
1804 );
1805 }
1806
1807 #[test]
1808 fn bytes_are_worded_in_binary_units() {
1809 assert_eq!(bytes_text(0), "0 B");
1810 assert_eq!(bytes_text(1023), "1023 B");
1811 assert_eq!(bytes_text(256 << 20), "256 MiB");
1812 assert_eq!(bytes_text(40 << 30), "40 GiB");
1813 assert_eq!(bytes_text(3 << 29), "1.5 GiB");
1814 assert_eq!(bytes_text(u64::MAX), "16777215.9 TiB");
1815 }
1816
1817 #[test]
1818 fn a_huge_retry_after_is_capped_on_the_way_in() {
1819 for huge in [u64::MAX, i64::MAX.unsigned_abs(), RETRY_AFTER_CAP_S + 1] {
1820 let error = CloudError::from_response(
1821 429,
1822 &json!({"error": {"code": "rate_limited", "message": "x", "retry_after_s": huge}}),
1823 );
1824 assert_eq!(
1825 error,
1826 CloudError::RateLimited {
1827 retry_after: Some(RETRY_AFTER_CAP_S)
1828 }
1829 );
1830 }
1831 let small = CloudError::from_response(
1832 429,
1833 &json!({"error": {"code": "rate_limited", "message": "x", "retry_after_s": 90}}),
1834 );
1835 assert_eq!(
1836 small,
1837 CloudError::RateLimited {
1838 retry_after: Some(90)
1839 }
1840 );
1841 }
1842
1843 #[test]
1844 fn upload_disabled_names_the_kind_and_is_not_retried() {
1845 let error = CloudError::from_response(
1846 403,
1847 &json!({"error": {"code": "upload_disabled", "message": "x", "kind": "metrics"}}),
1848 );
1849 assert_eq!(error, CloudError::UploadDisabled(CloudUploadKind::Metrics));
1850 assert!(!error.is_transient());
1851 assert!(error.to_string().contains("metrics upload off"));
1852 }
1853
1854 #[test]
1855 fn task_reasons_become_task_refusals_and_others_stay() {
1856 let refusal = |status, code: &str, reason: &str| {
1857 CloudError::from_response(
1858 status,
1859 &json!({"error": {"code": code, "message": "x", "reason": reason, "number": 7, "retry_after_s": 60}}),
1860 )
1861 };
1862 assert_eq!(
1863 refusal(409, "invalid_state", "stale_claim"),
1864 CloudError::Task {
1865 refusal: TaskRefusal::StaleClaim,
1866 number: Some(7),
1867 detail: None
1868 }
1869 );
1870 assert_eq!(
1871 refusal(403, "forbidden_right", "optin_scope"),
1872 CloudError::Task {
1873 refusal: TaskRefusal::OptinScope,
1874 number: Some(7),
1875 detail: None
1876 }
1877 );
1878 let permit_said = |check: &str, agent_role: Option<&str>, message: &str| {
1880 let mut e = json!({"error": {"code": "forbidden_right", "message": message,
1881 "reason": "not_permitted", "number": 7, "check": check,
1882 "role": "backend"}});
1883 if let Some(r) = agent_role {
1884 e["error"]["agent_role"] = r.into();
1885 }
1886 CloudError::from_response(403, &e).to_string()
1887 };
1888 let permit = |check: &str, agent_role: Option<&str>| permit_said(check, agent_role, "");
1889 assert_eq!(
1890 permit("presence", None),
1891 "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."
1892 );
1893 assert_eq!(
1894 permit("role", Some("web")),
1895 "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]"
1896 );
1897 assert!(
1898 permit("role", Some("web\u{1b}[31m"))
1899 .ends_with("(the task needs role backend) [check: role]"),
1900 "a role that is not a bus identifier is not printed"
1901 );
1902 assert_eq!(
1904 permit_said(
1905 "presence",
1906 None,
1907 "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."
1908 ),
1909 "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."
1910 );
1911 assert_eq!(
1912 permit_said(
1913 "role",
1914 Some("web"),
1915 "Agent coder-1 works as role web;\u{1b}[31m this task needs role backend."
1916 ),
1917 "task #7: Agent coder-1 works as role web; [31m this task needs role backend. [check: role]",
1918 "control characters of the service's message never reach the terminal"
1919 );
1920 assert_eq!(
1922 permit_said("", None, "Agent coder-1 may not take this task."),
1923 "task #7: Agent coder-1 may not take this task."
1924 );
1925 let inactive = refusal(409, "invalid_state", "optin_inactive");
1926 assert!(matches!(inactive, CloudError::Task { refusal, .. } if refusal.ends_claim()));
1927 assert!(matches!(
1928 refusal(409, "invalid_state", "optin_changed"),
1929 CloudError::Task {
1930 refusal: TaskRefusal::OptinChanged,
1931 ..
1932 }
1933 ));
1934 let budget = refusal(429, "rate_limited", "daily_budget");
1935 assert_eq!(
1936 budget,
1937 CloudError::Task {
1938 refusal: TaskRefusal::DailyBudget {
1939 retry_after: Some(60)
1940 },
1941 number: Some(7),
1942 detail: None
1943 }
1944 );
1945 assert!(!budget.is_transient(), "a used-up budget is not retried");
1946 assert!(
1947 budget
1948 .to_string()
1949 .starts_with("task #7: today's task budget")
1950 );
1951 for (fixture, expected) in [
1953 ("error.optin_scope.json", TaskRefusal::OptinScope),
1954 ("error.optin_changed.json", TaskRefusal::OptinChanged),
1955 ("error.optin_inactive.json", TaskRefusal::OptinInactive),
1956 (
1957 "error.daily_budget.json",
1958 TaskRefusal::DailyBudget {
1959 retry_after: Some(43200),
1960 },
1961 ),
1962 ("error.task_claimed.json", TaskRefusal::Claimed),
1963 (
1964 "error.task_not_permitted.json",
1965 TaskRefusal::NotPermitted(PermitCheck::Unknown),
1966 ),
1967 (
1968 "error.task_not_permitted_role.json",
1969 TaskRefusal::NotPermitted(PermitCheck::Role),
1970 ),
1971 ] {
1972 let path = format!(
1973 "{}/crates/lean-ctx-protocol/tests/fixtures/cloud/{fixture}",
1974 concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
1975 );
1976 let body: serde_json::Value =
1977 serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
1978 let code: CloudErrorCode =
1979 serde_json::from_value(body["error"]["code"].clone()).unwrap();
1980 assert!(
1981 matches!(
1982 CloudError::from_response(code.http_status(), &body),
1983 CloudError::Task { refusal, .. } if refusal == expected
1984 ),
1985 "{fixture}"
1986 );
1987 }
1988 for (fixture, expected) in [
1990 (
1991 "task_verify.error.self_verify.json",
1992 TaskRefusal::SelfVerify,
1993 ),
1994 (
1995 "task_verify.error.not_submitted.json",
1996 TaskRefusal::NotSubmitted,
1997 ),
1998 ] {
1999 let path = format!(
2000 "{}/crates/lean-ctx-protocol/tests/fixtures/cloud-v2/routes/{fixture}",
2001 concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
2002 );
2003 let body: serde_json::Value =
2004 serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
2005 let code: CloudErrorCode =
2006 serde_json::from_value(body["error"]["code"].clone()).unwrap();
2007 assert!(
2008 matches!(
2009 CloudError::from_response(code.http_status(), &body),
2010 CloudError::Task { refusal, .. } if refusal == expected
2011 ),
2012 "{fixture}"
2013 );
2014 }
2015 assert_eq!(
2016 refusal(403, "forbidden_right", "vetoed"),
2017 CloudError::Vetoed
2018 );
2019 assert_eq!(
2020 refusal(409, "invalid_state", "code_graph_disabled"),
2021 CloudError::Server {
2022 status: 409,
2023 code: "invalid_state".into()
2024 },
2025 "a reason of another section keeps its old meaning"
2026 );
2027 }
2028
2029 fn plan_required_example(file: &str, feature: &str) -> (u16, serde_json::Value) {
2031 let path = format!(
2032 "{}/crates/lean-ctx-protocol/tests/fixtures/cloud-v2/web/{file}",
2033 concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
2034 );
2035 let fixture: serde_json::Value =
2036 serde_json::from_slice(&std::fs::read(&path).expect(&path)).expect(&path);
2037 let example = fixture["errors"]
2038 .as_array()
2039 .expect("errors")
2040 .iter()
2041 .find(|e| {
2042 e["body"]["error"]["code"] == "plan_required"
2043 && e["body"]["error"]["feature"] == feature
2044 })
2045 .unwrap_or_else(|| panic!("{file}: no plan_required {feature}"));
2046 (
2047 u16::try_from(example["status"].as_u64().unwrap()).unwrap(),
2048 example["body"].clone(),
2049 )
2050 }
2051
2052 #[test]
2053 fn plan_required_keeps_the_feature_and_words_it() {
2054 let (status, body) = plan_required_example("vault-transfer.json", "repos");
2056 assert_eq!(status, 402);
2057 let error = CloudError::from_response(status, &body);
2058 assert!(
2059 matches!(&error, CloudError::PlanRequired(need) if need.feature.as_deref() == Some("repos"))
2060 );
2061 assert_eq!(
2062 error.clone().with_plan(CloudPlan::Unknown),
2063 error,
2064 "an unknown plan is not named"
2065 );
2066 assert!(!error.is_transient());
2067 let repos = error.with_plan(CloudPlan::NoPlan);
2068 assert!(!repos.to_string().contains("engine"));
2069 assert_eq!(
2070 repos.to_string(),
2071 "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"
2072 );
2073
2074 let (status, body) = plan_required_example("organisation-create.json", "company");
2076 let org = CloudError::from_response(status, &body).with_plan(CloudPlan::Team);
2077 assert_eq!(
2078 org.to_string(),
2079 "A company comes with Enterprise, on request: send a request and we set it up with you; this workspace is on Team"
2080 );
2081 let unnamed = CloudError::from_response(
2082 402,
2083 &json!({"error": {"code": "plan_required", "message": "", "feature": "audit_export", "plan_needed": "team"}}),
2084 );
2085 assert_eq!(
2086 unnamed.to_string(),
2087 "audit export is included in Team and Enterprise"
2088 );
2089 let hostile = CloudError::from_response(
2090 402,
2091 &json!({"error": {"code": "plan_required", "message": "x\u{1b}[2J", "feature": "Comp\u{1b}"}}),
2092 );
2093 assert_eq!(
2094 hostile,
2095 CloudError::PlanRequired(Box::new(PlanNeed {
2096 message: Some("x [2J".into()),
2097 ..PlanNeed::default()
2098 })),
2099 "a feature that is not a wire token is dropped, the message is terminal-safe"
2100 );
2101 }
2102
2103 #[test]
2104 fn plan_required_without_a_feature_keeps_the_1x_seat_text() {
2105 let path = format!(
2106 "{}/crates/lean-ctx-protocol/tests/fixtures/cloud/error.plan_required.json",
2107 concat!(env!("CARGO_MANIFEST_DIR"), "/../..")
2108 );
2109 let body: serde_json::Value =
2110 serde_json::from_slice(&std::fs::read(&path).expect(&path)).expect(&path);
2111 let error = CloudError::from_response(402, &body).with_plan(CloudPlan::NoPlan);
2112 assert_eq!(
2113 error.to_string(),
2114 "this workspace's plan does not include LeanCTX Cloud here (Personal 3 instances, 2 connected at once; Team and Enterprise 3 per seat, 2 connected at once per seat)"
2115 );
2116 assert!(
2117 matches!(&error, CloudError::PlanRequired(need) if need.plan.is_none()),
2118 "a 1.x refusal is about LeanCTX Cloud itself, not a feature of the plan"
2119 );
2120 }
2121
2122 #[test]
2123 fn a_locked_workspace_is_one_line_whatever_the_feature() {
2124 let locked = |reason: &str, feature: Option<&str>, needed: &str| {
2125 let mut body = json!({"error": {"code": "plan_required", "message": "Your trial has ended: this workspace is locked.",
2126 "plan_needed": needed, "reason": reason}});
2127 if let Some(f) = feature {
2128 body["error"]["feature"] = f.into();
2129 }
2130 CloudError::from_response(402, &body)
2131 };
2132 let trial = "Your Personal trial has ended: this workspace is locked (read and export only). Choose a plan in LeanCTX Cloud to sync again.";
2133 for feature in [None, Some("read_only")] {
2134 let e = locked("trial_ended", feature, "personal");
2135 assert_eq!(e.to_string(), trial);
2136 assert!(matches!(&e, CloudError::PlanRequired(n) if n.locked() == Some("trial_ended")));
2137 assert_eq!(
2138 e.with_plan(CloudPlan::Personal).to_string(),
2139 trial,
2140 "the lease's plan adds nothing to the line"
2141 );
2142 }
2143 assert_eq!(
2144 locked("plan_ended", Some("read_only"), "team").to_string(),
2145 "Your plan has ended: this workspace is locked (read and export only). Choose a plan in LeanCTX Cloud to sync again."
2146 );
2147 assert_eq!(
2148 locked("trial_ended", None, "team").to_string(),
2149 "Your Team trial has ended: this workspace is locked (read and export only). Choose a plan in LeanCTX Cloud to sync again."
2150 );
2151 let no_plan = locked("no_plan", None, "personal");
2153 assert!(
2154 no_plan.to_string().contains("2 connected at once"),
2155 "{no_plan}"
2156 );
2157 assert!(!no_plan.to_string().contains(LOCKED_MARK));
2158 }
2159
2160 #[test]
2161 fn non_contract_bodies_become_server_errors() {
2162 assert_eq!(
2163 CloudError::from_response(502, &json!("<html>")),
2164 CloudError::Server {
2165 status: 502,
2166 code: "unknown".into()
2167 }
2168 );
2169 assert!(
2170 CloudError::Server {
2171 status: 502,
2172 code: "unknown".into()
2173 }
2174 .is_transient()
2175 );
2176 }
2177}