1use std::collections::HashMap;
12use std::sync::{Arc, Mutex};
13
14use crate::backend::host_agent_files::LeftOut;
15use crate::backend::obj::{meta_get_string, Block};
16
17#[derive(Debug, Clone, Default, PartialEq, Eq)]
19struct NotGiven {
20 servers: Vec<String>,
22 folder: LeftOut,
24 no_path: Vec<String>,
26}
27
28static TOLD: Mutex<Option<HashMap<String, NotGiven>>> = Mutex::new(None);
30
31fn is_news(block_id: &str, what: &NotGiven) -> bool {
33 let mut told = TOLD.lock().unwrap_or_else(|e| e.into_inner());
34 let told = told.get_or_insert_with(HashMap::new);
35 if told.get(block_id).is_some_and(|last| last == what) {
36 return false;
37 }
38 told.insert(block_id.to_string(), what.clone());
39 true
40}
41
42fn not_given(meta: &crate::backend::obj::MetaMapType) -> Option<NotGiven> {
45 let folder = crate::backend::mcp_folder_rule::folder_of(meta)?;
46 let ours = std::fs::read_to_string(crate::backend::mcp_config_file::host_config_path(&folder)).ok();
47 Some(NotGiven {
48 servers: crate::backend::mcp_folder_rule::left_out(&folder, ours.as_deref()),
49 folder: crate::backend::host_agent_files::left_out(&folder),
50 no_path: crate::backend::host_agent_files::dir_of(&folder).map(|dir| crate::backend::host_agent_files::servers_with_no_path(&dir)).unwrap_or_default(),
51 })
52}
53
54pub(crate) async fn tell(
57 broker: &Arc<crate::backend::mps::Broker>,
58 filestore: &Arc<crate::backend::storage::filestore::FileStore>,
59 mstore: &Arc<crate::backend::storage::store::Store>,
60 block: &Block,
61) {
62 let meta = block.meta.clone();
63 let Some(what) = tokio::task::spawn_blocking(move || not_given(&meta)).await.ok().flatten() else { return };
64 if !is_news(&block.oid, &what) {
65 return;
66 }
67 tracing::warn!(block_id = %block.oid, servers = what.servers.len(), folder = ?what.folder, "this host agent takes nothing of its folder's own configuration: a container agent can write the folder");
68 let provider = meta_get_string(&block.meta, "agentProvider", "claude");
69 let frame = crate::backend::cli_notice::mcp_left_out_frame(&provider, &block.oid, &what.servers, &what.folder, &what.no_path);
70 crate::backend::cli_notice::append_to_pane(broker, filestore, mstore, &block.oid, &frame);
71}
72
73#[cfg(test)]
74mod tests {
75 use super::*;
76 use serde_json::json;
77
78 #[test]
79 fn a_pane_is_told_once_for_each_state_of_the_folder() {
80 let with = |servers: &[&str], skills: usize| NotGiven {
81 servers: servers.iter().map(|n| n.to_string()).collect(),
82 folder: LeftOut { skills, ..LeftOut::default() },
83 no_path: Vec::new(),
84 };
85 assert!(is_news("block-told-a", &with(&["one"], 0)));
86 assert!(!is_news("block-told-a", &with(&["one"], 0)), "the same again is not news");
87 assert!(is_news("block-told-a", &with(&["one", "two"], 0)), "another server is");
88 assert!(is_news("block-told-a", &with(&["one", "two"], 1)), "and so is a skill added to the folder");
89 assert!(is_news("block-told-b", &with(&["one"], 0)), "each pane is told for itself");
90 assert!(is_news("block-told-c", &NotGiven::default()), "a folder with nothing of its own is still told what is off there");
91 }
92
93 #[test]
94 fn what_is_not_given_is_the_folders_own_and_only_where_the_rule_holds() {
95 let (data, folder) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
96 let dir = folder.path().to_string_lossy().into_owned();
97 let pane = |mode: &str| -> crate::backend::obj::MetaMapType {
98 [("agentMode", json!(mode)), ("agentProvider", json!("claude")), ("cmd:cwd", json!(dir))].into_iter().map(|(k, v)| (k.to_string(), v)).collect()
99 };
100 std::fs::write(folder.path().join(".mcp.json"), r#"{"mcpServers":{"agentmux":{"command":"x"},"theirs":{"command":"y"}}}"#).unwrap();
101 std::fs::create_dir_all(folder.path().join(".claude")).unwrap();
102 std::fs::write(folder.path().join(".claude").join("settings.local.json"), "{}").unwrap();
103 std::fs::write(folder.path().join("CLAUDE.md"), "the folder's own").unwrap();
104 crate::backend::mcp_config_file::with_data_home(data.path(), || {
105 assert_eq!(not_given(&pane("host")), None, "a folder no container agent has to do with: nothing is said");
106 crate::backend::mcp_folder_rule::mark(&dir);
107 let first = not_given(&pane("host")).unwrap();
108 assert_eq!(first.servers, vec!["agentmux".to_string(), "theirs".to_string()], "no config of its own yet");
109 assert_eq!(first.folder, LeftOut { settings: 1, instructions: 1, ..LeftOut::default() });
110 let own = crate::backend::mcp_config_file::host_config_path(&dir);
111 assert!(!own.starts_with(folder.path()), "the agent's config is outside the folder");
112 crate::backend::mcp_config_file::write_relocated(&own, r#"{"mcpServers":{"agentmux":{"command":"agentmux-mcp"}}}"#).unwrap();
113 let mut after = not_given(&pane("host")).unwrap();
115 for _ in 0..20 {
116 if after.servers == vec!["theirs".to_string()] {
117 break;
118 }
119 std::thread::sleep(std::time::Duration::from_millis(50));
120 after = not_given(&pane("host")).unwrap();
121 }
122 assert_eq!(after.servers, vec!["theirs".to_string()], "own config {}: {:?}", own.display(), std::fs::read_to_string(&own).map(|text| text.len()));
123 assert_eq!(not_given(&pane("container")), None, "the container agent itself is not a host agent");
124 });
125 }
126}