1use std::time::Duration;
9
10use crate::backend::agent_availability::WaitReason;
11use crate::backend::agent_status::{decide, Decision, Intent};
12use crate::backend::obj::Block;
13use crate::backend::storage::jekt_held::HeldJekt;
14
15use super::availability_view::status_of;
16use super::AppState;
17
18const REPLAY_PER_PASS: usize = 8;
21const MAX_ATTEMPTS: i64 = 20;
23const SWEEP_EVERY: Duration = Duration::from_secs(30);
24const GATE_RECHECK_EVERY: Duration = Duration::from_secs(60);
26
27pub(crate) use crate::backend::reactive::is_spawn_gate_refusal;
30
31fn needs_login() -> &'static std::sync::Mutex<std::collections::HashMap<String, std::time::Instant>> {
40 static MAP: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, std::time::Instant>>> =
41 std::sync::OnceLock::new();
42 MAP.get_or_init(Default::default)
43}
44
45pub(crate) fn mark_needs_login(uid: &str) {
47 needs_login().lock().unwrap().insert(uid.to_string(), std::time::Instant::now());
48}
49
50#[derive(Debug, PartialEq, Eq)]
53enum GateCheck {
54 Open,
56 Wait,
58 Recheck,
60}
61
62fn gate_check_due(last: Option<std::time::Instant>, now: std::time::Instant) -> GateCheck {
63 match last {
64 None => GateCheck::Open,
65 Some(t) if now.duration_since(t) < GATE_RECHECK_EVERY => GateCheck::Wait,
66 Some(_) => GateCheck::Recheck,
67 }
68}
69
70async fn still_needs_login(state: &AppState, uid: &str) -> bool {
73 let last = needs_login().lock().unwrap().get(uid).copied();
74 match gate_check_due(last, std::time::Instant::now()) {
75 GateCheck::Open => return false,
76 GateCheck::Wait => return true,
77 GateCheck::Recheck => {}
78 }
79 let Some(block_id) = state.reactive_handler.block_for_uid(uid) else {
80 return true;
81 };
82 let (mstore, id_store, identity_store) =
83 (state.mstore.clone(), state.id_store.clone(), state.identity_store.clone());
84 let passed = tokio::task::spawn_blocking(move || {
85 let own_endpoint = mstore
88 .get::<Block>(&block_id)
89 .ok()
90 .flatten()
91 .is_some_and(|block| crate::backend::spawn_env::endpoint::own_claude_endpoint_of(&block.meta));
92 crate::identity::resolver::inject_identity_env_for_spawn(
93 mstore,
94 id_store,
95 identity_store,
96 None,
97 &block_id,
98 &mut Default::default(),
99 own_endpoint,
100 )
101 .is_ok()
102 })
103 .await
104 .unwrap_or(false);
106 if passed {
107 needs_login().lock().unwrap().remove(uid);
108 tracing::info!(target_uid = %uid, "durable jekt: signed in, delivering held messages");
109 return false;
110 }
111 mark_needs_login(uid);
112 true
113}
114
115fn routine_decision(status: &crate::backend::agent_status::AgentStatus, cold_after_ms: Option<u64>) -> Decision {
119 let message = |cold_after_ms| Intent::Message { urgent: false, routine: true, cold_after_ms };
120 match decide(status, message(None), || false) {
121 offline @ Decision::Wait { reason: WaitReason::ApiOffline, .. } => offline,
122 _ => decide(status, message(cold_after_ms), || false),
123 }
124}
125
126async fn target_decision(state: &AppState, uid: &str, cold_after_ms: Option<u64>) -> Decision {
131 let Some(block_id) = state.reactive_handler.block_for_uid(uid) else {
132 return Decision::Deliver;
133 };
134 let mstore = state.mstore.clone();
135 tokio::task::spawn_blocking(move || {
136 let block = mstore.get::<Block>(&block_id).ok().flatten();
137 let status = status_of(&mstore, Some(&block_id), block.as_ref(), &crate::connectivity::status(), agentmux_common::time::now_ms_u64());
138 routine_decision(&status, cold_after_ms)
139 })
140 .await
141 .unwrap_or(Decision::Wait { reason: WaitReason::UsageLimit, until_ms: None })
143}
144
145const PEER_PASS_LIMIT: Duration = Duration::from_secs(60);
148
149pub(crate) fn install(state: &AppState) {
153 let peers = state.clone();
154 tokio::spawn(async move {
155 loop {
156 let _ = tokio::time::timeout(PEER_PASS_LIMIT, super::reactive::peer_hold::replay_pass(&peers)).await;
157 tokio::time::sleep(SWEEP_EVERY).await;
158 }
159 });
160 let state = state.clone();
161 tokio::spawn(async move {
162 loop {
163 replay_pass(&state).await;
164 tokio::select! {
165 _ = crate::backend::reactive::held_jekt_wake().notified() => {}
166 _ = tokio::time::sleep(SWEEP_EVERY) => {}
167 }
168 }
169 });
170}
171
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
174pub(crate) enum ReplayOutcome {
175 Delivered,
176 Deferred,
179 Failed,
181 Dropped,
183 Expired,
187}
188
189pub(crate) async fn replay_pass(state: &AppState) -> Vec<(String, ReplayOutcome)> {
193 let mstore = state.mstore.clone();
194 let now = agentmux_common::time::now_ms();
195 let targets = tokio::task::spawn_blocking(move || {
196 match mstore.jekt_held_delete_expired(now) {
197 Ok(n) if n > 0 => {
198 for _ in 0..n {
199 crate::backend::agent_resolve::record_uid_fallback("jekt.held_expired");
200 }
201 tracing::info!(expired = n, "durable jekt: held messages expired");
202 }
203 Ok(_) => {}
204 Err(e) => tracing::warn!(error = %e, "durable jekt: expiry failed"),
205 }
206 mstore.jekt_held_targets().unwrap_or_default()
207 })
208 .await
209 .unwrap_or_default();
210
211 let mut targets = targets;
214 if !targets.is_empty() {
215 static ROTATION: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
216 let n = targets.len();
217 targets.rotate_left(ROTATION.fetch_add(1, std::sync::atomic::Ordering::Relaxed) % n);
218 }
219 let extra = state.config_watcher.get_full_config().settings.extra.clone();
220 let cold_after_ms = crate::backend::cold_hold::cold_after_ms(&extra).and_then(|ms| u64::try_from(ms).ok());
221 let quota_tight = crate::backend::quota_mode::is_tight(&extra);
222 let mut outcomes = Vec::new();
223 let mut spent = 0;
224 for uid in targets {
225 if spent >= REPLAY_PER_PASS {
226 break;
227 }
228 if !state.reactive_handler.has_uid_registration(&uid) {
229 continue;
230 }
231 if state.reactive_handler.block_for_uid(&uid).is_some_and(|b| crate::backend::reactive::controller_wait::awaits_controller(&b)) {
235 continue;
236 }
237 if still_needs_login(state, &uid).await {
238 continue;
239 }
240 let warm = match target_decision(state, &uid, cold_after_ms).await {
244 Decision::Wait { reason: WaitReason::UsageLimit | WaitReason::NeedsLogin | WaitReason::ApiOffline, .. } => continue,
245 Decision::Wait { reason: WaitReason::Cold | WaitReason::NotRunning, .. } => false,
247 _ => true,
248 };
249 let activity = state.reactive_handler.block_for_uid(&uid).and_then(|block_id| crate::backend::cold_hold::session_activity(&block_id));
252 let gate = crate::backend::storage::jekt_held::ReplayGate {
253 now_ms: now,
254 warm,
255 quota_open: !quota_tight || matches!(activity, Some((true, _))),
256 active_at_ms: activity.and_then(|(_, last_output)| last_output).unwrap_or(0),
257 };
258 let mstore = state.mstore.clone();
259 let budget = REPLAY_PER_PASS - spent;
260 let rows = tokio::task::spawn_blocking(move || mstore.jekt_held_ready_for(&uid, budget, &gate))
261 .await
262 .ok()
263 .and_then(Result::ok)
264 .unwrap_or_default();
265 for row in rows {
266 let id = row.request_id.clone();
267 let outcome = replay_one(state, row).await;
268 outcomes.push((id, outcome));
269 match outcome {
275 ReplayOutcome::Deferred => break,
276 ReplayOutcome::Failed | ReplayOutcome::Dropped => {
277 spent += 1;
278 break;
279 }
280 ReplayOutcome::Expired | ReplayOutcome::Delivered => spent += 1,
284 }
285 }
286 }
287 outcomes
288}
289
290pub(crate) use crate::backend::reactive::held_request::request_from_held;
291
292async fn replay_one(state: &AppState, row: HeldJekt) -> ReplayOutcome {
293 if row.sender_expires_at_ms.is_some_and(|expires| expires <= agentmux_common::time::now_ms()) {
300 let mstore = state.mstore.clone();
301 let id = row.request_id.clone();
302 let _ = tokio::task::spawn_blocking(move || mstore.jekt_held_delete(&id)).await;
303 crate::backend::agent_resolve::record_uid_fallback("jekt.held_sender_expired");
304 tracing::info!(
305 target_uid = %row.target_uid,
306 source_agent = %row.source_agent,
307 "durable jekt: the sender's expiry passed — dropping the held message instead of delivering it"
308 );
309 return ReplayOutcome::Expired;
310 }
311 let mut req = request_from_held(&row);
315 super::jekt_files::prepare(&mut req).await;
316 let charged = req.clone();
317 let resp = state.reactive_handler.inject_held(req);
318 super::jekt_files::settle(&charged, resp.success);
319 let mstore = state.mstore.clone();
320 let id = row.request_id.clone();
321 if resp.success {
322 let _ = tokio::task::spawn_blocking(move || mstore.jekt_held_delete(&id)).await;
323 crate::backend::agent_resolve::record_uid_fallback("jekt.held_delivered");
324 return ReplayOutcome::Delivered;
325 }
326 let error = resp.error.unwrap_or_default();
327 if crate::backend::reactive::is_transient_delivery_error(&error) {
331 return ReplayOutcome::Deferred;
332 }
333 if is_spawn_gate_refusal(&error) {
336 mark_needs_login(&row.target_uid);
337 return ReplayOutcome::Deferred;
338 }
339 let attempts = tokio::task::spawn_blocking({
340 let mstore = mstore.clone();
341 let id = id.clone();
342 let error = error.clone();
343 move || mstore.jekt_held_record_failure(&id, &error).unwrap_or(0)
345 })
346 .await
347 .unwrap_or(0);
348 if attempts >= MAX_ATTEMPTS {
349 let _ = tokio::task::spawn_blocking(move || mstore.jekt_held_delete(&id)).await;
350 crate::backend::agent_resolve::record_uid_fallback("jekt.held_failed");
351 tracing::warn!(target_uid = %row.target_uid, error = %error, "durable jekt: dropped after repeated failures");
352 return ReplayOutcome::Dropped;
353 }
354 ReplayOutcome::Failed
355}
356
357#[cfg(test)]
358mod tests {
359 use super::*;
360 use std::time::Instant;
361
362 #[test]
365 fn a_cold_session_with_an_offline_api_still_waits_for_the_api() {
366 use crate::backend::agent_availability::Availability;
367 use crate::backend::agent_status::{AgentStatus, Pane, Reach, Wanted};
368 let after = 55 * 60_000;
369 let status = |quiet, api| AgentStatus {
370 availability: Availability::Idle { quiet_for_ms: Some(quiet) },
371 pane: Pane::Shown,
372 wanted: Wanted::Running,
373 api,
374 controller: true,
375 };
376 let api_wait = Decision::Wait { reason: WaitReason::ApiOffline, until_ms: None };
377 assert_eq!(routine_decision(&status(after + 1, Reach::Offline), Some(after)), api_wait, "cold and offline");
378 assert_eq!(routine_decision(&status(5, Reach::Offline), Some(after)), api_wait, "warm and offline");
379 assert_eq!(
380 routine_decision(&status(after + 1, Reach::Online), Some(after)),
381 Decision::Wait { reason: WaitReason::Cold, until_ms: None },
382 "cold, API fine: the cold rule as before"
383 );
384 assert_eq!(routine_decision(&status(5, Reach::Online), Some(after)), Decision::Deliver);
385 }
386
387 #[test]
388 fn a_spawn_gate_refusal_is_recognised_and_nothing_else_is() {
389 assert!(is_spawn_gate_refusal("identity spawn gate: no credentials for claude: …"));
390 for other in ["agent not found: x", "rate limit exceeded", "persistent process not running", ""] {
391 assert!(!is_spawn_gate_refusal(other), "{other}");
392 }
393 }
394
395 #[test]
399 fn the_sign_in_check_runs_at_most_once_a_minute() {
400 let now = Instant::now();
401 assert_eq!(gate_check_due(None, now), GateCheck::Open);
402 assert_eq!(gate_check_due(Some(now), now), GateCheck::Wait);
403 assert_eq!(gate_check_due(Some(now), now + Duration::from_secs(59)), GateCheck::Wait);
404 assert_eq!(gate_check_due(Some(now), now + GATE_RECHECK_EVERY), GateCheck::Recheck);
405 }
406
407 #[tokio::test]
412 async fn a_row_past_its_senders_expiry_is_dropped_at_delivery_time() {
413 use crate::backend::reactive::types::InjectionRequest;
414 let state = crate::server::tests::test_state();
415 let now = agentmux_common::time::now_ms();
416 let req = InjectionRequest {
417 target_agent: "expired-target".to_string(),
418 message: "stale".to_string(),
419 source_agent: Some("sender".to_string()),
420 request_id: Some("req-expired-direct".to_string()),
421 expires_at_ms: Some(now - 1),
422 ..Default::default()
423 };
424 let mut row = crate::server::jekt_hold::held_row(&req, "req-expired-direct".to_string(), now - 1_000);
425 row.target_uid = "uid-expired-direct".to_string();
426 state.mstore.jekt_held_insert(&row).unwrap();
427
428 assert_eq!(replay_one(&state, row).await, ReplayOutcome::Expired);
429 assert!(state.mstore.jekt_held_for_target("uid-expired-direct", 10).unwrap().is_empty());
430 }
431
432 #[test]
436 fn a_held_rows_sender_expiry_rides_into_the_replay_request() {
437 use crate::backend::reactive::types::InjectionRequest;
438 let req = InjectionRequest {
439 target_agent: "agenty".to_string(),
440 message: "hi".to_string(),
441 source_agent: Some("sender".to_string()),
442 expires_at_ms: Some(1_234_567),
443 ..Default::default()
444 };
445 let row = crate::server::jekt_hold::held_row(&req, "req-sender-expiry".to_string(), 10);
446 assert_eq!(row.sender_expires_at_ms, Some(1_234_567), "kept on the row");
447 let replay = request_from_held(&row);
448 assert_eq!(replay.expires_at_ms, Some(1_234_567), "and on the delivery request");
449 }
450
451 #[test]
456 fn a_replay_names_the_target_the_sender_addressed() {
457 use crate::backend::reactive::types::InjectionRequest;
458 let req = InjectionRequest { target_agent: "Glim".to_string(), message: "hi".to_string(), ..Default::default() };
459 let mut row = crate::server::jekt_hold::held_row(&req, "req-name".to_string(), 10);
460 row.target_uid = "17e48252-bf89-4be9-addc-71b29035c22c".to_string();
461
462 let replay = request_from_held(&row);
463 assert_eq!(replay.target_agent, row.target_uid, "routed by UID");
464 assert_eq!(replay.marker_target.as_deref(), Some("Glim"), "marked by name");
465
466 row.target_agent = row.target_uid.clone();
467 assert_eq!(request_from_held(&row).marker_target, None, "nothing to add when the name is the UID");
468 }
469}
470
471#[cfg(test)]
472#[path = "jekt_held_starting_tests.rs"]
473mod starting_tests;
474
475#[cfg(test)]
476#[path = "jekt_held_gate_tests.rs"]
477mod gate_tests;