diff --git a/Cargo.lock b/Cargo.lock index afbeea1ab79..e5ae37e8e68 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -145,21 +145,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" dependencies = [ "cfg-if", - "cipher 0.4.4", + "cipher", "cpufeatures 0.2.17", ] -[[package]] -name = "aes" -version = "0.9.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1" -dependencies = [ - "cipher 0.5.2", - "cpubits", - "cpufeatures 0.3.1", -] - [[package]] name = "aes-gcm" version = "0.10.3" @@ -167,8 +156,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" dependencies = [ "aead", - "aes 0.8.4", - "cipher 0.4.4", + "aes", + "cipher", "ctr", "ghash", "subtle", @@ -180,7 +169,7 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69fa2b352dcefb5f7f3a5fb840e02665d311d878955380515e4fd50095dd3d8c" dependencies = [ - "aes 0.8.4", + "aes", ] [[package]] @@ -206,21 +195,6 @@ dependencies = [ "memchr", ] -[[package]] -name = "alloc-no-stdlib" -version = "2.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" - -[[package]] -name = "alloc-stdlib" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195" -dependencies = [ - "alloc-no-stdlib", -] - [[package]] name = "allocator-api2" version = "0.2.21" @@ -654,15 +628,6 @@ dependencies = [ "generic-array", ] -[[package]] -name = "block-padding" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b" -dependencies = [ - "hybrid-array", -] - [[package]] name = "block2" version = "0.5.1" @@ -701,17 +666,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e412e2cd0f2b2d93e02543ceae7917b3c70331573df19ee046bcbc35e45e87d7" dependencies = [ "byteorder", - "cipher 0.4.4", -] - -[[package]] -name = "brotli-decompressor" -version = "5.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583" -dependencies = [ - "alloc-no-stdlib", - "alloc-stdlib", + "cipher", ] [[package]] @@ -995,7 +950,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3264e2574e9ef2b53ce6f536dea83a69ac0bc600b762d1523ff83fe07230ce30" dependencies = [ "byteorder", - "cipher 0.4.4", + "cipher", ] [[package]] @@ -1012,7 +967,7 @@ dependencies = [ "maybe-owned", "rustix 1.1.6", "rustix-linux-procfs", - "windows-sys 0.60.2", + "windows-sys 0.61.2", "winx", ] @@ -1034,7 +989,7 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "26b07d673db1ccf000e90f54b819db9e75a8348d6eb056e9b8ab53231b7a9911" dependencies = [ - "cipher 0.4.4", + "cipher", ] [[package]] @@ -1055,16 +1010,7 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6" dependencies = [ - "cipher 0.4.4", -] - -[[package]] -name = "cbc" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896" -dependencies = [ - "cipher 0.5.2", + "cipher", ] [[package]] @@ -1085,7 +1031,7 @@ version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "738b8d467867f80a71351933f70461f5b56f24d5c93e0cf216e59229c968d330" dependencies = [ - "cipher 0.4.4", + "cipher", ] [[package]] @@ -1178,17 +1124,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" dependencies = [ "crypto-common 0.1.7", - "inout 0.1.4", -] - -[[package]] -name = "cipher" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" -dependencies = [ - "crypto-common 0.2.2", - "inout 0.2.6", + "inout", ] [[package]] @@ -1206,7 +1142,7 @@ version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8543454e3c3f5126effff9cd44d562af4e31fb8ce1cc0d3dcd8f084515dbc1aa" dependencies = [ - "cipher 0.4.4", + "cipher", "dbl", "digest 0.10.7", ] @@ -1361,12 +1297,6 @@ dependencies = [ "cfg-if", ] -[[package]] -name = "cpubits" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" - [[package]] name = "cpufeatures" version = "0.2.17" @@ -1650,7 +1580,7 @@ version = "0.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" dependencies = [ - "cipher 0.4.4", + "cipher", ] [[package]] @@ -1770,9 +1700,9 @@ version = "4.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "708b509edf7889e53d7efb0ffadd994cc6c2345ccb62f55cfd6b0682165e4fa6" dependencies = [ - "aes 0.8.4", - "block-padding 0.3.3", - "cbc 0.1.2", + "aes", + "block-padding", + "cbc", "dbus", "fastrand", "hkdf", @@ -1853,7 +1783,7 @@ version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ffdd80ce8ce993de27e9f063a444a4d53ce8e8db4c1f00cc03af5ad5a9867a1e" dependencies = [ - "cipher 0.4.4", + "cipher", ] [[package]] @@ -1994,21 +1924,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9954fabd903b82b9d7a68f65f97dc96dd9ad368e40ccc907a7c19d53e6bfac28" dependencies = [ "aead", - "cipher 0.4.4", + "cipher", "cmac", "ctr", "subtle", ] -[[package]] -name = "ecb" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26f2a8b3e564eba0877223dc343703ad0385794e882e6d13f3a4dd5c6b1f41ac" -dependencies = [ - "cipher 0.5.2", -] - [[package]] name = "ecdsa" version = "0.16.9" @@ -2326,7 +2247,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -2725,7 +2646,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" dependencies = [ "color_quant", - "weezl 0.1.12", + "weezl", ] [[package]] @@ -3163,7 +3084,7 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "075557004419d7f2031b8bb7f44bb43e55a83ca7b63076a8fb8fe75753836477" dependencies = [ - "cipher 0.4.4", + "cipher", ] [[package]] @@ -3252,20 +3173,10 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" dependencies = [ - "block-padding 0.3.3", + "block-padding", "generic-array", ] -[[package]] -name = "inout" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9" -dependencies = [ - "block-padding 0.4.2", - "hybrid-array", -] - [[package]] name = "interprocess" version = "2.4.8" @@ -3615,33 +3526,6 @@ version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" -[[package]] -name = "lopdf" -version = "0.45.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfffda0fe1ab0157e1a13c14bebd3f28671f2fccb7922f0722ec53926e6922d3" -dependencies = [ - "aes 0.9.4", - "bitflags 2.13.2", - "brotli-decompressor", - "cbc 0.2.1", - "ecb", - "encoding_rs", - "flate2", - "getrandom 0.4.3", - "indexmap", - "itoa", - "log", - "md-5 0.11.0", - "nom", - "rand 0.10.3", - "rangemap", - "sha2 0.11.1", - "stringprep", - "thiserror 2.0.21", - "weezl 0.2.1", -] - [[package]] name = "mach2" version = "0.6.0" @@ -3664,16 +3548,6 @@ dependencies = [ "digest 0.10.7", ] -[[package]] -name = "md-5" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98" -dependencies = [ - "cfg-if", - "digest 0.11.3", -] - [[package]] name = "memchr" version = "2.8.3" @@ -3758,7 +3632,7 @@ dependencies = [ "objc2-foundation 0.3.2", "png", "thiserror 2.0.21", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -4361,7 +4235,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c196e0276c471c843dd5777e7543a36a298a4be942a2a688d8111cd43390dedb" dependencies = [ "aead", - "cipher 0.4.4", + "cipher", "ctr", "subtle", ] @@ -4433,7 +4307,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -4572,13 +4446,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c7275cbf21850789239e1be05d9a887e6bba6aa8085a81be09ca021c8379baef" dependencies = [ "aead", - "aes 0.8.4", + "aes", "aes-gcm", "aes-kw", "argon2", "base64 0.22.1", "bitfields", - "block-padding 0.3.3", + "block-padding", "blowfish", "buffer-redux", "byteorder", @@ -4586,7 +4460,7 @@ dependencies = [ "camellia", "cast5", "cfb-mode", - "cipher 0.4.4", + "cipher", "const-oid 0.9.6", "crc24", "curve25519-dalek", @@ -4608,7 +4482,7 @@ dependencies = [ "idea", "k256", "log", - "md-5 0.10.6", + "md-5", "memchr", "nom", "num-bigint-dig", @@ -5003,7 +4877,6 @@ version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" dependencies = [ - "chacha20", "getrandom 0.4.3", "rand_core 0.10.1", ] @@ -5048,12 +4921,6 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08" -[[package]] -name = "rangemap" -version = "1.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a611d15b50743feb4c76b7d03edcb0e64f399c26961e4efe6975bc398be6aa3d" - [[package]] name = "raw-window-handle" version = "0.6.2" @@ -5406,7 +5273,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -5473,7 +5340,7 @@ dependencies = [ "security-framework 3.7.0", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -5590,8 +5457,8 @@ version = "4.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e4d35ad99a181be0a60ffcbe85d680d98f87bdc4d7644ade319b87076b9dbfd4" dependencies = [ - "aes 0.8.4", - "cbc 0.1.2", + "aes", + "cbc", "futures-util", "generic-array", "hkdf", @@ -6562,7 +6429,7 @@ dependencies = [ "solidcraft-viewport", "sysinfo", "web-time", - "weezl 0.1.12", + "weezl", ] [[package]] @@ -6632,7 +6499,6 @@ dependencies = [ "getrandom 0.2.17", "image", "log", - "lopdf", "minisign-verify", "nix 0.31.3", "pollster 0.4.0", @@ -6852,17 +6718,6 @@ dependencies = [ "float-cmp", ] -[[package]] -name = "stringprep" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" -dependencies = [ - "unicode-bidi", - "unicode-normalization", - "unicode-properties", -] - [[package]] name = "strsim" version = "0.11.1" @@ -6981,10 +6836,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.3.4", + "getrandom 0.4.3", "once_cell", "rustix 1.1.6", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -7046,7 +6901,7 @@ dependencies = [ "flate2", "half", "quick-error", - "weezl 0.1.12", + "weezl", "zune-jpeg", ] @@ -7250,7 +7105,7 @@ version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a78e83a30223c757c3947cd144a31014ff04298d8719ae10d03c31c0448c8013" dependencies = [ - "cipher 0.4.4", + "cipher", ] [[package]] @@ -7294,7 +7149,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" dependencies = [ "memoffset", "tempfile", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -8126,12 +7981,6 @@ version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" -[[package]] -name = "weezl" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4ca08e5ef825b65b056d9efbd95c8750683f0a6d0466d02e96dc2e4e360f3d2" - [[package]] name = "wgpu" version = "30.0.2" @@ -8343,7 +8192,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -8717,7 +8566,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d6f32a0ff4a9f6f01231eb2059cc85479330739333e0e58cadf03b6af2cca10" dependencies = [ "cfg-if", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] diff --git a/apps/solidcraft/src/main.rs b/apps/solidcraft/src/main.rs index 42f91946b15..8de4e0674d6 100644 --- a/apps/solidcraft/src/main.rs +++ b/apps/solidcraft/src/main.rs @@ -1004,6 +1004,15 @@ impl DialogFolder { Some(picked.path().to_string_lossy().into_owned()) } + /// A dialog's answer of several files as paths, their folder remembered for the next dialog. + fn answer_all(&self, picked: Option>) -> Vec { + let picked = picked.unwrap_or_default(); + if let Some(first) = picked.first() { + self.chosen(first.path()); + } + picked.iter().map(|p| p.path().to_string_lossy().into_owned()).collect() + } + /// A file was chosen in a dialog of this kind: remember its folder for the next one. fn picked(&self, kind: DialogKind, file: &std::path::Path) { self.chosen(file); @@ -1059,6 +1068,19 @@ impl DialogFolder { } } +/// Extensions as given and in lower and upper case, each once (Linux dialogs match case). +fn any_case(exts: &[&str]) -> Vec { + let mut all: Vec = Vec::new(); + for e in exts { + for v in [e.to_string(), e.to_ascii_lowercase(), e.to_ascii_uppercase()] { + if !all.contains(&v) { + all.push(v); + } + } + } + all +} + /// Linux file dialogs match patterns by case, so each extension goes in as lower and upper /// case, plus FreeCAD's own mixed casing. fn case_variants(exts: &[&str]) -> Vec { @@ -1128,8 +1150,15 @@ fn services(cc: &eframe::CreationContext<'_>, folder: &DialogFolder) -> Services let open_parent = parent.clone(); let program_parent = parent.clone(); let file_parent = parent.clone(); + let files_parent = parent.clone(); + let folders_parent = parent.clone(); let folder_parent = parent.clone(); + #[cfg(target_os = "macos")] + let any_parent = parent.clone(); let (open_folder, file_folder, save_folder, browse_folder) = (folder.clone(), folder.clone(), folder.clone(), folder.clone()); + let (files_folder, folders_folder) = (folder.clone(), folder.clone()); + #[cfg(target_os = "macos")] + let any_folder = folder.clone(); Services { pick_open: Some(Box::new(move |first: &[&str]| { // The chooser that opens may not be the desktop's own (#10159). @@ -1164,20 +1193,43 @@ fn services(cc: &eframe::CreationContext<'_>, folder: &DialogFolder) -> Services // One kind of file (the agent chat's attachments): only the types it names, as given and in // lower and upper case (Linux dialogs match case; macOS allows just the listed types). pick_file: Some(Box::new(move |label: &str, exts: &[&str]| { - let mut all: Vec = Vec::new(); - for e in exts { - for v in [e.to_string(), e.to_ascii_lowercase(), e.to_ascii_uppercase()] { - if !all.contains(&v) { - all.push(v); - } - } - } + let all = any_case(exts); let all: Vec<&str> = all.iter().map(String::as_str).collect(); // Any other file attaches by reference, so the list is not the only choice. let future = file_folder.start(DialogKind::Open, file_parent.clone()).add_filter(label, &all).add_filter("All files", &["*"]).pick_file(); let folder = file_folder.clone(); Box::pin(async move { folder.answer(DialogKind::Open, future.await) }) })), + // Several files at once (the agent chat's attachments: a batch of photos): only the types + // named, as `pick_file` lists them (for an endpoint, which is refused any other); with none + // named (for a coding agent, which reads any file itself), any file. + pick_files: Some(Box::new(move |label: &str, exts: &[&str]| { + let mut dialog = files_folder.start(DialogKind::Open, files_parent.clone()); + if !exts.is_empty() { + let all = any_case(exts); + let all: Vec<&str> = all.iter().map(String::as_str).collect(); + dialog = dialog.add_filter(label, &all); + } + let future = dialog.pick_files(); + let folder = files_folder.clone(); + Box::pin(async move { folder.answer_all(future.await) }) + })), + // Several folders at once (the agent chat attaches them by path). + pick_folders: Some(Box::new(move || { + let future = folders_folder.start(DialogKind::Open, folders_parent.clone()).pick_folders(); + let folder = folders_folder.clone(); + Box::pin(async move { folder.answer_all(future.await) }) + })), + // macOS's open panel chooses files and folders together; Windows' and Linux's dialogs + // choose one or the other, so there the chat offers both. + #[cfg(target_os = "macos")] + pick_files_or_folders: Some(Box::new(move || { + let future = any_folder.start(DialogKind::Open, any_parent.clone()).pick_files_or_folders(); + let folder = any_folder.clone(); + Box::pin(async move { folder.answer_all(future.await) }) + })), + #[cfg(not(target_os = "macos"))] + pick_files_or_folders: None, pick_program: Some(Box::new(move || { let dialog = program_parent.clone().set_title("Choose your slicer"); let dialog = if cfg!(target_os = "windows") { dialog.add_filter("Programs", &["exe"]) } else { dialog }; diff --git a/assets/locales/ar.json b/assets/locales/ar.json index 976005bf5c0..8c9f74009a4 100644 --- a/assets/locales/ar.json +++ b/assets/locales/ar.json @@ -6401,7 +6401,7 @@ "ui.add_parameter": "إضافة معامل", "ui.agent_chat": "محادثة الوكيل", "ui.agent_chat_add": "إرفاق ملفات", - "ui.agent_chat_add_file": "اختر ملفًا…", + "ui.agent_chat_add_file": "اختر ملفات…", "ui.agent_chat_allow": "سماح", "ui.agent_chat_allow_once": "السماح مرة واحدة", "ui.agent_chat_allowed": "مسموح", diff --git a/assets/locales/de.json b/assets/locales/de.json index ca0027283ce..a2c9f127440 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -6389,7 +6389,7 @@ "ui.add_parameter": "Parameter hinzufügen", "ui.agent_chat": "Agenten-Chat", "ui.agent_chat_add": "Dateien anhängen", - "ui.agent_chat_add_file": "Datei auswählen…", + "ui.agent_chat_add_file": "Dateien auswählen…", "ui.agent_chat_allow": "Erlauben", "ui.agent_chat_allow_once": "Einmal erlauben", "ui.agent_chat_allowed": "Erlaubt", diff --git a/assets/locales/en.json b/assets/locales/en.json index 93949b76c8f..2eec1b417dc 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -6401,7 +6401,7 @@ "ui.add_parameter": "Add parameter", "ui.agent_chat": "Agent chat", "ui.agent_chat_add": "Attach files", - "ui.agent_chat_add_file": "Choose a file…", + "ui.agent_chat_add_file": "Choose files…", "ui.agent_chat_allow": "Allow", "ui.agent_chat_allow_once": "Allow once", "ui.agent_chat_allowed": "Allowed", diff --git a/assets/locales/es.json b/assets/locales/es.json index c91921c5ff8..44acfe167d8 100644 --- a/assets/locales/es.json +++ b/assets/locales/es.json @@ -5827,7 +5827,7 @@ "ui.add_parameter": "Añadir parámetro", "ui.agent_chat": "Chat del agente", "ui.agent_chat_add": "Adjuntar archivos", - "ui.agent_chat_add_file": "Elegir un archivo…", + "ui.agent_chat_add_file": "Elegir archivos…", "ui.agent_chat_allow": "Permitir", "ui.agent_chat_allow_once": "Permitir una vez", "ui.agent_chat_allowed": "Permitido", diff --git a/assets/locales/fr.json b/assets/locales/fr.json index 644e5f9a91d..7eda53697b0 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -5973,7 +5973,7 @@ "ui.add_parameter": "Ajouter un paramètre", "ui.agent_chat": "Chat de l'agent", "ui.agent_chat_add": "Joindre des fichiers", - "ui.agent_chat_add_file": "Choisir un fichier…", + "ui.agent_chat_add_file": "Choisir des fichiers…", "ui.agent_chat_allow": "Autoriser", "ui.agent_chat_allow_once": "Autoriser une fois", "ui.agent_chat_allowed": "Autorisé", diff --git a/assets/locales/he.json b/assets/locales/he.json index 2596ec3ba84..6fa55611e14 100644 --- a/assets/locales/he.json +++ b/assets/locales/he.json @@ -6401,7 +6401,7 @@ "ui.add_parameter": "הוספת פרמטר", "ui.agent_chat": "צ'אט עם סוכן", "ui.agent_chat_add": "צירוף קבצים", - "ui.agent_chat_add_file": "בחירת קובץ…", + "ui.agent_chat_add_file": "בחירת קבצים…", "ui.agent_chat_allow": "התרה", "ui.agent_chat_allow_once": "התרה פעם אחת", "ui.agent_chat_allowed": "הותר", diff --git a/assets/locales/pending/agent-chat-files-by-place.json b/assets/locales/pending/agent-chat-files-by-place.json new file mode 100644 index 00000000000..84cfffebbfd --- /dev/null +++ b/assets/locales/pending/agent-chat-files-by-place.json @@ -0,0 +1,114 @@ +{ + "en": { + "ui.agent_chat_add_folder": "Choose folders…", + "ui.agent_chat_add_folder_tip": "A folder goes to the agent as its path: the agent reads the files it needs with its own tools", + "ui.agent_chat_folder_tip": "A folder: the agent is told where it is, and reads the files it needs with its own tools", + "ui.agent_chat_paste_past_max": "At most {max} files go in one message; save the picture as a file and attach that instead", + "ui.ai_auto_attached": "it reads something you attached", + "ui.agent_chat_add_any": "Choose files or folders…", + "ui.agent_chat_file_kinds_endpoint": "{name}: this agent takes only pictures (PNG, JPEG, GIF, WebP, BMP, TIFF), text files (SVG too), PDFs and CAD files (STEP, IGES, FreeCAD, Rhino, STL, 3MF, OBJ, glTF)", + "ui.agent_chat_file_pdf_too_big": "{name}: a PDF can be at most {max} MB", + "ui.ai_declined_read": "Declined: {title}. Claude Code reads only the files and folders you attach to this chat.", + "ui.ai_request_too_big": "The pictures and PDFs on this message come to {size} MB, and one request takes at most {max} MB. Remove some, or send them over several messages.", + "ui.ai_media_message_dropped": "this message and its files were taken out of the conversation; send it again to retry", + "ui.ai_unasked_read": "Stopped: Claude Code ran {tool} without asking first, so the chat couldn't check what it read. Its adapter may have changed; please report this." + }, + "ar": { + "ui.agent_chat_add_folder": "اختر مجلدات…", + "ui.agent_chat_add_folder_tip": "يُرسل المجلد إلى الوكيل بمساره: يقرأ الوكيل الملفات التي يحتاجها بأدواته الخاصة", + "ui.agent_chat_folder_tip": "مجلد: يُخبَر الوكيل بمكانه، ويقرأ الملفات التي يحتاجها بأدواته الخاصة", + "ui.agent_chat_paste_past_max": "يُرسل {max} ملفات كحد أقصى في رسالة واحدة؛ احفظ الصورة في ملف وأرفقه بدلًا منها", + "ui.ai_auto_attached": "يقرأ شيئًا أرفقته", + "ui.agent_chat_add_any": "اختر ملفات أو مجلدات…", + "ui.agent_chat_file_kinds_endpoint": "{name}: لا يقبل هذا الوكيل إلا الصور (PNG وJPEG وGIF وWebP وBMP وTIFF) والملفات النصية (وSVG أيضًا) وملفات PDF وملفات CAD (STEP وIGES وFreeCAD وRhino وSTL و3MF وOBJ وglTF)", + "ui.agent_chat_file_pdf_too_big": "{name}: يمكن أن يكون حجم ملف PDF {max} ميغابايت على الأكثر", + "ui.ai_declined_read": "تم الرفض: {title}. يقرأ Claude Code فقط الملفات والمجلدات التي ترفقها بهذه الدردشة.", + "ui.ai_request_too_big": "تبلغ الصور وملفات PDF في هذه الرسالة {size} ميغابايت، ويقبل الطلب الواحد {max} ميغابايت على الأكثر. أزل بعضها أو أرسلها على عدة رسائل.", + "ui.ai_media_message_dropped": "أُزيلت هذه الرسالة وملفاتها من المحادثة؛ أرسلها مرة أخرى لإعادة المحاولة", + "ui.ai_unasked_read": "أُوقف: شغّل Claude Code الأداة {tool} دون أن يسأل أولًا، فلم تتمكن الدردشة من التحقق مما قرأه. ربما تغيّر محوّله؛ يُرجى الإبلاغ عن ذلك." + }, + "de": { + "ui.agent_chat_add_folder": "Ordner auswählen…", + "ui.agent_chat_add_folder_tip": "Ein Ordner geht als Pfad an den Agenten: Der Agent liest die benötigten Dateien mit seinen eigenen Werkzeugen", + "ui.agent_chat_folder_tip": "Ein Ordner: Der Agent erfährt, wo er liegt, und liest die benötigten Dateien mit seinen eigenen Werkzeugen", + "ui.agent_chat_paste_past_max": "Höchstens {max} Dateien pro Nachricht; speichern Sie das Bild als Datei und hängen Sie diese an", + "ui.ai_auto_attached": "es liest etwas, das Sie angehängt haben", + "ui.agent_chat_add_any": "Dateien oder Ordner auswählen…", + "ui.agent_chat_file_kinds_endpoint": "{name}: Dieser Agent nimmt nur Bilder (PNG, JPEG, GIF, WebP, BMP, TIFF), Textdateien (auch SVG), PDFs und CAD-Dateien (STEP, IGES, FreeCAD, Rhino, STL, 3MF, OBJ, glTF) an", + "ui.agent_chat_file_pdf_too_big": "{name}: Eine PDF darf höchstens {max} MB groß sein", + "ui.ai_declined_read": "Abgelehnt: {title}. Claude Code liest nur die Dateien und Ordner, die Sie diesem Chat anhängen.", + "ui.ai_request_too_big": "Die Bilder und PDFs dieser Nachricht umfassen {size} MB, eine Anfrage darf höchstens {max} MB enthalten. Entfernen Sie einige oder senden Sie sie auf mehrere Nachrichten verteilt.", + "ui.ai_media_message_dropped": "diese Nachricht und ihre Dateien wurden aus dem Gespräch entfernt; senden Sie sie erneut, um es noch einmal zu versuchen", + "ui.ai_unasked_read": "Angehalten: Claude Code hat {tool} ausgeführt, ohne vorher zu fragen, daher konnte der Chat nicht prüfen, was es gelesen hat. Sein Adapter hat sich möglicherweise geändert; bitte melden Sie das." + }, + "he": { + "ui.agent_chat_add_folder": "בחירת תיקיות…", + "ui.agent_chat_add_folder_tip": "תיקייה נשלחת לסוכן לפי הנתיב שלה: הסוכן קורא את הקבצים שהוא צריך בכלים שלו", + "ui.agent_chat_folder_tip": "תיקייה: הסוכן מקבל את מיקומה, וקורא את הקבצים שהוא צריך בכלים שלו", + "ui.agent_chat_paste_past_max": "לכל היותר {max} קבצים בהודעה אחת; יש לשמור את התמונה כקובץ ולצרף אותו במקומה", + "ui.ai_auto_attached": "הוא קורא משהו שצירפת", + "ui.agent_chat_add_any": "בחירת קבצים או תיקיות…", + "ui.agent_chat_file_kinds_endpoint": "{name}: הסוכן הזה מקבל רק תמונות (PNG, JPEG, GIF, WebP, BMP, TIFF), קובצי טקסט (גם SVG), קובצי PDF וקובצי CAD (STEP, IGES, FreeCAD, Rhino, STL, 3MF, OBJ, glTF)", + "ui.agent_chat_file_pdf_too_big": "{name}: קובץ PDF יכול להיות לכל היותר {max} MB", + "ui.ai_declined_read": "נדחה: {title}. Claude Code קורא רק את הקבצים והתיקיות שצירפת לצ'אט הזה.", + "ui.ai_request_too_big": "התמונות וקובצי ה-PDF בהודעה הזו מגיעים ל-{size} MB, ובקשה אחת יכולה להכיל לכל היותר {max} MB. הסר חלק מהם או שלח אותם בכמה הודעות.", + "ui.ai_media_message_dropped": "ההודעה הזו והקבצים שלה הוצאו מהשיחה; שלח אותה שוב כדי לנסות שוב", + "ui.ai_unasked_read": "נעצר: Claude Code הפעיל את {tool} בלי לשאול קודם, ולכן הצ'אט לא יכול היה לבדוק מה הוא קרא. ייתכן שהמתאם שלו השתנה; נא לדווח על כך." + }, + "ja": { + "ui.agent_chat_add_folder": "フォルダーを選択…", + "ui.agent_chat_add_folder_tip": "フォルダーはパスとしてエージェントに渡されます。必要なファイルはエージェントが自分のツールで読み込みます", + "ui.agent_chat_folder_tip": "フォルダー: 場所がエージェントに伝えられ、必要なファイルはエージェントが自分のツールで読み込みます", + "ui.agent_chat_paste_past_max": "1 つのメッセージで送れるファイルは {max} 個までです。画像をファイルとして保存し、そのファイルを添付してください", + "ui.ai_auto_attached": "添付したものを読み込むため", + "ui.agent_chat_add_any": "ファイルまたはフォルダーを選択…", + "ui.agent_chat_file_kinds_endpoint": "{name}: このエージェントが受け付けるのは画像(PNG、JPEG、GIF、WebP、BMP、TIFF)、テキストファイル(SVG を含む)、PDF、CAD ファイル(STEP、IGES、FreeCAD、Rhino、STL、3MF、OBJ、glTF)だけです", + "ui.agent_chat_file_pdf_too_big": "{name}: PDF は {max} MB までです", + "ui.ai_declined_read": "拒否しました: {title}。Claude Code が読むのは、このチャットに添付したファイルとフォルダーだけです。", + "ui.ai_request_too_big": "このメッセージの画像と PDF は合計 {size} MB ですが、1 回のリクエストに入れられるのは最大 {max} MB です。いくつか外すか、複数のメッセージに分けて送ってください。", + "ui.ai_media_message_dropped": "このメッセージとそのファイルは会話から外されました。もう一度送ると再試行できます", + "ui.ai_unasked_read": "停止しました: Claude Code が先に確認せずに {tool} を実行したため、チャットは読み取った内容を確認できませんでした。アダプターが変更された可能性があります。報告してください。" + }, + "ko": { + "ui.agent_chat_add_folder": "폴더 선택…", + "ui.agent_chat_add_folder_tip": "폴더는 경로로 에이전트에게 전달됩니다. 에이전트가 필요한 파일을 자체 도구로 읽습니다", + "ui.agent_chat_folder_tip": "폴더: 위치가 에이전트에게 전달되고, 에이전트가 필요한 파일을 자체 도구로 읽습니다", + "ui.agent_chat_paste_past_max": "메시지 하나에는 파일을 최대 {max}개까지 보낼 수 있습니다. 그림을 파일로 저장한 뒤 그 파일을 첨부하세요", + "ui.ai_auto_attached": "첨부한 항목을 읽음", + "ui.agent_chat_add_any": "파일 또는 폴더 선택…", + "ui.agent_chat_file_kinds_endpoint": "{name}: 이 에이전트는 사진(PNG, JPEG, GIF, WebP, BMP, TIFF), 텍스트 파일(SVG 포함), PDF, CAD 파일(STEP, IGES, FreeCAD, Rhino, STL, 3MF, OBJ, glTF)만 받습니다", + "ui.agent_chat_file_pdf_too_big": "{name}: PDF는 최대 {max}MB까지입니다", + "ui.ai_declined_read": "거부됨: {title}. Claude Code는 이 채팅에 첨부한 파일과 폴더만 읽습니다.", + "ui.ai_request_too_big": "이 메시지의 그림과 PDF는 {size}MB인데, 요청 하나에는 최대 {max}MB까지 담을 수 있습니다. 일부를 빼거나 여러 메시지로 나누어 보내세요.", + "ui.ai_media_message_dropped": "이 메시지와 파일은 대화에서 빠졌습니다. 다시 시도하려면 다시 보내세요", + "ui.ai_unasked_read": "중지됨: Claude Code가 먼저 묻지 않고 {tool}을(를) 실행해서 채팅이 무엇을 읽었는지 확인할 수 없었습니다. 어댑터가 바뀌었을 수 있으니 신고해 주세요." + }, + "vi": { + "ui.agent_chat_add_folder": "Chọn thư mục…", + "ui.agent_chat_add_folder_tip": "Thư mục được gửi tới AI Agent theo đường dẫn: AI Agent đọc các tệp cần thiết bằng công cụ của mình", + "ui.agent_chat_folder_tip": "Một thư mục: AI Agent được cho biết nó nằm ở đâu, rồi đọc các tệp cần thiết bằng công cụ của mình", + "ui.agent_chat_paste_past_max": "Tối đa {max} tệp trong một tin nhắn; hãy lưu hình ảnh thành tệp rồi đính kèm tệp đó", + "ui.ai_auto_attached": "nó đọc thứ bạn đã đính kèm", + "ui.agent_chat_add_any": "Chọn tệp hoặc thư mục…", + "ui.agent_chat_file_kinds_endpoint": "{name}: tác nhân này chỉ nhận hình ảnh (PNG, JPEG, GIF, WebP, BMP, TIFF), tệp văn bản (cả SVG), PDF và tệp CAD (STEP, IGES, FreeCAD, Rhino, STL, 3MF, OBJ, glTF)", + "ui.agent_chat_file_pdf_too_big": "{name}: PDF chỉ được tối đa {max} MB", + "ui.ai_declined_read": "Đã từ chối: {title}. Claude Code chỉ đọc các tệp và thư mục bạn đính kèm vào cuộc trò chuyện này.", + "ui.ai_request_too_big": "Hình ảnh và PDF trong tin nhắn này tổng cộng {size} MB, mà một yêu cầu chỉ chứa tối đa {max} MB. Hãy bỏ bớt, hoặc gửi chúng qua nhiều tin nhắn.", + "ui.ai_media_message_dropped": "tin nhắn này và các tệp của nó đã bị đưa ra khỏi cuộc trò chuyện; hãy gửi lại để thử lại", + "ui.ai_unasked_read": "Đã dừng: Claude Code đã chạy {tool} mà không hỏi trước, nên cuộc trò chuyện không thể kiểm tra những gì nó đã đọc. Bộ điều hợp của nó có thể đã thay đổi; vui lòng báo cáo lỗi này." + }, + "zh": { + "ui.agent_chat_add_folder": "选择文件夹…", + "ui.agent_chat_add_folder_tip": "文件夹以路径形式交给智能体:智能体用自己的工具读取所需的文件", + "ui.agent_chat_folder_tip": "文件夹:智能体会得知它的位置,并用自己的工具读取所需的文件", + "ui.agent_chat_paste_past_max": "一条消息最多发送 {max} 个文件;请把图片另存为文件,再附加该文件", + "ui.ai_auto_attached": "它读取的是你附加的内容", + "ui.agent_chat_add_any": "选择文件或文件夹…", + "ui.agent_chat_file_kinds_endpoint": "{name}:此代理只接受图片(PNG、JPEG、GIF、WebP、BMP、TIFF)、文本文件(包括 SVG)、PDF 和 CAD 文件(STEP、IGES、FreeCAD、Rhino、STL、3MF、OBJ、glTF)", + "ui.agent_chat_file_pdf_too_big": "{name}:PDF 最大为 {max} MB", + "ui.ai_declined_read": "已拒绝:{title}。Claude Code 只读取你附加到本次聊天的文件和文件夹。", + "ui.ai_request_too_big": "这条消息中的图片和 PDF 共 {size} MB,而一次请求最多只能包含 {max} MB。请移除一些,或分几条消息发送。", + "ui.ai_media_message_dropped": "这条消息及其文件已从对话中移除;重新发送即可重试", + "ui.ai_unasked_read": "已停止:Claude Code 未先询问就运行了 {tool},因此聊天无法检查它读取了什么。它的适配器可能已更改;请报告此问题。" + } +} diff --git a/assets/locales/vi.json b/assets/locales/vi.json index fbea161811d..968f04a7d5d 100644 --- a/assets/locales/vi.json +++ b/assets/locales/vi.json @@ -6401,7 +6401,7 @@ "ui.add_parameter": "Thêm tham số", "ui.agent_chat": "Trò chuyện với AI Agent", "ui.agent_chat_add": "Đính kèm tệp", - "ui.agent_chat_add_file": "Chọn một tệp…", + "ui.agent_chat_add_file": "Chọn tệp…", "ui.agent_chat_allow": "Cho phép", "ui.agent_chat_allow_once": "Cho phép một lần", "ui.agent_chat_allowed": "Đã cho phép", diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 815f0baafa8..8a5f1773feb 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -97,7 +97,6 @@ quote = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] arboard = { version = "3.6", default-features = false, features = ["image-data"] } fontdb = { workspace = true } -lopdf = { version = "0.45", default-features = false } # Waits for wgpu error scopes when a plugin background effect is built. pollster = { workspace = true } diff --git a/crates/ui-egui/src/agent_chat/acp.rs b/crates/ui-egui/src/agent_chat/acp.rs index 8d1c6c1fe79..43f7ecfe111 100644 --- a/crates/ui-egui/src/agent_chat/acp.rs +++ b/crates/ui-egui/src/agent_chat/acp.rs @@ -173,6 +173,51 @@ pub fn is_bridge_tool(title: &str, kind: Option<&str>) -> bool { named && matches!(kind, None | Some("other")) } +/// The file or folder a permission question would read, when it asks for one of Claude Code's own +/// read tools ([`CLAUDE_ASK_TOOLS`]) as the Claude adapter forms such a question: `Read ` of +/// kind `read` with `rawInput.file_path`; `Find …` of kind `search` (Glob) with `rawInput.path`; +/// `grep …` of kind `search` with `rawInput.path` (or `file_path`). The path must be absolute; a +/// Glob pattern or Grep glob must be relative with no `..` (it could reach out of the folder +/// otherwise); an MCP tool's question (`_meta.claudeCode.mcpServer`) never counts. Anything else is +/// `None`, and the question goes to the user as before. +pub fn read_path(call: &Value) -> Option { + if call.pointer("/_meta/claudeCode/mcpServer").is_some() { + return None; + } + let title = call.get("title")?.as_str()?; + let kind = call.get("kind")?.as_str()?; + let input = call.get("rawInput")?; + let text = |key: &str| input.get(key).and_then(Value::as_str); + // A pattern, or any of its `{a,b}` alternatives, that starts at a root or home, names a drive, or + // steps up a folder could match outside the folder it is given. + let rooted = |s: &str| s.starts_with(['/', '\\', '~']); + let inside = |glob: &str| { + !glob.is_empty() + && !glob.contains(':') + && !rooted(glob) + && !glob.split(['{', ',']).any(rooted) + && !glob.split(['/', '\\', '{', ',', '}']).any(|part| part == "..") + }; + let path = match kind { + "read" if title.starts_with("Read ") => text("file_path")?, + "search" if title.starts_with("Find") => { + if !inside(text("pattern")?) { + return None; + } + text("path")? + } + "search" if title.starts_with("grep") => { + if text("glob").is_some_and(|glob| !inside(glob)) { + return None; + } + text("path").or_else(|| text("file_path"))? + } + _ => return None, + }; + let path = std::path::PathBuf::from(path); + path.is_absolute().then_some(path) +} + /// The MCP server the agent starts to reach the design: `solidcraft-cli mcp --connect` bridged to /// this app's control port. The server finds the port's token in the token file the app wrote /// (docs/control-protocol.md), so the token never travels through the agent, and it keeps its @@ -265,7 +310,8 @@ measure, screenshot, set_parameter, undo, skill_reference) to read and change th measure or inspect_design. Before building anything beyond one primitive, read `skill_reference` for `solidcraft-modeling` (its \ SKILL.md has the workflow, its reference.md the command shapes and this version's traps), work the numbers out first, and after \ each stage compare `measure` with them. Prefer one `batch` over many small calls. Saving, opening or exporting files waits for the user's approval in \ -the chat, and each message allows a limited number of changes. Don't use shell or file tools: work through the SolidCraft tools. \ +the chat, and each message allows a limited number of changes. Don't use shell tools and don't write files: work through the SolidCraft \ +tools. Read a file or folder with your own read tools only when the user attached it by path; to read another, ask the user to attach it. \ On a drawing, make section views and their section lines with `drawing.view.section`, and dimensions with \ `drawing.dimension.add` or `drawing.dimension.from_model`, never with free sketch lines or text notes: those do not move with their \ view, cannot be selected as section lines or dimensions, and do not update the model. If a drawing object has no command, say so \ @@ -288,33 +334,53 @@ pub fn system_note(instructions: &str) -> String { /// The Claude Code adapter's own tools that reach the computer rather than the design: turned off /// for the session (`_meta.claudeCode.options.disallowedTools`), so it works through SolidCraft's. +/// Its read tools are not among them when the session is for the adapter the chat recognises +/// ([`is_claude_adapter`]): they ask instead ([`CLAUDE_ASK_TOOLS`]). pub const CLAUDE_DISALLOWED_TOOLS: &[&str] = - &["Bash", "BashOutput", "KillShell", "Read", "Write", "Edit", "MultiEdit", "NotebookEdit", "Glob", "Grep", "WebFetch", "WebSearch", "Task"]; + &["Bash", "BashOutput", "KillShell", "Write", "Edit", "MultiEdit", "NotebookEdit", "WebFetch", "WebSearch", "Task"]; + +/// The Claude Code adapter's read tools. They are on only in a session for the adapter the chat +/// recognises by its command ([`is_claude_adapter`], decided when the agent starts), and there +/// every call asks (a `permissions.ask` rule in the session's settings), so the question reaches +/// the panel: the chat allows it by itself for a path the user attached by path to this +/// conversation ([`read_path`]) and declines any other, whatever the mode. Any other session keeps +/// them off, so an adapter started some other way (a wrapper script, `node …/dist/index.js`) +/// reads nothing. +pub const CLAUDE_ASK_TOOLS: &[&str] = &["Read", "Glob", "Grep"]; /// The Claude Code adapter's built-in tools the session has (`_meta.claudeCode.options.tools`): /// only these, so a tool a later Claude Code adds (or one the list above doesn't name, such as its /// schedulers and message senders) stays off (#19554). `ExitPlanMode` is how the agent leaves the -/// plan mode the panel's mode picker offers; it only asks. [`CLAUDE_DISALLOWED_TOOLS`] stays as a -/// second guard. +/// plan mode the panel's mode picker offers; it only asks. The read tools ([`CLAUDE_ASK_TOOLS`]) +/// join them only in a session for the adapter the chat recognises. [`CLAUDE_DISALLOWED_TOOLS`] +/// stays as a second guard. pub const CLAUDE_TOOLS: &[&str] = &["ExitPlanMode"]; /// The `session/new` parameters. `init` is the agent's `initialize` reply: agents read the system /// note from different places (#9811), and the standard field may only go to an agent offering it. -/// `note` is the system note ([`system_note`]). -pub fn session_new_params(cwd: &std::path::Path, bridge: Option<&McpBridge>, init: &Value, note: &str) -> Value { +/// `note` is the system note ([`system_note`]). `claude`: the agent was recognised as Claude Code's +/// adapter when it started ([`is_claude_adapter`]), so its read tools are on, behind the ask rule. +pub fn session_new_params(cwd: &std::path::Path, bridge: Option<&McpBridge>, init: &Value, note: &str, claude: bool) -> Value { let servers: Vec = bridge.map(McpBridge::to_json).into_iter().collect(); + let (tools, off): (Vec<&str>, Vec<&str>) = if claude { + (CLAUDE_TOOLS.iter().chain(CLAUDE_ASK_TOOLS).copied().collect(), CLAUDE_DISALLOWED_TOOLS.to_vec()) + } else { + (CLAUDE_TOOLS.to_vec(), CLAUDE_DISALLOWED_TOOLS.iter().chain(CLAUDE_ASK_TOOLS).copied().collect()) + }; let mut meta = json!({ // The Claude adapter's own key, for its versions without the standard field. "systemPrompt": {"append": note}, // Hosts may opt a session out of "bypass permissions" (the Claude adapter reads it): // every tool call the agent asks about reaches the panel. - // Its own shell and file tools are off: the agent works through SolidCraft's tools. - // Only the MCP servers given here (`strictMcpConfig`): not the user's claude.ai + // Its own shell and write tools are off: the agent works through SolidCraft's tools. Its + // read tools ask, so the chat sees every read, or are off too when the adapter wasn't + // recognised. Only the MCP servers given here (`strictMcpConfig`): not the user's claude.ai // connectors, nor the servers in their own Claude Code configuration (#19554). "claudeCode": {"options": { "allowDangerouslySkipPermissions": false, - "disallowedTools": CLAUDE_DISALLOWED_TOOLS, - "tools": CLAUDE_TOOLS, + "disallowedTools": off, + "tools": tools, + "settings": {"permissions": {"ask": CLAUDE_ASK_TOOLS}}, "strictMcpConfig": true, }}, }); @@ -336,6 +402,65 @@ pub fn session_new_params(cwd: &std::path::Path, bridge: Option<&McpBridge>, ini params } +/// The agent is Claude Code's ACP adapter, the one agent whose own tools SolidCraft turns off or +/// limits: its program (or the package `npx` starts) is `claude-agent-acp` or the older +/// `claude-code-acp`. +pub fn is_claude_adapter(argv: &[String]) -> bool { + argv.iter().any(|arg| { + let name = arg.rsplit(['/', '\\']).next().unwrap_or(arg); + name.starts_with("claude-agent-acp") || name.starts_with("claude-code-acp") + }) +} + +/// Claude Code's own tool calls in the running turn, by id: which of its tools each one is (the +/// adapter names it in `_meta.claudeCode.toolName` on the call's updates) and which asked first. +/// With it a question about one of Claude Code's read tools is known as such whatever command +/// started the adapter, and a read that completes without having asked is caught: the ask rule +/// ([`CLAUDE_ASK_TOOLS`]) is what lets the chat check every read, and an adapter that stopped +/// honouring it must not go unnoticed. +#[derive(Debug, Default)] +pub struct ClaudeCalls { + tools: std::collections::HashMap, + asked: std::collections::HashSet, +} + +impl ClaudeCalls { + /// More calls than any turn makes; past it, nothing new is recorded and nothing is caught. + const MAX: usize = 4096; + + /// An update of call `id` (`tool`: the Claude tool it names, `status`: its new status). + /// `Some(tool)` the first time one of Claude Code's read tools completes without having asked. + pub fn update(&mut self, id: &str, tool: Option<&str>, status: Option) -> Option { + if let Some(tool) = tool + && (self.tools.len() < Self::MAX || self.tools.contains_key(id)) + { + self.tools.insert(id.to_string(), tool.to_string()); + } + let unasked = status == Some(ToolStatus::Completed) + && self.asked.len() < Self::MAX + && !self.asked.contains(id) + && self.tools.get(id).is_some_and(|tool| CLAUDE_ASK_TOOLS.contains(&tool.as_str())); + if unasked { self.tools.remove(id) } else { None } + } + + /// A question about call `id` (`tool`: the Claude tool the question itself names): the Claude + /// tool it is about, from the question or from the call's updates. + pub fn question(&mut self, id: Option<&str>, tool: Option<&str>) -> Option { + if let Some(id) = id + && self.asked.len() < Self::MAX + { + self.asked.insert(id.to_string()); + } + tool.map(str::to_string).or_else(|| id.and_then(|id| self.tools.get(id)).cloned()) + } + + /// A new turn: the last one's calls are done. + pub fn clear(&mut self) { + self.tools.clear(); + self.asked.clear(); + } +} + /// The agent offers ACP's `systemPrompt` field on its sessions. fn takes_standard_note(init: &Value) -> bool { init.pointer("/agentCapabilities/sessionCapabilities/systemPrompt").is_some_and(|offer| !offer.is_null()) @@ -552,6 +677,9 @@ pub enum Incoming { status: Option, input: Option, output: Option, + /// Which of Claude Code's own tools it is (`_meta.claudeCode.toolName`), when the Claude + /// adapter says. + claude_tool: Option, }, /// The agent's plan: each entry with its status. Plan { @@ -565,6 +693,13 @@ pub enum Incoming { /// The tool call's kind (`execute`, `edit`, `other`, …), as the agent gives it. kind: Option, options: Vec, + /// The path it would read, when it is one of Claude Code's own read tools ([`read_path`]). + reads: Option, + /// The tool call it asks about (`toolCall.toolCallId`). + call: Option, + /// Which of Claude Code's own tools it is, when the question says + /// (`toolCall._meta.claudeCode.toolName`; the adapter gives it only for some). + claude_tool: Option, }, /// The agent says whether it is logged in (an extension both adapters send). AuthStatus(String), @@ -654,7 +789,10 @@ pub fn parse(line: &str) -> Option { .collect() }) .unwrap_or_default(); - Some(Incoming::Permission { rpc: id.clone(), title, kind, options }) + let reads = call.and_then(read_path); + let text = |pointer: &str| call.and_then(|c| c.pointer(pointer)).and_then(Value::as_str).map(str::to_string); + let (claude_tool, call) = (text("/_meta/claudeCode/toolName"), text("/toolCallId")); + Some(Incoming::Permission { rpc: id.clone(), title, kind, options, reads, call, claude_tool }) } (Some(m), Some(id)) => Some(Incoming::Unsupported { rpc: id.clone(), method: m.to_string() }), (Some("session/update"), None) => Some(update(params.get("update")?, params.get("sessionId").and_then(Value::as_str).unwrap_or(""))), @@ -681,6 +819,7 @@ fn update(u: &Value, session: &str) -> Incoming { // ACP's `rawInput`: the arguments the tool was called with. input: u.get("rawInput").filter(|v| v.is_object()).cloned(), output: tool_output(u), + claude_tool: u.pointer("/_meta/claudeCode/toolName").and_then(Value::as_str).map(str::to_string), }, None => Incoming::Ignored, }, @@ -852,7 +991,7 @@ mod tests { #[test] fn the_session_gets_the_bridged_mcp_server_without_a_token_or_any_path() { let b = McpBridge { cli: "/opt/solidcraft/solidcraft-cli".into(), port: 41234, allow_paths: Vec::new() }; - let p = session_new_params(std::path::Path::new("/home/u/designs"), Some(&b), &json!({}), SYSTEM_NOTE); + let p = session_new_params(std::path::Path::new("/home/u/designs"), Some(&b), &json!({}), SYSTEM_NOTE, true); let s = &p["mcpServers"][0]; assert_eq!(s["name"], BRIDGE_NAME); assert_eq!(s["args"], json!(["mcp", "--connect", "127.0.0.1:41234"])); @@ -867,7 +1006,7 @@ mod tests { let text = p.to_string(); assert!(!text.contains("allow-any-path") && !text.contains("TOKEN"), "{text}"); assert!(p["_meta"]["claudeCode"]["options"]["disallowedTools"].as_array().is_some_and(|t| t.iter().any(|x| x == "Bash"))); - assert_eq!(session_new_params(std::path::Path::new("/tmp"), None, &json!({}), SYSTEM_NOTE)["mcpServers"], json!([])); + assert_eq!(session_new_params(std::path::Path::new("/tmp"), None, &json!({}), SYSTEM_NOTE, true)["mcpServers"], json!([])); } #[test] @@ -877,7 +1016,7 @@ mod tests { port: 41234, allow_paths: vec![" /work/cad ".into(), "".into(), "/work/shared".into()], }; - let p = session_new_params(std::path::Path::new("/home/u/designs"), Some(&b), &json!({}), SYSTEM_NOTE); + let p = session_new_params(std::path::Path::new("/home/u/designs"), Some(&b), &json!({}), SYSTEM_NOTE, true); assert_eq!( p["mcpServers"][0]["args"], json!(["mcp", "--connect", "127.0.0.1:41234", "--allow-path", "/work/cad", "--allow-path", "/work/shared"]) @@ -887,15 +1026,17 @@ mod tests { /// #19554: Claude Code gets only the chat's MCP server, none of the user's claude.ai connectors /// or own servers (`strictMcpConfig`), and only the built-in tools the chat names (`tools`), - /// none of which the disallowed list turns off. + /// none of which the disallowed list turns off: its read tools only when the adapter was + /// recognised (#16458). #[test] fn claude_code_gets_only_the_chats_server_and_named_tools() { let b = McpBridge { cli: "/opt/solidcraft/solidcraft-cli".into(), port: 41234, allow_paths: Vec::new() }; - for bridge in [Some(&b), None] { - let p = session_new_params(std::path::Path::new("/tmp"), bridge, &json!({}), SYSTEM_NOTE); + for (bridge, claude) in [(Some(&b), true), (None, true), (None, false)] { + let p = session_new_params(std::path::Path::new("/tmp"), bridge, &json!({}), SYSTEM_NOTE, claude); let options = &p["_meta"]["claudeCode"]["options"]; assert_eq!(options["strictMcpConfig"], json!(true), "{p}"); - assert_eq!(options["tools"], json!(["ExitPlanMode"]), "{p}"); + let tools = if claude { json!(["ExitPlanMode", "Read", "Glob", "Grep"]) } else { json!(["ExitPlanMode"]) }; + assert_eq!(options["tools"], tools, "{p}"); assert!(CLAUDE_TOOLS.iter().all(|t| !CLAUDE_DISALLOWED_TOOLS.contains(t))); assert_eq!(p["mcpServers"].as_array().map(Vec::len), Some(usize::from(bridge.is_some()))); } @@ -907,7 +1048,7 @@ mod tests { fn the_system_note_takes_every_route_the_agent_offers() { // With the user's custom instructions (#8220), which go wherever the note goes. let note = system_note("Sketch on XZ with explicit plane vectors."); - let params = |init: Value| session_new_params(std::path::Path::new("/tmp"), None, &init, ¬e); + let params = |init: Value| session_new_params(std::path::Path::new("/tmp"), None, &init, ¬e, true); let standard = json!({"mode": "append", "content": [{"type": "text", "text": note}]}); let offers_standard = params(json!({"agentCapabilities": {"sessionCapabilities": {"systemPrompt": {}}}})); @@ -970,7 +1111,7 @@ mod tests { let b = McpBridge { cli: r"C:\Program Files\SolidCraft\solidcraft-cli.exe".into(), port: 41234, allow_paths: vec![r"D:\Projects\CAD".into()] }; - let p = session_new_params(&wsl_path(std::path::Path::new(r"C:\Users\u\work")), Some(&b.in_wsl()), &json!({}), SYSTEM_NOTE); + let p = session_new_params(&wsl_path(std::path::Path::new(r"C:\Users\u\work")), Some(&b.in_wsl()), &json!({}), SYSTEM_NOTE, true); assert_eq!(p["cwd"], "/mnt/c/Users/u/work"); assert_eq!(p["mcpServers"][0]["command"], "/mnt/c/Program Files/SolidCraft/solidcraft-cli.exe"); assert_eq!(p["mcpServers"][0]["args"], json!(["mcp", "--connect", "127.0.0.1:41234", "--allow-path", r"D:\Projects\CAD"])); @@ -1075,13 +1216,14 @@ mod tests { kind: None, status: Some(ToolStatus::Completed), input: None, - output: Some("ok".into()) + output: Some("ok".into()), + claude_tool: None, }) ); let perm = r#"{"jsonrpc":"2.0","id":7,"method":"session/request_permission","params":{"sessionId":"s","toolCall":{"toolCallId":"t1","title":"batch"},"options":[{"optionId":"allow","name":"Allow","kind":"allow_once"},{"optionId":"reject","name":"Reject","kind":"reject_once"}]}}"#; - let Some(Incoming::Permission { rpc, title, kind, options }) = parse(perm) else { panic!() }; + let Some(Incoming::Permission { rpc, title, kind, options, reads, .. }) = parse(perm) else { panic!() }; assert_eq!((title.as_str(), options.len(), options[1].kind.as_str()), ("batch", 2, "reject_once")); - assert_eq!(kind, None); + assert_eq!((kind, reads), (None, None)); assert_eq!(permission_reply(rpc.clone(), Some("allow"))["result"]["outcome"], json!({"outcome": "selected", "optionId": "allow"})); assert_eq!(permission_reply(rpc, None)["result"]["outcome"]["outcome"], "cancelled"); let fs = r#"{"jsonrpc":"2.0","id":8,"method":"fs/read_text_file","params":{}}"#; @@ -1158,4 +1300,125 @@ mod tests { assert_eq!(config_options(&json!({"configOptions":null})), ConfigParse::Invalid); assert_eq!(config_options(&json!({"configOptions":[{"type":"select","id":"broken"}]})), ConfigParse::Invalid); } + + /// In a session for the adapter the chat recognises, Claude Code's read tools are on and ask + /// before every call; its shell, write and web tools stay off. + #[test] + fn claudes_read_tools_ask_and_its_other_tools_are_off() { + let p = session_new_params(std::path::Path::new("/tmp"), None, &json!({}), SYSTEM_NOTE, true); + let options = &p["_meta"]["claudeCode"]["options"]; + let off: Vec<&str> = options["disallowedTools"].as_array().map(|t| t.iter().filter_map(Value::as_str).collect()).unwrap_or_default(); + for tool in ["Bash", "Write", "Edit", "WebFetch", "WebSearch", "Task"] { + assert!(off.contains(&tool), "{tool} off: {off:?}"); + } + for tool in CLAUDE_ASK_TOOLS { + assert!(!off.contains(tool), "{tool} on: {off:?}"); + } + assert_eq!(options["settings"]["permissions"]["ask"], json!(["Read", "Glob", "Grep"])); + assert!(options.get("resume").is_none()); + assert!(SYSTEM_NOTE.contains("attached it by path"), "{SYSTEM_NOTE}"); + let argv = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::>(); + assert!(is_claude_adapter(&argv(&["/opt/homebrew/bin/claude-agent-acp"]))); + assert!(is_claude_adapter(&argv(&["npx", "-y", "@zed-industries/claude-code-acp"]))); + assert!(is_claude_adapter(&argv(&["C:\\npm\\claude-agent-acp.cmd"]))); + assert!(!is_claude_adapter(&argv(&["codex-acp"])) && !is_claude_adapter(&argv(&["opencode", "acp"]))); + } + + /// An agent whose command doesn't name the Claude adapter (a wrapper script, `node + /// …/dist/index.js`) keeps Claude Code's read tools off with its other tools, so the adapter + /// started that way reads nothing, whatever the mode (#16458 review). + #[test] + fn an_adapter_started_another_way_gets_no_read_tools() { + let argv = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::>(); + for command in + [&["node", "/opt/claude/node_modules/@agentclientprotocol/claude-agent-acp/dist/index.js"][..], &["/home/u/bin/claude-wrapper.sh"]] + { + assert!(!is_claude_adapter(&argv(command)), "{command:?}"); + } + let p = session_new_params(std::path::Path::new("/tmp"), None, &json!({}), SYSTEM_NOTE, false); + let options = &p["_meta"]["claudeCode"]["options"]; + let off: Vec<&str> = options["disallowedTools"].as_array().map(|t| t.iter().filter_map(Value::as_str).collect()).unwrap_or_default(); + for tool in CLAUDE_ASK_TOOLS.iter().chain(CLAUDE_DISALLOWED_TOOLS) { + assert!(off.contains(tool), "{tool} off: {off:?}"); + } + assert_eq!(options["allowDangerouslySkipPermissions"], json!(false)); + } + + /// The adapter names its own tool on a call's updates, and a question names the call: so the + /// chat knows a question about Claude Code's Read whatever started the adapter, and a read + /// that completes without having asked is caught, once (#16458 review). + #[test] + fn claude_calls_name_questions_and_catch_a_read_that_never_asked() { + let tool = json!({"jsonrpc": "2.0", "method": "session/update", "params": {"sessionId": "s", "update": { + "sessionUpdate": "tool_call", "toolCallId": "t1", "title": "Read /x", "kind": "read", "status": "pending", + "_meta": {"claudeCode": {"toolName": "Read"}}}}}); + assert!(matches!(parse(&tool.to_string()), Some(Incoming::Tool { claude_tool: Some(t), .. }) if t == "Read")); + let perm = json!({"jsonrpc": "2.0", "id": 4, "method": "session/request_permission", "params": {"sessionId": "s", + "toolCall": {"toolCallId": "t1", "title": "Read /x", "kind": "read"}, "options": []}}); + assert!(matches!(parse(&perm.to_string()), Some(Incoming::Permission { call: Some(c), claude_tool: None, .. }) if c == "t1")); + + let mut calls = ClaudeCalls::default(); + assert_eq!(calls.update("t1", Some("Read"), Some(ToolStatus::Pending)), None); + assert_eq!(calls.question(Some("t1"), None).as_deref(), Some("Read"), "named by its call"); + assert_eq!(calls.update("t1", None, Some(ToolStatus::Completed)), None, "it asked"); + assert_eq!(calls.question(Some("t9"), Some("Glob")).as_deref(), Some("Glob"), "named by the question"); + assert_eq!(calls.question(Some("t8"), None), None, "another agent's call"); + + assert_eq!(calls.update("t2", Some("Grep"), Some(ToolStatus::Pending)), None); + assert_eq!(calls.update("t2", None, Some(ToolStatus::Completed)).as_deref(), Some("Grep"), "it never asked"); + assert_eq!(calls.update("t2", None, Some(ToolStatus::Completed)), None, "caught once"); + assert_eq!(calls.update("t3", Some("mcp__solidcraft-app__batch"), Some(ToolStatus::Completed)), None, "not a read tool"); + assert_eq!(calls.update("t4", Some("Read"), Some(ToolStatus::Failed)), None, "a failed read read nothing"); + assert_eq!(calls.update("t5", None, Some(ToolStatus::Completed)), None, "another agent's call"); + calls.clear(); + assert_eq!(calls.question(Some("t1"), None), None, "a new turn"); + } + + /// Only the Claude adapter's own Read, Glob and Grep questions, with an absolute path and a + /// pattern that can't reach out of it, give a path to check; anything else goes to the user. + #[test] + fn read_questions_give_their_path_only_in_the_adapters_own_form() { + let dir = std::env::temp_dir().join("photos"); + let file = dir.join("a.jpg"); + let (d, f) = (dir.to_string_lossy().to_string(), file.to_string_lossy().to_string()); + let read = |v: Value| read_path(&v); + assert_eq!(read(json!({"title": format!("Read {f}"), "kind": "read", "rawInput": {"file_path": f}})), Some(file.clone())); + assert_eq!( + read(json!({"title": format!("Find `{d}` `*.jpg`"), "kind": "search", "rawInput": {"path": d, "pattern": "**/*.jpg"}})), + Some(dir.clone()) + ); + assert_eq!( + read(json!({"title": "grep \"x\"", "kind": "search", "rawInput": {"path": d, "pattern": "x", "glob": "*.md"}})), + Some(dir.clone()) + ); + assert_eq!( + read(json!({"title": "grep \"x\"", "kind": "search", "rawInput": {"file_path": f, "pattern": "../x"}})), + Some(file.clone()), + "a regex is no path" + ); + for refused in [ + json!({"title": "Read a.jpg", "kind": "read", "rawInput": {"file_path": "a.jpg"}}), + json!({"title": "Find", "kind": "search", "rawInput": {"path": d, "pattern": "../*"}}), + json!({"title": "Find", "kind": "search", "rawInput": {"path": d, "pattern": "x/../../*"}}), + json!({"title": "Find", "kind": "search", "rawInput": {"path": d, "pattern": "/etc/*"}}), + json!({"title": "Find", "kind": "search", "rawInput": {"path": d, "pattern": "{x,/etc/*}"}}), + json!({"title": "Find", "kind": "search", "rawInput": {"path": d, "pattern": "~/.ssh/*"}}), + json!({"title": "Find", "kind": "search", "rawInput": {"path": d, "pattern": "C:/x"}}), + json!({"title": "Find", "kind": "search", "rawInput": {"pattern": "*"}}), + json!({"title": "grep x", "kind": "search", "rawInput": {"pattern": "x"}}), + json!({"title": "grep x", "kind": "search", "rawInput": {"path": d, "pattern": "x", "glob": "../**"}}), + json!({"title": format!("Read {f}"), "kind": "edit", "rawInput": {"file_path": f}}), + json!({"title": format!("Run cat {f}"), "kind": "read", "rawInput": {"file_path": f}}), + json!({"title": format!("Read {f}"), "kind": "read", "rawInput": {"file_path": f}, "_meta": {"claudeCode": {"mcpServer": {"name": "x"}}}}), + json!({"title": format!("Read {f}"), "kind": "read"}), + json!({"title": format!("Read {f}"), "rawInput": {"file_path": f}}), + ] { + assert_eq!(read(refused.clone()), None, "{refused}"); + } + let perm = json!({ + "jsonrpc": "2.0", "id": 9, "method": "session/request_permission", + "params": {"sessionId": "s", "toolCall": {"toolCallId": "t", "title": format!("Read {f}"), "kind": "read", "rawInput": {"file_path": f}}, "options": []}, + }); + assert!(matches!(parse(&perm.to_string()), Some(Incoming::Permission { reads: Some(p), .. }) if p == file)); + } } diff --git a/crates/ui-egui/src/agent_chat/acp_client.rs b/crates/ui-egui/src/agent_chat/acp_client.rs index 731e0e018f9..38bc7f46402 100644 --- a/crates/ui-egui/src/agent_chat/acp_client.rs +++ b/crates/ui-egui/src/agent_chat/acp_client.rs @@ -82,6 +82,11 @@ pub struct AcpBackend { exited: bool, config_pending: Option<(u64, String)>, modern_config: bool, + /// The agent is Claude Code's adapter, as its command says ([`acp::is_claude_adapter`]), + /// decided once when it starts: only then are its read tools on. + claude: bool, + /// Its own tool calls in the running turn ([`acp::ClaudeCalls`]). + calls: acp::ClaudeCalls, } impl AcpBackend { @@ -119,6 +124,8 @@ impl AcpBackend { exited: false, config_pending: None, modern_config: false, + claude: acp::is_claude_adapter(argv), + calls: acp::ClaudeCalls::default(), }; b.request(Pending::Initialize, "initialize", acp::initialize_params(env!("CARGO_PKG_VERSION"))); Ok(b) @@ -142,7 +149,7 @@ impl AcpBackend { fn new_session(&mut self) { self.config_pending = None; self.pending.retain(|_, request| *request != Pending::SetConfig); - let params = acp::session_new_params(&self.cwd, self.bridge.as_ref(), &self.init, &self.note); + let params = acp::session_new_params(&self.cwd, self.bridge.as_ref(), &self.init, &self.note, self.claude); self.request(Pending::SessionNew, "session/new", params); } @@ -243,7 +250,13 @@ impl AcpBackend { } } Incoming::Text { thought, text } => out.push(Event::Text { thought, text }), - Incoming::Tool { id, title, kind, status, input, output } => out.push(Event::Tool { id, title, kind, status, input, output }), + Incoming::Tool { id, title, kind, status, input, output, claude_tool } => { + let unasked = self.calls.update(&id, claude_tool.as_deref(), status); + out.push(Event::Tool { id, title, kind, status, input, output }); + if let Some(tool) = unasked { + out.push(Event::Unasked { tool }); + } + } // Accept updates only during the matching session's prompt. A prompt reply earlier in // this poll can start a queued turn when the chat reads the events. Incoming::Plan { session, entries } @@ -252,10 +265,11 @@ impl AcpBackend { out.push(Event::Plan(entries)); } Incoming::Plan { .. } => {} - Incoming::Permission { rpc, title, kind, options } => { + Incoming::Permission { rpc, title, kind, options, reads, call, claude_tool } => { + let claude_tool = self.calls.question(call.as_deref(), claude_tool.as_deref()); self.next_key += 1; self.permissions.insert(self.next_key, rpc); - out.push(Event::Permission { key: self.next_key, title, kind, options }); + out.push(Event::Permission { key: self.next_key, title, kind, options, reads, claude_tool }); } Incoming::AuthStatus(s) => out.push(Event::AuthStatus(s)), Incoming::ModeChanged(m) if !self.modern_config => out.push(Event::Modes { current: m, available: Vec::new() }), @@ -338,6 +352,7 @@ impl ChatBackend for AcpBackend { } fn prompt(&mut self, parts: &[PromptPart]) { + self.calls.clear(); if let Some(s) = self.session.clone() { self.request(Pending::Prompt, "session/prompt", acp::prompt_params(&s, parts)); } @@ -443,6 +458,10 @@ impl ChatBackend for AcpBackend { self.proc.as_ref().and_then(AgentProcess::pid) } + fn claude_code(&self) -> bool { + self.claude + } + fn shutdown(&mut self, wait: bool) { if let Some(restart) = self.restart.take() { restart.stop(wait); @@ -492,7 +511,7 @@ pub fn test_agent(argv: &[String], cwd: &std::path::Path) -> Result Option<&str> { p.pointer("/image_url/url").and_then(Value::as_str) } +/// One OpenAI content part's file name and `data:` URL, if it is a file (a PDF). +fn openai_part_file(p: &Value) -> Option<(&str, &str)> { + Some((p.pointer("/file/filename").and_then(Value::as_str).unwrap_or(""), p.pointer("/file/file_data").and_then(Value::as_str)?)) +} + /// One OpenAI tool call's id and function name. fn openai_tool_call(c: &Value) -> (&str, &str) { (c.get("id").and_then(Value::as_str).unwrap_or(""), c.pointer("/function/name").and_then(Value::as_str).unwrap_or("")) @@ -318,6 +330,10 @@ fn go_anthropic_messages(history: &[Value]) -> Vec { && let Some((mime, data)) = go_data_url(url) { go_push_block(&mut out, "user", json!({"type": "image", "source": {"type": "base64", "media_type": mime, "data": data}})); + } else if let Some((name, url)) = openai_part_file(p) + && let Some((mime, data)) = go_data_url(url) + { + go_push_block(&mut out, "user", anthropic_document(name, mime, data)); } } } @@ -388,6 +404,8 @@ fn responses_input(system: &str, history: &[Value]) -> Vec { .filter_map(|p| { if let Some(t) = openai_part_text(p) { Some(json!({"type": "input_text", "text": t})) + } else if let Some((name, url)) = openai_part_file(p) { + Some(json!({"type": "input_file", "filename": name, "file_data": url})) } else { openai_part_image_url(p).map(|url| json!({"type": "input_image", "image_url": url})) } @@ -513,7 +531,7 @@ fn go_gemini_contents(history: &[Value], sigs: &std::collections::HashMap 0 && media_bytes(&self.history) > MAX_REQUEST_MEDIA { + keep -= 1; + dropped |= drop_old_views(&mut self.history, keep); + } let trimmed = self.trim_history(); if (dropped || trimmed) && self.cfg.protocol == Protocol::Anthropic { drop_thinking(&mut self.history); } + // What is left over the limit is this message's own: it isn't sent, and nothing of it is + // dropped without the user knowing. + let media = media_bytes(&self.history); + if media > MAX_REQUEST_MEDIA { + self.history.pop(); + let mb = |b: usize| format!("{:.1}", (b / 4 * 3) as f64 / (1024.0 * 1024.0)); + let max = ((MAX_REQUEST_MEDIA / 4 * 3) / (1024 * 1024)).to_string(); + self.emit(Event::Error(solidcraft_ui_text::format("ui.ai_request_too_big", &[("size", &mb(media)), ("max", &max)]))); + self.emit(Event::TurnEnded { reason: "error".into() }); + return; + } + let carries_media = self.history.last().is_some_and(|m| media_bytes(std::slice::from_ref(m)) > 0); + let mut first = true; // No cap on requests: Stop sets `cancel`, checked at the top of every round. loop { // The history as of here is complete (every tool call answered): a cancelled request @@ -1197,12 +1236,22 @@ impl Worker { self.emit(Event::Text { thought: true, text: solidcraft_ui_text::tr("ui.agent_chat_context_trimmed").to_owned() }); continue; } + // Refused before any reply: a message with pictures or PDFs is taken back out, so + // the next message doesn't send a file the endpoint won't take again. After a reply + // or a tool call the history stays: those happened. + Err(e) if first && carries_media => { + self.history.truncate(sound.saturating_sub(1)); + self.emit(Event::Error(format!("{e} ({})", solidcraft_ui_text::tr("ui.ai_media_message_dropped")))); + self.emit(Event::TurnEnded { reason: "error".into() }); + return; + } Err(e) => { self.emit(Event::Error(e)); self.emit(Event::TurnEnded { reason: "error".into() }); return; } }; + first = false; for (thought, text) in reply.text { self.emit(Event::Text { thought, text }); } @@ -1637,25 +1686,33 @@ fn tool_arguments(raw: Option<&Value>) -> Result { } } -/// The message for what the user typed (and the view, as the endpoint's own content blocks). +/// A PDF as an Anthropic `document` block. +fn anthropic_document(name: &str, mime: &str, data: &str) -> Value { + json!({"type": "document", "source": {"type": "base64", "media_type": mime, "data": data}, "title": name}) +} + +/// The message for what the user typed (and the view, pictures and PDFs, as the endpoint's own +/// content blocks). fn user_message(protocol: Protocol, parts: &[PromptPart]) -> Value { - let images = parts.iter().any(|p| matches!(p, PromptPart::Image { .. })); - if !images { + let attached = parts.iter().any(|p| matches!(p, PromptPart::Image { .. } | PromptPart::Document { .. })); + if !attached { let text: Vec<&str> = parts.iter().filter_map(|p| if let PromptPart::Text(t) = p { Some(t.as_str()) } else { None }).collect(); return json!({"role": "user", "content": text.join("\n")}); } let content: Vec = parts .iter() - .filter_map(|p| match (protocol, p) { - (_, PromptPart::Text(t)) => Some(json!({"type": "text", "text": t})), + .map(|p| match (protocol, p) { + (_, PromptPart::Text(t)) => json!({"type": "text", "text": t}), (Protocol::OpenAi, PromptPart::Image { mime, base64 }) => { - Some(json!({"type": "image_url", "image_url": {"url": format!("data:{mime};base64,{base64}")}})) + json!({"type": "image_url", "image_url": {"url": format!("data:{mime};base64,{base64}")}}) } (Protocol::Anthropic, PromptPart::Image { mime, base64 }) => { - Some(json!({"type": "image", "source": {"type": "base64", "media_type": mime, "data": base64}})) + json!({"type": "image", "source": {"type": "base64", "media_type": mime, "data": base64}}) + } + (Protocol::OpenAi, PromptPart::Document { name, mime, base64, .. }) => { + json!({"type": "file", "file": {"filename": name, "file_data": format!("data:{mime};base64,{base64}")}}) } - // These endpoints take no documents (the chat doesn't send any); the message names the file. - (_, PromptPart::Document { .. }) => None, + (Protocol::Anthropic, PromptPart::Document { name, mime, base64, .. }) => anthropic_document(name, mime, base64), }) .collect(); json!({"role": "user", "content": content}) @@ -1853,49 +1910,78 @@ fn anthropic_reply(body: &Value) -> Reply { Reply { text, calls, assistant, stop } } -/// Keeps the newest `keep` pictures of the view in the history (both user-attached pictures and -/// tool-result screenshots/overlays) and swaps every older one for a short note, so the model -/// still knows a view was shown. Text is never touched. Pictures come as OpenAI `image_url` parts -/// (in user `content` or tool `tool_images`) or Anthropic `image` blocks (in user `content` or -/// `tool_result.content`), depending on the endpoint. True when a picture was swapped. +/// Keeps every picture and PDF the newest message carries (the one being sent, which may carry +/// several) and the newest `keep` pictures and `keep` PDFs in the rest of the history (pictures the +/// user attached and the tool results' screenshots and overlays alike), and swaps every older one +/// for a short note, so the model still knows it was shown. Text is never touched. Pictures come as +/// OpenAI `image_url` parts (in user `content` or tool `tool_images`) or Anthropic `image` blocks +/// (in user `content` or `tool_result.content`), PDFs as `file` parts or `document` blocks, +/// depending on the endpoint. True when one was swapped. fn drop_old_views(history: &mut [Value], keep: usize) -> bool { - let mut seen = 0; + let newest = history.iter().rposition(starts_a_turn); + let (mut pictures, mut documents) = (0, 0); let mut dropped = false; - let mut visit_image = |part: &mut Value| { - seen += 1; - if seen > keep { - *part = json!({"type": "text", "text": DROPPED_VIEW_NOTE}); + let mut visit = |part: &mut Value| { + let (seen, note) = match part.get("type").and_then(Value::as_str) { + Some("image_url" | "image") => (&mut pictures, DROPPED_VIEW_NOTE), + Some("file" | "document") => (&mut documents, DROPPED_DOCUMENT_NOTE), + _ => return, + }; + *seen += 1; + if *seen > keep { + *part = json!({"type": "text", "text": note}); dropped = true; } }; - for msg in history.iter_mut().rev() { + for (i, msg) in history.iter_mut().enumerate().rev() { if let Some(tool_images) = msg.get_mut("tool_images").and_then(Value::as_array_mut) { for part in tool_images.iter_mut().rev() { if part.get("type").and_then(Value::as_str) == Some("image_url") { - visit_image(part); + visit(part); } } } + // The message being sent keeps all of its own. + if Some(i) == newest { + continue; + } let Some(content) = msg.get_mut("content").and_then(Value::as_array_mut) else { continue }; for part in content.iter_mut().rev() { - match part.get("type").and_then(Value::as_str) { - Some("image_url" | "image") => visit_image(part), - Some("tool_result") => { - if let Some(nested) = part.get_mut("content").and_then(Value::as_array_mut) { - for sub in nested.iter_mut().rev() { - if sub.get("type").and_then(Value::as_str) == Some("image") { - visit_image(sub); - } + if part.get("type").and_then(Value::as_str) == Some("tool_result") { + if let Some(nested) = part.get_mut("content").and_then(Value::as_array_mut) { + for sub in nested.iter_mut().rev() { + if sub.get("type").and_then(Value::as_str) == Some("image") { + visit(sub); } } } - _ => {} + } else { + visit(part); } } } dropped } +/// The bytes of the pictures and PDFs in these messages, as sent (their text, base64 included). +fn media_bytes(history: &[Value]) -> usize { + fn text(v: &Value) -> usize { + match v { + Value::String(s) => s.len(), + Value::Array(a) => a.iter().map(text).sum(), + Value::Object(o) => o.values().map(text).sum(), + _ => 0, + } + } + history + .iter() + .filter_map(|m| m.get("content").and_then(Value::as_array)) + .flatten() + .filter(|p| matches!(p.get("type").and_then(Value::as_str), Some("image_url" | "image" | "file" | "document"))) + .map(text) + .sum() +} + /// Takes Anthropic thinking blocks out of every earlier reply. Each one is signed against all /// the conversation before it, so once a dropped view or trimmed message changes that, the API /// refuses the whole request (#9417); leaving earlier thinking out is allowed. A reply that was @@ -2453,8 +2539,9 @@ mod tests { h.push(json!({"role": "user", "content": "plain text"})); h.push(view(3)); + h.push(view(4)); assert!(drop_old_views(&mut h, 2)); - assert_eq!(pictures(&h), vec!["data:image/png;base64,V2", "data:image/png;base64,V3"]); + assert_eq!(pictures(&h), vec!["data:image/png;base64,V2", "data:image/png;base64,V3", "data:image/png;base64,V4"]); // The oldest view is a note now; the words sent with it, and every other message, stay. assert_eq!(h[1]["content"][0]["text"], "look 1"); assert_eq!(h[1]["content"][1], json!({"type": "text", "text": DROPPED_VIEW_NOTE})); @@ -2475,8 +2562,52 @@ mod tests { h.push(json!({"role": "assistant", "content": "done"})); } let size = json!({"messages": h}).to_string().len(); - assert_eq!(pictures(&h).len(), MAX_HISTORY_IMAGES); - assert!(size < (MAX_HISTORY_IMAGES + 1) * big.len(), "request body is {size} bytes"); + assert_eq!(pictures(&h).len(), MAX_HISTORY_IMAGES + 1, "the newest message's, and two before it"); + assert!(size < (MAX_HISTORY_IMAGES + 2) * big.len(), "request body is {size} bytes"); + } + + /// Every picture and PDF of the message being sent goes (Review: eight attached photos reached + /// an endpoint as their last two). PDFs go as the endpoint's own document parts; older ones, + /// past `keep`, become a note as older pictures do. + #[test] + fn the_newest_message_keeps_all_its_pictures_and_pdfs() { + let pdf = + |n: u8| PromptPart::Document { name: format!("d{n}.pdf"), uri: String::new(), mime: "application/pdf".into(), base64: format!("D{n}") }; + let photo = |n: u8| PromptPart::Image { mime: "image/jpeg".into(), base64: format!("P{n}") }; + let mut parts = vec![PromptPart::Text("these".into())]; + parts.extend((1..=8).map(photo)); + parts.extend((1..=3).map(pdf)); + let mut h = vec![json!({"role": "system", "content": "note"}), user_message(Protocol::OpenAi, &parts)]; + assert!(!drop_old_views(&mut h, MAX_HISTORY_IMAGES)); + assert_eq!(pictures(&h).len(), 8, "every photo of the message goes"); + let files: Vec<&Value> = h[1]["content"].as_array().unwrap().iter().filter(|p| p["type"] == "file").collect(); + assert_eq!(files.len(), 3); + assert_eq!(files[0]["file"], json!({"filename": "d1.pdf", "file_data": "data:application/pdf;base64,D1"})); + h.push(json!({"role": "assistant", "content": "ok"})); + h.push(user_message(Protocol::OpenAi, &[PromptPart::Text("next".into())])); + assert!(drop_old_views(&mut h, MAX_HISTORY_IMAGES)); + assert_eq!(pictures(&h), vec!["data:image/jpeg;base64,P7", "data:image/jpeg;base64,P8"]); + let kept: Vec<&str> = + h[1]["content"].as_array().unwrap().iter().filter_map(|p| p.pointer("/file/filename").and_then(Value::as_str)).collect(); + assert_eq!(kept, ["d2.pdf", "d3.pdf"]); + assert_eq!(h[1]["content"].as_array().unwrap().iter().filter(|p| p["text"] == DROPPED_DOCUMENT_NOTE).count(), 1); + + let anthropic = user_message(Protocol::Anthropic, &[PromptPart::Text("see".into()), pdf(1)]); + assert_eq!( + anthropic["content"][1], + json!({"type": "document", "source": {"type": "base64", "media_type": "application/pdf", "data": "D1"}, "title": "d1.pdf"}) + ); + // OpenCode Go turns the OpenAI-shaped history into each model family's own parts. + let go = vec![user_message(Protocol::OpenAi, &[PromptPart::Text("see".into()), pdf(1)])]; + assert_eq!(go_anthropic_messages(&go)[0]["content"][1], anthropic["content"][1]); + assert_eq!( + responses_input("sys", &go)[1]["content"][1], + json!({"type": "input_file", "filename": "d1.pdf", "file_data": "data:application/pdf;base64,D1"}) + ); + assert_eq!( + go_gemini_contents(&go, &std::collections::HashMap::new())[0]["parts"][1], + json!({"inlineData": {"mimeType": "application/pdf", "data": "D1"}}) + ); } #[test] @@ -2487,11 +2618,11 @@ mod tests { &[PromptPart::Text(format!("look {n}")), PromptPart::Image { mime: "image/png".into(), base64: format!("V{n}") }], ) }; - let mut h = vec![view(1), json!({"role": "assistant", "content": "ok"}), view(2), view(3)]; + let mut h = vec![view(1), json!({"role": "assistant", "content": "ok"}), view(2), view(3), view(4)]; drop_old_views(&mut h, 2); let kept: Vec<&str> = h.iter().filter_map(|m| m["content"].as_array()).flatten().filter_map(|p| p.pointer("/source/data").and_then(Value::as_str)).collect(); - assert_eq!(kept, vec!["V2", "V3"]); + assert_eq!(kept, vec!["V2", "V3", "V4"]); assert_eq!(h[0]["content"][0]["text"], "look 1"); assert_eq!(h[0]["content"][1], json!({"type": "text", "text": DROPPED_VIEW_NOTE})); } @@ -4033,10 +4164,13 @@ mod tests { }; let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) }; let mut b = ApiBackend::start(cfg, ctx).unwrap(); - for n in 1..=3 { - b.prompt(&[PromptPart::Text(format!("look {n}")), PromptPart::Image { mime: "image/png".into(), base64: format!("V{n}") }]); - wait_for_turn(&mut b); - } + let view = |n: &str| PromptPart::Image { mime: "image/png".into(), base64: format!("V{n}") }; + b.prompt(&[PromptPart::Text("look 1".into()), view("1a"), view("1b")]); + wait_for_turn(&mut b); + b.prompt(&[PromptPart::Text("look 2".into()), view("2")]); + wait_for_turn(&mut b); + b.prompt(&[PromptPart::Text("look 3".into())]); + wait_for_turn(&mut b); b.prompt(&[PromptPart::Text("and now?".into())]); wait_for_turn(&mut b); b.shutdown(true); @@ -4045,10 +4179,10 @@ mod tests { let replies = |i: usize| -> Vec { sent[i]["messages"].as_array().unwrap().iter().filter(|m| m["role"] == "assistant").map(|m| m["content"].clone()).collect() }; - // Two views fit: the reply goes back untouched, signature and all. + // Two views before the message fit: the reply goes back untouched, signature and all. assert_eq!(replies(1)[0][0]["signature"], "s1"); - // The third view drops the first: no earlier thinking is left, a thinking-only reply - // keeps a note, and the words stay. + // A third view before the message drops the oldest: no earlier thinking is left, a + // thinking-only reply keeps a note, and the words stay. let third = replies(2); assert_eq!(sent[2]["messages"][0]["content"][1]["text"], DROPPED_VIEW_NOTE); assert_eq!(third[0], json!([{"type": "text", "text": "Seen 1."}])); @@ -4059,6 +4193,100 @@ mod tests { assert_eq!(fourth[2][0]["signature"], "s3"); } + /// An Anthropic endpoint whose POSTs answer with the given statuses in turn (then 200), and + /// the request bodies it was sent. + fn recording_endpoint(statuses: Vec) -> (ApiBackend, Arc>>) { + let seen = Arc::new(std::sync::Mutex::new(Vec::::new())); + let log = seen.clone(); + let http: HttpFn = Arc::new(move |r: &HttpRequest| { + if r.method == "GET" { + return Ok((200, b"{\"data\":[]}".to_vec())); + } + let n = { + let mut l = log.lock().unwrap(); + l.push(serde_json::from_slice(r.body.as_deref().unwrap_or(b"null")).unwrap()); + l.len() + }; + let status = statuses.get(n - 1).copied().unwrap_or(200); + let body = if status == 200 { + json!({"content": [{"type": "text", "text": format!("Seen {n}.")}], "stop_reason": "end_turn"}) + } else { + json!({"error": {"message": "the document could not be read"}}) + }; + Ok((status, body.to_string().into_bytes())) + }); + let cfg = ApiConfig { + name: "Test".into(), + protocol: Protocol::Anthropic, + base_url: "http://localhost:1".into(), + model: "m".into(), + allow_insecure_http: false, + key: Some("sk-secret".into()), + http, + request_timeout_s: 300, + reasoning_effort: String::new(), + openai_responses: false, + }; + let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) }; + (ApiBackend::start(cfg, ctx).unwrap(), seen) + } + + fn pdf_of(name: &str, base64_len: usize) -> PromptPart { + PromptPart::Document { name: name.into(), uri: String::new(), mime: "application/pdf".into(), base64: "A".repeat(base64_len) } + } + + /// A message with a PDF the endpoint refuses before any reply is taken back out of the + /// history, so the next message doesn't send it again (Review: one refused PDF failed every + /// later message). A refused message with only words stays. + #[test] + fn a_refused_pdf_is_not_sent_again() { + let (mut b, seen) = recording_endpoint(vec![400]); + b.prompt(&[PromptPart::Text("read this".into()), pdf_of("locked.pdf", 16)]); + assert!(wait_for_turn(&mut b).iter().any(|e| matches!(e, Event::Error(_)))); + b.prompt(&[PromptPart::Text("and now?".into())]); + wait_for_turn(&mut b); + b.shutdown(true); + let sent = seen.lock().unwrap(); + assert_eq!(sent.len(), 2); + assert_eq!(media_bytes(sent[1]["messages"].as_array().unwrap()), 0, "{}", sent[1]["messages"]); + assert_eq!(sent[1]["messages"].as_array().unwrap().len(), 1, "only the new message"); + + let (mut b, seen) = recording_endpoint(vec![503]); + b.prompt(&[PromptPart::Text("hello".into())]); + wait_for_turn(&mut b); + b.prompt(&[PromptPart::Text("again".into())]); + wait_for_turn(&mut b); + b.shutdown(true); + assert_eq!(seen.lock().unwrap()[1]["messages"].as_array().unwrap().len(), 2, "words alone stay"); + } + + /// The pictures and PDFs of one request stay under `MAX_REQUEST_MEDIA`: older ones go first, + /// and a message whose own are over it is refused before anything is sent (Review: eight + /// 12 MB PDFs made a 128 MB request). + #[test] + fn a_request_keeps_its_pictures_and_pdfs_under_the_limit() { + let (mut b, seen) = recording_endpoint(Vec::new()); + let big = MAX_REQUEST_MEDIA / 2 + 1; + b.prompt(&[PromptPart::Text("one".into()), pdf_of("a.pdf", big)]); + wait_for_turn(&mut b); + b.prompt(&[PromptPart::Text("two".into()), pdf_of("b.pdf", big)]); + wait_for_turn(&mut b); + b.prompt(&[PromptPart::Text("three".into()), pdf_of("c.pdf", big), pdf_of("d.pdf", big)]); + let events = wait_for_turn(&mut b); + b.prompt(&[PromptPart::Text("four".into())]); + wait_for_turn(&mut b); + b.shutdown(true); + let sent = seen.lock().unwrap(); + assert_eq!(sent.len(), 3, "the third message is never sent"); + assert!(events.iter().any(|e| matches!(e, Event::Error(_))), "{events:?}"); + let second = sent[1]["messages"].as_array().unwrap(); + assert!(media_bytes(second) <= MAX_REQUEST_MEDIA); + assert_eq!(second[0]["content"][1]["text"], DROPPED_DOCUMENT_NOTE, "the older PDF went first"); + assert!(media_bytes(&second[2..]) >= big, "the new one went whole"); + let fourth = sent[2]["messages"].as_array().unwrap(); + assert!(!fourth.iter().any(|m| m.to_string().contains("three")), "the refused message is not kept"); + } + #[test] fn the_anthropic_test_sends_one_small_message_and_checks_the_key_rule() { crate::i18n::install(); @@ -4327,7 +4555,9 @@ mod tests { json!({"role": "user", "content": [anthropic_tool_result("t3", &make_out(3))]}), ]; assert!(drop_old_views(&mut anth_history, MAX_HISTORY_IMAGES)); - assert_eq!(anth_history[0]["content"][1], json!({"type": "text", "text": DROPPED_VIEW_NOTE})); + // The message being sent keeps every picture of its own (#16458): the reference the user + // attached stays, and the tool screenshots after it keep their newest two. + assert_eq!(anth_history[0]["content"][1]["source"]["data"], "U0"); assert_eq!( anth_history[2]["content"][0]["content"], json!([{"type": "text", "text": "view 1"}, {"type": "text", "text": DROPPED_VIEW_NOTE}]) diff --git a/crates/ui-egui/src/agent_chat/attach.rs b/crates/ui-egui/src/agent_chat/attach.rs index e4dcdca34eb..e3c067285ae 100644 --- a/crates/ui-egui/src/agent_chat/attach.rs +++ b/crates/ui-egui/src/agent_chat/attach.rs @@ -1,8 +1,10 @@ -//! Files a person adds to a message (the + button, a drop on the chat, a paste): pictures go to the -//! agent with it, text files go in as text, PDFs go as documents to agents that take them, CAD -//! files are imported into the design, and any other file is named by reference (its type, size -//! and place on this machine) for the agent to read with its own tools. The agent is told what -//! arrived. Each file is checked and bounded before it is kept; a refused one says why. +//! Files a person adds to a message (the + button, a drop on the chat, a paste). To an endpoint, +//! which has no tool that opens a file: pictures and PDFs go with the message, text files go in +//! as text, CAD files are imported into the design, and any other file is refused ([`read`]). A +//! coding agent reads with tools of its own, so to one every file and folder goes by its path +//! (its type, size and place on this machine; [`reference`], [`folder`]), however many there are. +//! The agent is told what arrived. Each file is checked and bounded before it is kept; a refused +//! one says why. use std::path::{Path, PathBuf}; use std::sync::Arc; @@ -22,19 +24,16 @@ fn failed(name: &str, e: impl std::fmt::Display) -> String { refused("ui.agent_chat_file_error", name, &[("error", &e.to_string())]) } -/// Most files on one message. +/// Most files whose contents go with one message. pub const MAX_FILES: usize = 8; +/// Most files and folders on one message to a coding agent, where they go by their path. +pub const MAX_ON_MESSAGE: usize = 200; /// Largest picture file read, before it is scaled down. const MAX_PICTURE_BYTES: u64 = 40 * 1024 * 1024; /// Largest text file sent in full. const MAX_TEXT_BYTES: u64 = 256 * 1024; -/// Largest PDF sent as a document; a bigger one goes by reference. +/// Largest PDF sent as a document; a bigger one is refused. const MAX_PDF_BYTES: u64 = 12 * 1024 * 1024; -/// Pages whose text is taken from a PDF, and the most characters of it kept. -const MAX_PDF_PAGES: usize = 300; -const MAX_PDF_CHARS: usize = 200_000; -/// A PDF page's content may inflate to at most this (a compressed bomb is refused by the reader). -const MAX_PDF_PAGE_BYTES: usize = 32 * 1024 * 1024; /// A picture's longer side is scaled down to this before it is sent. pub const MAX_SIDE: u32 = 2048; /// Largest picture sent, as it came or re-encoded: its base64 (a third larger) stays under 5 MB, @@ -67,7 +66,7 @@ pub enum Kind { Text, Cad, Pdf, - /// Anything else, attached by reference. + /// Anything else: to a coding agent by its path, to an endpoint not at all. Other, } @@ -93,11 +92,10 @@ pub enum Content { size: [u32; 2], }, Text(Arc), - /// A PDF, sent whole as a document to an agent that takes them; to the others, its text. + /// A PDF, sent whole as a document to an agent that takes them. Pdf { bytes: Arc>, path: PathBuf, - text: Option>, }, /// A file the agent is pointed to, not given: what it is, its size and where it is. Reference { @@ -105,64 +103,15 @@ pub enum Content { size: u64, mime: &'static str, }, + /// A folder a coding agent is pointed to: where it is, nothing of what it holds (it lists it + /// itself; counting a large folder on a network share would keep the message waiting). + Folder { + path: PathBuf, + }, /// A CAD file imported into the design as its own component. Imported, } -/// What was taken out of a PDF: its page count and its text, without layout, pictures or fonts. -#[derive(Clone, Debug, PartialEq)] -pub struct PdfText { - pub pages: usize, - pub text: String, - /// The text stops short: of the pages or of the characters kept. - pub cut: bool, -} - -/// The text of a PDF, from its pages in order (up to [`MAX_PDF_PAGES`] pages and -/// [`MAX_PDF_CHARS`] characters). `None` when it can't be read at all (damaged, or a reader -/// panic, which is caught); an encrypted or scanned one gives its page count and no text. -#[cfg(not(target_arch = "wasm32"))] -pub fn pdf_text(bytes: &[u8]) -> Option { - std::panic::catch_unwind(|| { - let doc = lopdf::Document::load_mem(bytes).ok()?; - let pages: Vec = doc.get_pages().keys().copied().collect(); - let mut text = String::new(); - let mut chars = 0usize; - let mut cut = pages.len() > MAX_PDF_PAGES; - if !doc.is_encrypted() { - for page in pages.iter().take(MAX_PDF_PAGES) { - // A page that can't be read is skipped; the others still give their text. - let chunks = doc.extract_text_chunks_with_limit(&[*page], MAX_PDF_PAGE_BYTES); - let page_text: String = chunks.into_iter().filter_map(Result::ok).collect(); - let page_text = page_text.trim(); - if page_text.is_empty() { - continue; - } - if !text.is_empty() { - text.push_str("\n\n"); - } - let room = MAX_PDF_CHARS.saturating_sub(chars); - let n = page_text.chars().count(); - if n > room { - text.extend(page_text.chars().take(room)); - cut = true; - break; - } - text.push_str(page_text); - chars += n; - } - } - Some(PdfText { pages: pages.len(), text, cut }) - }) - .ok() - .flatten() -} - -#[cfg(target_arch = "wasm32")] -pub fn pdf_text(_bytes: &[u8]) -> Option { - None -} - #[derive(Clone, Debug, PartialEq)] pub struct Attachment { /// Its own on the message, never reused (set when it is added there; 0 until then): the @@ -181,8 +130,15 @@ impl Attachment { pub fn is_picture(&self) -> bool { matches!(self.content, Content::Picture { .. }) } + /// The agent is told where it is, not given it: it costs the message no more than its line. + pub fn by_place(&self) -> bool { + matches!(self.content, Content::Reference { .. } | Content::Folder { .. }) + } /// The chip's mark for a file with no thumbnail: its extension, in capitals, cut to fit. pub fn mark(&self) -> String { + if matches!(self.content, Content::Folder { .. }) { + return String::new(); + } let ext = Path::new(&self.name).extension().and_then(|e| e.to_str()).unwrap_or(""); ext.chars().take(4).collect::().to_uppercase() } @@ -192,6 +148,22 @@ impl Attachment { fn mime_of(path: &Path) -> &'static str { let ext = path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).unwrap_or_default(); match ext.as_str() { + "png" => "image/png", + "jpg" | "jpeg" => "image/jpeg", + "gif" => "image/gif", + "webp" => "image/webp", + "bmp" => "image/bmp", + "tif" | "tiff" => "image/tiff", + "heic" | "heif" => "image/heic", + "svg" => "image/svg+xml", + "txt" | "log" | "ini" | "cfg" => "text/plain", + "md" | "markdown" => "text/markdown", + "csv" => "text/csv", + "tsv" => "text/tab-separated-values", + "json" => "application/json", + "yaml" | "yml" => "application/yaml", + "toml" => "application/toml", + "xml" => "application/xml", "pdf" => "application/pdf", "zip" => "application/zip", "7z" => "application/x-7z-compressed", @@ -252,7 +224,9 @@ pub(crate) fn name_of(path: &Path) -> String { path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.to_string_lossy().to_string()) } -/// Read a picture or text file for a message. CAD files are imported by the caller, not read here. +/// Read a picture, text file or PDF for a message to an endpoint, which has no tool that opens a +/// file: any other file, and a PDF too big to send, is refused. CAD files are imported by the +/// caller, not read here. pub fn read(path: &Path) -> Result { let name = name_of(path); let meta = std::fs::metadata(path).map_err(|e| failed(&name, e))?; @@ -278,22 +252,50 @@ pub fn read(path: &Path) -> Result { Kind::Cad => Err(refused("ui.agent_chat_file_cad_not_read", &name, &[])), Kind::Pdf => { let path = absolute(path); - // Too big to send: the agent is pointed to it instead. if meta.len() > MAX_PDF_BYTES { - return Ok(Attachment { id: 0, name, content: Content::Reference { path, size: meta.len(), mime: "application/pdf" }, thumb: None }); + return Err(refused("ui.agent_chat_file_pdf_too_big", &name, &[("max", &(MAX_PDF_BYTES / 1024 / 1024).to_string())])); + } + // The limit holds for what is read, too: a file that grew since `meta` is refused. + use std::io::Read as _; + let mut bytes = Vec::new(); + std::fs::File::open(&path).and_then(|f| f.take(MAX_PDF_BYTES + 1).read_to_end(&mut bytes)).map_err(|e| failed(&name, e))?; + if bytes.len() as u64 > MAX_PDF_BYTES { + return Err(refused("ui.agent_chat_file_pdf_too_big", &name, &[("max", &(MAX_PDF_BYTES / 1024 / 1024).to_string())])); } - let bytes = std::fs::read(&path).map_err(|e| failed(&name, e))?; - // Read here, off the window thread: for an agent that takes no documents. - let text = pdf_text(&bytes).map(Arc::new); - Ok(Attachment { id: 0, name, content: Content::Pdf { bytes: Arc::new(bytes), path, text }, thumb: None }) + Ok(Attachment { id: 0, name, content: Content::Pdf { bytes: Arc::new(bytes), path }, thumb: None }) } Kind::Other if matches!(path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).as_deref(), Some("heic" | "heif")) => { Err(refused("ui.agent_chat_file_heic", &name, &[])) } - Kind::Other => { - Ok(Attachment { id: 0, name, content: Content::Reference { path: absolute(path), size: meta.len(), mime: mime_of(path) }, thumb: None }) - } + Kind::Other => Err(refused("ui.agent_chat_file_kinds_endpoint", &name, &[])), + } +} + +/// A file for a coding agent, whatever its kind: its type, size and path. Nothing of it is read, +/// so the agent gets it whole, at full size, with its own tools. +pub fn reference(path: &Path) -> Result { + let name = name_of(path); + let meta = std::fs::metadata(path).map_err(|e| failed(&name, e))?; + if !meta.is_file() { + return Err(refused("ui.agent_chat_file_not_a_file", &name, &[])); } + Ok(Attachment { id: 0, name, content: Content::Reference { path: absolute(path), size: meta.len(), mime: mime_of(path) }, thumb: None }) +} + +/// A folder's name on its chip and in the message: its own name, marked as a folder. +pub(crate) fn folder_name(path: &Path) -> String { + format!("{}/", name_of(path).trim_end_matches(['/', '\\'])) +} + +/// A folder for a coding agent: it is told where the folder is and lists it with its own tools. +/// Nothing in it is read here. +pub fn folder(path: &Path) -> Result { + let name = folder_name(path); + let meta = std::fs::metadata(path).map_err(|e| failed(&name, e))?; + if !meta.is_dir() { + return Err(failed(&name, "not a folder")); + } + Ok(Attachment { id: 0, name, content: Content::Folder { path: absolute(path) }, thumb: None }) } /// The path as an absolute one, so the agent (working in another folder) finds the file. @@ -446,29 +448,14 @@ pub fn note(files: &[Attachment], pictures_sent: bool, documents_sent: bool, bud path.display() ); } - // An agent that takes no documents gets the text, or is pointed to the file. - Content::Pdf { path, bytes, text } => { - let size = size_text(bytes.len() as u64); - match text.as_deref().filter(|t| !t.text.trim().is_empty()) { - Some(t) => { - let cut = if t.cut { "; cut, the rest is in the file" } else { "" }; - let head = format!( - "Attached PDF `{}` ({} pages, {size}, at {}): its text only, layout, pictures and fonts are dropped{cut}", - f.name, - t.pages, - path.display() - ); - fit(&mut out, &mut left, &head, &t.text); - } - None => { - let why = if text.is_some() { "no text could be taken from it (scanned or protected)" } else { "its text could not be read" }; - out += &format!( - "\n\nAttached file `{}` (PDF, {size}, at {}): {why}; read it with your own tools, it is not in this message.", - f.name, - path.display() - ); - } - } + // An agent that takes no documents is pointed to the file. + Content::Pdf { path, bytes } => { + out += &format!( + "\n\nAttached file `{}` (PDF, {}, at {}): read it with your own tools; it is not in this message.", + f.name, + size_text(bytes.len() as u64), + path.display() + ); } Content::Reference { path, size, mime } => { out += &format!( @@ -478,6 +465,13 @@ pub fn note(files: &[Attachment], pictures_sent: bool, documents_sent: bool, bud path.display() ); } + Content::Folder { path } => { + out += &format!( + "\n\nAttached folder `{}` (at {}): read it with your own tools; its files are not in this message.", + f.name, + path.display() + ); + } Content::Imported => out += &format!("\n\n(I added `{}` to the design as a component of its own.)", f.name), Content::Picture { .. } => {} } @@ -722,39 +716,96 @@ mod tests { assert!(matches!(&p[0], PromptPart::Image { mime, base64 } if mime == "image/png" && base64.starts_with("iVBORw0KGgo"))); } - /// Any file that is neither a picture, text, CAD nor a PDF is named by reference (what it is, - /// its size and its place) instead of refused; the agent reads it with its own tools. + /// An endpoint has no tool that opens a file: any file that is neither a picture, text, CAD + /// nor a PDF is refused, saying what can go (a coding agent gets it by its path, see + /// `a_file_by_its_path_is_left_whole`). #[test] - fn other_files_go_by_reference() { + fn other_files_are_refused_for_an_endpoint() { crate::i18n::install(); let d = dir("reference"); let zip = d.join("fixtures.zip"); std::fs::write(&zip, vec![0u8; 3000]).unwrap(); let dxf = d.join("outline.DXF"); std::fs::write(&dxf, b"0\nSECTION\n").unwrap(); - let a = read(&zip).unwrap(); - let Content::Reference { path, size, mime } = &a.content else { panic!("a reference") }; - assert_eq!((*size, *mime), (3000, "application/zip")); - assert!(path.is_absolute() && path.ends_with("fixtures.zip")); - assert!(a.thumb.is_none() && a.mark() == "ZIP"); - assert!(matches!(read(&dxf).unwrap().content, Content::Reference { mime: "image/vnd.dxf", .. }), "by extension, in any case"); let bare = d.join("LICENSE_BLOB"); std::fs::write(&bare, b"x").unwrap(); - assert!(matches!(read(&bare).unwrap().content, Content::Reference { mime: "application/octet-stream", .. }), "no extension"); - let files = vec![a]; - let n = note(&files, true, true, usize::MAX); - assert!(n.contains("Attached file `fixtures.zip` (application/zip, 3 KB, at "), "{n}"); - assert!(n.contains("fixtures.zip): read it with your own tools"), "{n}"); - assert!(parts(&files, true, true).is_empty(), "a reference sends nothing but the note"); + for file in [&zip, &dxf, &bare] { + let e = read(file).unwrap_err(); + assert!(e.contains("PDFs") && e.contains("CAD files"), "says what can go: {e}"); + } + assert!(read(&zip).unwrap_err().starts_with("fixtures.zip: ")); assert!(read(&d).unwrap_err().contains("not a file"), "a folder is refused"); assert!(read(&d.join("missing.bin")).is_err()); let _ = std::fs::remove_dir_all(&d); } - /// A PDF goes whole as a document to an agent that takes them (and is named with its place); - /// to one that doesn't, and when it is too big to send, the agent is pointed to the file. + /// For a coding agent, a file of any kind goes by its path: nothing of it is read, and the + /// message points the agent to it. #[test] - fn pdfs_go_as_documents_or_by_reference() { + fn a_file_by_its_path_is_left_whole() { + crate::i18n::install(); + let d = dir("place"); + let photo = d.join("IMG_0001.JPG"); + image::RgbImage::from_pixel(64, 48, image::Rgb([90, 90, 90])).save_with_format(&photo, image::ImageFormat::Jpeg).unwrap(); + let size = std::fs::metadata(&photo).unwrap().len(); + let a = reference(&photo).unwrap(); + let Content::Reference { path, size: s, mime } = &a.content else { panic!("a reference: {:?}", a.content) }; + assert_eq!((*s, *mime), (size, "image/jpeg"), "its own size"); + assert!(path.is_absolute() && a.thumb.is_none() && a.by_place()); + let n = note(std::slice::from_ref(&a), true, true, usize::MAX); + assert!(n.contains("Attached file `IMG_0001.JPG` (image/jpeg, "), "{n}"); + assert!(n.contains("IMG_0001.JPG): read it with your own tools; it is not in this message."), "{n}"); + assert!(parts(&[a], true, true).is_empty(), "nothing but the note"); + let notes = d.join("brief.md"); + std::fs::write(¬es, "wall 2 mm").unwrap(); + assert!(matches!(reference(¬es).unwrap().content, Content::Reference { mime: "text/markdown", .. }), "text goes by its path too"); + let heic = d.join("photo.heic"); + std::fs::write(&heic, b"....ftypheic").unwrap(); + assert!(matches!(reference(&heic).unwrap().content, Content::Reference { mime: "image/heic", .. }), "the agent's tools may read it"); + let zip = d.join("fixtures.zip"); + std::fs::write(&zip, vec![0u8; 3000]).unwrap(); + let z = reference(&zip).unwrap(); + assert!(matches!(z.content, Content::Reference { size: 3000, mime: "application/zip", .. }) && z.mark() == "ZIP"); + let dxf = d.join("outline.DXF"); + std::fs::write(&dxf, b"0\nSECTION\n").unwrap(); + assert!(matches!(reference(&dxf).unwrap().content, Content::Reference { mime: "image/vnd.dxf", .. }), "by extension, in any case"); + let bare = d.join("LICENSE_BLOB"); + std::fs::write(&bare, b"x").unwrap(); + assert!(matches!(reference(&bare).unwrap().content, Content::Reference { mime: "application/octet-stream", .. }), "no extension"); + assert!(reference(&d).unwrap_err().contains("not a file")); + assert!(reference(&d.join("missing.jpg")).is_err()); + let _ = std::fs::remove_dir_all(&d); + } + + /// A folder goes by its path alone: nothing in it is listed, counted or read (a large folder on + /// a network share would keep the message waiting), and the agent lists it itself. + #[test] + fn a_folder_goes_by_its_path() { + crate::i18n::install(); + let d = dir("folder"); + let photos = d.join("site photos"); + std::fs::create_dir_all(photos.join("raw")).unwrap(); + std::fs::write(photos.join("A.jpg"), vec![0u8; 1024]).unwrap(); + let a = folder(&photos).unwrap(); + assert_eq!(a.name, "site photos/"); + assert!(a.by_place() && a.mark().is_empty()); + let Content::Folder { path } = &a.content else { panic!("a folder: {:?}", a.content) }; + assert!(path.is_absolute() && path.ends_with("site photos")); + let n = note(std::slice::from_ref(&a), true, true, usize::MAX); + assert!(n.contains("Attached folder `site photos/` (at "), "{n}"); + assert!(n.contains("site photos): read it with your own tools; its files are not in this message."), "{n}"); + assert!(!n.contains("A.jpg") && !n.contains("raw"), "nothing in it is listed: {n}"); + assert!(parts(&[a], true, true).is_empty()); + assert!(folder(&photos.join("A.jpg")).is_err(), "a file is not a folder"); + assert!(folder(&d.join("missing")).is_err()); + let _ = std::fs::remove_dir_all(&d); + } + + /// A PDF goes whole as a document (and is named with its place), whatever is in it: a scan or a + /// drawing too. One too big to send is refused. + #[test] + fn pdfs_go_as_documents() { + crate::i18n::install(); let d = dir("pdf"); let pdf = d.join("brief 1.pdf"); std::fs::write(&pdf, b"%PDF-1.4\n%%EOF\n").unwrap(); @@ -773,9 +824,10 @@ mod tests { assert!(n.contains("(PDF, 15 bytes, at ") && n.contains("read it with your own tools"), "{n}"); let big = d.join("drawing set.pdf"); std::fs::write(&big, vec![b'x'; usize::try_from(MAX_PDF_BYTES).unwrap() + 1]).unwrap(); - let b = read(&big).unwrap(); - assert!(matches!(b.content, Content::Reference { mime: "application/pdf", .. }), "too big to send: by reference"); - assert!(parts(&[b], true, true).is_empty()); + assert!(read(&big).unwrap_err().contains("at most 12 MB"), "too big to send"); + let full = d.join("full.pdf"); + std::fs::write(&full, vec![b'x'; usize::try_from(MAX_PDF_BYTES).unwrap()]).unwrap(); + assert!(matches!(read(&full).map(|a| a.content), Ok(Content::Pdf { bytes, .. }) if bytes.len() as u64 == MAX_PDF_BYTES), "at the limit"); let _ = std::fs::remove_dir_all(&d); } @@ -786,107 +838,4 @@ mod tests { assert_eq!(size_text(1536), "2 KB"); assert_eq!(size_text(5 * 1024 * 1024 + 512 * 1024), "5.5 MB"); } - - /// A PDF with one line of text on each page. - fn sample_pdf(pages: &[&str]) -> Vec { - use lopdf::content::{Content, Operation}; - use lopdf::{Document, Object, Stream, dictionary}; - let mut doc = Document::with_version("1.5"); - let pages_id = doc.new_object_id(); - let font = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica"}); - let resources = doc.add_object(dictionary! {"Font" => dictionary! {"F1" => font}}); - let mut kids = Vec::new(); - for line in pages { - let mut ops = vec![ - Operation::new("BT", vec![]), - Operation::new("Tf", vec!["F1".into(), 12.into()]), - Operation::new("Td", vec![72.into(), 700.into()]), - ]; - if !line.is_empty() { - ops.push(Operation::new("Tj", vec![Object::string_literal(*line)])); - } - ops.push(Operation::new("ET", vec![])); - let content = doc.add_object(Stream::new(dictionary! {}, Content { operations: ops }.encode().unwrap())); - kids.push(Object::Reference(doc.add_object(dictionary! {"Type" => "Page", "Parent" => pages_id, "Contents" => content}))); - } - let tree = dictionary! { - "Type" => "Pages", "Kids" => kids, "Count" => pages.len() as i64, "Resources" => resources, - "MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()], - }; - doc.objects.insert(pages_id, Object::Dictionary(tree)); - let catalog = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages_id}); - doc.trailer.set("Root", catalog); - let mut out = Vec::new(); - doc.save_to(&mut out).unwrap(); - out - } - - /// An agent that takes no documents gets the PDF's text, with its page count and a note that - /// the layout was dropped; one that takes documents gets the PDF and not the text. - #[test] - fn a_pdf_gives_its_text_to_agents_without_documents() { - let d = dir("pdftext"); - let path = d.join("brief.pdf"); - std::fs::write(&path, sample_pdf(&["Wall 2 mm", "Hole 5 mm"])).unwrap(); - let a = read(&path).unwrap(); - let Content::Pdf { text: Some(t), .. } = &a.content else { panic!("a PDF with its text: {:?}", a.content) }; - assert_eq!(t.pages, 2); - assert!(!t.cut && t.text.contains("Wall 2 mm") && t.text.contains("Hole 5 mm"), "{:?}", t.text); - assert!(t.text.find("Wall").unwrap() < t.text.find("Hole").unwrap(), "pages in order"); - let files = vec![a]; - let n = note(&files, false, false, usize::MAX); - assert!(n.contains("Attached PDF `brief.pdf` (2 pages"), "{n}"); - assert!(n.contains("layout, pictures and fonts are dropped") && n.contains("Wall 2 mm"), "{n}"); - let short = note(&files, false, false, 5); - assert!(short.contains("more characters left out"), "the text shares the message's budget: {short}"); - let with = note(&files, false, true, usize::MAX); - assert!(with.contains("as a document") && !with.contains("Wall 2 mm"), "{with}"); - let _ = std::fs::remove_dir_all(&d); - } - - /// A PDF that is all pictures (a scan), or can't be read, says so and points to the file; the - /// text kept is capped. - #[test] - fn pdfs_without_text_or_too_long_are_said_so() { - let blank = pdf_text(&sample_pdf(&[""])).unwrap(); - assert_eq!((blank.pages, blank.text.as_str()), (1, "")); - let a = Attachment { - id: 0, - name: "scan.pdf".into(), - content: Content::Pdf { bytes: Arc::new(vec![1; 10]), path: "/a/scan.pdf".into(), text: Some(Arc::new(blank)) }, - thumb: None, - }; - assert!(note(&[a], false, false, usize::MAX).contains("no text could be taken from it")); - let broken = Attachment { - id: 0, - name: "x.pdf".into(), - content: Content::Pdf { bytes: Arc::new(vec![1; 10]), path: "/a/x.pdf".into(), text: None }, - thumb: None, - }; - assert!(note(&[broken], false, false, usize::MAX).contains("its text could not be read")); - let long = "a".repeat(MAX_PDF_CHARS + 5000); - let t = pdf_text(&sample_pdf(&[&long])).unwrap(); - assert!(t.cut && t.text.chars().count() == MAX_PDF_CHARS, "{} characters", t.text.chars().count()); - } - - /// Hostile PDFs never panic: truncated and damaged copies of a real one are read or refused. - #[test] - fn damaged_pdfs_never_panic() { - let good = sample_pdf(&["Wall 2 mm", "Hole 5 mm"]); - assert!(pdf_text(&good).is_some()); - assert!(pdf_text(b"").is_none() && pdf_text(b"%PDF-1.7\n").is_none() && pdf_text(b"not a pdf").is_none()); - for cut in (0..good.len()).step_by(37) { - let _ = pdf_text(&good[..cut]); - } - let mut seed = 0x9e37_79b9_u32; - for _ in 0..200 { - let mut bad = good.clone(); - for _ in 0..4 { - seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); - let at = usize::try_from(seed >> 8).unwrap() % bad.len(); - bad[at] = (seed & 0xff) as u8; - } - let _ = pdf_text(&bad); - } - } } diff --git a/crates/ui-egui/src/agent_chat/backend.rs b/crates/ui-egui/src/agent_chat/backend.rs index 8206bbc61f7..b178d21208c 100644 --- a/crates/ui-egui/src/agent_chat/backend.rs +++ b/crates/ui-egui/src/agent_chat/backend.rs @@ -81,6 +81,17 @@ pub enum Event { /// The tool call's kind, as the agent gives it. kind: Option, options: Vec, + /// The path it would read, when it is one of Claude Code's own read tools + /// ([`super::acp::read_path`]). + reads: Option, + /// Which of Claude Code's own tools it asks about, when the Claude adapter says + /// ([`super::acp::ClaudeCalls`]), whatever command started it. + claude_tool: Option, + }, + /// One of Claude Code's read tools completed without asking first, which its session's ask + /// rule forbids ([`super::acp::ClaudeCalls`]): the panel stops the message and says so. + Unasked { + tool: String, }, /// It needs the user to sign in; `methods` are its own ways to do so. AuthRequired { @@ -170,6 +181,11 @@ pub trait ChatBackend { fn pid(&self) -> Option { None } + /// It is Claude Code's adapter, as its command said when it started (its read tools are on + /// only then, [`super::acp::CLAUDE_ASK_TOOLS`]). + fn claude_code(&self) -> bool { + false + } /// End it and everything it started. `wait`: block until done (quitting). fn shutdown(&mut self, wait: bool); } diff --git a/crates/ui-egui/src/agent_chat/mod.rs b/crates/ui-egui/src/agent_chat/mod.rs index da60aba545e..ebac2f77d18 100644 --- a/crates/ui-egui/src/agent_chat/mod.rs +++ b/crates/ui-egui/src/agent_chat/mod.rs @@ -613,6 +613,9 @@ pub struct AgentChat { thumbs: std::collections::HashMap, /// The last id given to a file added to a message. last_file_id: u64, + /// Files and folders sent by path in this conversation, as their real paths: the agent's own + /// read tools may read inside them without asking the user (see [`on_permission`]). + by_path: Vec, /// Files still being read for the next message. pub(crate) loading: Vec, /// Where the chat was drawn last frame (the panel, or its folded strip), for drops; `None` @@ -842,10 +845,42 @@ impl AgentChat { self.attachments.insert(at, file); name } + /// The files and folders of a message being sent that go by their path, and that its text + /// (`sent`) names, join [`Self::by_path`], resolved through links, so a read that leads + /// elsewhere doesn't match. The most recent [`MAX_BY_PATH`] are kept. + fn send_by_path(&mut self, files: &[attach::Attachment], sent: &str) { + for f in files { + let path = match &f.content { + attach::Content::Reference { path, .. } | attach::Content::Folder { path } | attach::Content::Pdf { path, .. } => path, + _ => continue, + }; + if !sent.contains(&format!("at {})", path.display())) { + continue; + } + if let Ok(real) = std::fs::canonicalize(path) + && !self.by_path.contains(&real) + { + self.by_path.push(real); + } + } + let over = self.by_path.len().saturating_sub(MAX_BY_PATH); + self.by_path.drain(..over); + } + /// The path, resolved through links, lies in a file or folder sent by path in this conversation: + /// a link inside an attached folder that leads out of it doesn't count. + pub(crate) fn attached_by_path(&self, path: &std::path::Path) -> bool { + let Ok(real) = std::fs::canonicalize(path) else { return false }; + self.by_path.iter().any(|sent| real.starts_with(sent)) + } /// Files on the next message, read or still being read. fn files(&self) -> usize { self.attachments.len() + self.loading.len() } + /// Files on the next message whose contents go with it (read or still being read): those that + /// go by their path don't count. + fn files_sent(&self) -> usize { + self.attachments.iter().filter(|f| !f.by_place()).count() + self.loading.len() + } /// Read a file for the next message on a worker thread, in the window's language. #[cfg(not(target_arch = "wasm32"))] fn load( @@ -1096,7 +1131,10 @@ impl AgentChat { self.push(Item::Plan(entries)); } } - Event::Permission { key, title, kind, options } => return Some(Outcome::Permission { key, title, kind, options }), + Event::Permission { key, title, kind, options, reads, claude_tool } => { + return Some(Outcome::Permission { key, title, kind, options, reads, claude_tool }); + } + Event::Unasked { tool } => return Some(Outcome::Unasked { tool }), Event::Modes { current, available } => { if self.config_options.is_none() && !available.is_empty() { self.modes = available; @@ -1229,7 +1267,16 @@ enum Outcome { /// A message was answered (or the agent stopped): the turn's bookkeeping ends. TurnEnd, /// The agent asks before running something of its own: answered by the mode, or asked. - Permission { key: u64, title: String, kind: Option, options: Vec }, + Permission { + key: u64, + title: String, + kind: Option, + options: Vec, + reads: Option, + claude_tool: Option, + }, + /// One of Claude Code's read tools ran without asking ([`Event::Unasked`]): the message stops. + Unasked { tool: String }, } /// The AI features are on (the master switch in Settings → AI) and this is the desktop app. @@ -1638,6 +1685,8 @@ const MAX_PENDING: usize = 20; /// Said to the agent before a message that interrupted it, so it knows its last step may be /// incomplete. const INTERRUPT_NOTE: &str = "[The user interrupted your previous step.]"; +/// Most files and folders a conversation keeps as sent by path ([`AgentChat::by_path`]). +const MAX_BY_PATH: usize = 1000; /// Said to the agent before a task it could not finish, so it goes on with it instead of /// starting again. const CONTINUE_NOTE: &str = "[The previous attempt was cut short before it finished. Continue the task from where it stopped.]"; @@ -2092,6 +2141,7 @@ fn submit(app: &mut SolveApp, ctx: &egui::Context, text: String, image: bool, co /// Send the queued messages as one prompt, in order. fn send_queue(app: &mut SolveApp, ctx: &egui::Context, interrupted: bool) { + let max = if takes_paths(app) { attach::MAX_ON_MESSAGE } else { attach::MAX_FILES }; let chat = &mut app.agent_chat; chat.pending_edit = None; if chat.pending.is_empty() { @@ -2111,10 +2161,11 @@ fn send_queue(app: &mut SolveApp, ctx: &egui::Context, interrupted: bool) { texts.push(pills::shift(&p.text, by)); } } - // One message carries at most MAX_FILES files; the rest are named, not sent. - if files.len() > attach::MAX_FILES { - let left: Vec = files.split_off(attach::MAX_FILES).into_iter().map(|f| f.name).collect(); - let max = attach::MAX_FILES.to_string(); + // One message carries at most MAX_FILES files (MAX_ON_MESSAGE to a coding agent, of which the + // contents of MAX_FILES go with it); the rest are named, not sent. + let (files, left) = within_caps(files, max); + if !left.is_empty() { + let max = if files.len() >= max { max } else { attach::MAX_FILES }.to_string(); chat.notice(trf("ui.agent_chat_files_left_out", &[("max", &max), ("files", &left.join(", "))]), true); } let text = texts.join("\n\n"); @@ -2122,6 +2173,21 @@ fn send_queue(app: &mut SolveApp, ctx: &egui::Context, interrupted: bool) { submit(app, ctx, text, image, context, files, interrupted); } +/// The files that fit on one message, in order, and the names of those that don't: past `max` in +/// all, or past [`attach::MAX_FILES`] whose contents go with it. +fn within_caps(files: Vec, max: usize) -> (Vec, Vec) { + let (mut kept, mut left, mut sent) = (Vec::new(), Vec::new(), 0); + for f in files { + if kept.len() >= max || (!f.by_place() && sent >= attach::MAX_FILES) { + left.push(f.name); + continue; + } + sent += usize::from(!f.by_place()); + kept.push(f); + } + (kept, left) +} + /// Send now: stop the running step and send the queue as the next prompt once the agent has said /// it stopped (its note tells the agent it was interrupted). With nothing running, sends the queue. pub fn send_now(app: &mut SolveApp, ctx: &egui::Context) { @@ -2177,6 +2243,7 @@ pub fn new_chat(app: &mut SolveApp) { chat.chips_version += 1; chat.pending.clear(); chat.attachments.clear(); + chat.by_path.clear(); chat.loading.clear(); chat.pending_edit = None; chat.queued = None; @@ -2272,10 +2339,15 @@ fn start_turn_with(app: &mut SolveApp, text: String, image: bool, at: Option = note.into_iter().chain(changed.as_deref()).collect(); let lead = if notes.is_empty() { text.clone() } else { format!("{}\n\n{text}", notes.join("\n")) }; - // The whole message stays within the cap: the files' text gets what the words leave. - let budget = MAX_PROMPT.saturating_sub(lead.chars().count() + FILE_NAMES_ROOM); + // The whole message stays within the cap: the files' text gets what the words and the lines + // naming files by their path leave. + let by_path = attach::note(&files.iter().filter(|f| f.by_place()).cloned().collect::>(), pictures, documents, 0); + let budget = MAX_PROMPT.saturating_sub(lead.chars().count() + by_path.chars().count() + FILE_NAMES_ROOM); let about_files = attach::note(&files, pictures, documents, budget); let sent: String = format!("{lead}{about_files}").chars().take(MAX_PROMPT).collect(); + // What goes by path may be read by the agent's own read tools without asking (see + // `on_permission`), once the message names it: a line cut off by the cap doesn't count. + app.agent_chat.send_by_path(&files, &sent); let mut parts = vec![PromptPart::Text(sent)]; if image { match crate::control::view_png(app, VIEW_IMAGE.0, VIEW_IMAGE.1) { @@ -2321,8 +2393,12 @@ fn start_turn_with(app: &mut SolveApp, text: String, image: bool, at: Option std::result::Result { + if takes_paths(app) { + return attach_by_path(app, path); + } if app.agent_chat.files() >= attach::MAX_FILES { return Err(trf("ui.agent_chat_files_max", &[("max", &attach::MAX_FILES.to_string())])); } @@ -2356,10 +2432,32 @@ pub fn attach_path(app: &mut SolveApp, path: &str) -> std::result::Result bool { + agents::current(app).is_some_and(|e| !e.kind.is_api()) +} + +/// Add a file or folder for a coding agent: nothing of it is read or imported; the agent is told +/// where it is and reads it, whole and at full size, with its own tools. +fn attach_by_path(app: &mut SolveApp, path: &str) -> std::result::Result { + if app.agent_chat.files() >= attach::MAX_ON_MESSAGE { + return Err(trf("ui.agent_chat_files_max", &[("max", &attach::MAX_ON_MESSAGE.to_string())])); + } + let p = std::path::Path::new(path); + let file = if p.is_dir() { attach::folder(p)? } else { attach::reference(p)? }; + Ok(app.agent_chat.add_file(file)) +} + +/// Add a picture from the clipboard (RGBA rows, as the system gives them) to the next message. It +/// goes with the message, to a coding agent too: there is no path to point it to. pub fn attach_rgba(app: &mut SolveApp, width: usize, height: usize, rgba: &[u8]) -> std::result::Result { - if app.agent_chat.files() >= attach::MAX_FILES { - return Err(trf("ui.agent_chat_files_max", &[("max", &attach::MAX_FILES.to_string())])); + let max = if takes_paths(app) { attach::MAX_ON_MESSAGE } else { attach::MAX_FILES }; + if app.agent_chat.files() >= max { + return Err(trf("ui.agent_chat_files_max", &[("max", &max.to_string())])); + } + if app.agent_chat.files_sent() >= attach::MAX_FILES { + return Err(trf("ui.agent_chat_paste_past_max", &[("max", &attach::MAX_FILES.to_string())])); } let n = app.agent_chat.pasted + 1; let name = format!("pasted picture {n}.png"); @@ -2480,14 +2578,42 @@ pub fn answer_permission(app: &mut SolveApp, index: usize, option: Option<&str>) /// The agent asks before running something of its own. The chat's own MCP tools are checked by /// SolidCraft's gate, so they're allowed here (no double question, see [`acp::is_bridge_tool`]); -/// otherwise the mode or an earlier "always allow" may answer, and the chat says so; otherwise the -/// user is asked. -fn on_permission(app: &mut SolveApp, key: u64, title: String, kind: Option<&str>, options: Vec) { +/// so is a read of a file or folder the user attached by path in this conversation (`reads`, see +/// [`acp::read_path`]); otherwise the mode or an earlier "always allow" may answer, and the chat +/// says so; otherwise the user is asked. `claude_tool`: which of Claude Code's own tools the +/// question is about, when its adapter says ([`acp::ClaudeCalls`]). +fn on_permission( + app: &mut SolveApp, + key: u64, + title: String, + kind: Option<&str>, + options: Vec, + reads: Option<&std::path::Path>, + claude_tool: Option<&str>, +) { + let attached = reads.is_some_and(|path| app.agent_chat.attached_by_path(path)); + // Claude Code reads only what was attached by path to this conversation: any other read, or + // one whose path or pattern can't be checked, is declined without asking, whatever the mode or + // a remembered answer. A question is Claude Code's read when its adapter names one of its read + // tools, whatever command started it, or when the agent is that adapter and the question is + // of kind read or search (not one of the chat's own tools). + let claude_read = claude_tool.is_some_and(|tool| acp::CLAUDE_ASK_TOOLS.contains(&tool)) + || (matches!(kind, Some("read" | "search")) && !acp::is_bridge_tool(&title, kind) && runs_claude_code(app)); + if !attached && claude_read { + let reject = options.iter().find(|o| o.kind == "reject_once").or_else(|| options.iter().find(|o| o.kind.starts_with("reject"))); + if let Some(b) = app.agent_chat.backend.as_mut() { + b.answer_permission(key, reject.map(|o| o.id.as_str())); + } + app.agent_chat.push(Item::Notice { text: trf("ui.ai_declined_read", &[("title", &title)]), error: false }); + return; + } let agent = app.agent_chat.running_id.clone(); let mode = agents::mode_in_force(app, &agent); let remembered = agents::always_allowed_in_force(app, &agent, &title); let why = if acp::is_bridge_tool(&title, kind) { Some("ui.ai_auto_ours") + } else if attached { + Some("ui.ai_auto_attached") } else if remembered { Some("ui.ai_auto_remembered") } else if mode == agents::Mode::All { @@ -2509,6 +2635,14 @@ fn on_permission(app: &mut SolveApp, key: u64, title: String, kind: Option<&str> } } +/// The running agent is Claude Code's ACP adapter: its backend recognised it when it started, or +/// its command says so now. +fn runs_claude_code(app: &SolveApp) -> bool { + let running = &app.agent_chat.running_id; + app.agent_chat.backend.as_ref().is_some_and(|b| b.claude_code()) + || agents::entries(app).iter().any(|entry| &entry.id == running && acp::is_claude_adapter(&entry.argv)) +} + fn approve_with(app: &mut SolveApp, id: u64, allow: bool, why: &str) { let chat = &mut app.agent_chat; let Some(i) = chat.held.iter().position(|h| h.id == id) else { return }; @@ -2932,7 +3066,17 @@ pub fn poll(app: &mut SolveApp, ctx: &egui::Context) { b.answer_permission(key, None); } } - Some(Outcome::Permission { key, title, kind, options }) => on_permission(app, key, title, kind.as_deref(), options), + Some(Outcome::Permission { key, title, kind, options, reads, claude_tool }) => { + on_permission(app, key, title, kind.as_deref(), options, reads.as_deref(), claude_tool.as_deref()) + } + Some(Outcome::Unasked { tool }) => { + // Claude Code's reads must ask (its session's ask rule) so that the chat can check + // each one; one that didn't means its adapter no longer honours the rule. + app.agent_chat.push(Item::Notice { text: trf("ui.ai_unasked_read", &[("tool", &tool)]), error: true }); + if app.agent_chat.turn.is_some() { + cancel(app); + } + } None => {} } if let Some(model) = confirmed_model { diff --git a/crates/ui-egui/src/agent_chat/panel.rs b/crates/ui-egui/src/agent_chat/panel.rs index 31fabd7af1b..647e7f5bcc8 100644 --- a/crates/ui-egui/src/agent_chat/panel.rs +++ b/crates/ui-egui/src/agent_chat/panel.rs @@ -82,8 +82,14 @@ pub enum PanelAction { at: Option, }, AttachDropped(Vec), - /// Choose a file to attach. + /// Choose files to attach, one or several: for an endpoint, those the chat can send or import; + /// for a coding agent, any type. ChooseAttachment, + /// Choose folders to attach, one or several, for a coding agent: it is told where each is. + ChooseFolder, + /// Choose files and folders in one dialog, for a coding agent, where the host's dialog can + /// (macOS). + ChooseAny, /// Attach the clipboard's picture (desktop only, as the clipboard reader is). #[cfg(not(target_arch = "wasm32"))] PastePicture, @@ -151,13 +157,13 @@ pub fn run(app: &mut SolveApp, ctx: &egui::Context, action: PanelAction) { PanelAction::SetConfigOption { id, value } => set_config_option(app, &id, &value), PanelAction::StartPick { at } => start_pick(app, at), PanelAction::AttachDropped(paths) => attach_dropped(app, paths.into_iter()), - PanelAction::ChooseAttachment => app.pick_file(tr("ui.agent_chat_attachable"), &attach::extensions(), |app, path| { - if let Some(path) = path - && let Err(e) = attach_path(app, &path) - { - app.agent_chat.notice(e, true); - } - }), + PanelAction::ChooseAttachment => { + // A coding agent reads any file itself; an endpoint gets what the chat can send or import. + let exts = if takes_paths(app) { Vec::new() } else { attach::extensions() }; + app.pick_files(tr("ui.agent_chat_attachable"), &exts, |app, paths| attach_dropped(app, paths.into_iter().map(std::path::PathBuf::from))) + } + PanelAction::ChooseFolder => app.pick_folders(|app, paths| attach_dropped(app, paths.into_iter().map(std::path::PathBuf::from))), + PanelAction::ChooseAny => app.pick_files_or_folders(|app, paths| attach_dropped(app, paths.into_iter().map(std::path::PathBuf::from))), #[cfg(not(target_arch = "wasm32"))] PanelAction::PastePicture => { if let Err(e) = paste_picture(app) { @@ -253,6 +259,9 @@ pub struct PanelView { pub shared: bool, /// The composer's height the shared host measured last time, if it has. pub composer_height: Option, + /// The host's file dialog chooses files and folders together (macOS): the + menu offers a + /// coding agent one Choose files or folders… instead of Choose files… and Choose folders…. + pub mixed_picker: bool, } impl PanelView { @@ -285,6 +294,7 @@ impl PanelView { rtl: crate::i18n::panel_direction(&app.preferences.language) == solidcraft_engine::panels::Direction::Rtl, shared: crate::panel_runtime::shared_content_measurement(ctx), composer_height: crate::panel_runtime::shared_content_composer_height(ctx), + mixed_picker: app.services.pick_files_or_folders.is_some(), } } } @@ -1331,7 +1341,7 @@ fn composer(chat: &mut AgentChat, view: &PanelView, ui: &mut egui::Ui, state: St Layout::left_to_right(Align::Center), |ui| { ui.set_min_height(Tokens::get().control_height + Tokens::get().space_2); - add_menu(chat, ui); + add_menu(chat, view, ui); let mode = view.permission; let permissions = ui .allocate_ui(vec2(Tokens::get().space_24 * 4.0, Tokens::get().control_height), |ui| { @@ -2793,6 +2803,10 @@ fn files_line<'a>(ui: &mut egui::Ui, names: impl Iterator) { /// The widest a file chip gets; a narrower chat makes them narrower. const CHIP_W: f32 = 170.0; +/// The tallest the file chips get past eight files, about three and a half rows: more scroll, and +/// the half row shows that there are more. A message to a coding agent holds up to 200 files, +/// which would otherwise push the conversation out of the panel; eight or fewer show whole. +pub(super) const CHIPS_MAX_HEIGHT: f32 = 112.0; /// The items of a message that are not pills in its text (those of Attach selection, or all of them /// when the message has no pills), with their "gone" flags and each one's place among all of the @@ -2960,6 +2974,7 @@ fn pill_input(chat: &mut AgentChat, view: &PanelView, ui: &mut egui::Ui, focused /// The files for the next message, as chips in rows that fit the chat: a picture's thumbnail (or /// a file mark), the name cut to fit, and a × that takes the file off. Laid out by hand: egui /// wraps plain widgets, not framed groups, and one row wider than the chat widens all below it. +/// Past eight files and [`CHIPS_MAX_HEIGHT`], the rows scroll. #[cfg(not(target_arch = "wasm32"))] fn attachment_chips(chat: &mut AgentChat, ui: &mut egui::Ui) { // Thumbnails of files no longer on the message are let go. @@ -2968,29 +2983,32 @@ fn attachment_chips(chat: &mut AgentChat, ui: &mut egui::Ui) { if chat.files() == 0 { return; } - let gap = ui.spacing().item_spacing.x; - let avail = ui.available_width().max(1.0); - let w = CHIP_W.min(avail); - let per_row = (((avail + gap) / (w + gap)).floor() as usize).max(1); let (mut remove, mut stop) = (None, None); // The files read, then those still being read (each takes its place once it is done). let read = chat.attachments.len(); let indices: Vec = (0..chat.files()).collect(); - for row in indices.chunks(per_row) { - ui.horizontal(|ui| { - for &i in row { - if let Some(f) = chat.attachments.get(i) { - if chip(ui, &mut chat.thumbs, f, i, w) { - remove = Some(i); + let most = if chat.files() > attach::MAX_FILES { CHIPS_MAX_HEIGHT } else { f32::INFINITY }; + egui::ScrollArea::vertical().id_salt("sc_agent_chat_chips").max_height(most).auto_shrink([false, true]).show(ui, |ui| { + let gap = ui.spacing().item_spacing.x; + let avail = ui.available_width().max(1.0); + let w = CHIP_W.min(avail); + let per_row = (((avail + gap) / (w + gap)).floor() as usize).max(1); + for row in indices.chunks(per_row) { + ui.horizontal(|ui| { + for &i in row { + if let Some(f) = chat.attachments.get(i) { + if chip(ui, &mut chat.thumbs, f, i, w) { + remove = Some(i); + } + } else if let Some(l) = chat.loading.get(i - read) + && loading_chip(ui, &l.name, l.importing(), i - read, w) + { + stop = Some(i - read); } - } else if let Some(l) = chat.loading.get(i - read) - && loading_chip(ui, &l.name, l.importing(), i - read, w) - { - stop = Some(i - read); } - } - }); - } + }); + } + }); if let Some(i) = remove && i < chat.attachments.len() { @@ -3004,6 +3022,17 @@ fn attachment_chips(chat: &mut AgentChat, ui: &mut egui::Ui) { } } +/// What a chip says when the pointer rests on it: the file's name; for one that goes by its path, +/// that place (and for a folder, what the agent does with it). +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn chip_tip(f: &attach::Attachment) -> String { + match &f.content { + attach::Content::Reference { path, .. } => path.display().to_string(), + attach::Content::Folder { path, .. } => format!("{}\n{}", path.display(), tr("ui.agent_chat_folder_tip")), + _ => f.name.clone(), + } +} + /// What a chip's × says: an imported part stays in the design when it comes off the message. #[cfg(not(target_arch = "wasm32"))] pub(super) fn remove_tip(f: &attach::Attachment) -> &'static str { @@ -3077,6 +3106,16 @@ fn chip(ui: &mut egui::Ui, thumbs: &mut std::collections::HashMap { + // A folder: a body with a tab on its top left. + let (r, _) = ui.allocate_exact_size(vec2(28.0, 20.0), Sense::hover()); + let s = Stroke::new(1.2, t.text_dim); + let body = Rect::from_min_max(pos2(r.left() + 3.0, r.top() + 5.0), pos2(r.right() - 3.0, r.bottom() - 2.0)); + let tab = Rect::from_min_max(pos2(body.left(), r.top() + 2.0), pos2(body.left() + 9.0, body.top())); + ui.painter().rect_stroke(body, 1.5, s, egui::StrokeKind::Inside); + ui.painter().rect_filled(tab, 1.0, t.text_dim); + r.width() + } None => { // A page marked with the file's type. let (r, _) = ui.allocate_exact_size(vec2(28.0, 20.0), Sense::hover()); @@ -3098,7 +3137,7 @@ fn chip(ui: &mut egui::Ui, thumbs: &mut std::collections::HashMap (SolveApp, Script, egui::Context) { (app, script, crate::fonts::test_context()) } +/// The chat's agent is a coding agent (Claude Code over ACP), which reads files with tools of its +/// own: every file and folder goes to it by its path. +fn with_coding_agent(app: &mut SolveApp) { + app.preferences.agents.push(agents::AgentConfig { + id: "claude-test".into(), + name: "Claude Code".into(), + command: "/opt/homebrew/bin/claude-agent-acp".into(), + ..Default::default() + }); + app.agent_chat.agent_id = Some("claude-test".into()); +} + fn ended(script: &Script, reason: &str) { script.report(Event::TurnEnded { reason: reason.into() }); } @@ -1255,6 +1398,8 @@ fn a_late_sign_in_retry_or_permission_cannot_restart_a_departed_turn() { title: "mcp__solidcraft-app__batch".into(), kind: None, options: vec![PermissionOption { id: "allow".into(), name: "Allow".into(), kind: "allow_once".into() }], + reads: None, + claude_tool: None, }); ended(&script, "auth"); script.report(Event::AuthRequired { methods: Vec::new() }); @@ -3642,6 +3787,126 @@ fn at_most_eight_files_on_a_message() { let _ = std::fs::remove_dir_all(&d); } +/// To a coding agent every file and folder goes by its path, whatever its kind and however many +/// (up to MAX_ON_MESSAGE): nothing is read, decoded or imported, and the agent reads them whole +/// with its own tools. A pasted picture has no path, so it goes with the message, at most eight. +#[test] +fn a_coding_agent_gets_every_file_and_folder_by_its_path() { + let d = attachable("by-path"); + std::fs::write(d.join("block.stl"), b"solid x\nendsolid x\n").unwrap(); + let (mut app, script, ctx) = app_with_script(); + with_coding_agent(&mut app); + for name in ["target.png", "brief.md", "block.stl"] { + attach_path(&mut app, &at(&d, name)).unwrap(); + } + attach_dropped(&mut app, [d.clone()].into_iter()); + for _ in 0..attach::MAX_FILES { + attach_path(&mut app, &at(&d, "target.png")).unwrap(); + } + assert!(app.agent_chat.loading.is_empty(), "nothing is read"); + assert_eq!(app.agent_chat.attachments.len(), attach::MAX_FILES + 4, "nothing refused past eight"); + assert!(app.agent_chat.attachments.iter().all(attach::Attachment::by_place), "all by path"); + assert!(matches!(app.agent_chat.attachments[2].content, attach::Content::Reference { mime: "model/stl", .. }), "not imported"); + assert!(attach_path(&mut app, &at(&d, "missing.png")).is_err(), "a missing file is still refused"); + send(&mut app, &ctx, "these".into()); + let sent = &script.prompts()[0]; + let text = text_of(sent); + assert_eq!(pictures_in(sent), 0, "{text}"); + assert!(text.contains("Attached file `target.png` (image/png, "), "{text}"); + assert!(text.contains("Attached file `brief.md` (text/markdown, ") && !text.contains("wall 2 mm"), "its text is not in it: {text}"); + assert!(text.contains("Attached file `block.stl` (model/stl, "), "{text}"); + let folder = d.file_name().unwrap().to_string_lossy().to_string(); + assert!(text.contains(&format!("Attached folder `{folder}/` (at ")), "{text}"); + assert_eq!(text.matches("read it with your own tools").count(), attach::MAX_FILES + 4, "{text}"); + for _ in 0..attach::MAX_FILES { + attach_rgba(&mut app, 2, 2, &[9; 16]).unwrap(); + } + assert!(attach_rgba(&mut app, 2, 2, &[9; 16]).unwrap_err().contains("save the picture as a file")); + new_chat(&mut app); + for _ in 0..attach::MAX_ON_MESSAGE { + attach_path(&mut app, &at(&d, "brief.md")).unwrap(); + } + assert!(attach_path(&mut app, &at(&d, "brief.md")).unwrap_err().contains("200"), "a bound on files in all"); + let _ = std::fs::remove_dir_all(&d); +} + +/// A folder attached through the control channel goes to a coding agent by its path, nothing in it +/// listed or read; without one (an endpoint can't open it), it is refused. +#[test] +fn an_attached_folder_tells_the_agent_where_it_is() { + let d = attachable("folder"); + let (mut app, script, ctx) = app_with_script(); + assert!(control(&mut app, &ctx, &json!({"attach": d.to_string_lossy()})).is_err(), "no coding agent: no folders"); + with_coding_agent(&mut app); + control(&mut app, &ctx, &json!({"attach": d.to_string_lossy()})).unwrap(); + assert!(app.agent_chat.loading.is_empty(), "nothing in it is read"); + send(&mut app, &ctx, "look in here".into()); + let text = text_of(&script.prompts()[0]); + assert!(text.contains(&format!("Attached folder `{}/` (at ", d.file_name().unwrap().to_string_lossy())), "{text}"); + assert!(!text.contains("target.png"), "nothing in it is listed: {text}"); + let _ = std::fs::remove_dir_all(&d); +} + +/// For a coding agent, where the host's dialogs choose files or folders but not both (Windows, +/// Linux), the + menu has Choose files… (any type) and Choose folders…, each taking several at +/// once; where one dialog mixes them (macOS), one Choose files or folders… takes both. +#[test] +fn the_plus_menu_chooses_several_files_and_folders() { + use solidcraft_ui_registry::handle_at; + let d = attachable("choose-many"); + let (one, two) = (d.join("one"), d.join("two")); + std::fs::create_dir_all(&one).unwrap(); + std::fs::create_dir_all(&two).unwrap(); + let mut h = narrow_chat(); + with_coding_agent(&mut h.app); + let chosen = vec![at(&d, "brief.md"), at(&d, "target.png")]; + h.app.services.pick_files = Some(Box::new(move |_: &str, exts: &[&str]| { + assert!(exts.is_empty(), "a coding agent reads any type: {exts:?}"); + let all = chosen.clone(); + Box::pin(async move { all }) + })); + let folders = vec![one.to_string_lossy().to_string(), two.to_string_lossy().to_string()]; + h.app.services.pick_folders = Some(Box::new(move || { + let all = folders.clone(); + Box::pin(async move { all }) + })); + h.frames(2); + let plus = handle_at("agent_chat:add").expect("a + button"); + let choose = |h: &mut crate::scenario::Harness, item: &str| { + h.call("ui.click", json!({"x": plus.x, "y": plus.y})); + h.frames(2); + let at = handle_at(item).unwrap_or_else(|| panic!("{item} in the + menu")); + h.call("ui.click", json!({"x": at.x, "y": at.y})); + h.frames(2); + settle_chat(h); + }; + choose(&mut h, "agent_chat:add_file"); + assert_eq!(status(&h.app)["attachments"], json!(["brief.md", "target.png"]), "both chosen files"); + assert!(handle_at("agent_chat:add_any").is_none(), "no mixed item where the dialogs don't mix"); + choose(&mut h, "agent_chat:add_folder"); + assert_eq!(status(&h.app)["attachments"], json!(["brief.md", "target.png", "one/", "two/"]), "both chosen folders"); + assert!(h.app.agent_chat.attachments.iter().all(attach::Attachment::by_place), "all by their path"); + // Cancelled: nothing more. + h.app.services.pick_files = Some(Box::new(|_: &str, _: &[&str]| Box::pin(async { Vec::new() }))); + choose(&mut h, "agent_chat:add_file"); + assert_eq!(h.app.agent_chat.attachments.len(), 4); + // One dialog for both. + h.app.agent_chat.attachments.clear(); + let mixed = vec![at(&d, "brief.md"), one.to_string_lossy().to_string()]; + h.app.services.pick_files_or_folders = Some(Box::new(move || { + let all = mixed.clone(); + Box::pin(async move { all }) + })); + h.frames(2); + choose(&mut h, "agent_chat:add_any"); + assert_eq!(status(&h.app)["attachments"], json!(["brief.md", "one/"]), "a file and a folder from one dialog"); + h.call("ui.click", json!({"x": plus.x, "y": plus.y})); + h.frames(2); + assert!(handle_at("agent_chat:add_file").is_none() && handle_at("agent_chat:add_folder").is_none(), "one item instead of two"); + assert!(handle_at("agent_chat:paste_picture").is_some()); + let _ = std::fs::remove_dir_all(&d); +} + /// While the agent works, a message queues with its files: the queue shows them, Stop keeps /// them, and they go with the queue. #[test] @@ -3925,6 +4190,33 @@ fn assert_inside_the_panel(chips: usize) { } } +/// Many files on a message (to a coding agent, up to 200) scroll in a strip of chips about three +/// rows high, so the text box stays in the panel; eight or fewer show whole, as before. +#[test] +fn many_files_scroll_in_a_strip_of_chips() { + use solidcraft_ui_registry::rect_of; + let d = attachable("many-chips"); + let mut h = narrow_chat(); + with_coding_agent(&mut h.app); + for _ in 0..attach::MAX_FILES { + attach_path(&mut h.app, &at(&d, "brief.md")).unwrap(); + } + h.frames(3); + let last = rect_of(&format!("agent_chat:file:{}", attach::MAX_FILES - 1)).expect("the eighth chip"); + let input = rect_of("agent_chat:input").expect("the text box"); + assert!(last.bottom() <= input.top(), "eight chips show whole: the eighth {last:?}, text box {input:?}"); + for _ in attach::MAX_FILES..40 { + attach_path(&mut h.app, &at(&d, "brief.md")).unwrap(); + } + h.frames(3); + let first = rect_of("agent_chat:file:0").expect("the first chip"); + let input = rect_of("agent_chat:input").expect("the text box"); + let panel = rect_of("agent_chat:panel").expect("the panel"); + assert!(input.top() - first.top() <= panel::CHIPS_MAX_HEIGHT + 24.0, "the chips stay in their strip: {first:?}, text box {input:?}"); + assert!(panel.contains_rect(input), "the text box stays in the panel: {input:?} in {panel:?}"); + let _ = std::fs::remove_dir_all(&d); +} + /// Files for the next message show as chips above the text box (a picture's thumbnail, the name, /// a × that takes it off), inside the chat, and Send sends files with no text. #[test] @@ -3984,9 +4276,10 @@ fn each_file_has_its_own_id_and_thumbnail() { let _ = std::fs::remove_dir_all(&d); } -/// The + button: "Choose a file…" asks the app's file picker for the types that can be attached -/// (not the design types Open shows) and attaches what it answers; "Paste a picture" attaches -/// the clipboard's picture (here given as RGBA, as the system does). +/// The + button: "Choose files…" asks the app's file picker for several files, the types that can +/// be attached listed (not the design types Open shows), and attaches what it answers; "Paste a +/// picture" attaches the clipboard's picture (here given as RGBA, as the system does). An endpoint +/// can't open folders, so there is no item for them, even where the host's dialog could mix them. #[test] fn the_plus_button_attaches_a_chosen_file_or_a_pasted_picture() { use solidcraft_ui_registry::handle_at; @@ -3995,17 +4288,19 @@ fn the_plus_button_attaches_a_chosen_file_or_a_pasted_picture() { let chosen = at(&d, "brief.md"); let asked = std::rc::Rc::new(std::cell::RefCell::new(Vec::::new())); let seen = asked.clone(); - h.app.services.pick_file = Some(Box::new(move |_label: &str, exts: &[&str]| { + h.app.services.pick_files = Some(Box::new(move |_label: &str, exts: &[&str]| { *seen.borrow_mut() = exts.iter().map(|e| e.to_string()).collect(); let p = chosen.clone(); - Box::pin(async move { Some(p) }) + Box::pin(async move { vec![p] }) })); + h.app.services.pick_files_or_folders = Some(Box::new(|| Box::pin(async { Vec::new() }))); h.frames(2); let plus = handle_at("agent_chat:add").expect("a + button"); h.call("ui.click", json!({"x": plus.x, "y": plus.y})); h.frames(2); - let choose = handle_at("agent_chat:add_file").expect("Choose a file… in its menu"); + let choose = handle_at("agent_chat:add_file").expect("Choose files… in its menu"); assert!(handle_at("agent_chat:paste_picture").is_some(), "Paste a picture in its menu"); + assert!(handle_at("agent_chat:add_folder").is_none() && handle_at("agent_chat:add_any").is_none(), "no folders"); h.call("ui.click", json!({"x": choose.x, "y": choose.y})); h.frames(4); assert_eq!(status(&h.app)["attachments"], json!(["brief.md"])); diff --git a/crates/ui-egui/src/file_picker.rs b/crates/ui-egui/src/file_picker.rs index 59d4670a08f..066d4c0b4f7 100644 --- a/crates/ui-egui/src/file_picker.rs +++ b/crates/ui-egui/src/file_picker.rs @@ -12,6 +12,8 @@ use crate::SolveApp; /// A host picker answer: a selected path, or `None` when cancelled. pub type FilePickerFuture = Pin>>>; +/// A host picker answer for several files: the selected paths, none when cancelled. +pub type FilesPickerFuture = Pin>>>; type Completion = Box)>; type Ready = Box; @@ -85,10 +87,59 @@ impl SolveApp { self.begin_picker(future, Box::new(complete)); } + /// Ask for files, several at once (the agent chat's files): the types `extensions` names listed + /// under `label`, or any type when it names none. The host's dialog for several, else one file + /// as [`Self::pick_file`] asks. + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + pub(crate) fn pick_files(&mut self, label: &str, extensions: &[&str], complete: impl FnOnce(&mut SolveApp, Vec) + 'static) { + if self.file_picker_busy() { + return; + } + match self.services.pick_files.as_ref() { + Some(pick) => { + let future = pick(label, extensions); + self.begin_file_task(future, complete); + } + None => self.pick_file(label, extensions, move |app, path| complete(app, path.into_iter().collect())), + } + } + + /// Ask for folders, several at once (the agent chat's files): the host's dialog for several, + /// else one as [`Self::pick_folder`] asks. + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + pub(crate) fn pick_folders(&mut self, complete: impl FnOnce(&mut SolveApp, Vec) + 'static) { + if self.file_picker_busy() { + return; + } + match self.services.pick_folders.as_ref() { + Some(pick) => { + let future = pick(); + self.begin_file_task(future, complete); + } + None => self.pick_folder("", move |app, path| complete(app, path.into_iter().collect())), + } + } + + /// Ask for files and folders in one dialog, several at once, where the host's dialog can + /// (macOS). Without one, the answer is a cancel (the chat then offers files and folders apart). + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + pub(crate) fn pick_files_or_folders(&mut self, complete: impl FnOnce(&mut SolveApp, Vec) + 'static) { + if self.file_picker_busy() { + return; + } + match self.services.pick_files_or_folders.as_ref() { + Some(pick) => { + let future = pick(); + self.begin_file_task(future, complete); + } + None => complete(self, Vec::new()), + } + } + /// Ask for a folder, starting in `current` (empty: the folder last used): a plugin field's - /// Browse button, the document library's folder, or a folder setting. The plugin dialog shows - /// Browse only when this service is set. Without a host dialog, the answer is a cancel and - /// nothing is changed. + /// Browse button, the document library's folder, a folder setting, or one the agent chat + /// attaches. The plugin dialog shows Browse only when this service is set. Without a host + /// dialog, the answer is a cancel and nothing is changed. pub(crate) fn pick_folder(&mut self, current: &str, complete: impl FnOnce(&mut SolveApp, Option) + 'static) { if self.file_picker_busy() { return; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index ec0153b1266..7aff6c74a62 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -242,7 +242,7 @@ pub(crate) mod frame_watch; #[cfg(test)] mod history_off_thread_tests; mod move_preview; -pub use file_picker::FilePickerFuture; +pub use file_picker::{FilePickerFuture, FilesPickerFuture}; #[cfg(test)] mod blend_arrow_tests; #[cfg(test)] @@ -638,11 +638,22 @@ pub struct Services { /// only the types it names, so the agent chat's files need a dialog of their own. `None`: the /// Open dialog. pub pick_file: Option FilePickerFuture>>, - /// Open a dialog asking for a folder, starting in the one given (empty: the folder last used). - /// `None` on the web build and when the host has no folder picker: a plugin field shows no - /// Browse button and the text field still accepts a pasted path, the document library cannot - /// choose a folder, and Settings › Design hides the folder settings. + /// Open a dialog for several files at once (the agent chat's files): the types it names listed + /// under its label, or any type when it names none (a coding agent reads them itself). `None`: + /// one file, with `pick_file`. + pub pick_files: Option FilesPickerFuture>>, + /// Open one dialog for files and folders together, several at once, where the system's dialog + /// can (macOS). `None` elsewhere: the chat offers files and folders apart. + pub pick_files_or_folders: Option FilesPickerFuture>>, + /// Open a dialog asking for a folder, starting in the one given (empty: the folder last used): + /// a plugin field's Browse button, the document library's folder, or one the agent chat + /// attaches. `None` on the web build and when the host has no folder picker: a plugin field + /// shows no Browse button and the text field still accepts a pasted path, the document library + /// cannot choose a folder, and Settings › Design hides the folder settings. pub pick_folder: Option FilePickerFuture>>, + /// Open a dialog for several folders at once (the agent chat's files). `None`: one, with + /// `pick_folder`. + pub pick_folders: Option FilesPickerFuture>>, /// Ask for a file to open. The extensions are the file type the command reads, offered as /// the picker's first filter (`&[]`: designs, CAD files and meshes, #1801). pub pick_open: Option FilePickerFuture>>, diff --git a/docs/agent-chat.md b/docs/agent-chat.md index 4f084935c40..b7f09771dd0 100644 --- a/docs/agent-chat.md +++ b/docs/agent-chat.md @@ -147,10 +147,13 @@ turn limit. Queue, Send now and Stop keep their existing behavior. ## Files and pictures A message can carry up to eight files, to show the agent what you mean: a concept picture, a -sketch, a brief, a part to fit around. +sketch, a brief, a part to fit around. That is for an OpenAI- or Anthropic-compatible endpoint, +which has only SolidCraft's tools, so the files go in the message as below. A coding agent reads +files with its own tools: it gets every file and folder by its path instead +([To a coding agent](#to-a-coding-agent)). -- **+** next to **Send** has **Choose a file…** (a file dialog for the types below) and **Paste a - picture** (the picture on the clipboard). +- **+** next to **Send** has **Choose files…** (a file dialog for the types below, several at + once) and **Paste a picture** (the picture on the clipboard). - **Drop files on the chat.** Files dropped on the panel (or its folded strip) attach to the next message, and the app doesn't open them too. While files are dragged over the chat, it says so. The window gives no position while something is dragged, so the drop is the chat's when the @@ -172,6 +175,16 @@ sketch, a brief, a part to fit around. shows a spinner meanwhile, and **Send** waits), and the message tells the agent it was added; a failed import says why and the agent is told nothing of it. Taking a part's chip off the message leaves the part in the design (Undo removes it). +- **PDFs** (up to 12 MB) go whole as documents, so the model sees their pages, drawings and + scans included. **Any other file** (a ZIP, a DXF) is refused: an endpoint has no tool that opens + a file. Drop a DXF on the design instead to bring it in as a sketch. +- The conversation keeps every picture and PDF of the newest message, and two of each from the + messages before it; older ones are swapped for a short note, as every request carries the + whole conversation. One request carries at most 18 MB of pictures and PDFs: older ones go first, + and a message whose own come to more isn't sent (the chat says how much it holds). An endpoint + that doesn't take PDFs, such as some OpenAI-compatible servers, refuses the message. +- A message with pictures or PDFs that the endpoint refuses before it answers is taken out of the + conversation, so the next message doesn't send them again; send it again to retry. - Every file is named in the message. In the conversation the attached pictures show under it as thumbnails (hold the pointer over one for a bigger preview, click it to open the viewer, where the file's name is shown and ‹ › step through the message's pictures, together with the picture @@ -182,8 +195,31 @@ sketch, a brief, a part to fit around. Files stay with their message: one queued while the agent works keeps its files, and one sent again after a sign-in sends them again. When several queued messages go as one prompt, their -files go with it, at most eight; the rest are named in the chat and not sent. **New chat** -clears the files waiting on the chips too. +files go with it, at most eight (200 to a coding agent); the rest are named in the chat and not +sent. **New chat** clears the files waiting on the chips too. + +### To a coding agent + +A coding agent (Claude Code, Codex, Gemini CLI…) reads files with its own tools, so it gets every +file and folder by its path, up to 200 on one message, whatever their type: + +- **+** has **Choose files…** (any type) and **Choose folders…**, several at once; on macOS, whose + file dialog chooses both together, one **Choose files or folders…**. Files and folders dropped + on the chat attach the same way. +- SolidCraft reads nothing of them: no picture is scaled down, no text is cut, no CAD file is + imported (drop it on the design for that). The message tells the agent each file's name, type, + size and path, and each folder's path, so a batch of photos reaches the agent whole however + many there are. Nothing in a folder is listed or counted (on a network share that would keep + the message waiting); the agent lists it itself. +- Their chips show the file's type, or a folder; holding the pointer over one shows its path. The + chips scroll past about three rows, so the text box and the conversation stay in view. +- A pasted picture has no path, so it still goes in the message, at most eight. +- Each path is a line in the message's text, which stops at 100,000 characters. A file or folder + whose line falls past that isn't named to the agent and doesn't count as sent: shorten the + message, or send the rest in another message. +- Claude Code reads what you sent by path without asking (*Auto-allowed* in the chat), and the + chat declines any other read of its own (see [What it can't do](#what-it-cant-do)). Another + coding agent reads with its own tools and asks as its own mode says. ## Typing while the agent works @@ -571,9 +607,11 @@ These settings cover SolidCraft's tools. A coding agent's own tools (its shell, follow the agent's own mode, which you pick in the panel's header. When an agent asks before using one of the chat's own SolidCraft tools and names it exactly as the Claude adapter does (`mcp__solidcraft-app__batch`), SolidCraft answers for you, since its own gate checks the call, -and notes it in the chat as *Auto-allowed*. Any other question appears in the panel, including -a SolidCraft tool an agent words differently and a SolidCraft MCP server you added to an agent -other than Claude Code yourself. With **Allow everything**, or after **Always allow**, those questions are answered the +and notes it in the chat as *Auto-allowed*. So it does when Claude Code reads something you sent +by path in this conversation, and it declines any other read of Claude Code's whatever the mode +(see below). Any other question appears in the panel, including a SolidCraft tool an agent words +differently and a SolidCraft MCP server you added to an agent other than Claude Code yourself. +With **Allow everything**, or after **Always allow**, those questions are answered the same way and noted too. What counts as "a command given a file name": a parameter that holds a file or folder (`file`, @@ -599,9 +637,20 @@ saves, opens or inserts. A sweep's or pattern's `path` (curve ids) and an occurr chat itself. - **Its own tools stay off where we can turn them off.** SolidCraft declares no file system and no terminal to the agent, runs it in an empty working folder of its own, and asks the Claude - Code adapter for a session with none of its own tools but the one that ends plan mode, and with - SolidCraft's MCP server as its only one. Your claude.ai connectors, your own MCP servers, and - Claude Code's shell, file, web, scheduling and messaging tools aren't there. + Code adapter for a session with none of its own tools but the one that ends plan mode and its + read tools (below), and with SolidCraft's MCP server as its only one. Your claude.ai + connectors, your own MCP servers, and Claude Code's shell, file-writing, web, scheduling and + messaging tools aren't there. +- **Claude Code reads only what you sent.** Its read tools (Read, Glob, Grep) are on, but they ask + before every read. The chat allows a read inside a file or folder you sent by path in this + conversation, and declines any other without asking you, whatever the mode and even after + **Always allow**: a file you didn't send, a search whose pattern starts at a root or your home + folder or steps up with `..`, or a link in a folder you sent that leads out of it (a path counts + once links are followed). To let it read another file, attach it. **New chat** starts with + nothing sent. The read tools are on only when the agent's command names the Claude Code adapter + (`claude-agent-acp`, or the older `claude-code-acp`); started any other way, through a script + of your own say, it can't read at all. If it ever reads without asking first, the chat stops + the message and says so. When the panel's agent is stopped, another agent is picked, or SolidCraft quits, the agent and every program it started (the CLI it wraps, its MCP server) are stopped. diff --git a/docs/control-protocol.md b/docs/control-protocol.md index ee519146a29..9f8bce6847f 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -1141,7 +1141,7 @@ its length, handles `measure:gap:1`, `measure:gap:2`, … in order along the row | `engine.execute` → `browser.expand_all` | `path?`: occurrence ids; `component?`: id; omit both for the whole tree | Open every Browser row under that scope, including folders that start closed (Origin, Named Views, Features). Display only: not saved in the design, not an undo step. | | `engine.execute` → `browser.collapse_all` | same | Close those rows. The design row stays open when the whole tree is collapsed. | | `engine.execute` → `view.history_layout` | `width?`, `dock?`: `bottom`, `left`, `under_browser`, `browser`, `collapsed?` | Update the History panel in the shared layout without changing the design. `browser` shows features in the Browser in place of a separate panel. | -| `ui.agent_chat` | `features?`, `toolbar_button?`, `connect_at_start?` and `open_at_start?` (connect the agent started last, and open the panel, when SolidCraft starts; both off by default, never with `--control`), `instructions?` (the custom instructions every new chat's system note carries, Preferences → AI; at most 4000 characters are kept), `permissions?` (`ask`, `edits`, `all`), `add_agent?` ({`name`, `kind`: `acp`, `api` or `anthropic` (`api` is OpenAI-compatible, `anthropic` Anthropic-compatible), `command` or `base_url` + `model` + `request_timeout_s?` (seconds one model request may take, 300 by default, rounded and clamped to 30 to 3600), `allow_insecure_http?` (OpenAI-compatible endpoints only; false by default; explicitly permits sending the key over unencrypted HTTP to this endpoint, without opening a confirmation dialog), `openai_responses?` (defaults to false and selects Responses for kind `api`)}; no keys), `add_dialog?` (`installed`, `custom`, `api`, `anthropic`, or `false` to close), `edit_dialog?` (the id of an agent you added: the same dialog filled with what it holds, as its **Edit** button opens it; the key is never shown), `default_agent?`, `agent?` (the conversation's agent, by id), `mode?` (the agent's own mode), `provider?` (which provider's group the model picker opens first, when the models come from several), `model?` (one of its models, or see below), `open?`, `toggle?` (true: show or hide the panel as its button does, unfolding a folded one), `side?` (`left` or `right`), `minimized?`, `width?` (placement of the open shared Assistant), `popped?` (in its own window), `picker?`, `refresh?`, `connect?`, `stop?`, `attach?`: a file's path (a picture, a text file or a CAD file, for the next message; CAD files are imported at once), `remove_file?` (index of a file on the next message), `send?`: text (files alone make a message too), `send_input?` (true: send what is in the message box, as Enter does), `attach_view?`, `attach_selection?`, `pick?` (true: open the context picker), `pick_at?` (with `pick`: the character of the message box its pill goes to; the end by default), `permission?`: an option id or `"cancel"` (the newest question of the agent's own), `approve?`: true, false or `"always"` (the oldest request held for Allow/Deny), `cancel?` (Stop: the queue stays), `send_now?` (stop the running step, then send the queued messages), `remove_pending?` (index), `new_chat?` (clear the chat, new session), `undo?` (the last message's changes) | the chat's state: `features`, `agents` (found and added), `currentAgent`, `state` (off, starting, ready, busy, auth, exited, failed: the agent never got ready, and Connect reads Retry), `connectAtStart`, `openAtStart`, `instructions`, `lastAgent` (the agent started last), `popped`, `window` (its place and size), `agent`, `modes`, `mode`, `models`, `model`, `modelWarning` (the model capability warning text, or `null` when unknown or tool support is reported; checked asynchronously and never blocks sending), `turnWarning` (the latest completed turn's no-tool notice, otherwise `null`; cleared on the next turn or new chat), `providers` (`name` and `count` of each, empty with one provider), `provider` (the one listed), `authMethods`, `toolsPort`, `pid`, `waiting`, `turn`, `pending` (queued messages, with their `files`), `input` (the message box's text, picks as `«n: …»` marks), `pills` (what the marks in the box stand for), `picked` (the same items as one list of `label` and `detail`, as before the pills), `attachments` (the files on the next message, by name), `loading` (pictures still being read for it, by name), `stopped`, `detection` and the conversation (`items`). With `features` off only the settings apply. Desktop only; see [Agent chat](agent-chat.md) | +| `ui.agent_chat` | `features?`, `toolbar_button?`, `connect_at_start?` and `open_at_start?` (connect the agent started last, and open the panel, when SolidCraft starts; both off by default, never with `--control`), `instructions?` (the custom instructions every new chat's system note carries, Preferences → AI; at most 4000 characters are kept), `permissions?` (`ask`, `edits`, `all`), `add_agent?` ({`name`, `kind`: `acp`, `api` or `anthropic` (`api` is OpenAI-compatible, `anthropic` Anthropic-compatible), `command` or `base_url` + `model` + `request_timeout_s?` (seconds one model request may take, 300 by default, rounded and clamped to 30 to 3600), `allow_insecure_http?` (OpenAI-compatible endpoints only; false by default; explicitly permits sending the key over unencrypted HTTP to this endpoint, without opening a confirmation dialog), `openai_responses?` (defaults to false and selects Responses for kind `api`)}; no keys), `add_dialog?` (`installed`, `custom`, `api`, `anthropic`, or `false` to close), `edit_dialog?` (the id of an agent you added: the same dialog filled with what it holds, as its **Edit** button opens it; the key is never shown), `default_agent?`, `agent?` (the conversation's agent, by id), `mode?` (the agent's own mode), `provider?` (which provider's group the model picker opens first, when the models come from several), `model?` (one of its models, or see below), `open?`, `toggle?` (true: show or hide the panel as its button does, unfolding a folded one), `side?` (`left` or `right`), `minimized?`, `width?` (placement of the open shared Assistant), `popped?` (in its own window), `picker?`, `refresh?`, `connect?`, `stop?`, `attach?`: a file's path (a picture, a text file or a CAD file, for the next message; CAD files are imported at once; to a coding agent, any file or a folder, which goes by its path), `remove_file?` (index of a file on the next message), `send?`: text (files alone make a message too), `send_input?` (true: send what is in the message box, as Enter does), `attach_view?`, `attach_selection?`, `pick?` (true: open the context picker), `pick_at?` (with `pick`: the character of the message box its pill goes to; the end by default), `permission?`: an option id or `"cancel"` (the newest question of the agent's own), `approve?`: true, false or `"always"` (the oldest request held for Allow/Deny), `cancel?` (Stop: the queue stays), `send_now?` (stop the running step, then send the queued messages), `remove_pending?` (index), `new_chat?` (clear the chat, new session), `undo?` (the last message's changes) | the chat's state: `features`, `agents` (found and added), `currentAgent`, `state` (off, starting, ready, busy, auth, exited, failed: the agent never got ready, and Connect reads Retry), `connectAtStart`, `openAtStart`, `instructions`, `lastAgent` (the agent started last), `popped`, `window` (its place and size), `agent`, `modes`, `mode`, `models`, `model`, `modelWarning` (the model capability warning text, or `null` when unknown or tool support is reported; checked asynchronously and never blocks sending), `turnWarning` (the latest completed turn's no-tool notice, otherwise `null`; cleared on the next turn or new chat), `providers` (`name` and `count` of each, empty with one provider), `provider` (the one listed), `authMethods`, `toolsPort`, `pid`, `waiting`, `turn`, `pending` (queued messages, with their `files`), `input` (the message box's text, picks as `«n: …»` marks), `pills` (what the marks in the box stand for), `picked` (the same items as one list of `label` and `detail`, as before the pills), `attachments` (the files on the next message, by name), `loading` (pictures still being read for it, by name), `stopped`, `detection` and the conversation (`items`). With `features` off only the settings apply. Desktop only; see [Agent chat](agent-chat.md) | | `ui.resize` | `width`, `height` | | | `ui.library` | `open?` (bool), `size?`: `small`, `medium`, `large` or `list`, `folder?` (a folder or share path), `subfolder?` (one inside it), `insert?` (a listed part's name), `at?`: `[x, y, z]` mm | the parts library panel (also `view.parts_library` and the app bar's documents button, `|||`): shows or hides it, sets the card size (three, two or one across; `list` is names only), sets its folder, browses into a subfolder (folder, subfolder and size are kept in the preferences), inserts a part (a design as a linked component placed at `at`, a STEP or mesh file imported); returns `open`, `size`, `folder`, `shown` and the shown folder's `entries` (`name`, `kind`: folder / design / step / mesh, `path`) | | `app.quit` | `force?` (quit without asking about unsaved designs); `ask?` (default true; `false` refuses unsaved designs by name without opening a prompt). `ask: false, force: true` explicitly discards unsaved designs and their recovery copies; legacy `force: true` alone keeps recovery copies | `quitting` (the window closes), `asking` (a "save changes?" prompt is open) | diff --git a/docs/design/in-app-agent-chat.md b/docs/design/in-app-agent-chat.md index 7c2bb2a4e5e..ebdee73c196 100644 --- a/docs/design/in-app-agent-chat.md +++ b/docs/design/in-app-agent-chat.md @@ -235,7 +235,8 @@ loads the user's claude.ai connectors and their own MCP servers (#19554). The se `_meta.claudeCode.options`, which the adapter spreads over its own defaults, close all of that: - `tools: ["ExitPlanMode"]` (`acp::CLAUDE_TOOLS`): the only built-in tools. A list of what is allowed, so a tool a later Claude Code adds stays off. `ExitPlanMode` ends the plan mode the - mode picker offers; without it the agent stays in plan mode. + mode picker offers; without it the agent stays in plan mode. Read, Glob and Grep join it when the + adapter was recognised (below). - `disallowedTools` (`acp::CLAUDE_DISALLOWED_TOOLS`): the shell, file and web tools, a second guard. - `strictMcpConfig: true`: only the servers in `session/new`'s `mcpServers`, that is @@ -248,8 +249,45 @@ a proxy). Plugins synced from the user's claude.ai organisation still load too; tool their skills can't run, but their hooks do. Checked with `claude-agent-acp` 0.107.0, from the session's `init` event and with `ToolSearch` over ACP after the connectors had time to load: before, 39 connector tools, the user's own servers and 21 built-in tools outside the disallowed -list; after, `solidcraft-app`'s tools and `ExitPlanMode`. Other agents' own permission requests -appear in the panel with their options. +list; after, `solidcraft-app`'s tools and `ExitPlanMode`. + +Claude Code's read tools (Read, Glob, Grep) are on when the agent's command names +the adapter (`acp::is_claude_adapter`, decided once when it starts), behind a +`permissions.ask` rule (`_meta.claudeCode.options.settings`), so every read arrives as +`session/request_permission` with the path in `rawInput` (`file_path` for Read, `path` and +`pattern` for Glob, `path` or `file_path` and `glob` for Grep). `acp::read_path` accepts only +that form, with an absolute path and a pattern that can't leave it; the chat answers allow-once +when the path, links followed, lies inside a file or folder sent by path in this conversation +(`AgentChat::by_path`, cleared by New chat), and declines any other read of Claude Code's (kind +`read` or `search`) without asking, whatever the mode or a remembered answer. Checked with +`claude-agent-acp` 0.107.0: without the rule these tools read any path without asking. + +It fails closed when the adapter runs some other way (a wrapper script, `node …/dist/index.js`). +The session keeps the read tools out of `tools` and in `disallowedTools`, and the chat still knows Claude Code's own +read from the adapter's `_meta.claudeCode.toolName`, which it puts on every tool call's updates +(the question carries the call's `toolCallId`): such a question is declined unless it reads what +was sent, whatever command started the agent. The same names catch an adapter that stops +honouring the ask rule: a read tool call that completes without having asked +(`acp::ClaudeCalls`) stops the message with an error, so the rule can't be lost quietly. + +An earlier version kept the read tools off until a message first sent a file by path, then opened +the session again with them on (`session/new` with `_meta.claudeCode.options.resume`). That +reopen raced New chat and the first session's opening, could lose another agent's conversation +(only Claude Code knows `resume`), and needed a notice when a resume failed. With the tools on +from the start and every unsent read declined, the agent can read exactly what it could then, +with none of those cases. The chat sees only the +path a Glob or Grep starts from, not where its walk goes, so a link inside an attached folder +that points out of it is safe only because Claude Code's walk doesn't follow links. Checked with +0.107.0, with a linked folder and a linked file that both point outside: Glob `**/*`, a Grep over +the folder, and patterns that name a link (`linkdir/**/*`, `linkfile*`) returned only the +folder's own file, even with a ripgrep config saying `--follow` (`RIPGREP_CONFIG_PATH`). Check +this again when the adapter's version moves. Other agents' own +permission requests appear in the panel with their options. + +A coding agent gets every attached file and folder by its path (`attach::reference`, +`attach::folder`); an endpoint, which has no tool that opens a path, gets pictures, text and PDFs +in the message (a PDF as an OpenAI `file` part or an Anthropic `document` block) and CAD files +imported (`attach::read`), at most eight, and is refused any other file. ### Processes