1use std::collections::HashMap;
20
21use axum::extract::{Query, State};
22use axum::http::StatusCode;
23use axum::response::{IntoResponse, Json, Response};
24use serde::Deserialize;
25use serde_json::json;
26
27use crate::backend::reactive::types::AgentRegistration;
28use crate::backend::work_facts::cross_channel::{self, own_channel};
29use crate::backend::work_facts::{self, claims, matching, WorkFacts};
30
31use super::caller::Caller;
32use super::AppState;
33
34const NOTE: &str = "Informational only: nothing is locked or blocked. If someone else is changing the same \
36 thing, message them (Message send) before you change it.";
37
38pub(crate) async fn local_facts(state: &AppState) -> Vec<WorkFacts> {
40 let regs = state.reactive_handler.list_agents();
41 let store = state.mstore.clone();
42 let channel = own_channel();
43 tokio::task::spawn_blocking(move || work_facts::collect_local(&store, ®s, &channel))
44 .await
45 .unwrap_or_default()
46}
47
48pub(super) async fn cross_channel_facts(state: &AppState) -> (Vec<WorkFacts>, Vec<String>) {
50 cross_channel::fetch(&state.http_client, &state.local_web_url).await
51}
52
53pub async fn handle_work_facts(State(state): State<AppState>) -> impl IntoResponse {
55 Json(json!({ "channel": own_channel(), "agents": local_facts(&state).await }))
56}
57
58#[derive(Debug, Default, Deserialize)]
62pub struct WhoParams {
63 pub path: Option<String>,
64 pub repo: Option<String>,
65 pub branch: Option<String>,
66 pub query: Option<String>,
67 pub pr: Option<i64>,
70 pub agent: Option<String>,
71 pub block: Option<String>,
72}
73
74pub(super) fn caller_block(regs: &[AgentRegistration], uid: Option<&str>, block: Option<&str>, agent: Option<&str>) -> Option<String> {
78 if let Some(uid) = uid {
79 if let Some(r) = regs.iter().find(|r| r.uid.as_deref() == Some(uid)) {
80 return Some(r.block_id.clone());
81 }
82 }
83 let block = block.map(str::trim).filter(|b| !b.is_empty());
84 if let Some(r) = block.and_then(|b| regs.iter().find(|r| r.block_id == b)) {
85 return Some(r.block_id.clone());
86 }
87 let agent = agent.map(str::trim).filter(|a| !a.is_empty())?;
88 let mut named = regs.iter().filter(|r| r.agent_id.eq_ignore_ascii_case(agent));
89 match (named.next(), named.next()) {
90 (Some(r), None) => Some(r.block_id.clone()),
91 _ => None,
92 }
93}
94
95pub(super) fn split_caller(facts: Vec<WorkFacts>, caller_block: Option<&str>) -> (Option<WorkFacts>, Vec<WorkFacts>) {
97 let (mine, others): (Vec<_>, Vec<_>) =
98 facts.into_iter().partition(|f| caller_block.is_some_and(|b| f.block_id == b));
99 (mine.into_iter().next(), others)
100}
101
102fn remote_agents(state: &AppState) -> Vec<serde_json::Value> {
105 let mut out = Vec::new();
106 for lan in state.lan_discovery.get_instances() {
107 for name in &lan.agents {
108 out.push(json!({ "agent": name, "channel": "lan", "status": "online" }));
109 }
110 }
111 if let Some(sub) = crate::muxbus::cloud_subscriber::get_global_subscriber() {
112 let cloud = crate::muxbus::cloud_installs::cached();
114 let own_wan_id = crate::backend::swarm_cloud::own_wan_id();
115 let now_ms = agentmux_common::time::now_ms_u64();
116 for name in sub.subscribed_agents() {
117 out.push(json!({ "agent": name, "channel": "wan", "status": cloud.as_ref().and_then(|c| crate::backend::swarm_cloud::agent_state(c, &name, own_wan_id.as_deref(), now_ms)).unwrap_or("online") }));
118 }
119 }
120 out
121}
122
123pub(crate) async fn handle_who_is_working_on(
125 State(state): State<AppState>,
126 caller: Option<axum::Extension<Caller>>,
127 Query(p): Query<WhoParams>,
128) -> Response {
129 let regs = state.reactive_handler.list_agents();
130 let uid = caller.as_ref().and_then(|c| c.0.uid().map(str::to_string));
131 let me_block = caller_block(®s, uid.as_deref(), p.block.as_deref(), p.agent.as_deref());
132 let store = state.work_store.clone();
133 let now = agentmux_common::time::now_ms();
134 let live_claims = tokio::task::spawn_blocking(move || store.work_claims_live(now).unwrap_or_default());
135 let (local, (cross, unreachable), live_claims) =
136 tokio::join!(local_facts(&state), cross_channel_facts(&state), live_claims);
137 let (me, mut others) = split_caller(local, me_block.as_deref());
138 others.extend(cross);
139
140 let q = matching::WhoQuery { path: p.path, repo: p.repo, branch: p.branch, query: p.query };
141 let target = match matching::resolve(&q, me.as_ref(), &others) {
142 Ok(t) => t,
143 Err(e) => return (StatusCode::BAD_REQUEST, Json(json!({ "error": e }))).into_response(),
144 };
145 let mut agents = matching::who_is_working_on(&target, &others);
146 let me_name = me.as_ref().map(|m| m.agent.clone()).or(p.agent).unwrap_or_default();
148 let theirs: Vec<_> = live_claims
149 .unwrap_or_default()
150 .into_iter()
151 .filter(|c| !claims::is_own(c, &me_name, uid.as_deref().unwrap_or("")))
152 .collect();
153 claims::add_claim_matches(&mut agents, &target, &theirs, &others, now);
154 let store = state.work_store.clone();
156 let asked = target.clone();
157 let pr = p.pr.filter(|n| *n > 0);
158 let recent_posts = tokio::task::spawn_blocking(move || super::coord_channel_handlers::recent_posts(&store, &asked, pr, now))
159 .await
160 .unwrap_or_default();
161 Json(json!({
162 "asked": target,
163 "caller": me.as_ref().map(|m| json!({ "agent": m.agent, "repo": m.repo, "branch": m.branch })),
164 "agents": agents,
165 "recent_posts": recent_posts,
166 "remote_agents": remote_agents(&state),
167 "unreachable_channels": unreachable,
168 "note": NOTE,
169 }))
170 .into_response()
171}
172
173pub(super) fn start_conversation_facts(state: &AppState) -> tokio::task::JoinHandle<Vec<WorkFacts>> {
177 let state = state.clone();
178 tokio::spawn(async move {
179 let (mut local, (cross, _)) = tokio::join!(local_facts(&state), cross_channel_facts(&state));
180 local.extend(cross);
181 local
182 })
183}
184
185pub(super) async fn annotate_conversations(
190 facts: tokio::task::JoinHandle<Vec<WorkFacts>>,
191 entries: &mut [serde_json::Value],
192) {
193 let facts = facts.await.unwrap_or_default();
194 let by_block: HashMap<&str, &WorkFacts> = facts.iter().map(|f| (f.block_id.as_str(), f)).collect();
195 for e in entries.iter_mut() {
196 let Some(f) = e.get("block_id").and_then(|b| b.as_str()).and_then(|b| by_block.get(b)) else {
197 continue;
198 };
199 let summary = work_facts::conversation_summary(f);
200 if let Some(obj) = e.as_object_mut() {
201 obj.insert("work".to_string(), summary);
202 }
203 }
204}
205
206#[cfg(test)]
207mod tests {
208 use super::*;
209
210 fn reg(agent: &str, block: &str, uid: Option<&str>) -> AgentRegistration {
211 AgentRegistration {
212 agent_id: agent.into(),
213 block_id: block.into(),
214 tab_id: None,
215 uid: uid.map(Into::into),
216 registered_at: 0,
217 last_seen: 0,
218 registration_nonce: 0,
219 }
220 }
221
222 #[test]
223 fn the_caller_is_found_by_token_then_block_then_unique_name() {
224 let regs = vec![reg("AgentY", "b1", Some("u1")), reg("Agent2", "b2", None), reg("Agent2", "b3", None)];
225 assert_eq!(caller_block(®s, Some("u1"), Some("b2"), None).as_deref(), Some("b1"));
226 assert_eq!(caller_block(®s, None, Some("b2"), Some("AgentY")).as_deref(), Some("b2"));
227 assert_eq!(caller_block(®s, None, None, Some("agenty")).as_deref(), Some("b1"));
228 assert_eq!(caller_block(®s, None, None, Some("Agent2")), None, "an ambiguous name names no one");
229 assert_eq!(caller_block(®s, None, Some("gone"), None), None);
230 }
231
232 #[test]
235 fn the_caller_is_excluded_and_its_repository_is_assumed() {
236 let fact = |agent: &str, block: &str, root: &str| WorkFacts {
237 agent: agent.into(),
238 block_id: block.into(),
239 repo: Some("o/r".into()),
240 repo_root: Some(root.into()),
241 dirty_files: vec!["a.rs".into()],
242 ..Default::default()
243 };
244 let (me, others) = split_caller(vec![fact("Me", "b1", "/me"), fact("Other", "b2", "/o")], Some("b1"));
245 assert_eq!(me.as_ref().map(|m| m.agent.as_str()), Some("Me"));
246 let q = matching::WhoQuery { path: Some("a.rs".into()), ..Default::default() };
247 let t = matching::resolve(&q, me.as_ref(), &others).unwrap();
248 let names: Vec<String> = matching::who_is_working_on(&t, &others).into_iter().map(|r| r.agent).collect();
249 assert_eq!(names, vec!["Other".to_string()]);
250
251 let (none, all) = split_caller(vec![fact("A", "b1", "/a")], None);
252 assert!(none.is_none());
253 assert_eq!(all.len(), 1, "an unknown caller excludes no one");
254 }
255
256 #[tokio::test]
257 async fn the_facts_endpoint_lists_this_srvs_agents() {
258 let state = crate::server::tests::test_state();
259 let unique = uuid::Uuid::new_v4();
260 let (agent, block) = (format!("facts-agent-{unique}"), format!("facts-block-{unique}"));
261 state.reactive_handler.register_agent(&agent, &block, None).unwrap();
262 let resp = handle_work_facts(State(state)).await.into_response();
263 assert_eq!(resp.status(), StatusCode::OK);
264 let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
265 let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
266 let agents: Vec<WorkFacts> = serde_json::from_value(body["agents"].clone()).unwrap();
267 let mine = agents.iter().find(|f| f.agent == agent).expect("registered agent listed");
268 assert_eq!(mine.block_id, block);
269 assert_eq!(mine.status, "stopped", "no controller in a test");
270 }
271
272 #[tokio::test]
273 async fn who_explains_a_question_it_cannot_answer() {
274 let state = crate::server::tests::test_state();
275 let resp = handle_who_is_working_on(
276 State(state),
277 None,
278 Query(WhoParams { path: Some("relative/x.rs".into()), ..Default::default() }),
279 )
280 .await;
281 assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
282 }
283
284 #[tokio::test]
285 async fn conversations_entries_gain_a_work_field_by_block() {
286 let state = crate::server::tests::test_state();
287 let unique = uuid::Uuid::new_v4();
288 let (agent, block) = (format!("conv-agent-{unique}"), format!("conv-block-{unique}"));
289 state.reactive_handler.register_agent(&agent, &block, None).unwrap();
290 let mut entries = vec![
291 json!({ "name": agent, "tier": "host", "block_id": block }),
292 json!({ "name": "remote", "tier": "lan" }),
293 ];
294 annotate_conversations(start_conversation_facts(&state), &mut entries).await;
295 assert!(entries[0]["work"].is_object(), "{}", entries[0]);
296 assert_eq!(entries[0]["work"]["dirty_count"], 0);
297 assert!(entries[1].get("work").is_none(), "LAN entries carry no facts");
298 }
299}