1use serde_json::json;
10
11use crate::backend::reactive::InjectionRequest;
12
13use super::reactive::{defined_here, echo_local_delivery, replay, HoldReason};
14use super::AppState;
15
16pub(in crate::server) async fn hold_for_absent_target(
28 state: &AppState,
29 auth_via: super::ReactiveAuthVia,
30 req: &InjectionRequest,
31 resp: &crate::backend::reactive::types::InjectionResponse,
32 reason: HoldReason,
33 replay: &mut replay::Reservation,
34) -> Option<serde_json::Value> {
35 hold_with_reason(state, auth_via, req, resp, reason, None, replay).await
36}
37
38pub(in crate::server) async fn hold_for_refusal_here(
45 state: &AppState,
46 auth_via: super::ReactiveAuthVia,
47 req: &InjectionRequest,
48 resp: &crate::backend::reactive::types::InjectionResponse,
49 replay: &mut replay::Reservation,
50) -> Option<serde_json::Value> {
51 let error = resp.error.as_deref().unwrap_or_default();
52 if super::jekt_held::is_spawn_gate_refusal(error) {
53 let held = hold_for_absent_target(state, auth_via, req, resp, HoldReason::NeedsLogin, replay).await;
54 return Some(held.unwrap_or_else(|| needs_login_refusal(serde_json::to_value(resp).unwrap_or_default())));
55 }
56 if crate::backend::reactive::controller_wait::is_no_controller(error) {
57 return hold_for_absent_target(state, auth_via, req, resp, HoldReason::Starting, replay).await;
58 }
59 None
60}
61
62pub(in crate::server) fn holding_unavailable(
68 mstore: &crate::backend::storage::store::Store,
69 block_id: &str,
70) -> Option<crate::backend::agent_state::Unavailable> {
71 let now_ms = agentmux_common::time::now_ms_u64();
72 use crate::backend::agent_availability::{of_unavailable, verdict, Verdict, WaitReason};
73 crate::backend::agent_state::unavailable_of_block(mstore, None, block_id, now_ms)
74 .filter(|unavailable| {
75 let rule = verdict(&of_unavailable(unavailable), false, true, None, || false);
76 matches!(rule, Verdict::Wait { reason: WaitReason::UsageLimit | WaitReason::NeedsLogin, .. })
77 })
78 .or_else(|| super::limit_probe::unavailable_while_probing(mstore, block_id, now_ms))
79}
80
81pub(super) fn peer_refused(body: &serde_json::Value) -> bool {
85 body.get("files_refused").and_then(|v| v.as_bool()) == Some(true)
86 || body.get("held").and_then(|v| v.as_bool()) == Some(true)
88 || body.get("refused_reason").and_then(|v| v.as_str()).is_some()
89 || body.get("error").and_then(|v| v.as_str()).is_some_and(crate::backend::reactive::is_unavailable_refusal)
90}
91
92pub(super) async fn local_target_unavailable(state: &AppState, target: &str) -> Option<crate::backend::agent_state::Unavailable> {
97 use crate::backend::reactive::handler::LookupOutcome;
98 let target = crate::backend::reactive::sanitize::route_name(target)?;
99 let LookupOutcome::One(reg) = state.reactive_handler.lookup_delivery_target(&target) else {
100 return None;
101 };
102 let mstore = state.mstore.clone();
103 tokio::task::spawn_blocking(move || holding_unavailable(&mstore, ®.block_id)).await.ok().flatten()
104}
105
106pub(super) async fn hold_before_delivery(
109 state: &AppState,
110 auth_via: super::ReactiveAuthVia,
111 req: &InjectionRequest,
112 replay: &mut replay::Reservation,
113) -> Option<serde_json::Value> {
114 if let Some(unavailable) = local_target_unavailable(state, &req.target_agent).await {
115 return Some(hold_for_unavailable(state, auth_via, req, &unavailable, replay).await);
116 }
117 if let Some(held) = hold_if_api_offline(state, auth_via, req, replay).await {
118 return Some(held);
119 }
120 super::jekt_cold::hold_if_cold(state, auth_via, req, replay).await
121}
122
123pub(super) fn api_is_offline_for(mstore: &crate::backend::storage::store::Store, block_id: &str, net: &crate::connectivity::ConnectivityStatus, now_ms: u64) -> bool {
127 use crate::backend::agent_status::{decide, Decision, Intent};
128 let block = mstore.get::<crate::backend::obj::Block>(block_id).ok().flatten();
129 let status = super::availability_view::status_of(mstore, Some(block_id), block.as_ref(), net, now_ms);
130 let message = Intent::Message { urgent: false, routine: true, cold_after_ms: None };
131 matches!(decide(&status, message, || false), Decision::Wait { reason: crate::backend::agent_availability::WaitReason::ApiOffline, .. })
132}
133
134async fn hold_if_api_offline(
139 state: &AppState,
140 auth_via: super::ReactiveAuthVia,
141 req: &InjectionRequest,
142 replay: &mut replay::Reservation,
143) -> Option<serde_json::Value> {
144 use crate::backend::reactive::handler::LookupOutcome;
145 use crate::backend::reactive::sanitize::route_name;
146 let route = route_name(&req.target_agent)?;
147 if req.source_agent.as_deref().and_then(route_name).as_deref() == Some(route.as_str()) {
148 return None;
149 }
150 let LookupOutcome::One(reg) = state.reactive_handler.lookup_delivery_target(&route) else {
151 return None;
152 };
153 let mstore = state.mstore.clone();
154 let offline = tokio::task::spawn_blocking(move || {
155 api_is_offline_for(&mstore, ®.block_id, &crate::connectivity::status(), agentmux_common::time::now_ms_u64())
156 })
157 .await
158 .unwrap_or(false);
159 if !offline {
160 return None;
161 }
162 let target = &req.target_agent;
163 let resp = crate::backend::reactive::types::InjectionResponse {
164 deferred: None,
165 success: false,
166 request_id: req.request_id.clone().filter(|id| !id.is_empty()).unwrap_or_else(|| uuid::Uuid::new_v4().to_string()),
167 block_id: None,
168 error: Some(format!("agent {target}'s model API is offline")),
169 timestamp: agentmux_common::time::now_ms_u64(),
170 effective_tier: None,
171 requires_stop: None,
172 channel_verified: None,
173 };
174 tracing::info!(target = %target, "reactive inject: the target's model API is offline, holding the message");
175 hold_with_reason(state, auth_via, req, &resp, HoldReason::ApiOffline, None, replay).await
176}
177
178pub(super) async fn hold_for_unavailable(
184 state: &AppState,
185 auth_via: super::ReactiveAuthVia,
186 req: &InjectionRequest,
187 unavailable: &crate::backend::agent_state::Unavailable,
188 replay: &mut replay::Reservation,
189) -> serde_json::Value {
190 use crate::backend::agent_state::AgentState;
191 let reason = HoldReason::for_state(unavailable.state).unwrap_or(HoldReason::Limited);
192 let target = &req.target_agent;
193 let why = match (unavailable.state, unavailable.resets_at_ms.and_then(local_time_label)) {
194 (AgentState::SignedOut, _) => format!("{target} needs to sign in again"),
195 (_, Some(until)) => format!("{target}'s account is out of quota until {until}"),
196 (_, None) => format!("{target}'s account is out of quota"),
197 };
198 let resp = crate::backend::reactive::types::InjectionResponse {
199 deferred: None,
200 success: false,
201 request_id: req.request_id.clone().filter(|id| !id.is_empty()).unwrap_or_else(|| uuid::Uuid::new_v4().to_string()),
202 block_id: None,
203 error: Some(format!("{}{why}", crate::backend::reactive::UNAVAILABLE_PREFIX)),
204 timestamp: agentmux_common::time::now_ms_u64(),
205 effective_tier: None,
206 requires_stop: None,
207 channel_verified: None,
208 };
209 tracing::info!(target = %target, state = ?unavailable.state, "reactive inject: target can't work now, holding or refusing");
210 if let Some(held) = hold_with_reason(state, auth_via, req, &resp, reason, unavailable.resets_at_ms, replay).await {
211 if held.get("held").and_then(|h| h.as_bool()) == Some(true) {
212 super::limit_probe::maybe_probe(state, req, unavailable).await;
213 }
214 return held;
215 }
216 with_refusal(serde_json::to_value(&resp).unwrap_or_default(), reason.wait_reason(), unavailable.resets_at_ms)
217}
218
219pub(super) fn with_refusal(
223 mut body: serde_json::Value,
224 reason: crate::backend::agent_availability::WaitReason,
225 until_ms: Option<u64>,
226) -> serde_json::Value {
227 body["refused_reason"] = json!(reason.as_str());
228 body["retry_when"] = json!(reason.retry_when());
229 if let Some(until) = until_ms {
230 body["until_ms"] = json!(until);
231 }
232 body
233}
234
235pub(super) fn needs_login_refusal(body: serde_json::Value) -> serde_json::Value {
237 with_refusal(body, crate::backend::agent_availability::WaitReason::NeedsLogin, None)
238}
239
240pub(super) fn local_time_label(ms: u64) -> Option<String> {
243 let t = chrono::DateTime::from_timestamp_millis(i64::try_from(ms).ok()?)?;
244 Some(t.with_timezone(&chrono::Local).format("%a %-I:%M %p").to_string())
245}
246
247async fn hold_with_reason(
250 state: &AppState,
251 auth_via: super::ReactiveAuthVia,
252 req: &InjectionRequest,
253 resp: &crate::backend::reactive::types::InjectionResponse,
254 reason: HoldReason,
255 until_ms: Option<u64>,
256 replay: &mut replay::Reservation,
257) -> Option<serde_json::Value> {
258 use crate::backend::storage::jekt_held::HoldOutcome;
259 let peer_waits = matches!(reason, HoldReason::NeedsLogin | HoldReason::Limited | HoldReason::Starting) && hold_applies_to_peer(req, resp);
262 if !hold_applies(auth_via, req, resp) && !peer_waits {
263 return None;
264 }
265 let mut held = held_row(req, resp.request_id.clone(), agentmux_common::time::now_ms());
266 let mstore = state.mstore.clone();
267 let outcome = tokio::task::spawn_blocking(move || {
268 let (uid, _slug) = defined_here(&mstore, &held.target_agent)?;
269 held.target_uid = uid;
270 Some(held)
271 })
272 .await
273 .ok()
274 .flatten()?;
275 if reason == HoldReason::NotRunning && state.reactive_handler.has_uid_registration(&outcome.target_uid) {
280 let by_uid = req.addressed_by_uid(&outcome.target_uid);
281 let resp = state.reactive_handler.inject_message(by_uid);
282 if resp.success {
283 replay.delivered();
284 echo_local_delivery(state, req, &resp);
287 }
288 let raced_away = resp.error.as_deref().is_some_and(|e| e.starts_with("agent not found"));
291 if !raced_away {
292 return Some(serde_json::to_value(&resp).unwrap_or_default());
293 }
294 }
295 let target_uid = outcome.target_uid.clone();
296 let mstore = state.mstore.clone();
297 let outcome = tokio::task::spawn_blocking(move || mstore.jekt_held_insert(&outcome))
298 .await
299 .ok()?;
300 let target = &req.target_agent;
301 match outcome {
302 Ok(HoldOutcome::Held) | Ok(HoldOutcome::AlreadyHeld) => {
303 replay.delivered();
304 crate::backend::agent_resolve::record_uid_fallback("jekt.held");
305 let start = match reason { HoldReason::NotRunning => super::jekt_start::start_for_held(state, req, &target_uid), HoldReason::Starting => super::jekt_start::HeldStart::Starting, _ => super::jekt_start::HeldStart::No };
306 let error = match reason {
307 HoldReason::NotRunning | HoldReason::Starting => start.not_running_text(target),
308 HoldReason::NeedsLogin => {
309 if resp.error.as_deref().is_some_and(super::jekt_held::is_spawn_gate_refusal) {
310 super::jekt_held::mark_needs_login(&target_uid);
311 }
312 format!(
313 "agent {target} is not signed in — held for delivery on this AgentMux instance for up to 24 h, delivered when it signs in"
314 )
315 }
316 HoldReason::Limited => format!(
317 "agent {target}'s account is out of quota — held for delivery on this AgentMux instance for up to 24 h, delivered when it can work again (an account move or the reset)"
318 ),
319 HoldReason::ApiOffline => format!("agent {target}'s model API is offline — held for up to 24 h, delivered when it answers again"),
320 HoldReason::Idle | HoldReason::Quota | HoldReason::PeerOffline => format!("agent {target}'s session is idle — held until it is next active"), };
322 let mut answer = json!({
323 "success": false,
324 "held": true,
325 "held_reason": reason.as_str(),
326 "retry_when": reason.wait_reason().retry_when(),
327 "request_id": resp.request_id,
328 "error": error,
329 });
330 start.annotate(&mut answer);
331 if let Some(until) = until_ms.filter(|_| reason == HoldReason::Limited) {
332 answer["held_until_ms"] = json!(until);
333 if let Some(label) = local_time_label(until) {
334 answer["held_until"] = json!(label);
335 }
336 }
337 Some(answer)
338 }
339 Ok(HoldOutcome::Full) => Some(json!({
340 "success": false,
341 "request_id": resp.request_id,
342 "error": format!(
343 "{} (hold full: too many messages already held for {target})",
344 resp.error.clone().unwrap_or_default()
345 ),
346 })),
347 Err(e) => {
348 tracing::warn!(error = %e, target = %target, "durable jekt: hold failed");
349 None
350 }
351 }
352}
353
354pub(super) fn held_row(req: &InjectionRequest, request_id: String, now: i64) -> crate::backend::storage::jekt_held::HeldJekt {
357 use crate::backend::storage::jekt_held::{HeldJekt, HELD_TTL_MS};
358 HeldJekt {
359 request_id,
360 target_uid: String::new(),
361 target_agent: req.target_agent.clone(),
362 source_agent: req.source_agent.clone().unwrap_or_default(),
363 audit_source_uid: req.audit_source_uid.clone(),
364 message: crate::backend::reactive::sanitize::sanitize_message(&req.message),
367 priority: req.priority.clone().unwrap_or_default(),
368 jekt_tier: req
369 .jekt_tier
370 .as_ref()
371 .and_then(|t| serde_json::to_value(t).ok())
372 .and_then(|v| v.as_str().map(str::to_string))
373 .unwrap_or_default(),
374 delivery_tier: if verified_peer(req) { req.delivery_tier.clone().unwrap_or_default() } else { "host".to_string() },
375 sig_verified: req.sig_verified,
376 reagent_verified: req.reagent_verified,
377 lan_verified: req.lan_verified,
378 channel_verified: req.channel_verified,
379 is_transcript_request: req.is_transcript_request,
380 transcript_request_escalate_forced: req.transcript_request_escalate_forced,
381 files_json: req
382 .files
383 .as_ref()
384 .and_then(|f| serde_json::to_string(f).ok())
385 .unwrap_or_default(),
386 sent_at_ms: now,
387 expires_at_ms: now + HELD_TTL_MS,
388 sender_expires_at_ms: req.expires_at_ms,
393 attempts: 0,
394 last_error: String::new(),
395 hold_reason: String::new(),
396 wan_json: wan_json_of(req),
397 }
398}
399
400fn wan_json_of(req: &InjectionRequest) -> String {
402 if req.delivery_tier.as_deref() != Some("wan") || !verified_peer(req) {
403 return String::new();
404 }
405 serde_json::to_string(&json!({ "verified": true, "instance": req.wan_instance })).unwrap_or_default()
406}
407
408pub(super) fn verified_peer(req: &InjectionRequest) -> bool {
412 use crate::backend::reactive::types::WanInstanceStatus;
413 match req.delivery_tier.as_deref() {
414 Some("lan") => req.lan_verified == Some(true),
415 Some("wan") => {
416 req.wan_verified == Some(true)
417 && req.wan_instance.as_ref().is_some_and(|i| i.status == WanInstanceStatus::Approved)
418 }
419 _ => false,
420 }
421}
422
423pub(super) fn hold_applies(
428 auth_via: super::ReactiveAuthVia,
429 req: &InjectionRequest,
430 resp: &crate::backend::reactive::types::InjectionResponse,
431) -> bool {
432 auth_via == super::ReactiveAuthVia::FullAuthKey
433 && req.delivery_tier.as_deref() == Some("host")
434 && req.source_agent.as_deref() != Some("cron")
435 && !resp.request_id.is_empty()
436}
437
438pub(crate) fn hold_wan_for_unavailable(
445 mstore: &crate::backend::storage::store::Store,
446 handler: &crate::backend::reactive::handler::ReactiveHandler,
447 req: &InjectionRequest,
448) -> bool {
449 use crate::backend::reactive::handler::LookupOutcome;
450 use crate::backend::storage::jekt_held::HoldOutcome;
451 let Some(id) = req.request_id.as_deref().filter(|id| !id.is_empty()) else {
452 return false;
453 };
454 if req.delivery_tier.as_deref() != Some("wan")
455 || !verified_peer(req)
456 || req.source_agent.as_deref() == Some("cron")
457 || (req.files.is_none() && req.files_delivery.is_some())
458 {
459 return false;
460 }
461 let Some(target) = crate::backend::reactive::sanitize::route_name(&req.target_agent) else {
462 return false;
463 };
464 let LookupOutcome::One(reg) = handler.lookup_delivery_target(&target) else {
465 return false;
466 };
467 if holding_unavailable(mstore, ®.block_id).is_none() {
468 return false;
469 }
470 let Some((uid, _slug)) = defined_here(mstore, &req.target_agent) else {
471 return false;
472 };
473 let mut held = held_row(req, id.to_string(), agentmux_common::time::now_ms());
474 held.target_uid = uid;
475 let kept = matches!(mstore.jekt_held_insert(&held), Ok(HoldOutcome::Held | HoldOutcome::AlreadyHeld));
476 if kept {
477 super::jekt_files::settle(req, false);
479 }
480 kept
481}
482
483pub(crate) fn give_back_for_unavailable(
489 mstore: &crate::backend::storage::store::Store,
490 handler: &crate::backend::reactive::handler::ReactiveHandler,
491 req: &InjectionRequest,
492) -> bool {
493 req.source_agent.as_deref() != Some("cron") && agent_unavailable(mstore, handler, &req.target_agent)
494}
495
496pub(crate) fn agent_unavailable(
499 mstore: &crate::backend::storage::store::Store,
500 handler: &crate::backend::reactive::handler::ReactiveHandler,
501 target: &str,
502) -> bool {
503 use crate::backend::reactive::handler::LookupOutcome;
504 let Some(target) = crate::backend::reactive::sanitize::route_name(target) else {
505 return false;
506 };
507 let LookupOutcome::One(reg) = handler.lookup_delivery_target(&target) else {
508 return false;
509 };
510 holding_unavailable(mstore, ®.block_id).is_some()
511}
512
513fn hold_applies_to_peer(
518 req: &InjectionRequest,
519 resp: &crate::backend::reactive::types::InjectionResponse,
520) -> bool {
521 verified_peer(req) && req.source_agent.as_deref() != Some("cron") && !resp.request_id.is_empty()
522}
523
524pub(super) fn peer_files_wait(req: &InjectionRequest, files_withheld: bool) -> bool {
530 !files_withheld
531 && verified_peer(req)
532 && req.source_agent.as_deref() != Some("cron")
533 && req.request_id.as_deref().is_some_and(|id| !id.is_empty())
534}
535
536#[cfg(test)]
537mod tests {
538 use super::*;
539 use crate::backend::agent_availability::WaitReason;
540 use crate::backend::reactive::types::{WanInstanceInfo, WanInstanceStatus};
541
542 fn peer(tier: &str) -> InjectionRequest {
543 InjectionRequest { delivery_tier: Some(tier.into()), source_agent: Some("a".into()), ..Default::default() }
544 }
545 fn wan(status: WanInstanceStatus) -> InjectionRequest {
546 InjectionRequest {
547 wan_verified: Some(true),
548 wan_instance: Some(WanInstanceInfo { id: "I1".into(), label: "host~I1".into(), status }),
549 ..peer("wan")
550 }
551 }
552
553 #[test]
554 fn only_a_message_that_proved_its_sender_is_a_verified_peer() {
555 assert!(verified_peer(&InjectionRequest { lan_verified: Some(true), ..peer("lan") }));
556 assert!(!verified_peer(&peer("lan")), "the LAN key alone proves nothing");
557 assert!(!verified_peer(&InjectionRequest { lan_verified: Some(false), ..peer("lan") }));
558 assert!(verified_peer(&wan(WanInstanceStatus::Approved)));
559 assert!(!verified_peer(&wan(WanInstanceStatus::New)), "a new install is not approved");
560 assert!(!verified_peer(&wan(WanInstanceStatus::Revoked)));
561 assert!(!verified_peer(&InjectionRequest { wan_verified: Some(true), ..peer("wan") }), "no instance, no proof");
562 assert!(!verified_peer(&InjectionRequest { lan_verified: Some(true), ..peer("host") }));
563 }
564
565 #[test]
566 fn a_held_peer_message_keeps_its_tier_and_proof_and_replays_as_it_arrived() {
567 let lan = InjectionRequest { lan_verified: Some(true), ..peer("lan") };
568 let row = held_row(&lan, "r1".into(), 1);
569 assert_eq!(row.delivery_tier, "lan");
570 let back = super::super::jekt_held::request_from_held(&row);
571 assert_eq!((back.delivery_tier.as_deref(), back.lan_verified), (Some("lan"), Some(true)));
572
573 let row = held_row(&wan(WanInstanceStatus::Approved), "r2".into(), 1);
574 assert_eq!(row.delivery_tier, "wan");
575 let back = super::super::jekt_held::request_from_held(&row);
576 assert_eq!(back.delivery_tier.as_deref(), Some("wan"));
577 assert_eq!(back.wan_verified, Some(true));
578 assert_eq!(back.wan_instance.map(|i| i.status), Some(WanInstanceStatus::Approved));
579 }
580
581 #[test]
582 fn an_unproven_or_host_message_is_held_and_replayed_as_host_never_raised_to_more() {
583 let row = held_row(&peer("lan"), "r3".into(), 1);
584 assert_eq!(row.delivery_tier, "host", "stored as before; a peer without proof is not held at all");
585 let mut stored = row.clone();
586 stored.delivery_tier = "lan".into();
587 stored.lan_verified = None;
588 let back = super::super::jekt_held::request_from_held(&stored);
589 assert_eq!((back.delivery_tier.as_deref(), back.lan_verified), (Some("lan"), None));
590 stored.delivery_tier = "channel".into();
591 assert_eq!(super::super::jekt_held::request_from_held(&stored).delivery_tier.as_deref(), Some("host"));
592 stored.delivery_tier = "wan".into();
593 stored.wan_json = "not json".into();
594 let back = super::super::jekt_held::request_from_held(&stored);
595 assert_eq!((back.delivery_tier.as_deref(), back.wan_verified), (Some("wan"), None));
596 }
597
598 #[test]
599 fn a_verified_peer_waits_for_an_agent_that_cannot_work_but_not_for_a_cron_fire() {
600 let resp = crate::backend::reactive::types::InjectionResponse {
601 deferred: None,
602 success: false,
603 request_id: "id".into(),
604 block_id: None,
605 error: None,
606 timestamp: 0,
607 effective_tier: None,
608 requires_stop: None,
609 channel_verified: None,
610 };
611 let lan = InjectionRequest { lan_verified: Some(true), ..peer("lan") };
612 assert!(hold_applies_to_peer(&lan, &resp));
613 assert!(!hold_applies_to_peer(&InjectionRequest { source_agent: Some("cron".into()), ..lan.clone() }, &resp));
614 assert!(!hold_applies_to_peer(&peer("lan"), &resp));
615 let with_files = InjectionRequest { files: Some(vec![agentmux_common::jekt_files::JektFile { sha256: "0".repeat(64), name: "a.txt".into(), size: 1 }]), ..lan.clone() };
616 assert!(hold_applies_to_peer(&with_files, &resp), "its files are kept in the store first, so it is held with them");
617 let no_id = crate::backend::reactive::types::InjectionResponse { request_id: String::new(), ..resp };
618 assert!(!hold_applies_to_peer(&lan, &no_id));
619 }
620
621 #[test]
622 fn a_refusal_carries_its_reason_and_what_ends_the_wait_as_data() {
623 let body = with_refusal(json!({"success": false, "error": "agent unavailable: X needs to sign in again"}), WaitReason::NeedsLogin, None);
624 assert_eq!((body["refused_reason"].as_str(), body["retry_when"].as_str()), (Some("needs_login"), Some("sign_in")));
625 assert!(body.get("until_ms").is_none());
626 let limited = with_refusal(json!({"success": false}), WaitReason::UsageLimit, Some(42));
627 assert_eq!((limited["refused_reason"].as_str(), limited["retry_when"].as_str(), limited["until_ms"].as_u64()), (Some("usage_limit"), Some("reset_or_account_move"), Some(42)));
628 }
629
630 #[test]
631 fn a_peer_refusal_is_known_by_its_reason_or_by_the_old_wording() {
632 assert!(peer_refused(&json!({"refused_reason": "usage_limit", "error": "anything"})));
633 assert!(peer_refused(&json!({"error": "agent unavailable: X's account is out of quota"})));
634 assert!(peer_refused(&json!({"files_refused": true})));
635 assert!(peer_refused(&json!({"success": false, "held": true, "held_reason": "usage_limit"})), "held there is final");
636 assert!(!peer_refused(&json!({"error": "agent not found: X"})));
637 }
638
639 #[test]
642 fn a_message_to_an_agent_between_turns_waits_for_its_offline_model_api() {
643 use crate::backend::agent_state::test_support::register_stub;
644 use crate::backend::blockcontroller::{delete_controller, BLOCK_CONTROLLER_PERSISTENT, STATUS_RUNNING};
645 use crate::connectivity::{ConnectivityStatus, Reachability, ServiceStatus};
646
647 let store = crate::backend::storage::store::Store::open_in_memory().unwrap();
648 let mut block = crate::backend::obj::Block::default();
649 block.oid = uuid::Uuid::new_v4().to_string();
650 block.meta.insert("agentProvider".into(), json!("claude"));
651 store.insert(&mut block).unwrap();
652 let service = crate::connectivity::model_api_of("claude").map(|api| crate::connectivity::service_for(api, None).id()).unwrap();
653 let net = |state| ConnectivityStatus {
654 revision: 1,
655 services: vec![ServiceStatus { service: service.clone(), label: "API".into(), state, since_ms: 1, last_error: None }],
656 };
657 let now = 1_000_000;
658
659 register_stub(&block.oid, BLOCK_CONTROLLER_PERSISTENT, STATUS_RUNNING, false);
660 assert!(api_is_offline_for(&store, &block.oid, &net(Reachability::Offline), now), "between turns, API offline");
661 assert!(!api_is_offline_for(&store, &block.oid, &net(Reachability::Online), now));
662 assert!(!api_is_offline_for(&store, &block.oid, &net(Reachability::Unknown), now), "not checked yet holds no message");
663 assert!(!api_is_offline_for(&store, &block.oid, &ConnectivityStatus { revision: 1, services: vec![] }, now), "an API srv does not track");
664 delete_controller(&block.oid);
665
666 register_stub(&block.oid, BLOCK_CONTROLLER_PERSISTENT, STATUS_RUNNING, true);
667 assert!(!api_is_offline_for(&store, &block.oid, &net(Reachability::Offline), now), "it joins the turn in flight");
668 delete_controller(&block.oid);
669 }
670}
671
672#[cfg(test)]
673#[path = "jekt_hold_files_tests.rs"]
674mod files_tests;