1use std::collections::HashMap;
10use std::sync::Arc;
11use std::time::Duration;
12
13use crate::backend::agent_runtime_state::AgentRuntimeState;
14use crate::backend::cold_hold::{REASON_IDLE, REASON_QUOTA};
15use crate::backend::jekt_held_summary::{
16 JektHeldAgent, JektHeldEvent, JektHeldSummaryResult, REASON_NEEDS_LOGIN, REASON_NOT_RUNNING, REASON_STARTING,
17 REASON_USAGE_LIMIT,
18};
19use crate::backend::rpc::engine::WshRpcEngine;
20use crate::backend::rpc_types::{NoArgsReq, COMMAND_JEKT_HELD_SUMMARY};
21use crate::backend::storage::jekt_held::HeldSummaryRow;
22
23use super::AppState;
24
25const WATCH_EVERY: Duration = Duration::from_secs(5);
27
28fn reason_for(stored: &str, state: Option<AgentRuntimeState>) -> &'static str {
31 if stored == REASON_IDLE {
32 return REASON_IDLE;
33 }
34 if stored == REASON_QUOTA {
35 return REASON_QUOTA;
36 }
37 match state {
38 Some(AgentRuntimeState::Limited) => REASON_USAGE_LIMIT,
39 Some(AgentRuntimeState::SignedOut) => REASON_NEEDS_LOGIN,
40 Some(AgentRuntimeState::Stopped | AgentRuntimeState::Error) => REASON_NOT_RUNNING,
41 Some(_) => REASON_STARTING,
43 None => "peer_offline",
44 }
45}
46
47pub(crate) fn summarize(rows: &[HeldSummaryRow], known: &HashMap<String, (String, AgentRuntimeState)>) -> JektHeldSummaryResult {
49 let mut agents: Vec<JektHeldAgent> = Vec::new();
50 for r in rows {
51 let local = known.get(&r.target_uid);
52 let reason = reason_for(&r.hold_reason, local.map(|(_, s)| *s));
53 let name = local.map(|(n, _)| n.clone()).filter(|n| !n.is_empty()).unwrap_or_else(|| r.target_agent.clone());
54 let since_ms = r.oldest_sent_at_ms.max(0) as u64;
55 let count = r.count.max(0) as u32;
56 match agents.iter_mut().find(|a| a.agent_id == r.target_uid && a.reason == reason) {
58 Some(a) => {
59 a.count += count;
60 a.since_ms = a.since_ms.min(since_ms);
61 }
62 None => agents.push(JektHeldAgent { agent_id: r.target_uid.clone(), agent_name: name, reason: reason.to_string(), count, since_ms }),
63 }
64 }
65 agents.sort_by_key(|a| a.since_ms);
66 JektHeldSummaryResult { agents }
67}
68
69fn totals(rows: &[HeldSummaryRow]) -> JektHeldEvent {
71 let mut uids: Vec<&str> = rows.iter().map(|r| r.target_uid.as_str()).collect();
72 uids.sort_unstable();
73 uids.dedup();
74 JektHeldEvent { messages: rows.iter().map(|r| r.count.max(0) as u32).sum(), agents: uids.len() as u32 }
75}
76
77fn read(state: &AppState) -> JektHeldSummaryResult {
79 let rows = state.mstore.jekt_held_summary().unwrap_or_default();
80 if rows.is_empty() {
81 return JektHeldSummaryResult { agents: Vec::new() };
82 }
83 let now = agentmux_common::time::now_ms_u64();
84 let known: HashMap<String, (String, AgentRuntimeState)> = super::agent_runtime::list(state, now)
85 .into_iter()
86 .map(|a| (a.agent_id, (a.name, a.state)))
87 .collect();
88 summarize(&rows, &known)
89}
90
91pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
95 let s = state.clone();
96 engine.register_typed(COMMAND_JEKT_HELD_SUMMARY, move |_req: Option<NoArgsReq>, ctx| {
97 let s = s.clone();
98 async move {
99 if ctx.agent_id.is_empty() {
100 ctx.operator_only("only the AgentMux window or an agent sees which agents have messages held")?;
101 }
102 tokio::task::spawn_blocking(move || read(&s)).await.map_err(|e| e.to_string())
103 }
104 });
105}
106
107pub(crate) fn install(state: &AppState) {
109 if tokio::runtime::Handle::try_current().is_err() {
110 return;
111 }
112 let state = state.clone();
113 tokio::spawn(async move {
114 let mut last: Option<Vec<HeldSummaryRow>> = None;
115 loop {
116 let mstore = state.mstore.clone();
117 if let Ok(rows) = tokio::task::spawn_blocking(move || mstore.jekt_held_summary().unwrap_or_default()).await {
118 let changed = match &last {
120 Some(prev) => *prev != rows,
121 None => !rows.is_empty(),
122 };
123 if changed {
124 state.broker.publish_event::<crate::backend::mps_events::JektHeld>(&totals(&rows), vec![], 0);
125 }
126 last = Some(rows);
127 }
128 tokio::time::sleep(WATCH_EVERY).await;
129 }
130 });
131}
132
133#[cfg(test)]
134mod tests {
135 use super::*;
136 use crate::backend::rpc_types::{RpcContext, RpcMessage};
137
138 fn row(uid: &str, reason: &str, count: i64, oldest: i64) -> HeldSummaryRow {
139 HeldSummaryRow { target_uid: uid.into(), target_agent: format!("name-of-{uid}"), hold_reason: reason.into(), count, oldest_sent_at_ms: oldest }
140 }
141
142 fn known(list: &[(&str, &str, AgentRuntimeState)]) -> HashMap<String, (String, AgentRuntimeState)> {
143 list.iter().map(|(u, n, s)| (u.to_string(), (n.to_string(), *s))).collect()
144 }
145
146 #[test]
147 fn the_reason_is_what_the_agents_state_says_unless_the_hold_stored_one() {
148 let k = known(&[
149 ("u-stopped", "Stopped", AgentRuntimeState::Stopped),
150 ("u-out", "Out", AgentRuntimeState::SignedOut),
151 ("u-lim", "Limited", AgentRuntimeState::Limited),
152 ("u-run", "Running", AgentRuntimeState::Working),
153 ("u-cold", "Cold", AgentRuntimeState::Idle),
154 ]);
155 let got = summarize(
156 &[row("u-stopped", "", 2, 10), row("u-out", "", 1, 20), row("u-lim", "", 3, 30), row("u-run", "", 1, 40), row("u-cold", REASON_IDLE, 1, 50), row("u-peer", "", 4, 60)],
157 &k,
158 );
159 let by: Vec<(&str, &str, u32)> = got.agents.iter().map(|a| (a.agent_id.as_str(), a.reason.as_str(), a.count)).collect();
160 assert_eq!(
161 by,
162 vec![
163 ("u-stopped", "not_running", 2),
164 ("u-out", "needs_login", 1),
165 ("u-lim", "usage_limit", 3),
166 ("u-run", "starting", 1),
167 ("u-cold", "idle", 1),
168 ("u-peer", "peer_offline", 4),
169 ]
170 );
171 assert_eq!(got.agents[0].agent_name, "Stopped", "the local agent's own name wins");
172 assert_eq!(got.agents[5].agent_name, "name-of-u-peer", "an agent of another machine keeps the name the hold recorded");
173 }
174
175 #[test]
176 fn two_stored_reasons_that_read_the_same_now_are_one_line_with_the_older_since() {
177 let k = known(&[("u", "Agent", AgentRuntimeState::Stopped)]);
178 let got = summarize(&[row("u", "", 2, 300), row("u", "other", 1, 100)], &k);
179 assert_eq!(got.agents.len(), 1);
180 assert_eq!((got.agents[0].count, got.agents[0].since_ms), (3, 100));
181 }
182
183 #[test]
184 fn the_event_carries_only_totals() {
185 let e = totals(&[row("a", "", 2, 1), row("a", REASON_QUOTA, 1, 2), row("b", "", 4, 3)]);
186 assert_eq!((e.messages, e.agents), (7, 2));
187 assert_eq!((totals(&[]).messages, totals(&[]).agents), (0, 0));
188 }
189
190 async fn call(state: &AppState, ctx: RpcContext) -> Result<serde_json::Value, String> {
191 let (engine, mut rx) = WshRpcEngine::new();
192 register(&engine, state);
193 engine.set_rpc_context(ctx);
194 engine.handle_message(RpcMessage { command: COMMAND_JEKT_HELD_SUMMARY.to_string(), reqid: "req-1".to_string(), data: Some(serde_json::json!({})), ..Default::default() });
195 let resp = tokio::time::timeout(Duration::from_secs(10), rx.recv()).await.unwrap().unwrap();
196 if resp.error.is_empty() { Ok(resp.data.unwrap_or_default()) } else { Err(resp.error) }
197 }
198
199 #[tokio::test]
200 async fn the_rpc_answers_counts_and_reasons_and_never_a_body_a_sender_or_an_id() {
201 let state = crate::server::tests::test_state();
202 assert_eq!(call(&state, RpcContext::operator_for_tests()).await.unwrap(), serde_json::json!({"agents": []}));
203 assert!(call(&state, RpcContext::default()).await.is_err(), "a connection that is neither the window nor an agent is refused");
204 let req = crate::backend::reactive::types::InjectionRequest {
205 target_agent: "ghost".to_string(),
206 message: "a secret body".to_string(),
207 source_agent: Some("a-secret-sender".to_string()),
208 request_id: Some("secret-request-id".to_string()),
209 ..Default::default()
210 };
211 let mut held = crate::server::jekt_hold::held_row(&req, "secret-request-id".to_string(), 1_000);
212 held.target_uid = "uid-ghost".to_string();
213 state.mstore.jekt_held_insert(&held).unwrap();
214 let mut second = held.clone();
215 second.request_id = "second-id".to_string();
216 second.sent_at_ms = 2_000;
217 state.mstore.jekt_held_insert(&second).unwrap();
218 for ctx in [RpcContext::operator_for_tests(), RpcContext { agent_id: "some-agent".to_string(), ..Default::default() }] {
219 let answer = call(&state, ctx).await.unwrap();
220 let text = answer.to_string();
221 for secret in ["a secret body", "a-secret-sender", "secret-request-id", "second-id"] {
222 assert!(!text.contains(secret), "{secret} left the hold table: {text}");
223 }
224 let agents = answer["agents"].as_array().unwrap();
225 assert_eq!(agents.len(), 1, "{text}");
226 assert_eq!(agents[0]["agent_id"], "uid-ghost");
227 assert_eq!(agents[0]["count"], 2);
228 assert_eq!(agents[0]["since_ms"], 1_000);
229 assert_eq!(agents[0]["reason"], "peer_offline", "an agent this machine has no definition of is a peer's");
230 }
231 }
232}