1use std::collections::HashMap;
22use std::sync::Mutex;
23use std::time::{Duration, Instant};
24
25use serde_json::{json, Value};
26
27use super::AppState;
28use crate::backend::agent_status::{decide, Decision, Intent};
29use crate::backend::obj::Block;
30use crate::backend::rpc_types::AttachmentRef;
31use crate::backend::storage::store::Store;
32use crate::persist_subscriber::parked::PARKED_META_KEY;
33
34pub(crate) const HELD_INPUT_META_KEY: &str = "agent:held_input";
36const EVERY: Duration = Duration::from_secs(20);
37const BACKOFF: Duration = Duration::from_secs(60);
39
40fn backoff() -> &'static Mutex<HashMap<String, Instant>> {
42 static MAP: std::sync::OnceLock<Mutex<HashMap<String, Instant>>> = std::sync::OnceLock::new();
43 MAP.get_or_init(Default::default)
44}
45
46fn held_messages<'a>(meta: &'a HashMap<String, Value>) -> Option<&'a Vec<Value>> {
48 let held = meta.get(HELD_INPUT_META_KEY)?;
49 let own = held.get("agentId").and_then(Value::as_str).filter(|id| !id.is_empty())?;
50 if meta.get("agentId").and_then(Value::as_str) != Some(own) {
51 return None;
52 }
53 held.get("messages")?.as_array().filter(|m| !m.is_empty())
54}
55
56fn is_parked(meta: &HashMap<String, Value>) -> bool {
57 meta.get(PARKED_META_KEY).and_then(Value::as_bool).unwrap_or(false)
58}
59
60fn sendable(meta: &HashMap<String, Value>) -> Option<&Value> {
63 let first = held_messages(meta)?.first()?;
64 (!first.get("unconfirmed").and_then(Value::as_bool).unwrap_or(false)).then_some(first)
65}
66
67pub(super) fn service_of(meta: &HashMap<String, Value>) -> Option<String> {
70 let provider = meta.get("agentProvider").and_then(Value::as_str).unwrap_or("");
71 let api = crate::connectivity::model_api_of(provider)?;
72 let url = meta.get("agent:api_endpoint").and_then(|v| v.get("url")).and_then(Value::as_str);
73 Some(crate::connectivity::service_for(api, url).id())
74}
75
76fn held_input_decision(store: &Store, block: &Block, net: &crate::connectivity::ConnectivityStatus, now_ms: u64) -> Decision {
80 let status = super::availability_view::status_of(store, Some(&block.oid), Some(block), net, now_ms);
81 decide(&status, Intent::HeldInput, || false)
82}
83
84fn edit_held(store: &Store, block_id: &str, require_parked: bool, edit: impl FnOnce(&mut Vec<Value>) -> bool) -> Result<bool, String> {
87 store
88 .with_tx(|tx| {
89 let Some(mut block) = tx.get::<Block>(block_id)? else { return Ok(false) };
90 if require_parked && !is_parked(&block.meta) {
91 return Ok(false);
92 }
93 let Some(held) = block.meta.get_mut(HELD_INPUT_META_KEY).and_then(Value::as_object_mut) else { return Ok(false) };
94 let Some(messages) = held.get_mut("messages").and_then(Value::as_array_mut) else { return Ok(false) };
95 if !edit(messages) {
96 return Ok(false);
97 }
98 if messages.is_empty() {
99 block.meta.remove(HELD_INPUT_META_KEY);
100 }
101 tx.update(&mut block)?;
102 Ok(true)
103 })
104 .map_err(|e| e.to_string())
105}
106
107fn claim(store: &Store, block_id: &str, id: &str, attempt: &str) -> Result<bool, String> {
109 edit_held(store, block_id, true, |messages| match messages.first_mut() {
110 Some(first) if first.get("id").and_then(Value::as_str) == Some(id) && first.get("unconfirmed").and_then(Value::as_bool) != Some(true) => {
111 first["unconfirmed"] = json!(true);
112 first["attempt"] = json!(attempt);
113 true
114 }
115 _ => false,
116 })
117}
118
119fn settle(store: &Store, block_id: &str, id: &str) -> Result<bool, String> {
121 edit_held(store, block_id, false, |messages| {
122 let before = messages.len();
123 messages.retain(|m| m.get("id").and_then(Value::as_str) != Some(id));
124 messages.len() != before
125 })
126}
127
128fn release(store: &Store, block_id: &str, id: &str, attempt: &str) -> Result<bool, String> {
130 edit_held(store, block_id, false, |messages| match messages.iter_mut().find(|m| m.get("id").and_then(Value::as_str) == Some(id)) {
131 Some(m) if m.get("attempt").and_then(Value::as_str) == Some(attempt) => {
132 m["unconfirmed"] = json!(false);
133 true
134 }
135 _ => false,
136 })
137}
138
139async fn deliver_next(state: &AppState, block_id: &str) {
141 let store = state.mstore.clone();
142 let block = {
143 let (store, id) = (store.clone(), block_id.to_string());
144 tokio::task::spawn_blocking(move || store.get::<Block>(&id).ok().flatten()).await.ok().flatten()
145 };
146 let Some(block) = block else { return };
147 if !is_parked(&block.meta) {
148 return;
149 }
150 let Some(first) = sendable(&block.meta).cloned() else { return };
151 let Some(id) = first.get("id").and_then(Value::as_str).map(str::to_string) else { return };
152 let text = first.get("text").and_then(Value::as_str).unwrap_or("").to_string();
153 let attachments: Vec<AttachmentRef> = match first.get("attachments") {
154 Some(a) => match serde_json::from_value(a.clone()) {
155 Ok(a) => a,
156 Err(_) => return,
157 },
158 None => Vec::new(),
159 };
160 let Some(ctrl) = crate::backend::blockcontroller::get_controller(block_id) else { return };
162 if ctrl.turn_tracker().is_some_and(|t| t.is_active_turn()) {
163 return;
164 }
165 let net = crate::connectivity::status();
166 let now_ms = agentmux_common::time::now_ms_u64();
167 let allowed = {
168 let (store, block) = (store.clone(), block.clone());
169 tokio::task::spawn_blocking(move || held_input_decision(&store, &block, &net, now_ms)).await
170 };
171 if !matches!(allowed, Ok(Decision::Deliver)) {
173 return;
174 }
175 let attempt = format!("srv_{}", agentmux_common::time::now_ms_u64());
176 let claimed = {
177 let (store, block_id, id, attempt) = (store.clone(), block_id.to_string(), id.clone(), attempt.clone());
178 tokio::task::spawn_blocking(move || claim(&store, &block_id, &id, &attempt)).await
179 };
180 match claimed {
181 Ok(Ok(true)) => {}
182 Ok(Ok(false)) => return,
183 Ok(Err(e)) => {
184 tracing::warn!(block_id, error = %e, "held input: couldn't mark a held message");
185 return;
186 }
187 Err(_) => return,
188 }
189 crate::backend::blockcontroller::core::broadcast_block_update(&store, &state.event_bus, block_id);
190 let deps = super::agent_handlers::AgentTurnDeps::from_state(state);
191 let sent = super::agent_handlers::run_agent_turn_joining(
192 &deps,
193 block_id.to_string(),
194 text,
195 Some(id.clone()),
196 super::agent_handlers::TurnRegistration::Register,
197 crate::backend::message_origin::MessageOrigin::user(),
198 attachments,
199 None,
200 false,
201 )
202 .await;
203 let (store2, block2, id2, attempt2) = (store.clone(), block_id.to_string(), id.clone(), attempt);
204 let settled = match &sent {
205 Ok(()) => tokio::task::spawn_blocking(move || settle(&store2, &block2, &id2)).await,
206 Err(_) => tokio::task::spawn_blocking(move || release(&store2, &block2, &id2, &attempt2)).await,
207 };
208 if let Ok(Err(e)) = settled {
209 tracing::warn!(block_id, error = %e, "held input: couldn't record what became of a held message");
210 }
211 match sent {
212 Ok(()) => tracing::info!(block_id, message = %id, "held input: sent a held message to a parked agent"),
213 Err(e) if crate::backend::reactive::is_transient_delivery_error(&e) => {
215 tracing::info!(block_id, message = %id, error = %e, "held input: a parked agent wasn't ready for a held message; it stays held");
216 }
217 Err(e) => {
218 tracing::warn!(block_id, message = %id, error = %e, "held input: a parked agent didn't take a held message; it stays held");
219 backoff().lock().unwrap_or_else(|e| e.into_inner()).insert(block_id.to_string(), Instant::now() + BACKOFF);
220 }
221 }
222 crate::backend::blockcontroller::core::broadcast_block_update(&store, &state.event_bus, block_id);
223}
224
225async fn pass(state: &AppState) {
227 let store = state.mstore.clone();
228 let blocks = tokio::task::spawn_blocking(move || store.get_all::<Block>().unwrap_or_default()).await.unwrap_or_default();
229 let now = Instant::now();
230 for block in blocks {
231 if !is_parked(&block.meta) || sendable(&block.meta).is_none() {
232 continue;
233 }
234 let waiting = backoff().lock().unwrap_or_else(|e| e.into_inner()).get(&block.oid).is_some_and(|until| *until > now);
235 if !waiting {
236 deliver_next(state, &block.oid).await;
237 }
238 }
239}
240
241pub(crate) fn install(state: &AppState) {
244 let state = state.clone();
245 tokio::spawn(async move {
246 loop {
247 tokio::select! {
248 _ = crate::backend::reactive::held_input_wake().notified() => {}
249 _ = tokio::time::sleep(EVERY) => {}
250 }
251 pass(&state).await;
252 }
253 });
254}
255
256#[cfg(test)]
257#[path = "held_input_tests.rs"]
258mod tests;