Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(agent): refuse Windows-hostile file names and match CRLF files in edit (#9263, #9262) (#9269)
Thinh Le4bf195c73941
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rsindex 033635110..919866779 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs@@ -14,8 +14,8 @@ use crate::skills;use crate::tools::jail;use crate::tools::proc;use crate::tools::sandbox::{- escapes_write_roots, hidden_under, in_scratch, lexical_normalize, resolve_path,- scratch_display_path, symlink_escapes_any_root,+ escapes_write_roots, hidden_under, in_scratch, lexical_normalize, refuse_windows_name,+ resolve_path, scratch_display_path, symlink_escapes_any_root,};use crate::tools::{BuiltinTool, ImageContentPart, ScreenshotBackend, ToolContext};@@ -357,15 +357,16 @@ fn render_edit_diff(edits: &[serde_json::Value], prior: &str) -> String {if n > 1 {out.push_str(&format!("@@ edit {}/{} @@\n", i + 1, n));}- match working.find(old) {+ let (old, new) = line_endings_of_file(&working, old, new);+ match working.find(&*old) {Some(pos) => {- let (old_block, new_block, start) = expand_hunk(&working, pos, old, new);+ let (old_block, new_block, start) = expand_hunk(&working, pos, &old, &new);out.push_str(&render_hunk_diff(&old_block, &new_block, start));- working.replace_range(pos..pos + old.len(), new);+ working.replace_range(pos..pos + old.len(), &new);}// `edit()` will reject this call, but the arguments are still worth// showing; there is no file position to number them against.- None => out.push_str(&render_hunk_diff(old, new, 1)),+ None => out.push_str(&render_hunk_diff(&old, &new, 1)),}}out.trim_end().to_string()@@ -725,6 +726,9 @@ async fn write(let Some(content) = arg_str(args, "content") else {return "ERROR: missing required argument 'content'".to_string();};+ if let Some((name, why)) = refuse_windows_name(path) {+ return format!("ERROR: refused to write '{name}' in {path}: the name {why}");+ }// Defense in depth: when the caller confines writes, re-canonicalize on the// canonical root (not the raw argument) so `..` and absolute paths are// caught even if the gate's decision was made against a stale view.@@ -764,6 +768,33 @@ async fn write(}}+/// Make an edit's line endings agree with the file it targets.+///+/// `read` hands the model a CRLF file verbatim, but a model writes a plain `\n`+/// between the lines of a multi-line `old_string`, so on a Windows project the+/// edit never matched (#9262). An exact match always wins; only when it fails,+/// the file has CRLF, and the CRLF spelling of `old_string` does match is that+/// spelling used -- for `new_string` as well, so the replaced lines keep the+/// file's own endings. Text the edit does not touch is never rewritten, so a+/// file with mixed endings stays mixed.+fn line_endings_of_file<'a>(+ content: &str,+ old: &'a str,+ new: &'a str,+) -> (std::borrow::Cow<'a, str>, std::borrow::Cow<'a, str>) {+ use std::borrow::Cow;+ let crlf = |s: &str| Cow::Owned::<str>(s.replace("\r\n", "\n").replace('\n', "\r\n"));+ if !old.contains('\n') || content.contains(old) || !content.contains("\r\n") {+ return (Cow::Borrowed(old), Cow::Borrowed(new));+ }+ let old_crlf = crlf(old);+ if content.contains(&*old_crlf) {+ (old_crlf, crlf(new))+ } else {+ (Cow::Borrowed(old), Cow::Borrowed(new))+ }+}+async fn edit(args: &serde_json::Value,root: &Path,@@ -780,6 +811,9 @@ async fn edit(if edits.is_empty() {return "ERROR: edits must contain at least one replacement".to_string();}+ if let Some((name, why)) = refuse_windows_name(path) {+ return format!("ERROR: refused to edit '{name}' in {path}: the name {why}");+ }let target = resolve_path(root, scratch, path);if confine && escapes_write_roots(root, scratch, write_roots, path).unwrap_or(true) {return format!("ERROR: refused to edit outside the agent workspace: {path}");@@ -802,7 +836,8 @@ async fn edit(let Some(new_string) = e.get("new_string").and_then(|v| v.as_str()) else {return format!("ERROR: {shown}: edit {}: missing 'new_string'", i + 1);};- let count = content.matches(old_string).count();+ let (old_string, new_string) = line_endings_of_file(&content, old_string, new_string);+ let count = content.matches(&*old_string).count();if count == 0 {return format!("ERROR: {shown}: edit {}: old_string not found", i + 1);}@@ -812,7 +847,7 @@ async fn edit(i + 1);}- content = content.replacen(old_string, new_string, 1);+ content = content.replacen(&*old_string, &new_string, 1);}match tokio::fs::write(&target, content).await {@@ -2105,6 +2140,132 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ async fn edit_file(root: &Path, file: &str, old: &str, new: &str) -> String {+ execute_builtin(+ lookup("edit").unwrap(),+ &json!({"path": file, "edits": [{"old_string": old, "new_string": new}]}),+ root,+ )+ .await+ }++ /// #9262: `read` shows a CRLF file with its `\r\n`, a model writes `\n`.+ #[tokio::test]+ async fn edit_matches_a_multi_line_old_string_in_a_crlf_file() {+ let root = unique_root();+ std::fs::write(root.join("a.txt"), b"one\r\ntwo\r\nthree\r\n").unwrap();+ let out = edit_file(&root, "a.txt", "one\ntwo", "ONE\nTWO").await;+ assert_eq!(out, "Applied 1 edit(s) to a.txt");+ // The replacement carries the file's own endings, and the rest is untouched.+ assert_eq!(+ std::fs::read(root.join("a.txt")).unwrap(),+ b"ONE\r\nTWO\r\nthree\r\n"+ );+ let _ = std::fs::remove_dir_all(&root);+ }++ #[tokio::test]+ async fn edit_keeps_working_when_the_model_already_sends_crlf() {+ let root = unique_root();+ std::fs::write(root.join("a.txt"), b"one\r\ntwo\r\nthree\r\n").unwrap();+ let out = edit_file(&root, "a.txt", "one\r\ntwo", "X").await;+ assert_eq!(out, "Applied 1 edit(s) to a.txt");+ assert_eq!(std::fs::read(root.join("a.txt")).unwrap(), b"X\r\nthree\r\n");+ let _ = std::fs::remove_dir_all(&root);+ }++ /// A file with mixed endings: an exact match wins, so the model's own+ /// spelling is never rewritten when it already fits.+ #[tokio::test]+ async fn edit_prefers_an_exact_match_in_a_mixed_ending_file() {+ let root = unique_root();+ std::fs::write(root.join("m.txt"), b"a\nb\r\nc\r\n").unwrap();+ let out = edit_file(&root, "m.txt", "a\nb", "A\nB").await;+ assert_eq!(out, "Applied 1 edit(s) to m.txt");+ assert_eq!(std::fs::read(root.join("m.txt")).unwrap(), b"A\nB\r\nc\r\n");+ let _ = std::fs::remove_dir_all(&root);+ }++ /// An LF file is not touched by the CRLF fallback.+ #[tokio::test]+ async fn edit_does_not_introduce_crlf_into_an_lf_file() {+ let root = unique_root();+ std::fs::write(root.join("l.txt"), b"one\ntwo\nthree\n").unwrap();+ let out = edit_file(&root, "l.txt", "one\ntwo", "ONE\nTWO").await;+ assert_eq!(out, "Applied 1 edit(s) to l.txt");+ assert_eq!(std::fs::read(root.join("l.txt")).unwrap(), b"ONE\nTWO\nthree\n");+ let _ = std::fs::remove_dir_all(&root);+ }++ /// A genuine miss in a CRLF file is still a miss, and a repeated block is+ /// still ambiguous after the endings are reconciled.+ #[tokio::test]+ async fn edit_crlf_fallback_still_reports_a_miss_and_ambiguity() {+ let root = unique_root();+ std::fs::write(root.join("d.txt"), b"x\r\ny\r\nx\r\ny\r\n").unwrap();+ let miss = edit_file(&root, "d.txt", "x\nz", "q").await;+ assert_eq!(miss, "ERROR: d.txt: edit 1: old_string not found");+ let dup = edit_file(&root, "d.txt", "x\ny", "q").await;+ assert!(dup.contains("old_string not unique (2 matches)"), "got: {dup}");+ assert_eq!(+ std::fs::read(root.join("d.txt")).unwrap(),+ b"x\r\ny\r\nx\r\ny\r\n"+ );+ let _ = std::fs::remove_dir_all(&root);+ }++ /// The approval preview must locate the edit the way `edit` will, or the+ /// user is shown a different change from the one that is applied.+ #[tokio::test]+ async fn crlf_edit_preview_matches_the_applied_change() {+ let root = unique_root();+ std::fs::write(root.join("p.txt"), b"zero\r\none\r\ntwo\r\nthree\r\n").unwrap();+ let args = json!({"path": "p.txt", "edits": [{"old_string": "one\ntwo", "new_string": "ONE\nTWO"}]});+ let diff = preview_diff(lookup("edit").unwrap(), &args, &root)+ .await+ .expect("a diff");+ assert!(diff.contains("ONE") && diff.contains("TWO"), "got: {diff}");+ // A miss is numbered from line 1; a located edit is numbered where it is.+ assert!(diff.contains("- 2 | one"), "numbered against the real file: {diff}");+ let _ = std::fs::remove_dir_all(&root);+ }++ /// #9263: Windows-only, because a name is only a problem where Win32 rewrites it.+ #[tokio::test]+ #[cfg(windows)]+ async fn write_and_edit_refuse_names_windows_cannot_address() {+ let root = unique_root();+ for name in ["aux", "con.txt", "NUL", "com1.log", "name.", "name ", "a.txt:stream", "sub/prn.c"] {+ let w = execute_builtin(+ lookup("write").unwrap(),+ &json!({"path": name, "content": "x"}),+ &root,+ )+ .await;+ assert!(w.starts_with("ERROR: refused to write"), "{name}: {w}");+ let e = edit_file(&root, name, "a", "b").await;+ assert!(e.starts_with("ERROR: refused to edit"), "{name}: {e}");+ }+ // Nothing was created, not even the parent of a refused nested path.+ assert_eq!(std::fs::read_dir(&root).unwrap().count(), 0);+ let _ = std::fs::remove_dir_all(&root);+ }++ #[tokio::test]+ async fn write_still_accepts_ordinary_names_that_resemble_reserved_ones() {+ let root = unique_root();+ for name in ["auxiliary.txt", "console.log", "com10.txt", "lpt.txt", "a.b.c", ".gitignore", "x y.txt"] {+ let w = execute_builtin(+ lookup("write").unwrap(),+ &json!({"path": name, "content": "x"}),+ &root,+ )+ .await;+ assert!(w.starts_with("Created "), "{name}: {w}");+ }+ let _ = std::fs::remove_dir_all(&root);+ }+#[test]fn edit_diff_single_hunk_has_no_header() {let d = render_edit_diff(&[json!({"old_string": "foo", "new_string": "bar"})], "foo");diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rsindex dd9f98557..c2fe4d026 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/sandbox.rs@@ -155,6 +155,58 @@ pub fn resolve_path(project_root: &Path, scratch: Option<&Path>, raw: &str) -> P}}+/// Why `name` cannot safely be a file name on Windows, or `None` if it can.+///+/// The tools address files through a `\\?\` path (the project root is one), and+/// Windows skips its name normalisation for those. A name Win32 would have+/// rewritten is then created exactly as given: `aux` and `con.txt` are+/// reserved device names and `name.` loses its dot, so every ordinary Windows+/// tool (PowerShell, Explorer, `del`) reports the path as not found, and a+/// `:` addresses an NTFS alternate data stream that no directory listing shows.+/// The tool would still report success, so the model believes the file exists.+///+/// Platform-independent on purpose, so it is testable anywhere; callers gate it+/// with [`refuse_windows_name`].+pub fn windows_name_problem(name: &str) -> Option<&'static str> {+ if name.contains(':') {+ return Some("contains ':' (an NTFS alternate data stream, not a file)");+ }+ if name.ends_with('.') || name.ends_with(' ') {+ return Some("ends with a dot or a space, which Windows silently strips");+ }+ // Reserved with or without an extension: `con.txt` is as reserved as `con`.+ let stem = name.split('.').next().unwrap_or(name).trim_end_matches(' ');+ let upper = stem.to_ascii_uppercase();+ // COM1-9 and LPT1-9; Windows also reserves the superscript digits.+ let numbered = ["COM", "LPT"].iter().any(|prefix| {+ let mut digit = upper.strip_prefix(prefix).into_iter().flat_map(str::chars);+ matches!(+ (digit.next(), digit.next()),+ (Some('1'..='9' | '\u{b9}' | '\u{b2}' | '\u{b3}'), None)+ )+ });+ let reserved =+ numbered || matches!(upper.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$");+ reserved.then_some("is a reserved Windows device name")+}++/// On Windows, the first component of `raw` that is not a valid file name, with+/// the reason; `None` elsewhere and for a path that is fine. Drive and root+/// components are not names, and `.`/`..` are resolved before they reach disk.+pub fn refuse_windows_name(raw: &str) -> Option<(String, &'static str)> {+ if !cfg!(windows) {+ return None;+ }+ use std::path::Component;+ Path::new(raw).components().find_map(|c| match c {+ Component::Normal(name) => {+ let name = name.to_string_lossy();+ windows_name_problem(&name).map(|why| (name.into_owned(), why))+ }+ _ => None,+ })+}+/// The spelling to hand a tool-facing path back to the model: the inverse of/// [`resolve_path`]. On Linux a file inside the scratch is named `/tmp/...`, the/// one name that works from both the filesystem tools (which remap it back) and@@ -408,6 +460,45 @@ fn canonicalize_lenient(path: &Path) -> Result<PathBuf, String> {}}+#[cfg(test)]+mod windows_name_tests {+ use super::windows_name_problem as problem;++ #[test]+ fn reserved_device_names_are_refused_with_or_without_an_extension() {+ for n in [+ "con", "CON", "Prn", "aux", "NUL", "con.txt", "aux.tar.gz", "nul.", "CONIN$", "CONOUT$",+ "com1", "COM9", "lpt1", "LPT9", "com1.log", "com\u{b9}", "lpt\u{b2}.txt", "aux .txt",+ ] {+ assert!(problem(n).is_some(), "{n:?} should be refused");+ }+ }++ #[test]+ fn names_that_only_resemble_reserved_ones_are_fine() {+ for n in [+ "auxiliary", "console.log", "com0", "com10", "lpt0", "com", "lpt", "conf", "nulls.txt",+ "a.con", "my.aux", ".aux", "x.nul.y", "readme.md", ".gitignore", "a.b.c", "x y.txt",+ ] {+ assert_eq!(problem(n), None, "{n:?} should be accepted");+ }+ }++ #[test]+ fn trailing_dot_or_space_and_colon_are_refused() {+ for n in ["name.", "name ", "name.txt.", "a.txt:stream", "a.txt::$DATA", "C:x"] {+ assert!(problem(n).is_some(), "{n:?} should be refused");+ }+ }++ #[test]+ fn the_refusal_gives_a_reason_the_model_can_act_on() {+ assert!(problem("aux").unwrap().contains("reserved"));+ assert!(problem("a:b").unwrap().contains("stream"));+ assert!(problem("a.").unwrap().contains("dot or a space"));+ }+}+#[cfg(test)]mod tests {use super::*;