1use axum::extract::{Query, State};
22use axum::http::StatusCode;
23use axum::response::{IntoResponse, Json};
24use serde_json::json;
25
26use crate::backend::storage::filestore::FileStore;
27
28use super::AppState;
29
30const LAST_ERROR_TAIL_BYTES: i64 = 8192;
38
39#[derive(serde::Serialize)]
60pub struct LastErrorFrame {
61 pub message: String,
64 pub source: &'static str,
71 pub written_ms: u64,
78}
79
80fn classify_last_error_source(message: &str) -> &'static str {
103 if message.starts_with("no credentials for")
104 || message.starts_with("credential injection could not run")
105 || message.starts_with("this agent's")
106 || message.starts_with("could not isolate this agent's")
112 {
113 "identity"
114 } else if message.starts_with("container exec failed")
115 || message.starts_with("container ensure_running failed")
116 || message.starts_with("Couldn't start the container")
117 {
118 "container_spawn"
119 } else if message.starts_with("queued message could not be sent") {
120 "host_spawn"
121 } else {
122 "unknown"
123 }
124}
125
126fn last_error_frame(source: &crate::backend::transcript::source::TranscriptSource<'_>) -> Option<LastErrorFrame> {
133 let tail = source.tail(LAST_ERROR_TAIL_BYTES)?;
134 let text = String::from_utf8_lossy(&tail.bytes);
135 let last_line = text.lines().rev().find(|l| !l.trim().is_empty())?;
136
137 let value: serde_json::Value = serde_json::from_str(last_line).ok()?;
138 if value.get("type").and_then(|v| v.as_str()) != Some("result")
139 || value.get("is_error").and_then(|v| v.as_bool()) != Some(true)
140 || value.get("subtype").and_then(|v| v.as_str()) != Some("error_during_execution")
141 {
142 return None;
143 }
144 let message = value.get("error")?.get("message")?.as_str()?.to_string();
145 let source = classify_last_error_source(message.strip_prefix("[AgentMux] ").unwrap_or(&message));
146
147 Some(LastErrorFrame {
148 message,
149 source,
150 written_ms: tail.modts.max(0) as u64,
151 })
152}
153
154pub async fn handle_muxspect_list(State(state): State<AppState>) -> impl IntoResponse {
164 let blocks: Vec<serde_json::Value> = state
165 .process_broker
166 .list()
167 .into_iter()
168 .map(|status| {
169 let is_agent = status.is_agent();
170 let last_error = last_error_frame(&crate::backend::transcript::source::TranscriptSource::resolve(&state.filestore, &state.mstore, &status.block_id));
171 let mut value = serde_json::to_value(&status).unwrap_or_default();
172 if let Some(obj) = value.as_object_mut() {
173 obj.insert("is_agent".to_string(), json!(is_agent));
174 obj.insert("last_error".to_string(), json!(last_error));
175 }
176 value
177 })
178 .collect();
179 Json(json!({ "blocks": blocks })).into_response()
180}
181
182#[derive(serde::Deserialize)]
183pub struct MuxspectDescribeQuery {
184 pub block_id: String,
185}
186
187pub async fn handle_muxspect_describe(
195 State(state): State<AppState>,
196 Query(q): Query<MuxspectDescribeQuery>,
197) -> impl IntoResponse {
198 if q.block_id.is_empty() {
199 return (
200 StatusCode::BAD_REQUEST,
201 Json(json!({ "error": "missing block_id" })),
202 )
203 .into_response();
204 }
205
206 let process_status = state.process_broker.status(&q.block_id);
216 let is_agent = process_status.is_agent();
217 let last_error = last_error_frame(&crate::backend::transcript::source::TranscriptSource::resolve(&state.filestore, &state.mstore, &q.block_id));
224
225 Json(json!({
226 "block_id": q.block_id,
227 "process_status": &process_status,
228 "is_agent": is_agent,
229 "controller_status": &process_status.controller_status,
230 "processes": &process_status.processes,
231 "tracking_confidence": process_status.liveness_confidence,
232 "last_error": last_error,
233 }))
234 .into_response()
235}
236
237#[derive(serde::Deserialize)]
238pub struct MuxspectFindQuery {
239 pub block_id: Option<String>,
240 pub agent: Option<String>,
241}
242
243fn describe_lifecycle_is_unknown(describe: Option<&serde_json::Value>) -> bool {
297 describe
298 .and_then(|d| d.get("process_status"))
299 .and_then(|ps| ps.get("lifecycle"))
300 .and_then(|l| l.as_str())
301 == Some("unknown")
302}
303
304pub async fn handle_muxspect_find(
305 State(state): State<AppState>,
306 Query(q): Query<MuxspectFindQuery>,
307) -> impl IntoResponse {
308 if q.block_id.as_deref().unwrap_or("").is_empty() && q.agent.as_deref().unwrap_or("").is_empty() {
309 return (
310 StatusCode::BAD_REQUEST,
311 Json(json!({ "error": "provide block_id or agent" })),
312 )
313 .into_response();
314 }
315
316 let mut results: Vec<serde_json::Value> = Vec::new();
317 let own_channel = std::env::var("AGENTMUX_CHANNEL").unwrap_or_else(|_| "stable".to_string());
318
319 let agents = state.reactive_handler.list_agents();
327 for status in state.process_broker.list() {
328 let block_matches = q.block_id.as_deref().is_some_and(|b| b == status.block_id);
329 let agent_matches = q.agent.as_deref().is_some_and(|name| {
330 agents
331 .iter()
332 .any(|r| r.block_id == status.block_id && r.agent_id.eq_ignore_ascii_case(name))
333 });
334 if !block_matches && !agent_matches {
335 continue;
336 }
337 results.push(json!({
338 "tier": "host",
339 "channel": own_channel,
340 "block_id": status.block_id,
341 "found": true,
342 "process_status": &status,
343 }));
344 }
345
346 if let Some(shared_dir) = crate::registry::resolve_shared_reactive_dir() {
366 let local_url = state.local_web_url.clone();
367 let matches: Vec<_> = crate::backend::reactive::registry::list_all_shared(&shared_dir)
368 .into_iter()
369 .filter(|e| e.channel != own_channel && e.local_url != local_url)
370 .filter(|e| {
371 q.block_id.as_deref().is_some_and(|b| b == e.block_id)
372 || q.agent.as_deref().is_some_and(|name| e.agent_id.eq_ignore_ascii_case(name))
373 })
374 .filter(|e| !crate::backend::reactive::registry::should_evict_on_forward_failure(e))
375 .collect();
376
377 let mut join_set = tokio::task::JoinSet::new();
378 for entry in matches {
379 let http_client = state.http_client.clone();
380 join_set.spawn(async move {
381 let fetch = http_client
382 .get(format!("{}/api/v1/muxspect/describe", entry.local_url))
383 .header(agentmux_common::AUTH_KEY_HEADER, &entry.auth_key)
384 .query(&[("block_id", entry.block_id.as_str())])
385 .send();
386
387 let describe = match tokio::time::timeout(
388 std::time::Duration::from_millis(CROSS_CHANNEL_PREVIEW_TIMEOUT_MS),
389 fetch,
390 )
391 .await
392 {
393 Ok(Ok(resp)) if resp.status().is_success() => resp.json::<serde_json::Value>().await.ok(),
394 _ => None, };
396
397 let lifecycle_unknown = describe_lifecycle_is_unknown(describe.as_ref());
398
399 json!({
400 "tier": "cross-channel",
401 "channel": entry.channel,
402 "block_id": entry.block_id,
403 "agent_id": entry.agent_id,
404 "found": !lifecycle_unknown,
405 "describe": describe,
406 })
407 });
408 }
409 while let Some(res) = join_set.join_next().await {
410 if let Ok(value) = res {
411 results.push(value);
412 }
413 }
414 }
415
416 Json(json!({
417 "query": { "block_id": q.block_id, "agent": q.agent },
418 "results": results,
419 }))
420 .into_response()
421}
422
423const DOCK_STUCK_THRESHOLD_MS: i64 = 30_000;
430
431#[derive(serde::Deserialize)]
432pub struct MuxspectDockQuery {
433 pub block_id: String,
434}
435
436#[derive(serde::Serialize)]
437pub struct DockNodeView {
438 pub node_id: String,
439 pub tool_name: String,
440 pub status: String,
441 pub age_ms: i64,
442 pub stuck: bool,
463 #[serde(skip_serializing_if = "Option::is_none")]
468 pub run_in_background: Option<bool>,
469}
470
471pub async fn handle_muxspect_dock(
476 State(state): State<AppState>,
477 Query(q): Query<MuxspectDockQuery>,
478) -> impl IntoResponse {
479 if q.block_id.is_empty() {
480 return (
481 StatusCode::BAD_REQUEST,
482 Json(json!({ "error": "missing block_id" })),
483 )
484 .into_response();
485 }
486
487 let now_ms = agentmux_common::time::now_ms();
488
489 let lifecycle = state.process_broker.status(&q.block_id).lifecycle;
493 let backed = lifecycle == crate::broker::process::Lifecycle::Running;
494
495 let nodes = dock_node_views(state.dock_snapshots.get(&q.block_id, now_ms), now_ms, backed);
496
497 let background_tasks = state.mstore.background_task_list_for_block(&q.block_id).unwrap_or_default();
508 let nodes = merge_background_tasks(nodes, background_tasks, now_ms);
509
510 Json(json!({ "block_id": q.block_id, "nodes": nodes })).into_response()
511}
512
513fn merge_background_tasks(
521 mut nodes: Vec<DockNodeView>,
522 background_tasks: Vec<crate::backend::storage::background_tasks::BackgroundTask>,
523 now_ms: i64,
524) -> Vec<DockNodeView> {
525 use std::collections::HashSet;
526 let existing: HashSet<String> = nodes.iter().map(|n| n.node_id.clone()).collect();
527 for task in background_tasks {
528 if task.status != crate::backend::storage::background_tasks::BackgroundTaskStatus::Running {
529 continue;
530 }
531 if existing.contains(&task.id) {
532 continue;
533 }
534 nodes.push(DockNodeView {
535 node_id: task.id,
536 tool_name: task.label,
537 status: "running".to_string(),
538 age_ms: (now_ms - task.started_at_ms).max(0),
539 stuck: false,
545 run_in_background: Some(true),
546 });
547 }
548 nodes
549}
550
551fn dock_node_views(
556 nodes: Vec<crate::backend::dock_snapshot::DockNodeSnapshot>,
557 now_ms: i64,
558 backed: bool,
559) -> Vec<DockNodeView> {
560 nodes
561 .into_iter()
562 .map(|n| {
563 let age_ms = (now_ms - n.observed_at).max(0);
564 let stuck = n.status == "running" && age_ms >= DOCK_STUCK_THRESHOLD_MS && !backed;
565 DockNodeView {
566 node_id: n.node_id,
567 tool_name: n.tool_name,
568 status: n.status,
569 age_ms,
570 stuck,
571 run_in_background: n.run_in_background,
572 }
573 })
574 .collect()
575}
576
577#[derive(serde::Deserialize, Default)]
578pub struct MuxspectBackgroundTasksQuery {
579 #[serde(default)]
584 pub block_id: Option<String>,
585}
586
587#[derive(serde::Serialize, ts_rs::TS)]
588#[ts(export, export_to = "../../../frontend/types/rpc/")]
589pub struct BackgroundTaskView {
590 pub id: String,
591 pub block_id: String,
592 pub label: String,
593 #[ts(type = "number | null")]
595 pub pid: Option<i64>,
596 #[ts(type = "number")]
597 pub started_at_ms: i64,
598 #[ts(type = "\"running\" | \"done\" | \"error\" | \"stopped\"")]
602 pub status: &'static str,
603 #[ts(type = "number")]
604 pub last_seen_ms: i64,
605 #[ts(type = "number | null")]
606 pub ended_at_ms: Option<i64>,
607 #[ts(type = "string | null")]
611 pub owner_tool_use_id: Option<String>,
612}
613
614impl From<crate::backend::storage::background_tasks::BackgroundTask> for BackgroundTaskView {
615 fn from(t: crate::backend::storage::background_tasks::BackgroundTask) -> Self {
616 BackgroundTaskView {
617 id: t.id,
618 block_id: t.block_id,
619 label: t.label,
620 pid: t.pid,
621 started_at_ms: t.started_at_ms,
622 status: t.status.as_str(),
623 last_seen_ms: t.last_seen_ms,
624 ended_at_ms: t.ended_at_ms,
625 owner_tool_use_id: t.owner_tool_use_id,
626 }
627 }
628}
629
630pub async fn handle_muxspect_migrations() -> impl IntoResponse {
648 let data_dir = crate::backend::base::get_mux_data_dir();
649 let report = tokio::task::spawn_blocking(move || crate::migrations::doctor_report_for_instance(&data_dir))
650 .await
651 .map_err(|e| format!("doctor task panicked: {e}"))
652 .and_then(|r| r);
653 match report {
654 Ok(report) => Json(report).into_response(),
655 Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": e }))).into_response(),
656 }
657}
658
659pub async fn handle_muxspect_background_tasks(
667 State(state): State<AppState>,
668 Query(q): Query<MuxspectBackgroundTasksQuery>,
669) -> impl IntoResponse {
670 let result = match q.block_id.as_deref() {
671 Some(block_id) if !block_id.is_empty() => state.mstore.background_task_list_for_block(block_id),
672 _ => state.mstore.background_task_list_running(),
673 };
674 match result {
675 Ok(tasks) => {
676 let views: Vec<BackgroundTaskView> = tasks.into_iter().map(Into::into).collect();
677 Json(json!({ "tasks": views })).into_response()
678 }
679 Err(e) => (
680 StatusCode::INTERNAL_SERVER_ERROR,
681 Json(json!({ "error": e.to_string() })),
682 )
683 .into_response(),
684 }
685}
686
687#[derive(serde::Deserialize)]
688pub struct MuxspectDockClearRequest {
689 pub block_id: String,
690 pub node_id: String,
691}
692
693pub async fn handle_muxspect_dock_clear(
704 State(state): State<AppState>,
705 Json(req): Json<MuxspectDockClearRequest>,
706) -> impl IntoResponse {
707 if req.block_id.is_empty() || req.node_id.is_empty() {
708 return (
709 StatusCode::BAD_REQUEST,
710 Json(json!({ "error": "missing block_id or node_id" })),
711 )
712 .into_response();
713 }
714
715 if !state.dock_snapshots.has_node(&req.block_id, &req.node_id) {
716 return (
717 StatusCode::NOT_FOUND,
718 Json(json!({ "error": "no such node in this block's dock snapshot", "cleared": false })),
719 )
720 .into_response();
721 }
722
723 state.broker.publish_event::<crate::backend::mps_events::DockClear>(&crate::backend::mps_events::DockClearEvent { node_id: req.node_id.clone() }, vec![format!("block:{}", req.block_id)], 0);
724 state.dock_snapshots.remove_node(&req.block_id, &req.node_id);
725
726 Json(json!({ "cleared": true, "block_id": req.block_id, "node_id": req.node_id })).into_response()
727}
728
729#[derive(serde::Deserialize)]
730pub struct MuxspectVerifySenderQuery {
731 pub name: String,
732}
733
734#[derive(serde::Serialize, Debug, PartialEq, Eq)]
750pub struct VerifySenderVerdict {
751 pub name: String,
752 pub status: &'static str,
754 #[serde(skip_serializing_if = "Option::is_none")]
755 pub tier: Option<&'static str>,
756 #[serde(skip_serializing_if = "Option::is_none")]
757 pub last_seen_ms: Option<i64>,
758 #[serde(skip_serializing_if = "Option::is_none")]
759 pub channel: Option<String>,
760 #[serde(skip_serializing_if = "Option::is_none")]
761 pub local_url: Option<String>,
762}
763
764struct SenderCandidate {
770 name: String,
771 tier: &'static str,
777 last_seen_ms: Option<i64>,
778 stale_eligible: bool,
794 channel: Option<String>,
795 local_url: Option<String>,
796}
797
798fn classify_sender(name: &str, candidates: &[SenderCandidate], now_ms: i64) -> VerifySenderVerdict {
812 let needle = name.to_lowercase();
813 let is_stale = |c: &&SenderCandidate| {
814 c.stale_eligible
815 && c.last_seen_ms
816 .is_some_and(|ls| now_ms - ls >= crate::backend::reactive::registry::FORWARD_FAILURE_GRACE_MS as i64)
817 };
818 let matches: Vec<&SenderCandidate> = candidates.iter().filter(|c| c.name.to_lowercase() == needle).collect();
819 let chosen = matches.iter().find(|c| !is_stale(c)).or_else(|| matches.first());
820
821 match chosen {
822 None => VerifySenderVerdict {
823 name: name.to_string(),
824 status: "not_found",
825 tier: None,
826 last_seen_ms: None,
827 channel: None,
828 local_url: None,
829 },
830 Some(c) => VerifySenderVerdict {
831 name: name.to_string(),
832 status: if is_stale(c) { "stale" } else { "found" },
833 tier: Some(c.tier),
834 last_seen_ms: c.last_seen_ms,
835 channel: c.channel.clone(),
836 local_url: c.local_url.clone(),
837 },
838 }
839}
840
841pub async fn handle_muxspect_verify_sender(
863 State(state): State<AppState>,
864 Query(q): Query<MuxspectVerifySenderQuery>,
865) -> impl IntoResponse {
866 if q.name.is_empty() {
867 return (StatusCode::BAD_REQUEST, Json(json!({ "error": "missing name" }))).into_response();
868 }
869
870 let mut candidates: Vec<SenderCandidate> = Vec::new();
871
872 candidates.extend(state.reactive_handler.list_agents().into_iter().map(|a| SenderCandidate {
873 name: a.agent_id,
874 tier: "host",
875 last_seen_ms: Some(a.last_seen as i64),
876 stale_eligible: false,
877 channel: None,
878 local_url: None,
879 }));
880
881 let own_channel = std::env::var("AGENTMUX_CHANNEL").unwrap_or_else(|_| "stable".to_string());
887 let local_url = state.local_web_url.clone();
888 if let Some(shared_dir) = crate::registry::resolve_shared_reactive_dir() {
889 candidates.extend(
890 crate::backend::reactive::registry::list_all_shared(&shared_dir)
891 .into_iter()
892 .filter(|e| e.channel != own_channel && e.local_url != local_url)
893 .map(|e| SenderCandidate {
894 name: e.agent_id,
895 tier: "cross-channel",
896 last_seen_ms: Some(e.updated_at as i64),
897 stale_eligible: true,
898 channel: Some(e.channel),
899 local_url: Some(e.local_url),
900 }),
901 );
902 }
903
904 for lan_instance in state.lan_discovery.get_instances() {
905 let peer_url = format!("{}:{}", lan_instance.address, lan_instance.port);
906 candidates.extend(lan_instance.agents.iter().map(|agent_name| SenderCandidate {
912 name: agent_name.clone(),
913 tier: "lan",
914 last_seen_ms: Some((lan_instance.last_seen as i64).saturating_mul(1000)),
915 stale_eligible: true,
916 channel: None,
917 local_url: Some(peer_url.clone()),
918 }));
919 }
920
921 if let Some(subscriber) = crate::muxbus::cloud_subscriber::get_global_subscriber() {
922 candidates.extend(subscriber.subscribed_agents().into_iter().map(|agent_name| SenderCandidate {
923 name: agent_name,
924 tier: "wan",
925 last_seen_ms: None,
926 stale_eligible: false,
927 channel: None,
928 local_url: None,
929 }));
930 }
931
932 let now_ms = agentmux_common::time::now_ms();
933
934 Json(classify_sender(&q.name, &candidates, now_ms)).into_response()
935}
936
937const PREVIEW_MAX_CHARS: usize = 200;
946
947const PREVIEW_TAIL_BYTES: i64 = 4096;
953
954const CROSS_CHANNEL_PREVIEW_TIMEOUT_MS: u64 = 1500;
959
960fn truncate_preview(line: &str) -> String {
965 if line.chars().count() > PREVIEW_MAX_CHARS {
966 line.chars().take(PREVIEW_MAX_CHARS).collect::<String>() + "…"
967 } else {
968 line.to_string()
969 }
970}
971
972fn last_line_preview_and_activity(
995 mstore: &std::sync::Arc<crate::backend::storage::store::Store>,
996 filestore: &std::sync::Arc<FileStore>,
997 block_id: &str,
998) -> (Option<String>, Option<u64>) {
999 if let Some(tail) = crate::backend::transcript::source::TranscriptSource::resolve(filestore, mstore, block_id).tail(PREVIEW_TAIL_BYTES) {
1000 let text = String::from_utf8_lossy(&tail.bytes);
1001 if let Some(last) = text.lines().rev().find(|l| !l.trim().is_empty()) {
1002 return (Some(truncate_preview(last)), Some(tail.modts.max(0) as u64));
1003 }
1004 }
1005
1006 match crate::backend::session_archive::read_session_output(mstore, filestore, block_id) {
1007 Ok((raw_bytes, _)) => {
1008 let text = String::from_utf8_lossy(&raw_bytes);
1009 let preview = text
1010 .lines()
1011 .rev()
1012 .find(|l| !l.trim().is_empty())
1013 .map(truncate_preview);
1014 (preview, None)
1015 }
1016 Err(_) => (None, None),
1017 }
1018}
1019
1020pub async fn handle_muxspect_conversations(State(state): State<AppState>) -> impl IntoResponse {
1040 let mut agents: Vec<serde_json::Value> = Vec::new();
1041 let work_facts = super::work_facts_handlers::start_conversation_facts(&state); for reg in state.reactive_handler.list_agents() {
1045 let (m, f, b) = (state.mstore.clone(), state.filestore.clone(), reg.block_id.clone());
1046 let (preview, activity_ms) = super::transcript_tail::off_worker(move || last_line_preview_and_activity(&m, &f, &b)).await;
1047 let turn_active = crate::backend::blockcontroller::get_block_controller_status(®.block_id).map(|s| s.turn_active).unwrap_or(false);
1048 let (agent_state, unavailable) = crate::backend::agent_state::state_and_unavailable(&state.mstore, ®.block_id);
1049 agents.push(json!({
1050 "name": reg.agent_id,
1051 "tier": "host",
1052 "block_id": reg.block_id,
1053 "turn_active": turn_active,
1054 "state": agent_state, "unavailable": unavailable, "last_activity_ms": activity_ms.unwrap_or(reg.last_seen),
1057 "last_message_preview": preview,
1058 }));
1059 }
1060
1061 let own_channel = std::env::var("AGENTMUX_CHANNEL").unwrap_or_else(|_| "stable".to_string());
1070 let local_url = state.local_web_url.clone();
1071 if let Some(shared_dir) = crate::registry::resolve_shared_reactive_dir() {
1072 let cross_channel_entries: Vec<_> =
1073 crate::backend::reactive::registry::list_all_shared(&shared_dir)
1074 .into_iter()
1075 .filter(|e| e.channel != own_channel && e.local_url != local_url)
1076 .collect();
1077
1078 let mut join_set = tokio::task::JoinSet::new();
1079 for entry in cross_channel_entries {
1080 let http_client = state.http_client.clone();
1081 join_set.spawn(async move {
1082 let mut preview: Option<String> = None;
1083 let mut turn_active: Option<bool> = None;
1084
1085 let fetch = http_client
1086 .get(format!("{}/agentmux/reactive/transcript", entry.local_url))
1087 .header(agentmux_common::AUTH_KEY_HEADER, &entry.auth_key)
1088 .query(&[
1089 ("agent", entry.agent_id.as_str()),
1090 ("max_lines", "1"),
1091 ("forwarded", "true"),
1092 ])
1093 .send();
1094
1095 if let Ok(Ok(resp)) = tokio::time::timeout(
1096 std::time::Duration::from_millis(CROSS_CHANNEL_PREVIEW_TIMEOUT_MS),
1097 fetch,
1098 )
1099 .await
1100 {
1101 if resp.status().is_success() {
1102 if let Ok(body) = resp.json::<serde_json::Value>().await {
1103 turn_active = body.get("turn_active").and_then(|v| v.as_bool());
1104 preview = body
1105 .get("lines")
1106 .and_then(|v| v.as_array())
1107 .and_then(|arr| arr.last())
1108 .and_then(|v| v.as_str())
1109 .map(truncate_preview);
1110 }
1111 }
1112 }
1113 json!({
1118 "name": entry.agent_id,
1119 "tier": "cross-channel",
1120 "channel": entry.channel,
1121 "block_id": entry.block_id,
1122 "turn_active": turn_active,
1123 "last_activity_ms": entry.updated_at,
1124 "last_message_preview": preview,
1125 })
1126 });
1127 }
1128 while let Some(res) = join_set.join_next().await {
1129 if let Ok(value) = res {
1132 agents.push(value);
1133 }
1134 }
1135 }
1136
1137 for lan_instance in state.lan_discovery.get_instances() {
1139 for agent_name in &lan_instance.agents {
1140 agents.push(json!({
1141 "name": agent_name,
1142 "tier": "lan",
1143 "host": format!("{}:{}", lan_instance.address, lan_instance.port),
1144 "remote_fetch_required": true,
1145 }));
1146 }
1147 }
1148
1149 if let Some(subscriber) = crate::muxbus::cloud_subscriber::get_global_subscriber() {
1151 for agent_name in subscriber.subscribed_agents() {
1152 agents.push(json!({
1153 "name": agent_name,
1154 "tier": "wan",
1155 "remote_fetch_required": true,
1156 }));
1157 }
1158 }
1159
1160 super::work_facts_handlers::annotate_conversations(work_facts, &mut agents).await; Json(json!({ "agents": agents })).into_response()
1162}
1163
1164fn flatten_layout_nodes(
1170 node: &agentmux_common::LayoutNode,
1171 depth: usize,
1172 index_path: &str,
1173 out: &mut Vec<serde_json::Value>,
1174) {
1175 let is_branch = !node.children.is_empty();
1176 out.push(json!({
1177 "id": node.id,
1178 "depth": depth,
1179 "path": index_path,
1180 "kind": if is_branch { "branch" } else { "leaf" },
1181 "flex_direction": match node.flex_direction {
1182 agentmux_common::FlexDirection::Row => "row",
1183 agentmux_common::FlexDirection::Column => "column",
1184 },
1185 "size": node.size,
1186 "locked": crate::backend::layout::is_node_locked(node),
1193 "effectively_minimized": crate::backend::layout::is_effectively_minimized(node),
1197 "block_id": node.data.as_ref().map(|d| d.block_id.clone()),
1198 "child_count": node.children.len(),
1199 }));
1200 for (i, child) in node.children.iter().enumerate() {
1201 let child_path = if index_path.is_empty() {
1202 i.to_string()
1203 } else {
1204 format!("{index_path}.{i}")
1205 };
1206 flatten_layout_nodes(child, depth + 1, &child_path, out);
1207 }
1208}
1209
1210pub async fn handle_muxspect_layout(
1227 State(state): State<AppState>,
1228 Query(q): Query<MuxspectLayoutQuery>,
1229) -> impl IntoResponse {
1230 let tabs = match state.mstore.get_all::<crate::backend::obj::Tab>() {
1231 Ok(t) => t,
1232 Err(e) => {
1233 return Json(json!({ "error": format!("failed to list tabs: {e}") })).into_response();
1238 }
1239 };
1240
1241 let mut layouts = Vec::new();
1242 for tab in tabs {
1243 if let Some(want) = q.tab_id.as_deref() {
1244 if tab.oid != want {
1245 continue;
1246 }
1247 }
1248 let ls = match state
1249 .mstore
1250 .must_get::<crate::backend::obj::LayoutState>(&tab.layoutstate)
1251 {
1252 Ok(ls) => ls,
1253 Err(e) => {
1254 layouts.push(json!({
1257 "tab_id": tab.oid,
1258 "tab_name": tab.name,
1259 "layoutstate_oid": tab.layoutstate,
1260 "error": format!("layoutstate unreadable: {e}"),
1261 }));
1262 continue;
1263 }
1264 };
1265
1266 let violations = crate::backend::layout::validate_layout_invariants(&ls.rootnode);
1267 let mut nodes = Vec::new();
1268 if let Some(root) = ls.rootnode.as_ref() {
1269 flatten_layout_nodes(root, 0, "", &mut nodes);
1270 }
1271 let leaf_count = nodes.iter().filter(|n| n["kind"] == "leaf").count();
1272 let minimized_leaves = nodes
1273 .iter()
1274 .filter(|n| n["kind"] == "leaf" && n["locked"] == true)
1275 .count();
1276
1277 layouts.push(json!({
1278 "tab_id": tab.oid,
1279 "tab_name": tab.name,
1280 "layoutstate_oid": ls.oid,
1281 "magnified_node_id": ls.magnifiednodeid,
1282 "node_count": nodes.len(),
1283 "leaf_count": leaf_count,
1284 "minimized_leaf_count": minimized_leaves,
1285 "violations": violations,
1286 "healthy": violations.is_empty(),
1287 "nodes": nodes,
1288 }));
1289 }
1290
1291 if let Some(want) = q.tab_id.as_deref() {
1300 if layouts.is_empty() {
1301 return Json(json!({ "error": format!("no tab with id '{want}' in this instance") }))
1302 .into_response();
1303 }
1304 }
1305
1306 Json(json!({ "layouts": layouts })).into_response()
1307}
1308
1309#[derive(serde::Deserialize)]
1310pub struct MuxspectLayoutQuery {
1311 pub tab_id: Option<String>,
1313}
1314
1315#[cfg(test)]
1316mod tests {
1317 use super::*;
1318 use crate::backend::storage::filestore::{FileMeta, FileOpts};
1319
1320 fn error_frame_line(message: &str) -> String {
1321 json!({
1322 "type": "result",
1323 "is_error": true,
1324 "subtype": "error_during_execution",
1325 "error": {"message": message}
1326 })
1327 .to_string()
1328 }
1329
1330 #[test]
1334 fn describe_lifecycle_is_unknown_true_for_lifecycle_unknown() {
1335 let describe = json!({ "process_status": { "lifecycle": "unknown" } });
1336 assert!(describe_lifecycle_is_unknown(Some(&describe)));
1337 }
1338
1339 #[test]
1340 fn describe_lifecycle_is_unknown_false_for_a_real_lifecycle() {
1341 for lifecycle in ["running", "idle", "done", "error"] {
1342 let describe = json!({ "process_status": { "lifecycle": lifecycle } });
1343 assert!(!describe_lifecycle_is_unknown(Some(&describe)), "lifecycle={lifecycle}");
1344 }
1345 }
1346
1347 #[test]
1348 fn describe_lifecycle_is_unknown_false_when_the_forward_itself_failed() {
1349 assert!(!describe_lifecycle_is_unknown(None));
1352 }
1353
1354 #[test]
1355 fn describe_lifecycle_is_unknown_false_for_malformed_or_missing_fields() {
1356 assert!(!describe_lifecycle_is_unknown(Some(&json!({}))));
1357 assert!(!describe_lifecycle_is_unknown(Some(&json!({ "process_status": {} }))));
1358 assert!(!describe_lifecycle_is_unknown(Some(&json!({ "process_status": { "lifecycle": 123 } }))));
1359 }
1360
1361 #[test]
1362 fn classify_last_error_source_matches_every_known_construction_site() {
1363 assert_eq!(
1368 classify_last_error_source("no credentials for claude: the bound account was deleted or is unresolvable. Bind an account for this provider in Connectors → Accounts."),
1369 "identity"
1370 );
1371 assert_eq!(
1372 classify_last_error_source("credential injection could not run (task join failed); the spawn was refused rather than falling back to the global CLI login. Retry, and check `muxlog auth` if it persists."),
1373 "identity"
1374 );
1375 assert_eq!(
1377 classify_last_error_source("this agent's claude identity points directly at your personal claude config directory (C:\\Users\\user\\.claude) instead of an isolated AgentMux account — AgentMux no longer allows spawning an agent against your own global CLI login. Re-bind this identity to an isolated account in Connectors \u{2192} Accounts (delete the current claude account and log in again to create a fresh, isolated one), then retry."),
1378 "identity"
1379 );
1380 assert_eq!(
1382 classify_last_error_source("could not isolate this agent's claude config directory (C:\\Users\\user\\.agentmux\\shared\\identities\\id-1\\claude): permission denied. Refusing to spawn with an unprotected config dir — retry, and check the directory's permissions if it persists."),
1383 "identity"
1384 );
1385 assert_eq!(
1386 classify_last_error_source("container exec failed: no such container"),
1387 "container_spawn"
1388 );
1389 assert_eq!(
1390 classify_last_error_source("container ensure_running failed: image not found"),
1391 "container_spawn"
1392 );
1393 assert_eq!(
1394 classify_last_error_source("Couldn't start the container for this agent: the registry refused access to x."),
1395 "container_spawn"
1396 );
1397 assert_eq!(
1398 classify_last_error_source("queued message could not be sent: lease held by another process"),
1399 "host_spawn"
1400 );
1401 assert_eq!(classify_last_error_source("something nobody wrote yet"), "unknown");
1402 assert_eq!(
1406 classify_last_error_source(
1407 &crate::identity::resolver::SpawnGateError::AgentDeleted {
1408 agent_id: "uid-x".to_string()
1409 }
1410 .to_string()
1411 ),
1412 "identity"
1413 );
1414 }
1415
1416 #[test]
1417 fn last_error_frame_none_for_missing_block() {
1418 let filestore = FileStore::open_in_memory().unwrap();
1419 assert!(last_error_frame(&crate::backend::transcript::source::TranscriptSource::own(&filestore, "no-such-block")).is_none());
1420 }
1421
1422 #[test]
1423 fn last_error_frame_none_for_empty_output() {
1424 let filestore = FileStore::open_in_memory().unwrap();
1425 filestore
1426 .make_file("block-1", "output", FileMeta::new(), FileOpts::default())
1427 .unwrap();
1428 assert!(last_error_frame(&crate::backend::transcript::source::TranscriptSource::own(&filestore, "block-1")).is_none());
1429 }
1430
1431 #[test]
1432 fn last_error_frame_found_when_last_line_is_the_frame() {
1433 let filestore = FileStore::open_in_memory().unwrap();
1434 filestore
1435 .make_file("block-1", "output", FileMeta::new(), FileOpts::default())
1436 .unwrap();
1437 let mut content = String::new();
1438 content.push_str("{\"type\":\"assistant\",\"text\":\"normal turn output\"}\n");
1439 content.push_str(&error_frame_line(
1440 "[AgentMux] no credentials for claude: bind an account in Connectors → Accounts.",
1441 ));
1442 content.push('\n');
1443 filestore.write_file("block-1", "output", content.as_bytes()).unwrap();
1444
1445 let found = last_error_frame(&crate::backend::transcript::source::TranscriptSource::own(&filestore, "block-1")).expect("last line is an error frame");
1446 assert_eq!(
1447 found.message,
1448 "[AgentMux] no credentials for claude: bind an account in Connectors → Accounts."
1449 );
1450 assert_eq!(found.source, "identity");
1451 assert!(found.written_ms > 0);
1452 }
1453
1454 #[test]
1456 fn last_error_frame_is_read_from_the_agents_zone() {
1457 use crate::backend::transcript::source::TranscriptSource;
1458 let (own, global, zone) = (FileStore::open_in_memory().unwrap(), FileStore::open_in_memory().unwrap(), "agent:error-frame-global:current");
1459 global.make_file(zone, "output", FileMeta::new(), FileOpts::default()).unwrap();
1460 global.append_lines(zone, "output", format!("{}\n", error_frame_line("[AgentMux] no credentials for claude: bind an account in Connectors → Accounts.")).as_bytes()).unwrap();
1461 let found = last_error_frame(&TranscriptSource { fs: &global, zone: zone.to_string(), global: true, own: None }).expect("the frame in the agent zone");
1462 assert_eq!(found.source, "identity");
1463 assert!(last_error_frame(&TranscriptSource::own(&own, "blk")).is_none());
1464 }
1465
1466 #[test]
1472 fn last_error_frame_none_when_normal_output_follows_an_earlier_error() {
1473 let filestore = FileStore::open_in_memory().unwrap();
1474 filestore
1475 .make_file("block-1", "output", FileMeta::new(), FileOpts::default())
1476 .unwrap();
1477 let mut content = String::new();
1478 content.push_str(&error_frame_line("[AgentMux] container exec failed: transient"));
1479 content.push('\n');
1480 content.push_str("{\"type\":\"assistant\",\"text\":\"turn resumed fine after the retry\"}\n");
1481 filestore.write_file("block-1", "output", content.as_bytes()).unwrap();
1482
1483 assert!(last_error_frame(&crate::backend::transcript::source::TranscriptSource::own(&filestore, "block-1")).is_none());
1484 }
1485
1486 #[test]
1487 fn last_error_frame_ignores_a_result_frame_that_is_not_an_error() {
1488 let filestore = FileStore::open_in_memory().unwrap();
1489 filestore
1490 .make_file("block-1", "output", FileMeta::new(), FileOpts::default())
1491 .unwrap();
1492 let normal_result = json!({"type": "result", "is_error": false, "subtype": "success"}).to_string();
1493 filestore
1494 .write_file("block-1", "output", format!("{normal_result}\n").as_bytes())
1495 .unwrap();
1496
1497 assert!(last_error_frame(&crate::backend::transcript::source::TranscriptSource::own(&filestore, "block-1")).is_none());
1498 }
1499
1500 fn dock_node(id: &str, status: &str, observed_at: i64) -> crate::backend::dock_snapshot::DockNodeSnapshot {
1501 crate::backend::dock_snapshot::DockNodeSnapshot {
1502 node_id: id.to_string(),
1503 tool_name: "Bash".to_string(),
1504 status: status.to_string(),
1505 timestamp: Some(observed_at),
1506 observed_at,
1507 run_in_background: None,
1508 }
1509 }
1510
1511 #[test]
1512 fn dock_node_views_flags_stuck_running_node_past_threshold_when_unbacked() {
1513 let now_ms = 100_000;
1514 let views = dock_node_views(vec![dock_node("n1", "running", 50_000)], now_ms, false);
1515 assert_eq!(views.len(), 1);
1516 assert_eq!(views[0].age_ms, 50_000);
1517 assert!(views[0].stuck, "running, 50s old, unbacked — must be flagged stuck");
1518 }
1519
1520 #[test]
1521 fn dock_node_views_does_not_flag_running_node_within_threshold() {
1522 let now_ms = 100_000;
1523 let views = dock_node_views(vec![dock_node("n1", "running", 90_000)], now_ms, false);
1525 assert!(!views[0].stuck, "a tool merely taking a while must not be flagged instantly");
1526 }
1527
1528 #[test]
1529 fn dock_node_views_does_not_flag_running_node_when_backed_by_a_live_process() {
1530 let now_ms = 100_000;
1531 let views = dock_node_views(vec![dock_node("n1", "running", 50_000)], now_ms, true);
1534 assert!(!views[0].stuck, "backed by a live process — not stuck, just slow");
1535 }
1536
1537 #[test]
1538 fn dock_node_views_does_not_flag_non_running_nodes_regardless_of_age() {
1539 let now_ms = 100_000;
1540 for status in ["success", "failed", "canceled", "denied"] {
1541 let views = dock_node_views(vec![dock_node("n1", status, 0)], now_ms, false);
1542 assert!(!views[0].stuck, "status={status} already resolved, must never be flagged stuck");
1543 }
1544 }
1545
1546 #[test]
1547 fn dock_node_views_preserves_every_input_node() {
1548 let now_ms = 100_000;
1549 let views = dock_node_views(
1550 vec![dock_node("n1", "running", 99_000), dock_node("n2", "success", 80_000)],
1551 now_ms,
1552 false,
1553 );
1554 assert_eq!(views.len(), 2);
1555 assert_eq!(views[0].node_id, "n1");
1556 assert_eq!(views[1].node_id, "n2");
1557 }
1558
1559 #[test]
1560 fn dock_node_views_surfaces_run_in_background_even_though_status_is_terminal() {
1561 let now_ms = 100_000;
1568 let mut bg_node = dock_node("n1", "success", 0);
1569 bg_node.run_in_background = Some(true);
1570 let views = dock_node_views(vec![bg_node], now_ms, false);
1571 assert_eq!(views[0].run_in_background, Some(true));
1572 assert!(!views[0].stuck, "status is terminal — the raw heuristic correctly stays quiet");
1573 }
1574
1575 fn bg_task(
1576 id: &str,
1577 status: crate::backend::storage::background_tasks::BackgroundTaskStatus,
1578 started_at_ms: i64,
1579 ) -> crate::backend::storage::background_tasks::BackgroundTask {
1580 crate::backend::storage::background_tasks::BackgroundTask {
1581 id: id.to_string(),
1582 block_id: "block-1".to_string(),
1583 label: "task dev".to_string(),
1584 pid: Some(4242),
1585 started_at_ms,
1586 status,
1587 last_seen_ms: started_at_ms,
1588 ended_at_ms: None,
1589 owner_tool_use_id: None,
1590 }
1591 }
1592
1593 #[test]
1594 fn merge_background_tasks_adds_a_running_task_the_cache_evicted() {
1595 use crate::backend::storage::background_tasks::BackgroundTaskStatus;
1598 let now_ms = 100_000_000;
1599 let merged = merge_background_tasks(vec![], vec![bg_task("bg-1", BackgroundTaskStatus::Running, 1_000)], now_ms);
1600 assert_eq!(merged.len(), 1);
1601 assert_eq!(merged[0].node_id, "bg-1");
1602 assert_eq!(merged[0].status, "running");
1603 assert_eq!(merged[0].age_ms, now_ms - 1_000);
1604 assert_eq!(merged[0].run_in_background, Some(true));
1605 assert!(!merged[0].stuck);
1606 }
1607
1608 #[test]
1609 fn merge_background_tasks_skips_a_task_the_cache_still_has() {
1610 use crate::backend::storage::background_tasks::BackgroundTaskStatus;
1611 let now_ms = 100_000;
1612 let existing = dock_node_views(vec![dock_node("bg-1", "running", 90_000)], now_ms, false);
1613 let merged = merge_background_tasks(existing, vec![bg_task("bg-1", BackgroundTaskStatus::Running, 1_000)], now_ms);
1614 assert_eq!(merged.len(), 1, "must not duplicate a node the live cache already has");
1615 assert_eq!(merged[0].tool_name, "Bash", "the live cache's own entry wins, not a synthesized one");
1616 }
1617
1618 #[test]
1619 fn merge_background_tasks_ignores_non_running_tasks() {
1620 use crate::backend::storage::background_tasks::BackgroundTaskStatus;
1621 let now_ms = 100_000;
1622 for status in [BackgroundTaskStatus::Done, BackgroundTaskStatus::Error, BackgroundTaskStatus::Stopped] {
1623 let merged = merge_background_tasks(vec![], vec![bg_task("bg-1", status, 1_000)], now_ms);
1624 assert!(merged.is_empty(), "status={status:?} is terminal — must not be synthesized as a live dock row");
1625 }
1626 }
1627
1628 #[test]
1629 fn merge_background_tasks_on_no_tasks_is_a_true_no_op() {
1630 let now_ms = 100_000;
1631 let existing = dock_node_views(vec![dock_node("n1", "running", 90_000)], now_ms, false);
1632 let expected_len = existing.len();
1633 let merged = merge_background_tasks(existing, vec![], now_ms);
1634 assert_eq!(merged.len(), expected_len);
1635 assert_eq!(merged[0].node_id, "n1");
1636 }
1637
1638 #[tokio::test]
1639 async fn handle_muxspect_dock_rejects_empty_block_id() {
1640 let state = crate::server::tests::test_state();
1641 let resp = handle_muxspect_dock(
1642 State(state),
1643 Query(MuxspectDockQuery { block_id: String::new() }),
1644 )
1645 .await
1646 .into_response();
1647 assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
1648 }
1649
1650 #[tokio::test]
1651 async fn handle_muxspect_dock_clear_rejects_empty_ids() {
1652 let state = crate::server::tests::test_state();
1653 let resp = handle_muxspect_dock_clear(
1654 State(state),
1655 Json(MuxspectDockClearRequest { block_id: String::new(), node_id: "n1".to_string() }),
1656 )
1657 .await
1658 .into_response();
1659 assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
1660 }
1661
1662 #[tokio::test]
1663 async fn handle_muxspect_dock_clear_404s_on_unknown_node() {
1664 let state = crate::server::tests::test_state();
1665 let resp = handle_muxspect_dock_clear(
1666 State(state),
1667 Json(MuxspectDockClearRequest { block_id: "block-1".to_string(), node_id: "no-such-node".to_string() }),
1668 )
1669 .await
1670 .into_response();
1671 assert_eq!(resp.status(), StatusCode::NOT_FOUND);
1672 }
1673
1674 #[tokio::test]
1675 async fn handle_muxspect_dock_clear_succeeds_and_removes_from_cache() {
1676 let state = crate::server::tests::test_state();
1677 state.dock_snapshots.push_delta("block-1", dock_node("n1", "running", 0));
1678 assert!(state.dock_snapshots.has_node("block-1", "n1"));
1679
1680 let resp = handle_muxspect_dock_clear(
1681 State(state.clone()),
1682 Json(MuxspectDockClearRequest { block_id: "block-1".to_string(), node_id: "n1".to_string() }),
1683 )
1684 .await
1685 .into_response();
1686 assert_eq!(resp.status(), StatusCode::OK);
1687 assert!(
1688 !state.dock_snapshots.has_node("block-1", "n1"),
1689 "a cleared node must not still be reported by a subsequent `dock` read"
1690 );
1691 }
1692
1693 async fn json_body(resp: axum::response::Response) -> serde_json::Value {
1694 let body = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
1695 serde_json::from_slice(&body).unwrap()
1696 }
1697
1698 #[tokio::test]
1699 async fn handle_muxspect_background_tasks_scoped_to_block_includes_terminal_tasks() {
1700 let state = crate::server::tests::test_state();
1701 state.mstore.background_task_observe("t1", "block-1", "task dev", 0, 0).unwrap();
1702 state.mstore.background_task_observe("t2", "block-1", "finished build", 0, 0).unwrap();
1703 state
1704 .mstore
1705 .background_task_complete(
1706 "t2",
1707 crate::backend::storage::background_tasks::BackgroundTaskStatus::Done,
1708 500,
1709 )
1710 .unwrap();
1711 state.mstore.background_task_observe("t3", "block-2", "other pane", 0, 0).unwrap();
1713
1714 let resp = handle_muxspect_background_tasks(
1715 State(state),
1716 Query(MuxspectBackgroundTasksQuery { block_id: Some("block-1".to_string()) }),
1717 )
1718 .await
1719 .into_response();
1720 assert_eq!(resp.status(), StatusCode::OK);
1721 let body = json_body(resp).await;
1722 let ids: Vec<&str> = body["tasks"].as_array().unwrap().iter().map(|t| t["id"].as_str().unwrap()).collect();
1723 assert_eq!(ids, vec!["t1", "t2"], "block-scoped query includes terminal tasks for that block");
1724 }
1725
1726 #[tokio::test]
1727 async fn handle_muxspect_background_tasks_without_block_id_lists_running_globally() {
1728 let state = crate::server::tests::test_state();
1729 state.mstore.background_task_observe("t1", "block-1", "still running", 0, 0).unwrap();
1730 state.mstore.background_task_observe("t2", "block-2", "also running", 0, 0).unwrap();
1731 state.mstore.background_task_observe("t3", "block-1", "finished", 0, 0).unwrap();
1732 state
1733 .mstore
1734 .background_task_complete(
1735 "t3",
1736 crate::backend::storage::background_tasks::BackgroundTaskStatus::Done,
1737 500,
1738 )
1739 .unwrap();
1740
1741 let resp = handle_muxspect_background_tasks(
1742 State(state),
1743 Query(MuxspectBackgroundTasksQuery { block_id: None }),
1744 )
1745 .await
1746 .into_response();
1747 assert_eq!(resp.status(), StatusCode::OK);
1748 let body = json_body(resp).await;
1749 let ids: Vec<&str> = body["tasks"].as_array().unwrap().iter().map(|t| t["id"].as_str().unwrap()).collect();
1750 assert_eq!(ids, vec!["t1", "t2"], "global query is running-only, across every block");
1751 }
1752
1753 fn candidate(name: &str, tier: &'static str, last_seen_ms: Option<i64>, stale_eligible: bool) -> SenderCandidate {
1754 SenderCandidate { name: name.to_string(), tier, last_seen_ms, stale_eligible, channel: None, local_url: None }
1755 }
1756
1757 #[test]
1758 fn classify_sender_not_found_on_empty_candidates() {
1759 let verdict = classify_sender("AgentA", &[], 1_000_000);
1760 assert_eq!(verdict.status, "not_found");
1761 assert_eq!(verdict.tier, None);
1762 }
1763
1764 #[test]
1765 fn classify_sender_found_on_host_tier() {
1766 let candidates = [candidate("AgentA", "host", Some(999_000), false)];
1767 let verdict = classify_sender("AgentA", &candidates, 1_000_000);
1768 assert_eq!(verdict.status, "found");
1769 assert_eq!(verdict.tier, Some("host"));
1770 }
1771
1772 #[test]
1773 fn classify_sender_found_on_cross_channel_tier() {
1774 let candidates = [candidate("AgentA", "cross-channel", Some(999_000), true)];
1775 let verdict = classify_sender("AgentA", &candidates, 1_000_000);
1776 assert_eq!(verdict.status, "found");
1777 assert_eq!(verdict.tier, Some("cross-channel"));
1778 }
1779
1780 #[test]
1781 fn classify_sender_found_on_lan_or_wan_tier() {
1782 let lan = classify_sender("Peer", &[candidate("Peer", "lan", Some(999_000), true)], 1_000_000);
1783 assert_eq!(lan.status, "found");
1784 let wan = classify_sender("Peer", &[candidate("Peer", "wan", None, false)], 1_000_000);
1785 assert_eq!(wan.status, "found");
1786 }
1787
1788 #[test]
1789 fn classify_sender_name_match_is_case_insensitive() {
1790 let candidates = [candidate("agenta", "host", Some(999_000), false)];
1791 let verdict = classify_sender("AgentA", &candidates, 1_000_000);
1792 assert_eq!(verdict.status, "found");
1793 }
1794
1795 #[test]
1803 fn classify_sender_host_tier_never_stale_regardless_of_age() {
1804 let now_ms = 1_000_000;
1805 let ancient = now_ms - 10 * crate::backend::reactive::registry::FORWARD_FAILURE_GRACE_MS as i64;
1806 let candidates = [candidate("AgentA", "host", Some(ancient), false)];
1807 let verdict = classify_sender("AgentA", &candidates, now_ms);
1808 assert_eq!(verdict.status, "found", "host tier is stale_eligible: false — age must never matter");
1809 }
1810
1811 #[test]
1818 fn classify_sender_stale_when_last_seen_past_the_real_grace_threshold() {
1819 let now_ms = 1_000_000;
1820 let stale_ts = now_ms - crate::backend::reactive::registry::FORWARD_FAILURE_GRACE_MS as i64;
1821 let candidates = [candidate("AgentA", "cross-channel", Some(stale_ts), true)];
1822 let verdict = classify_sender("AgentA", &candidates, now_ms);
1823 assert_eq!(verdict.status, "stale");
1824 assert_eq!(verdict.tier, Some("cross-channel"), "still reports which tier it was found on");
1825 }
1826
1827 #[test]
1828 fn classify_sender_wan_tier_has_no_last_seen_and_is_never_stale() {
1829 let candidates = [candidate("AgentA", "wan", None, false)];
1833 let verdict = classify_sender("AgentA", &candidates, 1_000_000);
1834 assert_eq!(verdict.status, "found");
1835 }
1836
1837 #[test]
1842 fn classify_sender_reports_first_matching_tier_when_present_on_multiple() {
1843 let candidates = [
1844 candidate("AgentA", "host", Some(999_000), false),
1845 candidate("AgentA", "cross-channel", Some(999_000), true),
1846 ];
1847 let verdict = classify_sender("AgentA", &candidates, 1_000_000);
1848 assert_eq!(verdict.tier, Some("host"));
1849 }
1850
1851 #[test]
1859 fn classify_sender_prefers_a_live_candidate_over_an_earlier_stale_one() {
1860 let now_ms = 1_000_000;
1861 let stale_ts = now_ms - crate::backend::reactive::registry::FORWARD_FAILURE_GRACE_MS as i64;
1862 let candidates = [
1863 candidate("AgentA", "cross-channel", Some(stale_ts), true), candidate("AgentA", "lan", Some(999_000), true), ];
1866 let verdict = classify_sender("AgentA", &candidates, now_ms);
1867 assert_eq!(verdict.status, "found");
1868 assert_eq!(verdict.tier, Some("lan"));
1869 }
1870
1871 #[test]
1872 fn classify_sender_falls_back_to_first_stale_match_when_all_are_stale() {
1873 let now_ms = 1_000_000;
1874 let stale_ts = now_ms - crate::backend::reactive::registry::FORWARD_FAILURE_GRACE_MS as i64;
1875 let candidates = [
1876 candidate("AgentA", "cross-channel", Some(stale_ts), true),
1877 candidate("AgentA", "lan", Some(stale_ts), true),
1878 ];
1879 let verdict = classify_sender("AgentA", &candidates, now_ms);
1880 assert_eq!(verdict.status, "stale");
1881 assert_eq!(verdict.tier, Some("cross-channel"), "falls back to the most-trusted tier among stale matches");
1882 }
1883
1884 #[tokio::test]
1885 async fn handle_muxspect_verify_sender_rejects_empty_name() {
1886 let state = crate::server::tests::test_state();
1887 let resp = handle_muxspect_verify_sender(State(state), Query(MuxspectVerifySenderQuery { name: String::new() }))
1888 .await
1889 .into_response();
1890 assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
1891 }
1892
1893 #[tokio::test]
1894 async fn handle_muxspect_verify_sender_not_found_is_still_200() {
1895 let state = crate::server::tests::test_state();
1899 let resp = handle_muxspect_verify_sender(
1900 State(state),
1901 Query(MuxspectVerifySenderQuery { name: "NoSuchAgent".to_string() }),
1902 )
1903 .await
1904 .into_response();
1905 assert_eq!(resp.status(), StatusCode::OK);
1906 let body = json_body(resp).await;
1907 assert_eq!(body["status"], "not_found");
1908 }
1909
1910 #[tokio::test]
1911 async fn handle_muxspect_conversations_empty_state_is_still_200() {
1912 let state = crate::server::tests::test_state();
1916 let resp = handle_muxspect_conversations(State(state)).await.into_response();
1917 assert_eq!(resp.status(), StatusCode::OK);
1918 let body = json_body(resp).await;
1919 assert!(body["agents"].is_array());
1920 }
1921
1922 #[tokio::test]
1923 async fn handle_muxspect_conversations_includes_a_registered_host_agent() {
1924 let state = crate::server::tests::test_state();
1925 let unique = uuid::Uuid::new_v4();
1926 let agent_id = format!("conversations-test-agent-{unique}");
1927 let block_id = format!("conversations-test-block-{unique}");
1928 state
1929 .reactive_handler
1930 .register_agent(&agent_id, &block_id, None)
1931 .unwrap();
1932
1933 let resp = handle_muxspect_conversations(State(state)).await.into_response();
1934 assert_eq!(resp.status(), StatusCode::OK);
1935 let body = json_body(resp).await;
1936 let agents = body["agents"].as_array().expect("agents array");
1937 let entry = agents
1938 .iter()
1939 .find(|a| a["name"] == agent_id)
1940 .expect("registered agent should appear in the listing");
1941 assert_eq!(entry["tier"], "host");
1942 assert_eq!(entry["last_message_preview"], serde_json::Value::Null);
1947 }
1948
1949 fn insert_bare_block(
1954 mstore: &std::sync::Arc<crate::backend::storage::store::Store>,
1955 block_id: &str,
1956 ) {
1957 use crate::backend::obj::Block;
1958 let mut block = Block {
1959 oid: block_id.to_string(),
1960 parentoref: String::new(),
1961 version: 1,
1962 runtimeopts: None,
1963 stickers: None,
1964 meta: Default::default(),
1965 subblockids: None,
1966 };
1967 mstore.insert(&mut block).expect("mstore insert");
1968 }
1969
1970 #[test]
1971 fn last_line_preview_and_activity_returns_last_non_blank_line() {
1972 let filestore = std::sync::Arc::new(FileStore::open_in_memory().unwrap());
1973 let mstore = std::sync::Arc::new(crate::backend::storage::store::Store::open_in_memory().unwrap());
1974 let block_id = uuid::Uuid::new_v4().to_string();
1975 filestore
1976 .make_file(&block_id, "output", crate::backend::storage::filestore::FileMeta::default(), crate::backend::storage::filestore::FileOpts::default())
1977 .expect("make_file");
1978 filestore
1979 .append_data(&block_id, "output", b"first line\n\nlast line\n")
1980 .expect("append_data");
1981 insert_bare_block(&mstore, &block_id);
1982
1983 let (preview, activity_ms) = last_line_preview_and_activity(&mstore, &filestore, &block_id);
1984 assert_eq!(preview, Some("last line".to_string()));
1985 assert!(activity_ms.is_some());
1988 }
1989
1990 #[test]
1991 fn last_line_preview_and_activity_truncates_long_lines() {
1992 let filestore = std::sync::Arc::new(FileStore::open_in_memory().unwrap());
1993 let mstore = std::sync::Arc::new(crate::backend::storage::store::Store::open_in_memory().unwrap());
1994 let block_id = uuid::Uuid::new_v4().to_string();
1995 let long_line = "x".repeat(PREVIEW_MAX_CHARS + 50);
1996 filestore
1997 .make_file(&block_id, "output", crate::backend::storage::filestore::FileMeta::default(), crate::backend::storage::filestore::FileOpts::default())
1998 .expect("make_file");
1999 filestore
2000 .append_data(&block_id, "output", format!("{long_line}\n").as_bytes())
2001 .expect("append_data");
2002 insert_bare_block(&mstore, &block_id);
2003
2004 let (preview, _) = last_line_preview_and_activity(&mstore, &filestore, &block_id);
2005 let preview = preview.unwrap();
2006 assert_eq!(preview.chars().count(), PREVIEW_MAX_CHARS + 1); assert!(preview.ends_with('…'));
2008 }
2009
2010 #[test]
2011 fn last_line_preview_and_activity_returns_none_for_missing_block() {
2012 let filestore = std::sync::Arc::new(FileStore::open_in_memory().unwrap());
2013 let mstore = std::sync::Arc::new(crate::backend::storage::store::Store::open_in_memory().unwrap());
2014 let (preview, activity_ms) = last_line_preview_and_activity(&mstore, &filestore, "no-such-block");
2015 assert_eq!(preview, None);
2016 assert_eq!(activity_ms, None);
2017 }
2018
2019 #[test]
2023 fn flatten_layout_nodes_reports_depth_path_and_effective_minimize() {
2024 use agentmux_common::{FlexDirection, LayoutNode, LayoutNodeData};
2025
2026 fn leaf(id: &str, block: &str, minimized: bool) -> LayoutNode {
2027 let mut n = LayoutNode {
2028 id: id.to_string(),
2029 flex_direction: FlexDirection::Row,
2030 size: 10.0,
2031 children: Vec::new(),
2032 data: Some(LayoutNodeData {
2033 block_id: block.to_string(),
2034 ..Default::default()
2035 }),
2036 ..Default::default()
2037 };
2038 n.minimized = minimized;
2039 n
2040 }
2041
2042 let inner = LayoutNode {
2044 id: "inner".into(),
2045 flex_direction: FlexDirection::Row,
2046 size: 10.0,
2047 children: vec![leaf("a", "blk-a", true), leaf("b", "blk-b", true)],
2048 data: None,
2049 ..Default::default()
2050 };
2051 let root = LayoutNode {
2052 id: "root".into(),
2053 flex_direction: FlexDirection::Column,
2054 size: 10.0,
2055 children: vec![leaf("top", "blk-top", false), inner, leaf("bot", "blk-bot", false)],
2056 data: None,
2057 ..Default::default()
2058 };
2059
2060 let mut out = Vec::new();
2061 flatten_layout_nodes(&root, 0, "", &mut out);
2062
2063 assert_eq!(out.len(), 6);
2065 assert_eq!(out[0]["id"], "root");
2066 assert_eq!(out[0]["depth"], 0);
2067 assert_eq!(out[0]["kind"], "branch");
2068 assert_eq!(out[0]["flex_direction"], "column");
2069
2070 assert_eq!(out[1]["path"], "0");
2072 assert_eq!(out[2]["path"], "1");
2073 assert_eq!(out[3]["path"], "1.0");
2074 assert_eq!(out[3]["depth"], 2);
2075
2076 assert_eq!(out[2]["id"], "inner");
2081 assert_eq!(out[2]["locked"], false);
2082 assert_eq!(out[2]["effectively_minimized"], true);
2083 assert_eq!(out[2]["child_count"], 2);
2084
2085 assert_eq!(out[3]["block_id"], "blk-a");
2087 assert_eq!(out[3]["locked"], true);
2088 assert_eq!(out[1]["locked"], false);
2089 assert_eq!(out[1]["effectively_minimized"], false);
2090 }
2091
2092 #[test]
2093 fn truncate_preview_is_shared_by_host_and_cross_channel_paths() {
2094 let long = "y".repeat(PREVIEW_MAX_CHARS + 10);
2100 let truncated = truncate_preview(&long);
2101 assert_eq!(truncated.chars().count(), PREVIEW_MAX_CHARS + 1);
2102 assert!(truncated.ends_with('…'));
2103
2104 let short = "short line";
2105 assert_eq!(truncate_preview(short), short);
2106 }
2107}