Skip to main content

agentmux_srv/server/
agent_media_files.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A file a container agent's message shows or opens: read from the agent's own folders, never from a host path.
5//!
6//! A message of a container agent can name any path: `![](C:/Users/me/photo.png)`, `![](/etc/x.png)`, a link the
7//! agent made inside its workspace that points elsewhere. The window that draws the message reads a path as the
8//! person, so reading the path as written would show the person's own files in a pane the agent can screenshot. So
9//! a request that names the agent's pane (`block_id`) is answered here: the path is taken as the agent wrote it, a
10//! path in its container (`/workspace/a.png`) or a path of the folder it shares (a relative path resolved against
11//! the working directory), found in one of the folders the pane binds writable into its container, and opened by
12//! walking down from that folder without following a link (`workspace_copy::open_beneath`). A path anywhere else
13//! (another folder of the host, a drive or network path, the agent's home inside its container) is refused with the
14//! reason, and so is one that leaves the folder through a link.
15//!
16//! The pane's own folders only: another container agent's workspace is not this agent's. A folder bound read-only
17//! is not listed (the agent can't change it, but nothing in this check needs it).
18
19use std::path::{Path, PathBuf};
20
21use crate::backend::container::mounts::writable::{writable_binds, WritableBind};
22use crate::backend::obj::{Block, MetaMapType};
23use crate::backend::work_facts::paths::{normalize_path, relative_to};
24use crate::server::AppState;
25
26/// The refusal for a path that is not in the agent's own folders.
27pub(crate) const OUTSIDE: &str = "This file isn't in a folder the agent shares with its container, so it isn't shown from the agent's message. Only the agent's own folders can be shown there.";
28
29/// The refusal for a path that is in the agent's folder and leads out of it.
30pub(crate) const LEADS_OUT: &str = "This file is in the agent's folder and leads out of it: a link the agent made points elsewhere. Nothing outside the agent's folder is shown from its message.";
31
32/// The refusal for an agent with no folder to show.
33const NO_FOLDER: &str = "This agent shares no folder with its container, so there is nothing to show from its message.";
34
35/// A file found in one of an agent's folders.
36#[derive(Debug, PartialEq, Eq)]
37pub(crate) struct Found {
38    /// The bound folder, resolved.
39    pub root: PathBuf,
40    /// The file, resolved, inside `root`.
41    pub file: PathBuf,
42    /// The file's path in the container: what its copy is called.
43    pub of: String,
44}
45
46/// The settings of the pane `block_id` when it is a container agent's pane: the one an agent's message is shown
47/// in, whose folders its paths may lead into. `None` for any other pane (a native agent's messages are unchanged)
48/// and for a pane that is not there.
49pub(crate) fn pane_meta(state: &AppState, block_id: &str) -> Option<MetaMapType> {
50    let block = state.mstore.get::<Block>(block_id).ok().flatten()?;
51    crate::backend::runtime_adapter::RuntimeKind::of_block_meta(&block.meta).is_container().then_some(block.meta)
52}
53
54/// `path` with `.` and `..` taken out, as one text with `/` separators; `None` when a `..` would leave its root.
55fn collapse(path: &str) -> Option<String> {
56    // Not `normalize_path`: on Windows it reads `/c/x` as the drive `C:`, and a container's `/c/x` is its own folder.
57    let text = path.trim().replace('\\', "/");
58    let (root, rest) = match text.strip_prefix('/') {
59        Some(rest) => ("/", rest),
60        // A drive: `C:/...`.
61        None => match text.split_once('/') {
62            Some((drive, rest)) if drive.ends_with(':') => (&text[..drive.len() + 1], rest),
63            _ => return None,
64        },
65    };
66    let mut kept: Vec<&str> = Vec::new();
67    for part in rest.split('/') {
68        match part {
69            "" | "." => {}
70            ".." => {
71                kept.pop()?;
72            }
73            other => kept.push(other),
74        }
75    }
76    Some(format!("{root}{}", kept.join("/")))
77}
78
79/// What `lexical` (collapsed, absolute) is inside `bind`, if it is: as the container names it (`/workspace/a.png`;
80/// a container's paths are case-sensitive) or as the host does (the folder's own path, which a relative path of the
81/// message is resolved against). Returns how long the match is, so the deepest folder wins, and the rest of the path.
82fn within(bind: &WritableBind, lexical: &str) -> Option<(usize, String)> {
83    let target = bind.target.trim_end_matches('/');
84    if let Some(rest) = lexical.strip_prefix(target).filter(|rest| rest.is_empty() || rest.starts_with('/')) {
85        return Some((target.len(), rest.trim_start_matches('/').to_string()));
86    }
87    let host = normalize_path(&bind.host.to_string_lossy());
88    relative_to(lexical, &host).map(|rest| (host.len(), rest))
89}
90
91/// Whether `path` is a name or a path from the working folder: not rooted, and not led by a drive.
92fn is_relative(path: &str) -> bool {
93    let text = path.replace('\\', "/");
94    !text.starts_with('/') && !text.split_once('/').is_some_and(|(drive, _)| drive.ends_with(':'))
95}
96
97/// `asked`, as a message of the container agent of the pane `meta` wrote it, found in the agent's own folders.
98pub(crate) fn resolve(meta: &MetaMapType, asked: &str) -> Result<Found, String> {
99    let binds = writable_binds(meta, None);
100    if binds.is_empty() {
101        return Err(NO_FOLDER.to_string());
102    }
103    let asked = asked.trim();
104    // `~` is the agent's home inside its container, never the person's; a network path is another computer.
105    if asked.is_empty() || asked.starts_with('~') || asked.starts_with("\\\\") || asked.starts_with("//") {
106        return Err(OUTSIDE.to_string());
107    }
108    // A name with no folder is read from where the agent's shell starts, its workspace.
109    let from_workspace = format!("{}/{asked}", crate::backend::container::CONTAINER_WORKSPACE_DIR.trim_end_matches('/'));
110    let asked = if is_relative(asked) { from_workspace.as_str() } else { asked };
111    let lexical = collapse(asked).ok_or_else(|| OUTSIDE.to_string())?;
112    let (bind, rest) = binds
113        .iter()
114        .filter_map(|bind| within(bind, &lexical).map(|(len, rest)| (len, bind, rest)))
115        .max_by_key(|(len, ..)| *len)
116        .map(|(_, bind, rest)| (bind, rest))
117        .ok_or_else(|| OUTSIDE.to_string())?;
118    let canonical = crate::server::browser_uploads::canonical;
119    let root = canonical(&bind.host).map_err(|_| "The agent's folder can't be read right now.".to_string())?;
120    let spelled = if rest.is_empty() { bind.host.clone() } else { bind.host.join(&rest) };
121    let Ok(file) = canonical(&spelled) else {
122        // A link on the way that leads out of the folder with nothing at its end is refused as one with a file is.
123        if crate::server::link_file_check::dangling_link_leaves(&spelled, &[&bind.host, &root]) {
124            return Err(LEADS_OUT.to_string());
125        }
126        return Err("That file doesn't exist.".to_string());
127    };
128    if !file.starts_with(&root) {
129        return Err(LEADS_OUT.to_string());
130    }
131    let target = bind.target.trim_end_matches('/');
132    let of = if rest.is_empty() { bind.target.clone() } else { format!("{target}/{rest}") };
133    Ok(Found { root, file, of })
134}
135
136/// The file `asked` names, opened from the agent's own folders (see [`resolve`]) without following a link.
137pub(crate) fn open(meta: &MetaMapType, asked: &str) -> Result<(std::fs::File, Found), String> {
138    let found = resolve(meta, asked)?;
139    let file = crate::backend::workspace_copy::open_beneath(&found.root, &found.file)?;
140    Ok((file, found))
141}
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146
147    /// An agent's workspace with a picture in it, the person's own folder beside it, and a pane that binds the
148    /// workspace at `/workspace`.
149    struct Fixture {
150        _tmp: tempfile::TempDir,
151        ws: PathBuf,
152        private: PathBuf,
153        meta: MetaMapType,
154    }
155
156    fn fixture() -> Fixture {
157        let tmp = tempfile::tempdir().unwrap();
158        let ws = tmp.path().join("ws");
159        let private = tmp.path().join("private");
160        std::fs::create_dir_all(ws.join("img")).unwrap();
161        std::fs::create_dir_all(&private).unwrap();
162        std::fs::write(ws.join("img").join("a.png"), "the agent's picture").unwrap();
163        std::fs::write(private.join("photo.png"), "the person's photo").unwrap();
164        let mut meta = MetaMapType::new();
165        meta.insert("agentMode".to_string(), serde_json::json!("container"));
166        meta.insert(crate::backend::blockcontroller::META_KEY_CMD_CWD.to_string(), serde_json::json!(ws.to_string_lossy()));
167        Fixture { _tmp: tmp, ws, private, meta }
168    }
169
170    fn read(opened: Result<(std::fs::File, Found), String>) -> String {
171        use std::io::Read as _;
172        let mut text = String::new();
173        opened.unwrap().0.read_to_string(&mut text).unwrap();
174        text
175    }
176
177    /// Puts a link to the folder `to` where the folder `at` was; false where the platform refuses one.
178    fn swap_for_a_link(at: &Path, to: &Path) -> bool {
179        std::fs::remove_dir_all(at).unwrap();
180        #[cfg(unix)]
181        return std::os::unix::fs::symlink(to, at).is_ok();
182        #[cfg(windows)]
183        return std::process::Command::new("cmd")
184            .args(["/C", "mklink", "/J", &at.to_string_lossy(), &to.to_string_lossy()])
185            .output()
186            .map(|o| o.status.success())
187            .unwrap_or(false);
188    }
189
190    #[test]
191    fn a_path_in_the_container_is_read_from_the_folder_the_container_shares() {
192        let f = fixture();
193        assert_eq!(read(open(&f.meta, "/workspace/img/a.png")), "the agent's picture");
194        let found = resolve(&f.meta, "/workspace/img/a.png").unwrap();
195        assert_eq!(found.of, "/workspace/img/a.png");
196    }
197
198    #[test]
199    fn a_path_of_the_shared_folder_on_the_host_is_read_too_which_is_how_a_relative_path_arrives() {
200        let f = fixture();
201        // The pane resolves a relative path against the working directory, which is the host's folder.
202        let relative = format!("{}/img/a.png", f.ws.to_string_lossy());
203        assert_eq!(read(open(&f.meta, &relative)), "the agent's picture");
204        assert_eq!(read(open(&f.meta, &format!("{}/img/../img/a.png", f.ws.to_string_lossy()))), "the agent's picture");
205    }
206
207    #[test]
208    fn a_path_that_exists_on_the_host_but_is_not_in_the_agents_folders_is_refused() {
209        let f = fixture();
210        let photo = f.private.join("photo.png");
211        assert_eq!(resolve(&f.meta, &photo.to_string_lossy()).unwrap_err(), OUTSIDE);
212        assert_eq!(resolve(&f.meta, "/workspace/../private/photo.png").unwrap_err(), OUTSIDE);
213        // A container path that is not the shared folder is the container's own: not on the host to read.
214        assert_eq!(resolve(&f.meta, "/etc/hostname").unwrap_err(), OUTSIDE);
215        assert_eq!(resolve(&f.meta, "/workspaces/img/a.png").unwrap_err(), OUTSIDE, "a folder that only starts with the same letters is not inside it");
216        assert_eq!(resolve(&f.meta, "/Workspace/img/a.png").unwrap_err(), OUTSIDE, "a container's paths are case-sensitive");
217    }
218
219    #[test]
220    fn home_unc_drive_and_dot_dot_paths_are_refused() {
221        let f = fixture();
222        for asked in ["~/img/a.png", "~", "//server/share/a.png", "\\\\server\\share\\a.png", "C:/Users/me/photo.png", "C:\\Users\\me\\photo.png", "/../x.png", "", "  "] {
223            assert_eq!(resolve(&f.meta, asked).unwrap_err(), OUTSIDE, "{asked:?}");
224        }
225    }
226
227    #[test]
228    fn a_link_in_the_folder_that_leads_out_is_refused_whether_it_is_a_file_or_a_folder_on_the_way() {
229        let f = fixture();
230        if swap_for_a_link(&f.ws.join("img"), &f.private) {
231            // A folder of the workspace that now points at the person's folder.
232            assert_eq!(resolve(&f.meta, "/workspace/img/photo.png").unwrap_err(), LEADS_OUT);
233            let host = format!("{}/img/photo.png", f.ws.to_string_lossy());
234            assert_eq!(resolve(&f.meta, &host).unwrap_err(), LEADS_OUT);
235        }
236    }
237
238    #[cfg(unix)]
239    #[test]
240    fn a_file_link_out_of_the_folder_is_refused_and_an_inside_link_is_read() {
241        let f = fixture();
242        std::os::unix::fs::symlink(f.private.join("photo.png"), f.ws.join("out.png")).unwrap();
243        std::os::unix::fs::symlink(f.ws.join("img").join("a.png"), f.ws.join("in.png")).unwrap();
244        assert_eq!(resolve(&f.meta, "/workspace/out.png").unwrap_err(), LEADS_OUT);
245        assert_eq!(read(open(&f.meta, "/workspace/in.png")), "the agent's picture");
246    }
247
248    #[cfg(unix)]
249    #[test]
250    fn a_link_out_of_the_folder_is_refused_alike_whether_or_not_its_target_is_there() {
251        let f = fixture();
252        std::os::unix::fs::symlink(f.private.join("not-there.png"), f.ws.join("gone.png")).unwrap();
253        std::os::unix::fs::symlink(f.private.join("not-there-dir"), f.ws.join("gone-dir")).unwrap();
254        std::os::unix::fs::symlink(f.ws.join("img").join("later.png"), f.ws.join("soon.png")).unwrap();
255        assert_eq!(resolve(&f.meta, "/workspace/gone.png").unwrap_err(), LEADS_OUT);
256        assert_eq!(resolve(&f.meta, "/workspace/gone-dir/a.png").unwrap_err(), LEADS_OUT);
257        // A link to a folder that is there, with nothing at the end of the path, is refused as one with a file is.
258        std::os::unix::fs::symlink(&f.private, f.ws.join("up")).unwrap();
259        assert_eq!(resolve(&f.meta, "/workspace/up/nothing.png").unwrap_err(), LEADS_OUT);
260        assert_eq!(resolve(&f.meta, "/workspace/up/photo.png").unwrap_err(), LEADS_OUT);
261        // A link inside the folder whose own target runs through that link answers alike, with or without a file at its end.
262        std::os::unix::fs::symlink(f.ws.join("up").join("nothing.png"), f.ws.join("via-up.png")).unwrap();
263        std::os::unix::fs::symlink(f.ws.join("up").join("photo.png"), f.ws.join("via-up-file.png")).unwrap();
264        std::fs::create_dir_all(f.ws.join("x").join("y")).unwrap();
265        std::os::unix::fs::symlink(&f.ws, f.ws.join("x").join("y").join("dirlink")).unwrap();
266        std::os::unix::fs::symlink("../probe.png", f.ws.join("d.png")).unwrap();
267        assert_eq!(resolve(&f.meta, "/workspace/x/y/dirlink/d.png").unwrap_err(), LEADS_OUT);
268        std::os::unix::fs::symlink("up/../probe.png", f.ws.join("dotdot.png")).unwrap();
269        assert_eq!(resolve(&f.meta, "/workspace/dotdot.png").unwrap_err(), LEADS_OUT);
270        assert_eq!(resolve(&f.meta, "/workspace/via-up.png").unwrap_err(), LEADS_OUT);
271        assert_eq!(resolve(&f.meta, "/workspace/via-up-file.png").unwrap_err(), LEADS_OUT);
272        let host = format!("{}/gone.png", f.ws.to_string_lossy());
273        assert_eq!(resolve(&f.meta, &host).unwrap_err(), LEADS_OUT);
274        // A link inside the folder whose target is not there yet is only a file that is not there.
275        assert_eq!(resolve(&f.meta, "/workspace/soon.png").unwrap_err(), "That file doesn't exist.");
276    }
277
278    #[test]
279    fn a_name_with_no_folder_is_read_from_the_workspace() {
280        let f = fixture();
281        assert_eq!(resolve(&f.meta, "img/a.png").unwrap().of, "/workspace/img/a.png");
282        assert_eq!(read(open(&f.meta, "img/a.png")), "the agent's picture");
283        assert_eq!(resolve(&f.meta, "img/none.png").unwrap_err(), "That file doesn't exist.");
284        assert_eq!(resolve(&f.meta, "../a.png").unwrap_err(), OUTSIDE);
285    }
286
287    #[cfg(unix)]
288    #[test]
289    fn a_folder_reached_through_a_link_above_it_says_a_missing_file_is_not_there() {
290        let mut f = fixture();
291        let door = f._tmp.path().join("door");
292        std::os::unix::fs::symlink(f._tmp.path(), &door).unwrap();
293        f.meta.insert(crate::backend::blockcontroller::META_KEY_CMD_CWD.to_string(), serde_json::json!(door.join("ws").to_string_lossy()));
294        assert_eq!(resolve(&f.meta, "/workspace/img/none.png").unwrap_err(), "That file doesn't exist.");
295        assert_eq!(read(open(&f.meta, "/workspace/img/a.png")), "the agent's picture");
296        std::os::unix::fs::symlink(&f.private, f.ws.join("up")).unwrap();
297        assert_eq!(resolve(&f.meta, "/workspace/up/nothing.png").unwrap_err(), LEADS_OUT);
298    }
299
300    #[test]
301    fn a_link_swapped_in_after_the_path_was_found_is_not_followed() {
302        let f = fixture();
303        let found = resolve(&f.meta, "/workspace/img/a.png").unwrap();
304        // The person's folder holds a file of the same name, which is what a followed link would read.
305        std::fs::write(f.private.join("a.png"), "the person's file").unwrap();
306        if swap_for_a_link(&f.ws.join("img"), &f.private) {
307            // What was resolved a moment ago is opened again, now under a link: the open does not follow it.
308            assert!(crate::backend::workspace_copy::open_beneath(&found.root, &found.file).is_err());
309        }
310    }
311
312    #[test]
313    fn an_agent_with_no_shared_folder_has_nothing_to_show() {
314        let mut meta = MetaMapType::new();
315        meta.insert("agentMode".to_string(), serde_json::json!("container"));
316        assert_eq!(resolve(&meta, "/workspace/a.png").unwrap_err(), NO_FOLDER);
317        // A native agent's pane binds nothing either: it is not asked here at all (`pane_meta`).
318        assert_eq!(resolve(&MetaMapType::new(), "/workspace/a.png").unwrap_err(), NO_FOLDER);
319    }
320
321    #[test]
322    fn only_the_workspace_and_the_volumes_the_person_declared_can_be_shown_never_the_folders_the_app_binds_itself() {
323        let f = fixture();
324        let shared = f.private.to_string_lossy().replace('\\', "/");
325        let volumes = format!("[\"{shared}:/data\",\"{shared}:/docs:ro\",\"cache:/cache\"]");
326        let mut meta = f.meta.clone();
327        meta.insert("agent:container_volumes".to_string(), serde_json::json!(volumes));
328        let targets: Vec<String> = writable_binds(&meta, None).into_iter().map(|b| b.target).collect();
329        assert_eq!(targets, ["/workspace", "/data"], "a read-only volume and a named volume are not folders of the host to show");
330        // The agent's Personal Memory, its credentials, its Git hooks and its AWS folder are bound by the app under the
331        // container's home, outside these folders.
332        for app_owned in ["/root/.claude/projects/-workspace/memory/m.md", "/root/.claude/.credentials.json", "/root/.aws/credentials", "/docs/photo.png", "/cache/x"] {
333            assert_eq!(resolve(&meta, app_owned).unwrap_err(), OUTSIDE, "{app_owned}");
334        }
335    }
336
337    #[test]
338    fn a_file_that_is_not_there_says_so() {
339        let f = fixture();
340        assert_eq!(resolve(&f.meta, "/workspace/img/missing.png").unwrap_err(), "That file doesn't exist.");
341    }
342
343    #[test]
344    fn collapse_takes_dots_out_and_refuses_to_leave_the_root() {
345        assert_eq!(collapse("/a/./b//c/../d").as_deref(), Some("/a/b/d"));
346        assert_eq!(collapse("C:\\a\\b\\..\\c").as_deref(), Some("C:/a/c"));
347        assert_eq!(collapse("/c/x/../y").as_deref(), Some("/c/y"));
348        assert_eq!(collapse("/a/../..").as_deref(), None);
349        assert_eq!(collapse("relative/path").as_deref(), None);
350    }
351
352    #[test]
353    fn the_deepest_of_two_folders_holds_a_path_that_both_do() {
354        let f = fixture();
355        let mut meta = f.meta.clone();
356        let inner = f.ws.join("img");
357        meta.insert("agent:container_volumes".to_string(), serde_json::json!(format!("[\"{}:/workspace/pictures\"]", inner.to_string_lossy().replace('\\', "/"))));
358        let found = resolve(&meta, "/workspace/pictures/a.png").unwrap();
359        assert_eq!(found.of, "/workspace/pictures/a.png");
360        assert_eq!(read(open(&meta, "/workspace/pictures/a.png")), "the agent's picture");
361    }
362}