Skip to main content

agentmux_srv/server/editor_handlers/
file_io.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The editor's file RPCs (read, write, list, reveal, create, delete; a rename is `fs.rename`), moved out of
5//! `register_editor_handlers` unchanged as named functions. Each mutation takes the user's home folder as a
6//! parameter, so a test can point it at a temp dir; the registration passes `dirs::home_dir()`.
7
8use std::path::Path;
9
10use super::{editor_may_change, is_a_home, remote_fs};
11use crate::backend::base::expand_home_dir_safe;
12use crate::backend::rpc_types::{
13    CommandReadEditorFileData, CommandReadEditorFileResult, CommandWriteEditorFileData, CreateEditorDirReq,
14    CreateEditorDirResult, CreateEditorFileReq, CreateEditorFileResult, DeleteEditorFileReq, DirEntry, ListEditorDirReq,
15    ListEditorDirResult, OpenInShellReq,
16};
17use crate::backend::text_encoding::DecodedFile;
18
19/// readeditorfile and writeeditorfile refuse more than this.
20const MAX_EDITOR_FILE_BYTES: usize = 10_000_000;
21
22/// The reply to a read: the detected encoding, BOM and line ending ride back so a save round-trips the original
23/// format. See docs/specs/SPEC_EDITOR_FILE_ENCODINGS_2026_06_17.md.
24fn read_result(decoded: DecodedFile, read_only: bool) -> CommandReadEditorFileResult {
25    CommandReadEditorFileResult {
26        content: decoded.content,
27        encoding: decoded.encoding,
28        bom: decoded.bom.to_string(),
29        line_ending: decoded.line_ending.to_string(),
30        had_decode_errors: decoded.had_decode_errors,
31        read_only,
32    }
33}
34
35/// A file on an SSH host: read there by its helper, decoded here the same way (remote terminals spec §6.3).
36pub(super) async fn read_remote_file(
37    connection: &str,
38    cmd: &CommandReadEditorFileData,
39    auth_key: &str,
40) -> Result<CommandReadEditorFileResult, String> {
41    let r = remote_fs::Remote { connection, block_id: cmd.block_id.as_deref(), auth_key };
42    let (bytes, read_only) = remote_fs::read_file(r, &cmd.path).await.map_err(|e| format!("readeditorfile: {e}"))?;
43    Ok(read_result(crate::backend::text_encoding::decode_file(&bytes), read_only))
44}
45
46/// Reads the bytes and detects the encoding (BOM, then UTF-8, then a heuristic), decoding to UTF-8 for the
47/// editor, so non-UTF-8 files (Windows-1252 .ini, UTF-16, Shift_JIS, ...) open instead of erroring.
48pub(super) fn read_local_file(path: &str) -> Result<CommandReadEditorFileResult, String> {
49    let expanded = expand_home_dir_safe(path);
50    let path = expanded.as_path();
51    let metadata = std::fs::metadata(path).map_err(|e| format!("readeditorfile: {e}"))?;
52    if metadata.len() > MAX_EDITOR_FILE_BYTES as u64 {
53        return Err("File too large (>10MB)".to_string());
54    }
55    let bytes = std::fs::read(path).map_err(|e| format!("readeditorfile: {e}"))?;
56    Ok(read_result(crate::backend::text_encoding::decode_file(&bytes), metadata.permissions().readonly()))
57}
58
59/// The file's original encoding, BOM and line endings, so a non-UTF-8 file round-trips instead of being
60/// silently rewritten as UTF-8. Absent fields default to UTF-8. The bool is true when some character has no
61/// representation in that encoding.
62fn encode_content(cmd: &CommandWriteEditorFileData) -> (Vec<u8>, bool) {
63    crate::backend::text_encoding::encode_file(
64        &cmd.content,
65        cmd.encoding.as_deref().unwrap_or(""),
66        cmd.bom.as_deref().unwrap_or("none"),
67        cmd.line_ending.as_deref().unwrap_or("lf"),
68    )
69}
70
71/// A file on an SSH host: encoded here as for a local file, then written there atomically by its helper.
72pub(super) async fn write_remote_file(connection: &str, cmd: &CommandWriteEditorFileData, auth_key: &str) -> Result<(), String> {
73    let (out_bytes, had_unmappable) = encode_content(cmd);
74    if had_unmappable {
75        return Err("writeeditorfile: file contains characters that can't be represented in its encoding — save it as UTF-8 instead".to_string());
76    }
77    let r = remote_fs::Remote { connection, block_id: cmd.block_id.as_deref(), auth_key };
78    remote_fs::write_file(r, &cmd.path, out_bytes).await
79}
80
81/// Writes restricted to under the user's home directory: an allowlist, safer than an incomplete denylist.
82pub(super) fn write_local_file(home: &Path, cmd: &CommandWriteEditorFileData) -> Result<(), String> {
83    let expanded = expand_home_dir_safe(&cmd.path);
84    let path = expanded.as_path();
85    let canonical_home = home.canonicalize().map_err(|e| format!("writeeditorfile: home dir: {e}"))?;
86
87    // The target path, resolved: canonicalize an existing one, or the parent plus the filename for a new file.
88    let canonical = path
89        .canonicalize()
90        .or_else(|_| {
91            path.parent()
92                .and_then(|p| p.canonicalize().ok())
93                .map(|p| p.join(path.file_name().unwrap_or_default()))
94                .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, "invalid path"))
95        })
96        .map_err(|e| format!("writeeditorfile: {e}"))?;
97
98    if !editor_may_change(&canonical, &canonical_home) {
99        return Err(format!("writeeditorfile: path {} is outside home directory", canonical.display()));
100    }
101
102    let (out_bytes, had_unmappable) = encode_content(cmd);
103    // Refuse a lossy write: rather than silently emit numeric-character-reference replacements (corrupting
104    // the file), fail loudly so the user can save as UTF-8. The UI for an in-place "Save with Encoding →
105    // UTF-8" is Phase 3 of SPEC_EDITOR_FILE_ENCODINGS.
106    if had_unmappable {
107        let enc = cmd.encoding.as_deref().filter(|s| !s.is_empty()).unwrap_or("its current encoding");
108        return Err(format!("writeeditorfile: file contains characters that can't be represented in {enc} — save it as UTF-8 instead"));
109    }
110    std::fs::write(&canonical, &out_bytes).map_err(|e| format!("writeeditorfile: {e}"))?;
111    tracing::info!(path = %canonical.display(), bytes = out_bytes.len(), "editor file saved");
112    Ok(())
113}
114
115/// Content past the limit is refused before anything else, remote or local.
116pub(super) fn check_write_size(cmd: &CommandWriteEditorFileData) -> Result<(), String> {
117    if cmd.content.len() > MAX_EDITOR_FILE_BYTES {
118        return Err("Content too large (>10MB)".to_string());
119    }
120    Ok(())
121}
122
123/// Lists a directory for the editor's file-tree pane. Symlinks are followed (matches VS Code semantics; the
124/// frontend marks followed symlinks with a ↗ overlay). Spec: docs/specs/SPEC_EDITOR_FILE_TREE_2026-05-26.md
125pub(super) fn list_dir(cmd: &ListEditorDirReq) -> Result<ListEditorDirResult, String> {
126    let expanded = expand_home_dir_safe(&cmd.path);
127    let canonical = expanded.canonicalize().map_err(|e| format!("listeditordir: {e}"))?;
128    let read_dir = std::fs::read_dir(&canonical).map_err(|e| format!("listeditordir: {e}"))?;
129
130    let mut entries: Vec<DirEntry> = read_dir.flatten().map(|entry| dir_entry(&entry)).collect();
131    // Folders first, then files; alphabetical, case-insensitive.
132    entries.sort_by(|a, b| match (a.is_dir, b.is_dir) {
133        (true, false) => std::cmp::Ordering::Less,
134        (false, true) => std::cmp::Ordering::Greater,
135        _ => a.name.to_lowercase().cmp(&b.name.to_lowercase()),
136    });
137    Ok(ListEditorDirResult { path: canonical.to_string_lossy().into_owned(), entries })
138}
139
140/// `file_type()` is the entry's own type, so a symlink shows as one (no follow); `metadata()` follows symlinks,
141/// so a symlinked dir reports `is_dir`. Both are needed: `is_symlink` from the first, `is_dir` and size from
142/// the second (a symlink-to-dir reads as a directory, matching VS Code).
143fn dir_entry(entry: &std::fs::DirEntry) -> DirEntry {
144    let name = entry.file_name().to_string_lossy().to_string();
145    let is_symlink = entry.file_type().map(|t| t.is_symlink()).unwrap_or(false);
146    let metadata = entry.metadata().ok();
147    let is_dir = metadata.as_ref().map(|m| m.is_dir()).unwrap_or(false);
148    let size = metadata.as_ref().and_then(|m| if !m.is_dir() { Some(m.len()) } else { None });
149    let mtime = metadata
150        .as_ref()
151        .and_then(|m| m.modified().ok())
152        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
153        .map(|d| d.as_millis() as u64);
154    DirEntry { name, is_dir, is_symlink, size, mtime }
155}
156
157// ── Editor file-tree mutations ─────────────────────────────────────────────
158// Spec: docs/specs/SPEC_FILE_TREE_CONTEXT_MENU_2026_06_14.md. All validate the target path is under the user's
159// home directory before performing any mutation: the same policy as writeeditorfile.
160
161/// A new file or folder name is one plain path component.
162pub(super) fn is_plain_name(name: &str) -> bool {
163    !(name.contains('/') || name.contains('\\') || name.contains('\0') || name == "." || name == ".." || name.is_empty())
164}
165
166/// Reveals a path in the OS file manager.
167pub(super) fn reveal_in_shell(home: &Path, cmd: &OpenInShellReq) -> Result<(), String> {
168    let expanded = expand_home_dir_safe(&cmd.path);
169    let path = expanded.as_path();
170    let canonical_home = home.canonicalize().map_err(|e| format!("openinshell: home: {e}"))?;
171    let canonical = path.canonicalize().map_err(|e| format!("openinshell: {e}"))?;
172    if !editor_may_change(&canonical, &canonical_home) {
173        return Err("openinshell: path outside home directory".to_string());
174    }
175    // The file manager is third-party and long-lived, and a user can launch anything from it, including another
176    // AgentMux build, which would then adopt THIS instance's channel and data dir (invariant I7;
177    // retro-env-inheritance-instance-isolation-breach-2026-09-17 §2.2). So: strict policy, not the pane keep-set.
178    #[cfg(target_os = "windows")]
179    {
180        let mut cmd = std::process::Command::new("explorer.exe");
181        crate::backend::pane_env::sanitize_external_std_command(&mut cmd);
182        let _ = cmd.arg(format!("/select,{}", canonical.display())).spawn();
183    }
184    #[cfg(target_os = "macos")]
185    {
186        let mut cmd = std::process::Command::new("open");
187        crate::backend::pane_env::sanitize_external_std_command(&mut cmd);
188        let _ = cmd.arg("-R").arg(&canonical).spawn();
189    }
190    #[cfg(target_os = "linux")]
191    {
192        // The one function every reveal goes through: it selects the file where the desktop's file manager can
193        // (D-Bus `ShowItems`) and otherwise opens its folder, under the same strict policy (I7).
194        // It waits up to two seconds for the file manager to answer, and this handler runs on the async runtime:
195        // a thread of its own keeps that wait off it (the answer was never used, as with the spawn before).
196        std::thread::spawn(move || {
197            let _ = crate::backend::fs_ops::platform::reveal(&canonical);
198        });
199    }
200    Ok(())
201}
202
203/// Creates an empty file inside an existing directory.
204pub(super) fn create_file(home: &Path, cmd: &CreateEditorFileReq) -> Result<CreateEditorFileResult, String> {
205    let expanded = expand_home_dir_safe(&cmd.parent_path);
206    let canonical_home = home.canonicalize().map_err(|e| format!("createeditorfile: home: {e}"))?;
207    let canonical_parent = expanded.as_path().canonicalize().map_err(|e| format!("createeditorfile: {e}"))?;
208    if !editor_may_change(&canonical_parent, &canonical_home) {
209        return Err("createeditorfile: path outside home directory".to_string());
210    }
211    if !is_plain_name(&cmd.name) {
212        return Err("createeditorfile: name must be a plain filename".to_string());
213    }
214    let file_path = canonical_parent.join(&cmd.name);
215    if file_path.exists() {
216        return Err("createeditorfile: file already exists".to_string());
217    }
218    // Created exclusively: a file that appeared since the check above is never emptied.
219    match std::fs::OpenOptions::new().write(true).create_new(true).open(&file_path) {
220        Ok(_) => Ok(CreateEditorFileResult { file_path: file_path.to_string_lossy().into_owned() }),
221        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => Err("createeditorfile: file already exists".to_string()),
222        Err(e) => Err(format!("createeditorfile: {e}")),
223    }
224}
225
226/// Creates a directory inside an existing directory.
227pub(super) fn create_dir(home: &Path, cmd: &CreateEditorDirReq) -> Result<CreateEditorDirResult, String> {
228    let expanded = expand_home_dir_safe(&cmd.parent_path);
229    let canonical_home = home.canonicalize().map_err(|e| format!("createeditordir: home: {e}"))?;
230    let canonical_parent = expanded.as_path().canonicalize().map_err(|e| format!("createeditordir: {e}"))?;
231    if !editor_may_change(&canonical_parent, &canonical_home) {
232        return Err("createeditordir: path outside home directory".to_string());
233    }
234    if !is_plain_name(&cmd.name) {
235        return Err("createeditordir: name must be a plain name".to_string());
236    }
237    let dir_path = canonical_parent.join(&cmd.name);
238    if dir_path.exists() {
239        return Err("createeditordir: already exists".to_string());
240    }
241    std::fs::create_dir(&dir_path).map_err(|e| format!("createeditordir: {e}"))?;
242    Ok(CreateEditorDirResult { dir_path: dir_path.to_string_lossy().into_owned() })
243}
244
245/// Deletes a file or directory.
246pub(super) fn delete_file(home: &Path, cmd: &DeleteEditorFileReq) -> Result<(), String> {
247    let expanded = expand_home_dir_safe(&cmd.path);
248    let path = expanded.as_path();
249    let canonical_home = home.canonicalize().map_err(|e| format!("deleteeditorfile: home: {e}"))?;
250    let canonical = path.canonicalize().map_err(|e| format!("deleteeditorfile: {e}"))?;
251    if !editor_may_change(&canonical, &canonical_home) || is_a_home(&canonical, &canonical_home) {
252        return Err("deleteeditorfile: path outside or is the home directory".to_string());
253    }
254    // symlink_metadata (not metadata) detects a symlink without following it. Deleting via `canonical` would
255    // delete the symlink TARGET; the entry at the original path is always what's removed, so a symlink is
256    // unlinked.
257    let meta = std::fs::symlink_metadata(path).map_err(|e| format!("deleteeditorfile: {e}"))?;
258    if meta.file_type().is_symlink() {
259        // On Windows, directory junctions/symlinks must use remove_dir; remove_file fails for directory
260        // symlinks on that platform.
261        #[cfg(windows)]
262        if path.is_dir() {
263            std::fs::remove_dir(path).map_err(|e| format!("deleteeditorfile: {e}"))?;
264        } else {
265            std::fs::remove_file(path).map_err(|e| format!("deleteeditorfile: {e}"))?;
266        }
267        #[cfg(not(windows))]
268        std::fs::remove_file(path).map_err(|e| format!("deleteeditorfile: {e}"))?;
269    } else if canonical.is_dir() {
270        if cmd.recursive {
271            std::fs::remove_dir_all(&canonical).map_err(|e| format!("deleteeditorfile: {e}"))?;
272        } else {
273            std::fs::remove_dir(&canonical).map_err(|e| format!("deleteeditorfile: directory not empty: {e}"))?;
274        }
275    } else {
276        std::fs::remove_file(&canonical).map_err(|e| format!("deleteeditorfile: {e}"))?;
277    }
278    Ok(())
279}