Skip to main content

agentmux_srv/server/
agent_folder_open.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A file of a container agent's folder, opened by the person: the read-only copy, never the path.
5//!
6//! A container agent can change its folder while a window reads it, so an Editor given a path in it reads
7//! whatever the agent puts there later, as the person. Two opens the person makes lead into such a folder: a
8//! click on a file in a Files pane confined to it (`files_root.rs`), and a click on a link in a message
9//! (`from_link`). Both get what the agent's own `pane.open` gets (`container_pane_snapshot.rs`): a file opens
10//! as a read-only copy that goes with its pane, and a linked folder opens as a Files pane confined to it. A
11//! link that leads out of the agent's folder, or one whose folder can't be told from an agent's, is refused
12//! with the reason.
13
14use std::path::{Path, PathBuf};
15
16use crate::backend::fs_ops::container_folders::{self, Place};
17use crate::backend::rpc_types::CommandPaneOpenData;
18use crate::server::container_pane_snapshot::{self, Snapshot};
19use crate::server::AppState;
20
21/// The refusal for a link whose folder can't be told from a container agent's.
22const NOT_KNOWN: &str = "AgentMux can't tell right now whether this link leads into a container agent's folder, so it isn't opened. Try again in a moment, or open it from the Files pane.";
23
24/// The refusal for a link that is written inside a container agent's folder and resolves outside it.
25const LEADS_OUT: &str = "This link is in a container agent's folder and leads out of it: a link the agent made points elsewhere. Nothing outside the agent's folder is opened from it.";
26
27type Turned = (CommandPaneOpenData, Option<Snapshot>);
28
29/// `pane.open` where it leads into a container agent's folder: `cmd` is turned to open the read-only copy (or
30/// the confined Files pane). The copy taken is returned, for the caller to note to the pane that opens.
31pub(crate) async fn bind(state: &AppState, cmd: &mut CommandPaneOpenData) -> Result<Option<Snapshot>, String> {
32    // A file or a link clicked in a container agent's message: found in the agent's own folders, whatever else the open names.
33    // For a pane that is not a container agent's the open goes on as asked.
34    if let Some(pane) = cmd.message_of.take() {
35        if let Some(meta) = crate::server::agent_media_files::pane_meta(state, &pane) {
36            let asked = cmd.clone();
37            let turned = tokio::task::spawn_blocking(move || {
38                let snapshots = container_pane_snapshot::root();
39                from_message(asked, &meta, snapshots.as_deref())
40            })
41            .await
42            .map_err(|e| format!("filesystem task failed: {e}"))?;
43            let (turned, snapshot) = turned?;
44            *cmd = turned;
45            return Ok(snapshot);
46        }
47    }
48    let from_pane = crate::server::files_root::bind_pane_open(state, cmd).await?;
49    if from_pane.is_none() && cmd.from_link != Some(true) {
50        return Ok(None);
51    }
52    let asked = cmd.clone();
53    // Reads and copies a file: off the async workers.
54    let turned = tokio::task::spawn_blocking(move || {
55        let snapshots = container_pane_snapshot::root();
56        turn(asked, from_pane, snapshots.as_deref(), &container_folders::place)
57    })
58    .await
59    .map_err(|e| format!("filesystem task failed: {e}"))?;
60    let (turned, snapshot) = turned?;
61    *cmd = turned;
62    Ok(snapshot)
63}
64
65/// What [`bind`] does with the disk. `from_pane` is the folder of the confined pane the open came from, whose
66/// check left the file's resolved path in `cmd`; `snapshots` is where the copies are kept.
67fn turn(mut cmd: CommandPaneOpenData, from_pane: Option<PathBuf>, snapshots: Option<&Path>, place: &dyn Fn(&str) -> Place) -> Result<Turned, String> {
68    let Some(root) = from_pane else { return linked(cmd, snapshots, place) };
69    let within = crate::server::browser_uploads::canonical(&root).map_err(|_| "The folder this pane shows can't be read any more.".to_string())?;
70    let file = PathBuf::from(cmd.file.clone().unwrap_or_default());
71    let of = called(&within, &file, place);
72    let snapshot = container_pane_snapshot::for_person(&mut cmd, snapshots, &within, &file, of)?;
73    Ok((cmd, Some(snapshot)))
74}
75
76/// What a file's pane calls it: the container's own name for it where that is known, else its path from `within`.
77fn called(within: &Path, file: &Path, place: &dyn Fn(&str) -> Place) -> String {
78    if let Place::Inside(inside) = place(&file.to_string_lossy()) {
79        return inside.dir;
80    }
81    let rest = file.strip_prefix(within).unwrap_or(file);
82    rest.components().map(|c| c.as_os_str().to_string_lossy().into_owned()).collect::<Vec<_>>().join("/")
83}
84
85/// A file or a link clicked in a message of the container agent whose pane is `meta`: the file the agent's own folders
86/// hold under that path, as a read-only copy named as the container names it, or a folder of them, as a Files pane
87/// confined to it. A path anywhere else, and one that leads out of the folder through a link, is refused with the
88/// reason; so is an open on another computer.
89fn from_message(mut cmd: CommandPaneOpenData, meta: &crate::backend::obj::MetaMapType, snapshots: Option<&Path>) -> Result<Turned, String> {
90    if cmd.connection.as_deref().map(str::trim).is_some_and(|c| !c.is_empty() && c != "local") {
91        return Err("A file of an agent's message is on this computer; it isn't opened from another one.".to_string());
92    }
93    let asked = cmd.file.clone().unwrap_or_default();
94    let found = crate::server::agent_media_files::resolve(meta, &asked)?;
95    // The copy does not change when the file does, so there is no folder to follow; and the open is no link.
96    cmd.follow_folder = None;
97    cmd.from_link = None;
98    if found.file.is_dir() {
99        // A Files pane that lists and navigates inside the folder and changes nothing.
100        cmd.view = "files".into();
101        cmd.file = None;
102        cmd.meta = Some(crate::server::files_root::confined_meta(&found.file, &found.of));
103        return Ok((cmd, None));
104    }
105    cmd.view = "editor".into();
106    cmd.meta = None;
107    let snapshot = container_pane_snapshot::for_person(&mut cmd, snapshots, &found.root, &found.file, found.of)?;
108    Ok((cmd, Some(snapshot)))
109}
110
111/// A link in a message. A path no container agent can write opens as asked, and so does anything that is not
112/// a file or folder of this computer.
113fn linked(mut cmd: CommandPaneOpenData, snapshots: Option<&Path>, place: &dyn Fn(&str) -> Place) -> Result<Turned, String> {
114    let local = cmd.connection.as_deref().map(str::trim).is_none_or(|c| c.is_empty() || c == "local");
115    let path = cmd.file.as_deref().map(str::trim).filter(|f| !f.is_empty()).and_then(|f| crate::backend::fs_ops::resolve_request_path(f).ok());
116    let (true, None, "editor" | "files", Some(path)) = (local, &cmd.meta, cmd.view.as_str(), path) else {
117        return Ok((cmd, None));
118    };
119    let inside = match place(&path.to_string_lossy()) {
120        Place::Host => return Ok((cmd, None)),
121        Place::Unknown => return Err(NOT_KNOWN.to_string()),
122        Place::Inside(inside) => inside,
123    };
124    let canonical = crate::server::browser_uploads::canonical;
125    let within = canonical(Path::new(inside.bound())).map_err(|_| "The agent's folder this link leads into can't be read.".to_string())?;
126    let real = canonical(&path).map_err(|_| "What this link leads to doesn't exist any more.".to_string())?;
127    if !real.starts_with(&within) {
128        return Err(LEADS_OUT.to_string());
129    }
130    if real.is_dir() {
131        // The meta is used as it is: a Files pane that lists and navigates inside the folder and changes nothing.
132        cmd.view = "files".into();
133        cmd.file = None;
134        cmd.meta = Some(crate::server::files_root::confined_meta(&real, &inside.dir));
135        return Ok((cmd, None));
136    }
137    cmd.view = "editor".into();
138    let snapshot = container_pane_snapshot::for_person(&mut cmd, snapshots, &within, &real, inside.dir)?;
139    Ok((cmd, Some(snapshot)))
140}
141
142#[cfg(test)]
143mod tests {
144    use super::*;
145
146    /// An agent's folder with a file in it, the person's own folder beside it, and where the copies go.
147    fn folders() -> (tempfile::TempDir, PathBuf, PathBuf, PathBuf) {
148        let tmp = tempfile::tempdir().unwrap();
149        let (ws, private, snaps) = (tmp.path().join("ws"), tmp.path().join("private"), tmp.path().join("snaps"));
150        std::fs::create_dir_all(ws.join("src")).unwrap();
151        std::fs::create_dir_all(&private).unwrap();
152        std::fs::write(ws.join("src").join("a.txt"), "the agent's file").unwrap();
153        std::fs::write(private.join("a.txt"), "the person's own file").unwrap();
154        (tmp, ws, private, snaps)
155    }
156
157    /// Puts a link to the folder `to` where the folder `at` was; false where the platform refuses one.
158    fn swap_for_a_link(at: &Path, to: &Path) -> bool {
159        std::fs::remove_dir_all(at).unwrap();
160        #[cfg(unix)]
161        return std::os::unix::fs::symlink(to, at).is_ok();
162        #[cfg(windows)]
163        return std::process::Command::new("cmd")
164            .args(["/C", "mklink", "/J", &at.to_string_lossy(), &to.to_string_lossy()])
165            .output()
166            .map(|o| o.status.success())
167            .unwrap_or(false);
168    }
169
170    fn link(view: &str, path: &Path) -> CommandPaneOpenData {
171        CommandPaneOpenData { view: view.into(), file: Some(path.to_string_lossy().into_owned()), from_link: Some(true), ..Default::default() }
172    }
173
174    /// `ws` is bound into a container at `/workspace`.
175    fn agents(ws: &Path) -> impl Fn(&str) -> Place {
176        let ws = ws.to_path_buf();
177        move |asked| container_folders::inside_one(Path::new(asked), &ws, "agentmux-aria", "/workspace").map_or(Place::Host, Place::Inside)
178    }
179
180    #[test]
181    fn a_file_clicked_in_a_confined_pane_opens_as_a_copy_that_a_later_swap_does_not_change() {
182        let (_tmp, ws, private, snaps) = folders();
183        let within = crate::server::browser_uploads::canonical(&ws).unwrap();
184        let cmd = CommandPaneOpenData { view: "editor".into(), file: Some(within.join("src").join("a.txt").to_string_lossy().into_owned()), ..Default::default() };
185        let (open, snapshot) = turn(cmd, Some(ws.clone()), Some(&snaps), &|_| Place::Host).unwrap();
186        let copy = PathBuf::from(open.file.unwrap());
187        assert!(copy.starts_with(&snaps) && !copy.starts_with(&within), "the pane is given the copy, never the folder's path");
188        assert!(std::fs::metadata(&copy).unwrap().permissions().readonly());
189        assert!(open.title.unwrap().starts_with("src/a.txt (read-only snapshot, "));
190        if swap_for_a_link(&ws.join("src"), &private) {
191            assert_eq!(std::fs::read_to_string(&copy).unwrap(), "the agent's file", "what is put in the file's place later is not read");
192        }
193        snapshot.expect("a copy").discard();
194        assert!(!copy.exists(), "a pane that did not open leaves no copy");
195    }
196
197    #[test]
198    fn a_file_swapped_for_a_link_before_the_copy_is_not_read() {
199        let (_tmp, ws, private, snaps) = folders();
200        let within = crate::server::browser_uploads::canonical(&ws).unwrap();
201        let cmd = CommandPaneOpenData { view: "editor".into(), file: Some(within.join("src").join("a.txt").to_string_lossy().into_owned()), ..Default::default() };
202        if swap_for_a_link(&ws.join("src"), &private) {
203            assert!(turn(cmd, Some(ws.clone()), Some(&snaps), &|_| Place::Host).is_err());
204            assert_eq!(std::fs::read_dir(&snaps).map(|d| d.count()).unwrap_or(0), 0, "a refused file leaves no copy");
205        }
206    }
207
208    #[test]
209    fn a_linked_file_in_a_container_agents_folder_opens_as_a_copy_named_as_the_container_names_it() {
210        let (_tmp, ws, _private, snaps) = folders();
211        let place = agents(&ws);
212        let (open, snapshot) = turn(link("editor", &ws.join("src").join("a.txt")), None, Some(&snaps), &place).unwrap();
213        let copy = PathBuf::from(open.file.unwrap());
214        assert!(copy.starts_with(&snaps), "{}", copy.display());
215        assert_eq!(std::fs::read_to_string(&copy).unwrap(), "the agent's file");
216        assert!(open.title.unwrap().starts_with("/workspace/src/a.txt (read-only snapshot, "));
217        assert_eq!(snapshot.expect("a copy").of, "/workspace/src/a.txt");
218    }
219
220    #[test]
221    fn a_linked_folder_in_a_container_agents_folder_opens_as_a_files_pane_confined_to_it() {
222        let (_tmp, ws, _private, snaps) = folders();
223        let place = agents(&ws);
224        // The window takes a path for a file when it can't list it: what is on the disk decides.
225        for view in ["files", "editor"] {
226            let (open, snapshot) = turn(link(view, &ws.join("src")), None, Some(&snaps), &place).unwrap();
227            assert!(snapshot.is_none() && open.file.is_none(), "a folder is not copied");
228            let want = crate::server::browser_uploads::canonical(&ws.join("src")).unwrap().to_string_lossy().into_owned();
229            let meta = open.meta.expect("the pane's own meta");
230            assert_eq!((open.view.as_str(), meta["view"].as_str()), ("files", Some("files")));
231            assert_eq!(meta[crate::server::files_root::FILES_ROOT_META_KEY], want.as_str());
232            assert_eq!(meta["files:path"], want.as_str());
233            assert!(meta["frame:title"].as_str().unwrap().starts_with("/workspace/src (read-only"));
234        }
235    }
236
237    #[test]
238    fn a_link_out_of_a_container_agents_folder_is_refused_with_the_reason() {
239        let (_tmp, ws, private, snaps) = folders();
240        let place = agents(&ws);
241        if swap_for_a_link(&ws.join("src"), &private) {
242            for (view, path) in [("editor", ws.join("src").join("a.txt")), ("files", ws.join("src"))] {
243                let err = turn(link(view, &path), None, Some(&snaps), &place).unwrap_err();
244                assert_eq!(err, LEADS_OUT);
245            }
246            assert_eq!(std::fs::read_dir(&snaps).map(|d| d.count()).unwrap_or(0), 0);
247        }
248    }
249
250    #[test]
251    fn a_link_is_refused_while_its_folders_owner_cannot_be_told() {
252        let (_tmp, ws, _private, snaps) = folders();
253        let err = turn(link("editor", &ws.join("src").join("a.txt")), None, Some(&snaps), &|_| Place::Unknown).unwrap_err();
254        assert_eq!(err, NOT_KNOWN);
255    }
256
257    #[test]
258    fn a_linked_path_no_container_agent_can_write_opens_as_asked() {
259        let (_tmp, ws, private, snaps) = folders();
260        let place = agents(&ws);
261        let asked = link("editor", &private.join("a.txt"));
262        let (open, snapshot) = turn(asked.clone(), None, Some(&snaps), &place).unwrap();
263        assert!(snapshot.is_none());
264        assert_eq!((open.file, open.view, open.meta.is_none()), (asked.file, asked.view, true));
265        // A path on another machine, and an open that brings its own meta, are not this computer's files.
266        let mut remote = link("editor", &ws.join("src").join("a.txt"));
267        remote.connection = Some("user@host".into());
268        assert!(turn(remote, None, Some(&snaps), &place).unwrap().1.is_none());
269    }
270
271    /// The pane of a container agent whose workspace is `ws`.
272    fn agent_pane(ws: &Path) -> crate::backend::obj::MetaMapType {
273        let mut meta = crate::backend::obj::MetaMapType::default();
274        meta.insert("agentMode".into(), "container".into());
275        meta.insert(crate::backend::blockcontroller::META_KEY_CMD_CWD.into(), ws.to_string_lossy().into_owned().into());
276        meta
277    }
278
279    fn clicked(path: &str) -> CommandPaneOpenData {
280        CommandPaneOpenData { view: "editor".into(), file: Some(path.into()), follow_folder: Some(true), message_of: Some("pane".into()), ..Default::default() }
281    }
282
283    #[test]
284    fn a_picture_clicked_in_a_container_agents_message_opens_as_a_read_only_copy_named_as_the_container_names_it() {
285        let (_tmp, ws, _private, snaps) = folders();
286        std::fs::write(ws.join("pic.png"), "the agent's picture").unwrap();
287        for asked in ["/workspace/pic.png".to_string(), format!("{}/pic.png", ws.to_string_lossy())] {
288            let (open, snapshot) = from_message(clicked(&asked), &agent_pane(&ws), Some(&snaps)).unwrap();
289            let snapshot = snapshot.unwrap();
290            let copy = PathBuf::from(open.file.clone().unwrap());
291            assert!(copy.starts_with(&snaps), "{asked}: the pane is given the copy, never the folder's path");
292            assert_eq!(std::fs::read_to_string(&copy).unwrap(), "the agent's picture");
293            assert!(std::fs::metadata(&copy).unwrap().permissions().readonly());
294            assert!(open.title.clone().unwrap().starts_with("/workspace/pic.png (read-only snapshot, "));
295            assert_eq!((open.view.as_str(), open.follow_folder, open.from_link, open.meta.is_none()), ("editor", None, None, true));
296            assert_eq!(snapshot.of, "/workspace/pic.png");
297        }
298    }
299
300    #[test]
301    fn a_folder_linked_in_a_container_agents_message_opens_in_a_files_pane_confined_to_it() {
302        let (_tmp, ws, private, snaps) = folders();
303        let pane = agent_pane(&ws);
304        for asked in ["/workspace/src".to_string(), format!("{}/src/", ws.to_string_lossy()), "/workspace".to_string()] {
305            let (open, snapshot) = from_message(clicked(&asked), &pane, Some(&snaps)).unwrap();
306            assert!(snapshot.is_none(), "{asked}: a folder is not copied");
307            assert_eq!((open.view.as_str(), open.file.is_none(), open.from_link), ("files", true, None));
308            assert!(open.meta.is_some(), "{asked}: the pane is confined to the folder");
309        }
310        // The person's own folder is not the agent's, however it is spelled.
311        for asked in [private.to_string_lossy().into_owned(), "/workspace/../private".into(), "~".into()] {
312            assert_eq!(from_message(clicked(&asked), &pane, Some(&snaps)).unwrap_err(), crate::server::agent_media_files::OUTSIDE, "{asked}");
313        }
314    }
315
316    #[test]
317    fn a_file_clicked_in_a_message_that_is_not_in_the_agents_folders_is_refused_and_leaves_no_copy() {
318        let (_tmp, ws, private, snaps) = folders();
319        let pane = agent_pane(&ws);
320        for asked in [
321            private.join("a.txt").to_string_lossy().into_owned(),
322            "/workspace/../private/a.txt".into(),
323            "~/a.txt".into(),
324            "//host/share/a.png".into(),
325            "C:/Users/me/a.png".into(),
326            "/etc/hostname".into(),
327        ] {
328            let err = from_message(clicked(&asked), &pane, Some(&snaps)).unwrap_err();
329            assert_eq!(err, crate::server::agent_media_files::OUTSIDE, "{asked}");
330        }
331        let mut elsewhere = clicked("/workspace/src/a.txt");
332        elsewhere.connection = Some("user@host".into());
333        assert!(from_message(elsewhere, &pane, Some(&snaps)).is_err(), "a file of another computer is not opened from a message");
334        assert_eq!(std::fs::read_dir(&snaps).map(|d| d.count()).unwrap_or(0), 0);
335    }
336
337    #[test]
338    fn a_link_that_leads_out_of_the_agents_folder_is_refused_when_clicked_in_a_message() {
339        let (_tmp, ws, private, snaps) = folders();
340        if swap_for_a_link(&ws.join("src"), &private) {
341            let err = from_message(clicked("/workspace/src/a.txt"), &agent_pane(&ws), Some(&snaps)).unwrap_err();
342            assert_eq!(err, crate::server::agent_media_files::LEADS_OUT);
343            assert_eq!(std::fs::read_dir(&snaps).map(|d| d.count()).unwrap_or(0), 0);
344        }
345    }
346
347    #[tokio::test]
348    async fn a_click_in_a_pane_that_is_not_a_container_agents_opens_as_asked_and_the_field_is_not_kept() {
349        let (_tmp, ws, private, _snaps) = folders();
350        let state = crate::server::tests::test_state();
351        let mut meta = agent_pane(&ws);
352        meta.insert("agentMode".into(), "host".into());
353        let mut block = crate::backend::obj::Block { oid: "pane".into(), meta, ..Default::default() };
354        state.mstore.insert(&mut block).unwrap();
355        let asked = private.join("a.txt").to_string_lossy().into_owned();
356        let mut cmd = clicked(&asked);
357        assert!(bind(&state, &mut cmd).await.unwrap().is_none());
358        assert_eq!((cmd.file.as_deref(), cmd.message_of), (Some(asked.as_str()), None));
359        // A pane that is not there is not a container agent's either.
360        let mut gone = clicked(&asked);
361        gone.message_of = Some("no-such-pane".into());
362        assert!(bind(&state, &mut gone).await.unwrap().is_none());
363        assert_eq!(gone.file.as_deref(), Some(asked.as_str()));
364    }
365
366    #[tokio::test]
367    async fn an_open_without_a_link_or_a_confined_pane_is_left_as_it_is() {
368        let (_tmp, ws, _private, _snaps) = folders();
369        let state = crate::server::tests::test_state();
370        let asked = CommandPaneOpenData { view: "editor".into(), file: Some(ws.join("src").join("a.txt").to_string_lossy().into_owned()), ..Default::default() };
371        let mut cmd = asked.clone();
372        assert!(bind(&state, &mut cmd).await.unwrap().is_none());
373        assert_eq!(cmd.file, asked.file, "an open the person makes any other way is not changed");
374    }
375}