Skip to main content

agentmux_srv/server/
held_input.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Held input for an agent no pane shows (`docs/specs/SPEC_OFFLINE_RESILIENCE_2026_10_20.md` ยง4.4,
5//! "Held input for a parked agent"). The operator's messages typed while the model API was out wait in
6//! the block's meta (`agent:held_input`) and the pane sends them when it is open and the API answers. A
7//! parked block (`agent:parked`: no tab, so no pane, as after closing the pane of an agent that keeps
8//! running) has no pane to do that, so srv sends them: the oldest, when its agent runs, is between
9//! turns and the API answers. A stopped agent has no controller, so its message waits; the look that
10//! follows an agent registering (`reactive::held_input_wake`) sends it as the agent starts.
11//!
12//! Only parked blocks: a block in a tab has a pane, or will when its window opens, and that pane keeps
13//! the send path it has (slash commands, runtime arguments, the busy queue).
14//!
15//! The claim is the pane's own mark. Before a message goes, `agent:held_input` is rewritten in one
16//! transaction that also checks the block is still parked: the message is `unconfirmed`, which a pane
17//! that mounts later reads as "may have gone" and never sends by itself. A pane attaching in between
18//! clears the parked mark in a transaction of its own, so exactly one of the two wins. Once srv
19//! accepted the message it is taken off the list; a send that failed is marked held again.
20
21use 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
34/// The block meta a pane keeps its held messages in (`useOfflineInput.ts`).
35pub(crate) const HELD_INPUT_META_KEY: &str = "agent:held_input";
36const EVERY: Duration = Duration::from_secs(20);
37/// After a failed send a block is left alone this long.
38const BACKOFF: Duration = Duration::from_secs(60);
39
40/// Blocks to leave alone until a time, after a send that failed.
41fn 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
46/// The held list of a block, if it is the agent's own: `agentId` is the agent the messages were typed to.
47fn 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
60/// The oldest held message, when it may go: one marked `unconfirmed` may have gone already and
61/// waits for the operator.
62fn 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
67/// The block's model API, as its pane reads it (`agentProvider`, and `agent:api_endpoint` when the CLI
68/// was pointed at another address).
69pub(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
76/// What may be done about the oldest held message of `block` now: the one decision every path asks
77/// (`agent_status::decide`). It goes only on `Deliver`: not while the agent has no process, is out of
78/// quota until a known reset, is signed out, or its model API does not answer.
79fn 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
84/// Edit the held list of a block inside one transaction. `edit` gets the messages; `None` back means
85/// leave the block as it is.
86fn 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
107/// Mark the message `id` as sent by srv and possibly gone, if it is still first and unmarked and the block is still parked.
108fn 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
119/// srv accepted the message: it is no longer held.
120fn 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
128/// The send failed and the message did not go: held as before, for the next pass or a pane.
129fn 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
139/// One parked block: send its oldest held message if it may go.
140async 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    // The agent runs and is between turns, and its API answers.
161    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    // A panicked read sends nothing.
172    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        // An agent still starting, stopping or full says "try again shortly": the next look does.
214        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
225/// One look at every parked block that holds input.
226async 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
241/// Start looking for parked blocks with input to send: every [`EVERY`], and when an agent registers, so
242/// the input held for an agent that was stopped goes out as it starts.
243pub(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;