agentmux_srv_core/backend/
folder_overlap.rs1use std::collections::HashSet;
20use std::path::{Path, PathBuf};
21use std::sync::Mutex;
22
23use serde::{Deserialize, Serialize};
24
25use crate::backend::obj::MetaMapType;
26use crate::backend::storage::agents::AgentDefinition;
27use crate::backend::storage::store::Store;
28
29#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
31#[ts(export, export_to = "../../../frontend/types/rpc/")]
32pub struct Overlap {
33 pub host_id: String,
34 pub host_name: String,
35 pub container_id: String,
36 pub container_name: String,
37 #[serde(default)]
40 pub untrusted: bool,
41}
42
43fn working_folder(def: &AgentDefinition) -> Option<PathBuf> {
45 let dir = def.working_directory.trim();
46 (!dir.is_empty()).then(|| crate::backend::base::expand_home_dir_safe(dir))
47}
48
49fn writable_folders(def: &AgentDefinition) -> Vec<PathBuf> {
52 if !crate::backend::runtime_adapter::RuntimeKind::of_agent_mode(&def.agent_type).is_container() {
53 return Vec::new();
54 }
55 let mut meta = MetaMapType::new();
56 meta.insert("agentMode".to_string(), serde_json::json!("container"));
57 meta.insert(crate::backend::blockcontroller::META_KEY_CMD_CWD.to_string(), serde_json::json!(def.working_directory));
58 meta.insert("agent:container_volumes".to_string(), serde_json::json!(def.container_volumes));
59 crate::backend::container::mounts::writable::writable_binds(&meta, None).into_iter().map(|bind| bind.host).collect()
60}
61
62fn is_container(def: &AgentDefinition) -> bool {
63 crate::backend::runtime_adapter::RuntimeKind::of_agent_mode(&def.agent_type).is_container()
64}
65
66fn between(host: &AgentDefinition, folder: &Path, container: &AgentDefinition) -> Option<Overlap> {
67 writable_folders(container)
68 .iter()
69 .any(|bound| crate::backend::fs_ops::container_folders::overlap(folder, bound))
70 .then(|| Overlap {
71 host_id: host.id.clone(),
72 host_name: host.name.clone(),
73 container_id: container.id.clone(),
74 container_name: container.name.clone(),
75 untrusted: untrusted(&host.id, &container.id),
76 })
77}
78
79pub fn for_host_in(store: &Store, host: &AgentDefinition, folder: &Path) -> Vec<Overlap> {
81 if is_container(host) {
82 return Vec::new();
83 }
84 let all = store.agent_def_list().unwrap_or_default();
85 all.iter().filter(|other| other.id != host.id && is_container(other)).filter_map(|c| between(host, folder, c)).collect()
86}
87
88pub fn of(store: &Store, def: &AgentDefinition, host_folder: Option<&Path>) -> Vec<Overlap> {
92 if !is_container(def) {
93 let folder = host_folder.map(Path::to_path_buf).or_else(|| working_folder(def));
94 return folder.map_or_else(Vec::new, |folder| for_host_in(store, def, &folder));
95 }
96 let all = store.agent_def_list().unwrap_or_default();
97 all.iter()
98 .filter(|other| other.id != def.id && !is_container(other))
99 .filter_map(|host| working_folder(host).and_then(|folder| between(host, &folder, def)))
100 .collect()
101}
102
103fn choices_dir() -> Option<PathBuf> {
105 #[cfg(any(test, feature = "test-support"))]
106 return CHOICES_DIR_FOR_TEST.lock().unwrap_or_else(|e| e.into_inner()).clone();
107 #[cfg(not(any(test, feature = "test-support")))]
108 return crate::registry::paths::resolve_shared_folder_overlap_choices_dir();
109}
110
111#[cfg(any(test, feature = "test-support"))]
112static CHOICES_DIR_FOR_TEST: std::sync::Mutex<Option<PathBuf>> = std::sync::Mutex::new(None);
113
114#[cfg(any(test, feature = "test-support"))]
116pub fn set_choices_dir_for_test(dir: Option<PathBuf>) -> Option<PathBuf> {
117 std::mem::replace(&mut *CHOICES_DIR_FOR_TEST.lock().unwrap_or_else(|e| e.into_inner()), dir)
118}
119
120fn choice_file(host_id: &str, container_id: &str) -> Option<PathBuf> {
121 let key = agentmux_common::mcp_config_path::spelling_key(&format!("{host_id}\n{container_id}"));
122 Some(choices_dir()?.join(key))
123}
124
125pub const GO_AHEAD_ACTION: &str = "folder-overlap.go-ahead";
127
128pub fn row_note(action: &str, host: (&str, &str), container: (&str, &str)) -> String {
131 format!("{action} {} {}: host agent {} and container agent {}", host.0, container.0, host.1, container.1)
132}
133
134fn row_prefix(host_id: &str, container_id: &str) -> String {
135 format!("{GO_AHEAD_ACTION} {host_id} {container_id}:")
136}
137
138fn is_go_ahead_row(entry: &crate::backend::reactive::AuditLogEntry, prefix: &str) -> bool {
141 entry.event_kind == "action"
142 && entry.outcome.as_deref() == Some(GO_AHEAD_ACTION)
143 && entry.source_agent.is_none()
144 && entry.success
145 && entry.reason.as_deref().is_some_and(|reason| reason.starts_with(prefix))
146}
147
148fn audit_files() -> Vec<PathBuf> {
150 #[cfg(any(test, feature = "test-support"))]
151 return AUDIT_FILES_FOR_TEST.lock().unwrap_or_else(|e| e.into_inner()).clone();
152 #[cfg(not(any(test, feature = "test-support")))]
153 return [super::reactive::audit_store::shared_path_for_reading(), super::reactive::audit_store::own_path()].into_iter().flatten().collect();
154}
155
156#[cfg(any(test, feature = "test-support"))]
157static AUDIT_FILES_FOR_TEST: Mutex<Vec<PathBuf>> = Mutex::new(Vec::new());
158
159#[cfg(any(test, feature = "test-support"))]
161pub fn set_audit_files_for_test(files: Vec<PathBuf>) -> Vec<PathBuf> {
162 std::mem::replace(&mut *AUDIT_FILES_FOR_TEST.lock().unwrap_or_else(|e| e.into_inner()), files)
163}
164
165fn file_has_record(path: &Path, prefix: &str) -> bool {
168 use std::io::BufRead;
169 let Ok(file) = std::fs::File::open(path) else { return false };
170 std::io::BufReader::new(file)
171 .lines()
172 .map_while(Result::ok)
173 .filter(|line| line.contains(prefix))
174 .filter_map(|line| serde_json::from_str::<crate::backend::reactive::AuditLogEntry>(&line).ok())
175 .any(|entry| is_go_ahead_row(&entry, prefix))
176}
177
178fn recorded_pairs() -> &'static Mutex<HashSet<String>> {
181 static RECORDED: std::sync::OnceLock<Mutex<HashSet<String>>> = std::sync::OnceLock::new();
182 RECORDED.get_or_init(Mutex::default)
183}
184
185fn recorded_key(host_id: &str, container_id: &str) -> String {
186 format!("{host_id}\n{container_id}")
187}
188
189fn recorded(host_id: &str, container_id: &str) -> bool {
193 let key = recorded_key(host_id, container_id);
194 if recorded_pairs().lock().unwrap_or_else(|e| e.into_inner()).contains(&key) {
195 return true;
196 }
197 let prefix = row_prefix(host_id, container_id);
198 let in_memory = super::reactive::get_global_handler().get_audit_log(usize::MAX).iter().any(|entry| is_go_ahead_row(entry, &prefix));
199 let found = in_memory || audit_files().iter().any(|file| file_has_record(file, &prefix));
200 if found {
201 recorded_pairs().lock().unwrap_or_else(|e| e.into_inner()).insert(key);
202 }
203 found
204}
205
206fn has_choice_file(host_id: &str, container_id: &str) -> bool {
207 choice_file(host_id, container_id).is_some_and(|file| file.is_file())
208}
209
210pub fn accepted(host_id: &str, container_id: &str) -> bool {
213 has_choice_file(host_id, container_id) && recorded(host_id, container_id)
214}
215
216pub fn untrusted(host_id: &str, container_id: &str) -> bool {
218 has_choice_file(host_id, container_id) && !recorded(host_id, container_id)
219}
220
221pub fn accept(host_id: &str, container_id: &str) -> Result<(), String> {
224 accept_as((host_id, host_id), (container_id, container_id))
225}
226
227pub fn accept_as(host: (&str, &str), container: (&str, &str)) -> Result<(), String> {
230 let file = choice_file(host.0, container.0).ok_or("the choice can't be kept: AgentMux has no shared folder here")?;
231 if let Some(dir) = file.parent() {
232 std::fs::create_dir_all(dir).map_err(|e| format!("the choice can't be kept: {e}"))?;
233 }
234 let note = row_note(GO_AHEAD_ACTION, host, container);
235 super::reactive::get_global_handler().log_fleet_action_audit(None, host.1, "", GO_AHEAD_ACTION, true, None, &uuid::Uuid::new_v4().to_string(), Some(¬e));
236 recorded_pairs().lock().unwrap_or_else(|e| e.into_inner()).insert(recorded_key(host.0, container.0));
237 std::fs::write(&file, format!("{}\n{}\n", host.0, container.0)).map_err(|e| format!("the choice can't be kept: {e}"))
238}
239
240#[cfg(any(test, feature = "test-support"))]
242pub fn write_choice_without_a_record_for_test(host_id: &str, container_id: &str) {
243 let file = choice_file(host_id, container_id).expect("a choices folder is set");
244 std::fs::create_dir_all(file.parent().unwrap()).unwrap();
245 std::fs::write(&file, format!("{host_id}\n{container_id}\n")).unwrap();
246}
247
248#[cfg(any(test, feature = "test-support"))]
250pub fn forget_what_was_recorded_for_test() {
251 recorded_pairs().lock().unwrap_or_else(|e| e.into_inner()).clear();
252}
253
254pub fn forget_agent(id: &str) {
256 recorded_pairs().lock().unwrap_or_else(|e| e.into_inner()).retain(|key| !key.lines().any(|line| line == id));
257 let Some(dir) = choices_dir() else { return };
258 let Ok(entries) = std::fs::read_dir(&dir) else { return };
259 for entry in entries.flatten() {
260 let path = entry.path();
261 if std::fs::read_to_string(&path).is_ok_and(|text| text.lines().any(|line| line == id)) {
262 let _ = std::fs::remove_file(path);
263 }
264 }
265}
266
267pub fn unchosen(overlaps: Vec<Overlap>) -> Vec<Overlap> {
269 overlaps.into_iter().filter(|o| !accepted(&o.host_id, &o.container_id)).collect()
270}
271
272pub fn refusal(overlaps: &[Overlap]) -> String {
275 let pairs = overlaps
276 .iter()
277 .map(|o| format!("{} (host) and {} (container)", o.host_name, o.container_name))
278 .collect::<Vec<_>>()
279 .join("; ");
280 let untrusted = overlaps.iter().filter(|o| o.untrusted).map(|o| format!("{} and {}", o.host_name, o.container_name)).collect::<Vec<_>>().join("; ");
281 let why = if untrusted.is_empty() {
282 String::new()
283 } else {
284 format!(" A choice is kept for {untrusted}, but AgentMux has no record that the person made it, so it does not count.")
285 };
286 format!(
287 "{pairs} share a folder, so the container agent can change what the host agent runs.{why} Only the person can go ahead with that, from the AgentMux window. Give them separate workspaces, or bind the shared folder read-only into the container agent (a volume ending in :ro)"
288 )
289}
290
291pub fn check(store: &Store, def: &AgentDefinition, host_folder: Option<&Path>) -> Result<(), String> {
294 let pending = unchosen(of(store, def, host_folder));
295 if pending.is_empty() { Ok(()) } else { Err(refusal(&pending)) }
296}
297
298pub const OPEN_REFUSAL_CODE: &str = "SHARED_FOLDER";
300
301pub fn open_folder(def: &AgentDefinition) -> PathBuf {
303 let named = def.working_directory.trim();
304 let dir = if named.is_empty() { crate::backend::storage::agents::default_agent_working_dir(&def.name) } else { named.to_string() };
305 crate::backend::base::expand_home_dir_safe(&dir)
306}
307
308pub fn check_open(store: &Store, def: &AgentDefinition) -> Result<(), String> {
311 if is_container(def) {
312 return Ok(());
313 }
314 check(store, def, Some(&open_folder(def))).map_err(|refusal| format!("{OPEN_REFUSAL_CODE}: {refusal}"))
315}
316
317pub fn waiting_reason(store: &Store, def: &AgentDefinition) -> Option<String> {
320 if is_container(def) {
321 return None;
322 }
323 let pending = unchosen(of(store, def, Some(&open_folder(def))));
324 if pending.is_empty() {
325 return None;
326 }
327 let pairs = pending.iter().map(|o| format!("{} (host) and {} (container)", o.host_name, o.container_name)).collect::<Vec<_>>().join("; ");
328 Some(format!("{OPEN_REFUSAL_CODE}: waits for the person's go-ahead for a shared folder: {pairs}"))
329}
330
331pub fn folders_changed(old: &AgentDefinition, new: &AgentDefinition) -> bool {
333 old.working_directory != new.working_directory || old.agent_type != new.agent_type || old.container_volumes != new.container_volumes
334}
335
336pub fn is_a_pair(store: &Store, host_id: &str, container_id: &str) -> bool {
338 let kind = |id: &str| store.agent_def_get(id).ok().flatten().map(|def| is_container(&def));
339 kind(host_id) == Some(false) && kind(container_id) == Some(true)
340}
341
342#[cfg(test)]
343#[path = "folder_overlap_tests.rs"]
344mod tests;