1use std::path::{Path, PathBuf};
19
20use crate::backend::rpc_types::CommandPaneOpenData;
21
22const EDITOR_LIMIT: u64 = 10_000_000;
24const MEDIA_LIMIT: u64 = 50_000_000;
26const MAX_SNAPSHOTS: usize = 40;
28const MARKER: &str = ".block";
30
31#[derive(Debug)]
33pub(crate) struct Snapshot {
34 dir: PathBuf,
35 pub of: String,
37 pub taken: String,
39}
40
41impl Snapshot {
42 pub fn note(&self) -> String {
44 format!(
45 "This is a read-only snapshot of {} taken at {}. It does not change when the file does: open it again to refresh it.",
46 self.of, self.taken
47 )
48 }
49
50 fn title(&self) -> String {
52 format!("{} (read-only snapshot, {})", self.of, self.taken)
53 }
54
55 pub fn opened(&self, block_id: &str) {
57 if let Err(e) = std::fs::write(self.dir.join(MARKER), block_id) {
58 tracing::warn!(error = %e, "[container-snapshot] couldn't note the pane; the copy goes when srv next starts");
59 }
60 }
61
62 pub fn discard(&self) {
64 remove_snapshot(&self.dir);
65 }
66}
67
68fn remove_snapshot(dir: &Path) {
70 if let Ok(files) = std::fs::read_dir(dir.join("copy")) {
71 for f in files.flatten() {
72 let _ = crate::backend::fs_ops::platform::remove_file_force(&f.path());
73 }
74 }
75 let _ = std::fs::remove_dir_all(dir);
76}
77
78pub(crate) fn root() -> Option<PathBuf> {
80 agentmux_common::DataPaths::from_env().map(|p| p.data_dir.join("container-snapshots"))
81}
82
83fn take(root: Option<&Path>, within: &Path, file: &Path, of: String, limit: u64) -> Result<(PathBuf, Snapshot), String> {
86 let root = root.ok_or("srv has no folder to keep snapshots in")?;
87 let dir = root.join(uuid::Uuid::new_v4().to_string());
88 {
89 static RESERVING: std::sync::Mutex<()> = std::sync::Mutex::new(());
91 let _reserving = RESERVING.lock().unwrap_or_else(|e| e.into_inner());
92 if std::fs::read_dir(root).map(|d| d.count()).unwrap_or(0) >= MAX_SNAPSHOTS {
93 return Err(format!("there are {MAX_SNAPSHOTS} snapshots open already: close some of those panes first"));
94 }
95 std::fs::create_dir_all(&dir).map_err(|e| format!("srv can't keep a snapshot: {e}"))?;
96 }
97 let copy = crate::backend::workspace_copy::copy_file(within, file, &dir.join("copy"), limit).inspect_err(|_| remove_snapshot(&dir))?;
99 let taken = chrono::Local::now().format("%H:%M").to_string();
100 Ok((copy, Snapshot { dir, of, taken }))
101}
102
103pub(crate) fn for_person(cmd: &mut CommandPaneOpenData, root: Option<&Path>, within: &Path, file: &Path, of: String) -> Result<Snapshot, String> {
107 let (copy, snapshot) = take(root, within, file, of, MEDIA_LIMIT)?;
108 cmd.file = Some(copy.to_string_lossy().into_owned());
109 cmd.title = Some(snapshot.title());
110 Ok(snapshot)
111}
112
113pub(crate) fn prepare(workspace: &Path, root: Option<&Path>, req: CommandPaneOpenData) -> Result<(CommandPaneOpenData, Option<Snapshot>), String> {
116 let limit = match req.view.as_str() {
117 "editor" if req.follow_folder == Some(true) => MEDIA_LIMIT,
119 "editor" => EDITOR_LIMIT,
120 "media" => MEDIA_LIMIT,
121 "sysinfo" | "help" | "tower" => 0,
122 "term" => return Err("a terminal pane runs on the host, so a container agent can't open one. Use your own shell in the container, or ask a native agent or your leader.".into()),
123 "browser" => return Err("use the Browser tool to open a page: it opens a browser pane in the agent's own Incognito jar.".into()),
124 v if v.starts_with("ext:") => return Err("a widget opens from the user's widget bar once they approve it; the Widget tool's open isn't available to a container agent yet.".into()),
125 "files" => return folder_pane(workspace, req),
126 other => return Err(format!("INVALID_VIEW: a container agent can open editor, media, sysinfo, help and tower panes, not '{other}'")),
127 };
128 if req.connection.as_deref().map(str::trim).is_some_and(|c| !c.is_empty() && c != "local") {
129 return Err("a pane on another machine reaches it as the user, so a container agent can't open one.".into());
130 }
131 let mut open = CommandPaneOpenData {
133 view: req.view.clone(),
134 title: req.title.clone(),
135 split_direction: req.split_direction.clone(),
136 split_reference_block_id: req.split_reference_block_id.clone(),
137 focus: req.focus,
138 line: req.line,
139 offset: req.offset,
140 page: req.page,
141 tree_expanded: req.tree_expanded,
142 follow_folder: (req.view == "media" || req.follow_folder == Some(true)).then_some(true),
143 ..Default::default()
144 };
145 if limit == 0 {
146 return Ok((open, None));
147 }
148 let raw = req.file.as_deref().map(str::trim).filter(|f| !f.is_empty()).ok_or_else(|| format!("MISSING_ARG: view={} requires 'file'", req.view))?;
149 let real = super::container_workspace::inside(workspace, raw)?;
150 let real = PathBuf::from(real);
151 let workspace_real = crate::server::browser_uploads::canonical(workspace).map_err(|e| format!("the agent's workspace can't be read: {e}"))?;
152 let of = container_path(&workspace_real, &real).ok_or_else(|| format!("{raw} is outside this agent's workspace"))?;
153 let (copy, snapshot) = take(root, &workspace_real, &real, of, limit)?;
154 open.file = Some(copy.to_string_lossy().into_owned());
155 open.title = Some(snapshot.title());
156 Ok((open, Some(snapshot)))
157}
158
159fn folder_pane(workspace: &Path, req: CommandPaneOpenData) -> Result<(CommandPaneOpenData, Option<Snapshot>), String> {
162 if req.connection.as_deref().map(str::trim).is_some_and(|c| !c.is_empty() && c != "local") {
163 return Err("a pane on another machine reaches it as the user, so a container agent can't open one.".into());
164 }
165 let raw = req.file.as_deref().map(str::trim).filter(|f| !f.is_empty()).ok_or("MISSING_ARG: view=files requires 'file' (the folder)")?;
166 let real = PathBuf::from(super::container_workspace::inside(workspace, raw)?);
167 if !real.is_dir() {
168 return Err(format!("{raw} is not a folder. To show a file, open it with view=editor or media: a read-only snapshot of it is shown."));
169 }
170 let workspace_real = crate::server::browser_uploads::canonical(workspace).map_err(|e| format!("the agent's workspace can't be read: {e}"))?;
171 let of = container_path(&workspace_real, &real).ok_or_else(|| format!("{raw} is outside this agent's workspace"))?;
172 let open = CommandPaneOpenData {
174 view: "files".into(),
175 title: req.title.clone(),
176 split_direction: req.split_direction.clone(),
177 split_reference_block_id: req.split_reference_block_id.clone(),
178 focus: req.focus,
179 meta: Some(super::files_root::confined_meta(&real, &of)),
180 ..Default::default()
181 };
182 Ok((open, None))
183}
184
185fn container_path(workspace: &Path, real: &Path) -> Option<String> {
187 let rel = real.strip_prefix(workspace).ok()?;
188 let parts: Vec<String> = rel.components().map(|c| c.as_os_str().to_string_lossy().into_owned()).collect();
189 Some(if parts.is_empty() { "/workspace".to_string() } else { format!("/workspace/{}", parts.join("/")) })
190}
191
192pub(crate) fn open_for(
194 state: &crate::server::AppState,
195 block_id: &str,
196 req: CommandPaneOpenData,
197) -> Result<(CommandPaneOpenData, Option<Snapshot>), String> {
198 let workspace = super::container_workspace::workspace_of(state, block_id).ok_or("this container agent has no workspace folder to open files from")?;
199 let asked = req.clone();
201 let (mut open, snapshot) = prepare(&workspace, root().as_deref(), req)?;
202 crate::server::app_api::floater_place::carry_over(&asked, &mut open);
203 Ok((open, snapshot))
204}
205
206pub(crate) fn forget(block_id: &str) {
208 if let Some(root) = root() {
209 remove_where(&root, |noted| noted == Some(block_id));
210 }
211}
212
213fn remove_where(root: &Path, gone: impl Fn(Option<&str>) -> bool) {
215 let Ok(entries) = std::fs::read_dir(root) else { return };
216 for entry in entries.flatten() {
217 let noted = std::fs::read_to_string(entry.path().join(MARKER)).ok().map(|b| b.trim().to_string()).filter(|b| !b.is_empty());
218 if gone(noted.as_deref()) {
219 remove_snapshot(&entry.path());
220 }
221 }
222}
223
224pub(crate) fn sweep(pane_exists: impl Fn(&str) -> bool) {
226 if let Some(root) = root() {
227 remove_where(&root, |noted| noted.is_none_or(|b| !pane_exists(b)));
228 }
229}
230
231pub(crate) fn spawn_sweeper(mut events: tokio::sync::broadcast::Receiver<agentmux_common::ipc::Event>) {
233 use agentmux_common::ipc::Event;
234 tokio::spawn(async move {
235 loop {
236 match events.recv().await {
237 Ok(Event::BlockDeleted { block_id, .. }) => forget(&block_id),
238 Ok(Event::TabDeleted { block_ids, .. } | Event::WorkspaceDeleted { block_ids, .. }) => block_ids.iter().for_each(|b| forget(b)),
239 Ok(_) => {}
240 Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
241 Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
242 }
243 }
244 });
245}
246
247#[cfg(test)]
248mod tests {
249 use super::*;
250
251 fn setup() -> (tempfile::TempDir, PathBuf, PathBuf) {
252 let tmp = tempfile::tempdir().unwrap();
253 let ws = tmp.path().join("ws");
254 std::fs::create_dir_all(ws.join("docs")).unwrap();
255 std::fs::write(ws.join("docs/notes.md"), "# notes").unwrap();
256 std::fs::write(tmp.path().join("secret.txt"), "outside").unwrap();
257 let root = tmp.path().join("snaps");
258 (tmp, ws, root)
259 }
260
261 fn open(view: &str, file: Option<&str>) -> CommandPaneOpenData {
262 CommandPaneOpenData { view: view.into(), file: file.map(str::to_string), ..Default::default() }
263 }
264
265 #[test]
266 fn a_file_opens_as_a_read_only_copy_that_says_what_it_is() {
267 let (_tmp, ws, root) = setup();
268 for given in ["/workspace/docs/notes.md", "docs/notes.md"] {
269 let (open, snap) = prepare(&ws, Some(&root), CommandPaneOpenData { follow_folder: Some(false), ..self::open("editor", Some(given)) }).unwrap();
270 let snap = snap.expect("a snapshot");
271 let copy = PathBuf::from(open.file.clone().unwrap());
272 assert!(copy.starts_with(&root) && !copy.starts_with(&ws), "the pane is given the copy, never the workspace");
273 assert_eq!(std::fs::read_to_string(©).unwrap(), "# notes");
274 assert!(std::fs::metadata(©).unwrap().permissions().readonly());
275 assert_eq!(snap.of, "/workspace/docs/notes.md");
276 let title = open.title.unwrap();
277 assert!(title.starts_with("/workspace/docs/notes.md (read-only snapshot, ") && !title.contains(root.to_str().unwrap()), "{title}");
278 assert!(snap.note().contains("open it again to refresh"));
279 }
280 }
281
282 #[test]
283 fn a_file_named_like_the_marker_cannot_take_its_place() {
284 let (_tmp, ws, root) = setup();
285 std::fs::write(ws.join(MARKER), "payload").unwrap();
286 let (open, snap) = prepare(&ws, Some(&root), open("editor", Some(MARKER))).unwrap();
287 let snap = snap.unwrap();
288 snap.opened("pane-x");
289 let copy = PathBuf::from(open.file.unwrap());
290 assert_eq!(std::fs::read_to_string(©).unwrap(), "payload");
291 assert_eq!(std::fs::read_to_string(copy.parent().unwrap().parent().unwrap().join(MARKER)).unwrap(), "pane-x");
292 remove_where(&root, |noted| noted == Some("pane-x"));
293 assert!(!copy.exists(), "closing its pane takes it");
294 }
295
296 #[test]
297 fn only_the_checked_fields_survive_and_a_path_outside_is_refused() {
298 let (tmp, ws, root) = setup();
299 let mut req = open("media", Some("docs/notes.md"));
300 req.url = Some("http://x".into());
301 req.cwd = Some("/".into());
302 req.meta = Some(Default::default());
303 req.connection = Some("local".into());
304 req.viewer = Some("text".into());
305 let (out, _) = prepare(&ws, Some(&root), req).unwrap();
306 assert!(out.url.is_none() && out.cwd.is_none() && out.meta.is_none() && out.connection.is_none() && out.viewer.is_none());
307 let outside = tmp.path().join("secret.txt");
308 for given in ["../secret.txt".to_string(), "/etc/passwd".to_string(), outside.to_string_lossy().into_owned()] {
309 assert!(prepare(&ws, Some(&root), open("editor", Some(&given))).is_err(), "{given}");
310 }
311 let mut ssh = open("editor", Some("docs/notes.md"));
312 ssh.connection = Some("user@host".into());
313 assert!(prepare(&ws, Some(&root), ssh).unwrap_err().contains("another machine"));
314 }
315
316 #[test]
317 fn the_views_that_cannot_be_snapshots_say_why() {
318 let (_tmp, ws, root) = setup();
319 for view in ["sysinfo", "help", "tower"] {
320 let (_, snap) = prepare(&ws, Some(&root), open(view, None)).unwrap();
321 assert!(snap.is_none(), "{view} shows no file");
322 }
323 assert!(prepare(&ws, Some(&root), open("term", None)).unwrap_err().contains("runs on the host"));
324 assert!(prepare(&ws, Some(&root), open("browser", None)).unwrap_err().contains("Browser tool"));
325 assert!(prepare(&ws, Some(&root), open("launcher", None)).unwrap_err().contains("INVALID_VIEW"));
327 assert!(prepare(&ws, Some(&root), open("editor", None)).unwrap_err().contains("MISSING_ARG"));
328 }
329
330 #[test]
331 fn a_big_file_and_too_many_snapshots_are_refused_and_leave_nothing_behind() {
332 let (_tmp, ws, root) = setup();
333 std::fs::write(ws.join("big.md"), vec![b'x'; (EDITOR_LIMIT + 1) as usize]).unwrap();
334 assert!(prepare(&ws, Some(&root), open("editor", Some("big.md"))).unwrap_err().contains("a snapshot can be"));
335 assert_eq!(std::fs::read_dir(&root).map(|d| d.count()).unwrap_or(0), 0, "a refused file leaves no folder");
336 std::fs::create_dir_all(&root).unwrap();
337 for i in 0..MAX_SNAPSHOTS {
338 std::fs::create_dir_all(root.join(format!("s{i}"))).unwrap();
339 }
340 assert!(prepare(&ws, Some(&root), open("editor", Some("docs/notes.md"))).unwrap_err().contains("close some of those panes"));
341 }
342
343 #[test]
344 fn requests_at_once_cannot_take_more_than_the_snapshots_left() {
345 let (_tmp, ws, root) = setup();
346 std::fs::create_dir_all(&root).unwrap();
347 for i in 0..MAX_SNAPSHOTS - 2 {
348 std::fs::create_dir_all(root.join(format!("s{i}"))).unwrap();
349 }
350 let taken = std::thread::scope(|scope| {
351 let tries: Vec<_> = (0..12).map(|_| scope.spawn(|| prepare(&ws, Some(&root), open("editor", Some("docs/notes.md"))).is_ok())).collect();
352 tries.into_iter().map(|t| t.join().unwrap()).filter(|ok| *ok).count()
353 });
354 assert_eq!(taken, 2, "two were left");
355 assert_eq!(std::fs::read_dir(&root).unwrap().count(), MAX_SNAPSHOTS);
356 }
357
358 #[test]
359 fn a_recording_is_held_to_the_media_limit_however_the_tool_names_the_view() {
360 let (_tmp, ws, root) = setup();
361 std::fs::write(ws.join("take.webm"), vec![b'x'; (EDITOR_LIMIT + 1) as usize]).unwrap();
362 assert!(prepare(&ws, Some(&root), open("editor", Some("take.webm"))).is_err());
364 let media = CommandPaneOpenData { follow_folder: Some(true), ..open("editor", Some("take.webm")) };
365 let (checked, snap) = prepare(&ws, Some(&root), media).unwrap();
366 assert_eq!(checked.follow_folder, Some(true));
367 snap.unwrap().discard();
368 assert!(prepare(&ws, Some(&root), open("media", Some("take.webm"))).is_ok());
369 }
370
371 #[test]
372 fn a_copy_goes_with_its_pane_and_the_unclaimed_go_at_start() {
373 let (_tmp, ws, root) = setup();
374 let take = |note: Option<&str>| {
375 let (open, snap) = prepare(&ws, Some(&root), open("editor", Some("docs/notes.md"))).unwrap();
376 let snap = snap.unwrap();
377 if let Some(block) = note {
378 snap.opened(block);
379 }
380 PathBuf::from(open.file.unwrap()).parent().unwrap().parent().unwrap().to_path_buf()
381 };
382 let (kept, closed, opening) = (take(Some("pane-a")), take(Some("pane-b")), take(None));
383 remove_where(&root, |noted| noted == Some("pane-b"));
384 assert!(kept.exists() && !closed.exists(), "closing a pane takes only its copy");
385 assert!(opening.exists(), "a copy whose pane is still opening is left alone");
386 let (live, dead) = (take(Some("live")), take(Some("dead")));
388 remove_where(&root, |noted| noted.is_none_or(|b| b != "live"));
389 assert!(live.exists() && !dead.exists() && !kept.exists() && !opening.exists());
390 }
391
392 #[tokio::test]
395 async fn the_route_holds_a_container_token_to_snapshots_and_leaves_the_instance_key_alone() {
396 use axum::body::Body;
397 use axum::http::{Request, StatusCode};
398 use tower::ServiceExt;
399 let state = crate::server::tests::test_state();
400 let tmp = tempfile::tempdir().unwrap();
401 let mut meta = crate::backend::obj::MetaMapType::new();
402 meta.insert("cmd:cwd".to_string(), serde_json::json!(tmp.path().to_string_lossy()));
403 let mut block = crate::backend::obj::Block { oid: uuid::Uuid::new_v4().to_string(), meta, ..Default::default() };
404 state.mstore.insert(&mut block).unwrap();
405 let token = crate::backend::container::credential::token_for_block(&block.oid, Some("agent-tok"));
406 let app = crate::server::build_router(state);
407 let call = |key: String, body: &'static str| {
408 let app = app.clone();
409 async move {
410 let req = Request::builder()
411 .method("POST")
412 .uri("/api/v1/pane/open")
413 .header("X-AuthKey", key)
414 .header("Content-Type", "application/json")
415 .body(Body::from(body))
416 .unwrap();
417 let resp = app.oneshot(req).await.unwrap();
418 let status = resp.status();
419 let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
420 (status, String::from_utf8_lossy(&bytes).into_owned())
421 }
422 };
423 let (status, body) = call(token.clone(), r#"{"view":"term"}"#).await;
424 assert_eq!(status, StatusCode::FORBIDDEN, "{body}");
425 assert!(body.contains("runs on the host"), "{body}");
426 let (status, body) = call(token, r#"{"view":"editor","file":"/etc/passwd"}"#).await;
427 assert_eq!(status, StatusCode::FORBIDDEN, "{body}");
428 assert!(body.contains("outside this agent's workspace") || body.contains("no such file"), "{body}");
429 let (status, body) = call("test-secret-key".to_string(), r#"{"view":"term"}"#).await;
430 assert_ne!(status, StatusCode::FORBIDDEN, "the instance key is not confined: {body}");
431 }
432 #[test]
433 fn a_folder_opens_as_a_files_pane_confined_to_it() {
434 let (_tmp, ws, root) = setup();
435 let want = crate::server::browser_uploads::canonical(&ws.join("docs")).unwrap().to_string_lossy().into_owned();
436 for given in ["/workspace/docs", "docs"] {
437 let mut req = open("files", Some(given));
438 req.cwd = Some("/".into());
439 req.url = Some("http://x".into());
440 let mut agents_meta = crate::backend::obj::MetaMapType::new();
441 agents_meta.insert("files:root".into(), "/".into());
442 req.meta = Some(agents_meta);
443 let (out, snap) = prepare(&ws, Some(&root), req).unwrap();
444 assert!(snap.is_none(), "a folder is not copied");
445 assert!(out.file.is_none() && out.cwd.is_none() && out.url.is_none(), "nothing of the agent's survives but where the pane goes");
446 let meta = out.meta.expect("the pane's own meta");
447 assert_eq!(meta["view"], "files");
448 assert_eq!(meta["files:path"], want.as_str());
449 assert_eq!(meta["files:root"], want.as_str(), "the root is the checked folder, not what the agent put in meta");
450 assert!(meta["frame:title"].as_str().unwrap().starts_with("/workspace/docs (read-only"));
451 }
452 let (whole, _) = prepare(&ws, Some(&root), open("files", Some("/workspace"))).unwrap();
453 let ws_real = crate::server::browser_uploads::canonical(&ws).unwrap().to_string_lossy().into_owned();
454 assert_eq!(whole.meta.unwrap()["files:root"], ws_real.as_str());
455 }
456
457 #[test]
458 fn a_folder_pane_is_refused_for_a_file_outside_the_workspace_or_another_machine() {
459 let (tmp, ws, root) = setup();
460 assert!(prepare(&ws, Some(&root), open("files", Some("docs/notes.md"))).unwrap_err().contains("not a folder"));
461 assert!(prepare(&ws, Some(&root), open("files", None)).unwrap_err().contains("MISSING_ARG"));
462 let outside = tmp.path().to_string_lossy().into_owned();
463 for given in ["..".to_string(), "/etc".to_string(), outside] {
464 assert!(prepare(&ws, Some(&root), open("files", Some(&given))).is_err(), "{given}");
466 }
467 let mut ssh = open("files", Some("docs"));
468 ssh.connection = Some("user@host".into());
469 assert!(prepare(&ws, Some(&root), ssh).unwrap_err().contains("another machine"));
470 }
471
472 #[test]
474 fn a_link_out_of_the_workspace_is_not_opened_as_its_folder() {
475 let (tmp, ws, root) = setup();
476 let outside = tmp.path().join("private");
477 std::fs::create_dir_all(&outside).unwrap();
478 let link = ws.join("leads-out");
479 #[cfg(unix)]
480 let made = std::os::unix::fs::symlink(&outside, &link).is_ok();
481 #[cfg(windows)]
482 let made = std::os::windows::fs::symlink_dir(&outside, &link).is_ok();
483 if made {
484 assert!(prepare(&ws, Some(&root), open("files", Some("leads-out"))).unwrap_err().contains("outside"));
485 }
486 }
487}