From f5ca4b5e5304b3443ef9a935bfb25dbb3c255e12 Mon Sep 17 00:00:00 2001 From: Seth LaForge Date: Fri, 13 Nov 2026 18:20:23 -0800 Subject: [PATCH 01/12] Assistant: pick several files at once or a whole folder; files past the eighth go to the agent as paths (#16452) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Choose files… (was Choose a file…) picks several files in one dialog, and the new Choose a folder… attaches a folder, as dropping one on the chat does. A folder goes to the agent as its path, its file and folder counts, and the names of its first 200 entries. Past eight files, further files are no longer refused. Each one goes as its path, type, size and (for a picture) its size in pixels, and the agent reads the original at full size with its own tools. A message holds up to 200 files in all; a pasted picture, which has no path, is refused past eight. Co-Authored-By: Claude Opus 5.5 --- apps/solidcraft/src/main.rs | 53 ++- assets/locales/ar.json | 2 +- assets/locales/de.json | 2 +- assets/locales/en.json | 2 +- assets/locales/es.json | 2 +- assets/locales/fr.json | 2 +- assets/locales/he.json | 2 +- .../pending/agent-chat-files-by-place.json | 66 ++++ assets/locales/vi.json | 2 +- crates/ui-egui/src/agent_chat/attach.rs | 356 +++++++++++++++--- crates/ui-egui/src/agent_chat/mod.rs | 112 ++++-- crates/ui-egui/src/agent_chat/panel.rs | 54 ++- crates/ui-egui/src/agent_chat/tests.rs | 129 ++++++- crates/ui-egui/src/file_picker.rs | 40 +- crates/ui-egui/src/lib.rs | 7 +- docs/agent-chat.md | 31 +- docs/control-protocol.md | 2 +- 17 files changed, 740 insertions(+), 124 deletions(-) create mode 100644 assets/locales/pending/agent-chat-files-by-place.json diff --git a/apps/solidcraft/src/main.rs b/apps/solidcraft/src/main.rs index a7b97270fed..bce4873a261 100644 --- a/apps/solidcraft/src/main.rs +++ b/apps/solidcraft/src/main.rs @@ -585,6 +585,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() + } + fn folder(&self) -> Option { self.0.lock().ok().and_then(|state| state.folder.clone()) } @@ -598,6 +607,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 { @@ -656,7 +678,10 @@ 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 folder_parent = parent.clone(); let (open_folder, file_folder, save_folder) = (folder.clone(), folder.clone(), folder.clone()); + let (files_folder, folder_folder) = (folder.clone(), folder.clone()); Services { pick_open: Some(Box::new(move |first: &[&str]| { // The chooser that opens may not be the desktop's own (#10159). @@ -679,23 +704,31 @@ fn services(cc: &eframe::CreationContext<'_>, folder: &DialogFolder) -> Services let folder = open_folder.clone(); Box::pin(async move { folder.answer(future.await) }) })), - // 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). + // One kind of file (a plug-in, 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(file_parent.clone()).add_filter(label, &all).add_filter("All files", &["*"]).pick_file(); let folder = file_folder.clone(); Box::pin(async move { folder.answer(future.await) }) })), + // The same, several files at once (the agent chat's attachments: a batch of photos). + pick_files: Some(Box::new(move |label: &str, exts: &[&str]| { + let all = any_case(exts); + let all: Vec<&str> = all.iter().map(String::as_str).collect(); + let future = files_folder.start(files_parent.clone()).add_filter(label, &all).add_filter("All files", &["*"]).pick_files(); + let folder = files_folder.clone(); + Box::pin(async move { folder.answer_all(future.await) }) + })), + // A folder (the agent chat attaches one by its place). + pick_folder: Some(Box::new(move || { + let future = folder_folder.start(folder_parent.clone()).pick_folder(); + let folder = folder_folder.clone(); + Box::pin(async move { folder.answer(future.await) }) + })), 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 7cd753b0477..dcb154b6466 100644 --- a/assets/locales/ar.json +++ b/assets/locales/ar.json @@ -5182,7 +5182,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 09fa58ed38a..786dce5eb1e 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -4861,7 +4861,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 85499a14f59..56f75c734ea 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -5182,7 +5182,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 e1ad1bae344..badfac392a5 100644 --- a/assets/locales/es.json +++ b/assets/locales/es.json @@ -5182,7 +5182,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 e885ac27310..a28ab9ecb5f 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -4405,7 +4405,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 33e183115d5..35a126913c4 100644 --- a/assets/locales/he.json +++ b/assets/locales/he.json @@ -5182,7 +5182,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..e9bf5f27a8c --- /dev/null +++ b/assets/locales/pending/agent-chat-files-by-place.json @@ -0,0 +1,66 @@ +{ + "en": { + "ui.agent_chat_add_folder": "Choose a folder…", + "ui.agent_chat_add_folder_tip": "The agent is told where the folder is and what it holds, and reads the files it needs itself, at full size", + "ui.agent_chat_file_by_place_tip": "Not in the message: the agent is told where it is and reads it with its own tools", + "ui.agent_chat_files_by_place": "Past {max} files, the rest go by their place on disk: the agent reads them with its own tools, at full size", + "ui.agent_chat_folder_tip": "A folder: the agent is told where it is and what it holds, 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" + }, + "ar": { + "ui.agent_chat_add_folder": "اختر مجلدًا…", + "ui.agent_chat_add_folder_tip": "يُخبَر الوكيل بمكان المجلد وما يحتويه، ويقرأ بنفسه الملفات التي يحتاجها بحجمها الكامل", + "ui.agent_chat_file_by_place_tip": "ليس ضمن الرسالة: يُخبَر الوكيل بمكانه ويقرؤه بأدواته الخاصة", + "ui.agent_chat_files_by_place": "بعد {max} ملفات، تُرسل البقية بمكانها على القرص: يقرؤها الوكيل بأدواته الخاصة بحجمها الكامل", + "ui.agent_chat_folder_tip": "مجلد: يُخبَر الوكيل بمكانه وما يحتويه، ويقرأ الملفات التي يحتاجها بأدواته الخاصة", + "ui.agent_chat_paste_past_max": "يُرسل {max} ملفات كحد أقصى في رسالة واحدة؛ احفظ الصورة في ملف وأرفقه بدلًا منها" + }, + "de": { + "ui.agent_chat_add_folder": "Ordner auswählen…", + "ui.agent_chat_add_folder_tip": "Der Agent erfährt, wo der Ordner liegt und was er enthält, und liest die benötigten Dateien selbst, in voller Größe", + "ui.agent_chat_file_by_place_tip": "Nicht in der Nachricht: Der Agent erfährt, wo die Datei liegt, und liest sie mit seinen eigenen Werkzeugen", + "ui.agent_chat_files_by_place": "Ab {max} Dateien gehen die übrigen über ihren Ort auf der Festplatte: Der Agent liest sie mit seinen eigenen Werkzeugen, in voller Größe", + "ui.agent_chat_folder_tip": "Ein Ordner: Der Agent erfährt, wo er liegt und was er enthält, 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" + }, + "he": { + "ui.agent_chat_add_folder": "בחירת תיקייה…", + "ui.agent_chat_add_folder_tip": "הסוכן מקבל את מיקום התיקייה ואת תוכנה, וקורא בעצמו את הקבצים שהוא צריך, בגודלם המלא", + "ui.agent_chat_file_by_place_tip": "לא בתוך ההודעה: הסוכן מקבל את מיקום הקובץ וקורא אותו בכלים שלו", + "ui.agent_chat_files_by_place": "מעבר ל־{max} קבצים, השאר נשלחים לפי מיקומם בדיסק: הסוכן קורא אותם בכלים שלו, בגודלם המלא", + "ui.agent_chat_folder_tip": "תיקייה: הסוכן מקבל את מיקומה ואת תוכנה, וקורא את הקבצים שהוא צריך בכלים שלו", + "ui.agent_chat_paste_past_max": "לכל היותר {max} קבצים בהודעה אחת; יש לשמור את התמונה כקובץ ולצרף אותו במקומה" + }, + "ja": { + "ui.agent_chat_add_folder": "フォルダーを選択…", + "ui.agent_chat_add_folder_tip": "フォルダーの場所と中身がエージェントに伝えられ、必要なファイルはエージェントがフルサイズのまま自分で読み込みます", + "ui.agent_chat_file_by_place_tip": "メッセージには含まれません。場所がエージェントに伝えられ、エージェントが自分のツールで読み込みます", + "ui.agent_chat_files_by_place": "{max} 個を超えたファイルはディスク上の場所で渡されます。エージェントが自分のツールでフルサイズのまま読み込みます", + "ui.agent_chat_folder_tip": "フォルダー: 場所と中身がエージェントに伝えられ、必要なファイルはエージェントが自分のツールで読み込みます", + "ui.agent_chat_paste_past_max": "1 つのメッセージで送れるファイルは {max} 個までです。画像をファイルとして保存し、そのファイルを添付してください" + }, + "ko": { + "ui.agent_chat_add_folder": "폴더 선택…", + "ui.agent_chat_add_folder_tip": "폴더의 위치와 내용이 에이전트에게 전달되고, 에이전트가 필요한 파일을 원래 크기 그대로 직접 읽습니다", + "ui.agent_chat_file_by_place_tip": "메시지에 포함되지 않음: 에이전트에게 위치가 전달되고 에이전트가 자체 도구로 읽습니다", + "ui.agent_chat_files_by_place": "{max}개를 넘는 파일은 디스크 위치로 전달됩니다. 에이전트가 자체 도구로 원래 크기 그대로 읽습니다", + "ui.agent_chat_folder_tip": "폴더: 위치와 내용이 에이전트에게 전달되고, 에이전트가 필요한 파일을 자체 도구로 읽습니다", + "ui.agent_chat_paste_past_max": "메시지 하나에는 파일을 최대 {max}개까지 보낼 수 있습니다. 그림을 파일로 저장한 뒤 그 파일을 첨부하세요" + }, + "vi": { + "ui.agent_chat_add_folder": "Chọn một thư mục…", + "ui.agent_chat_add_folder_tip": "AI Agent được cho biết thư mục nằm ở đâu và chứa gì, rồi tự đọc các tệp cần thiết ở kích thước đầy đủ", + "ui.agent_chat_file_by_place_tip": "Không nằm trong tin nhắn: AI Agent được cho biết vị trí của tệp và đọc nó bằng công cụ của mình", + "ui.agent_chat_files_by_place": "Quá {max} tệp, các tệp còn lại được gửi theo vị trí trên ổ đĩa: AI Agent đọc chúng bằng công cụ của mình, ở kích thước đầy đủ", + "ui.agent_chat_folder_tip": "Một thư mục: AI Agent được cho biết nó nằm ở đâu và chứa gì, 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 đó" + }, + "zh": { + "ui.agent_chat_add_folder": "选择文件夹…", + "ui.agent_chat_add_folder_tip": "智能体会得知文件夹的位置和内容,并自行以原始尺寸读取所需的文件", + "ui.agent_chat_file_by_place_tip": "不在消息中:智能体会得知它的位置,并用自己的工具读取", + "ui.agent_chat_files_by_place": "超过 {max} 个文件后,其余文件按磁盘位置提供:智能体用自己的工具以原始尺寸读取", + "ui.agent_chat_folder_tip": "文件夹:智能体会得知它的位置和内容,并用自己的工具读取所需的文件", + "ui.agent_chat_paste_past_max": "一条消息最多发送 {max} 个文件;请把图片另存为文件,再附加该文件" + } +} diff --git a/assets/locales/vi.json b/assets/locales/vi.json index 46a91221ccd..8f90ce14cf0 100644 --- a/assets/locales/vi.json +++ b/assets/locales/vi.json @@ -5182,7 +5182,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/src/agent_chat/attach.rs b/crates/ui-egui/src/agent_chat/attach.rs index c3516c06a28..078faf110ba 100644 --- a/crates/ui-egui/src/agent_chat/attach.rs +++ b/crates/ui-egui/src/agent_chat/attach.rs @@ -1,7 +1,9 @@ //! 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 +//! and place on this machine) for the agent to read with its own tools. A folder goes by its place +//! too, with what it holds; and past [`MAX_FILES`] files, every further one does, so a batch of +//! photos reaches the agent whole, at full size, 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}; @@ -22,8 +24,14 @@ 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 (pictures, PDFs, text, imported parts); past it, +/// a file goes by its place ([`reference`]). pub const MAX_FILES: usize = 8; +/// Most files and folders on one message, those that go by their place included. +pub const MAX_ON_MESSAGE: usize = 200; +/// A folder's entries read to say what it holds, and the most of them named in the message. +const MAX_FOLDER_SCAN: usize = 10_000; +const MAX_FOLDER_NAMED: 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. @@ -99,16 +107,37 @@ pub enum Content { path: PathBuf, text: Option>, }, - /// A file the agent is pointed to, not given: what it is, its size and where it is. + /// A file the agent is pointed to, not given: what it is, its size and where it is (and a + /// picture's size in pixels, from its header). Reference { path: PathBuf, size: u64, mime: &'static str, + pixels: Option<[u32; 2]>, + }, + /// A folder the agent is pointed to: where it is and what it holds, none of its files. + Folder { + path: PathBuf, + listing: Arc, }, /// A CAD file imported into the design as its own component. Imported, } +/// What a folder holds at its top level, as far as it was read (hidden entries left out). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Listing { + /// The first [`MAX_FOLDER_NAMED`] names in order, a file's with its size; a folder's ends in + /// `/` and has none. + pub entries: Vec<(String, Option)>, + pub files: usize, + pub folders: usize, + /// The files' sizes together. + pub bytes: u64, + /// Reading stopped at [`MAX_FOLDER_SCAN`] entries: it holds more than counted. + pub cut: bool, +} + /// 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 { @@ -181,8 +210,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 +228,21 @@ 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", + "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", @@ -279,20 +330,90 @@ pub fn read(path: &Path) -> Result { 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 Ok(Attachment { + id: 0, + name, + content: Content::Reference { path, size: meta.len(), mime: "application/pdf", pixels: None }, + thumb: None, + }); } 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 }) } - 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 if heic(path) => 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 }) + let content = Content::Reference { path: absolute(path), size: meta.len(), mime: mime_of(path), pixels: None }; + Ok(Attachment { id: 0, name, content, thumb: None }) + } + } +} + +fn heic(path: &Path) -> bool { + matches!(path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).as_deref(), Some("heic" | "heif")) +} + +/// A file the agent is pointed to instead of given, whatever its kind (one past [`MAX_FILES`]): +/// its type, size and place, and a picture's size in pixels, read from its header. Nothing else +/// 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, &[])); + } + if heic(path) { + return Err(refused("ui.agent_chat_file_heic", &name, &[])); + } + let pixels = if kind(path) == Kind::Picture { pixels(path) } else { None }; + let content = Content::Reference { path: absolute(path), size: meta.len(), mime: mime_of(path), pixels }; + Ok(Attachment { id: 0, name, content, thumb: None }) +} + +/// A picture's width and height from its header, without decoding it. +fn pixels(path: &Path) -> Option<[u32; 2]> { + let (w, h) = image::ImageReader::open(path).ok()?.with_guessed_format().ok()?.into_dimensions().ok()?; + Some([w, h]) +} + +/// 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 message: the agent is told where it is and what it holds at its top level (up +/// to [`MAX_FOLDER_SCAN`] entries read, [`MAX_FOLDER_NAMED`] named, hidden ones left out), and +/// reads the files it needs with its own tools. None of its files is read here. +pub fn folder(path: &Path) -> Result { + let name = folder_name(path); + let entries = std::fs::read_dir(path).map_err(|e| failed(&name, e))?; + let mut listing = Listing::default(); + for (seen, entry) in entries.enumerate() { + if seen >= MAX_FOLDER_SCAN { + listing.cut = true; + break; + } + let Ok(entry) = entry else { continue }; + let entry_name = entry.file_name().to_string_lossy().to_string(); + if entry_name.starts_with('.') { + continue; + } + // A link counts as what it leads to, as the agent's tools would see it; a broken one is + // left out. + let Ok(meta) = std::fs::metadata(entry.path()) else { continue }; + if meta.is_dir() { + listing.folders += 1; + listing.entries.push((format!("{entry_name}/"), None)); + } else { + listing.files += 1; + listing.bytes = listing.bytes.saturating_add(meta.len()); + listing.entries.push((entry_name, Some(meta.len()))); } } + listing.entries.sort_by_cached_key(|(n, _)| n.to_lowercase()); + listing.entries.truncate(MAX_FOLDER_NAMED); + Ok(Attachment { id: 0, name, content: Content::Folder { path: absolute(path), listing: Arc::new(listing) }, thumb: None }) } /// The path as an absolute one, so the agent (working in another folder) finds the file. @@ -418,7 +539,8 @@ fn fit(out: &mut String, left: &mut usize, head: &str, text: &str) { /// pictures and imported parts by name (the agent sees the pictures themselves as images). /// `pictures_sent` and `documents_sent`: whether this agent takes pictures and PDFs. The text files share `budget` characters /// in order: one that doesn't fit is cut and says how much is missing, and one past the budget -/// is named only, so the message stays within the prompt cap. +/// is named only, so the message stays within the prompt cap. The lines that name files (those +/// that go by their place, a folder's listing) take their room from the budget first. pub fn note(files: &[Attachment], pictures_sent: bool, documents_sent: bool, budget: usize) -> String { let mut out = String::new(); let pictures: Vec<&str> = files.iter().filter(|f| f.is_picture()).map(|f| f.name.as_str()).collect(); @@ -430,57 +552,99 @@ pub fn note(files: &[Attachment], pictures_sent: bool, documents_sent: bool, bud format!("\n\n(Pictures attached but not sent, this agent takes none: {list}.)") }; } - let mut left = budget; + let named: usize = files.iter().filter_map(|f| named_line(f, documents_sent)).map(|l| l.chars().count()).sum(); + let mut left = budget.saturating_sub(named); for f in files { + if let Some(line) = named_line(f, documents_sent) { + out += &line; + continue; + } match &f.content { Content::Text(t) => fit(&mut out, &mut left, &format!("Attached file `{}`", f.name), t), - Content::Pdf { path, bytes, .. } if documents_sent => { - out += &format!( - "\n\nAttached PDF `{}` ({}, at {}): sent with this message as a document.", + // An agent that takes no documents gets the text (one with none is named instead). + Content::Pdf { path, bytes, text: Some(t) } => { + let cut = if t.cut { "; cut, the rest is in the file" } else { "" }; + let head = format!( + "Attached PDF `{}` ({} pages, {}, at {}): its text only, layout, pictures and fonts are dropped{cut}", f.name, + t.pages, size_text(bytes.len() as u64), path.display() ); + fit(&mut out, &mut left, &head, &t.text); } - // 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() - ); - } - } - } - Content::Reference { path, size, mime } => { - out += &format!( - "\n\nAttached file `{}` ({mime}, {}, at {}): read it with your own tools; it is not in this message.", - f.name, - size_text(*size), - path.display() - ); - } - Content::Imported => out += &format!("\n\n(I added `{}` to the design as a component of its own.)", f.name), - Content::Picture { .. } => {} + _ => {} } } out } +/// The line that names a file without its contents: a PDF sent as a document, or one whose text +/// could not be taken; a file or folder that goes by its place; an imported part. `None` for +/// pictures (named together) and for text, which shares the budget. +fn named_line(f: &Attachment, documents_sent: bool) -> Option { + let line = match &f.content { + Content::Pdf { path, bytes, .. } if documents_sent => { + format!("\n\nAttached PDF `{}` ({}, at {}): sent with this message as a document.", f.name, size_text(bytes.len() as u64), path.display()) + } + Content::Pdf { path, bytes, text } if text.as_deref().is_none_or(|t| t.text.trim().is_empty()) => { + let why = if text.is_some() { "no text could be taken from it (scanned or protected)" } else { "its text could not be read" }; + format!( + "\n\nAttached file `{}` (PDF, {}, at {}): {why}; 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, pixels } => { + let pixels = pixels.map(|[w, h]| format!("{w}×{h} px, ")).unwrap_or_default(); + format!( + "\n\nAttached file `{}` ({mime}, {pixels}{}, at {}): read it with your own tools; it is not in this message.", + f.name, + size_text(*size), + path.display() + ) + } + Content::Folder { path, listing } => folder_line(&f.name, path, listing), + Content::Imported => format!("\n\n(I added `{}` to the design as a component of its own.)", f.name), + Content::Text(_) | Content::Pdf { .. } | Content::Picture { .. } => return None, + }; + Some(line) +} + +/// A folder in the message: where it is, what it holds, and the names of the first entries. +fn folder_line(name: &str, path: &Path, l: &Listing) -> String { + let mut out = format!("\n\nAttached folder `{name}` (at {}): ", path.display()); + if l.files + l.folders == 0 { + out += "it is empty (hidden files aside)."; + return out; + } + let count = |n: usize, one: &str| if n == 1 { format!("1 {one}") } else { format!("{n} {one}s") }; + out += &format!("{}, {} in all", count(l.files, "file"), size_text(l.bytes)); + if l.folders > 0 { + out += &format!(", and {}", count(l.folders, "folder")); + } + if l.cut { + out += &format!(" in the first {MAX_FOLDER_SCAN} entries read; it holds more"); + } + out += ". Read what you need from it with your own tools; its files are not in this message, and none was scaled down.\nIn it: "; + let names: Vec = l + .entries + .iter() + .map(|(n, size)| match size { + Some(s) => format!("{n} ({})", size_text(*s)), + None => n.clone(), + }) + .collect(); + out += &names.join(", "); + let more = (l.files + l.folders).saturating_sub(l.entries.len()); + if more > 0 || l.cut { + out += &format!(", and {more}{} more", if l.cut { "+" } else { "" }); + } + out.push('.'); + out +} + /// The pictures and PDFs as parts of the message, to the agents that take them. pub fn parts(files: &[Attachment], pictures: bool, documents: bool) -> Vec { files @@ -709,7 +873,7 @@ mod tests { 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") }; + 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"); @@ -727,6 +891,102 @@ mod tests { let _ = std::fs::remove_dir_all(&d); } + /// Past the files whose contents go with a message, a file of any kind goes by its place: + /// nothing is read or scaled, a picture's size in pixels comes from its header, and the + /// message points the agent to it. HEIC is refused here too. + #[test] + fn a_file_by_its_place_is_left_whole() { + crate::i18n::install(); + let d = dir("place"); + let photo = d.join("IMG_0001.JPG"); + image::RgbImage::from_pixel(4032, 3024, 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, pixels } = &a.content else { panic!("a reference: {:?}", a.content) }; + assert_eq!((*s, *mime, *pixels), (size, "image/jpeg", Some([4032, 3024])), "its own size, not scaled down"); + 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, 4032×3024 px, "), "{n}"); + assert!(n.contains("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", pixels: None, .. }), + "text goes by its place too" + ); + let heic = d.join("photo.heic"); + std::fs::write(&heic, b"....ftypheic").unwrap(); + assert!(reference(&heic).unwrap_err().contains("HEIC")); + assert!(reference(&d).unwrap_err().contains("not a file")); + assert!(reference(&d.join("missing.jpg")).is_err()); + let fake = d.join("fake.png"); + std::fs::write(&fake, b"not a picture").unwrap(); + assert!(matches!(reference(&fake).unwrap().content, Content::Reference { pixels: None, .. }), "a bad header just has no size"); + let _ = std::fs::remove_dir_all(&d); + } + + /// A folder goes by its place: the message says where it is, how many files and folders it + /// holds and their size, and names its entries in order (hidden ones left out, a long list cut + /// with how many more there are). None of its files is read. + #[test] + fn a_folder_goes_by_its_place_with_what_it_holds() { + 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("b.jpg"), vec![0u8; 2048]).unwrap(); + std::fs::write(photos.join("A.jpg"), vec![0u8; 1024]).unwrap(); + std::fs::write(photos.join(".DS_Store"), b"x").unwrap(); + let a = folder(&photos).unwrap(); + assert_eq!(a.name, "site photos/"); + assert!(a.by_place() && a.mark().is_empty()); + let Content::Folder { path, listing } = &a.content else { panic!("a folder: {:?}", a.content) }; + assert!(path.is_absolute() && path.ends_with("site photos")); + assert_eq!((listing.files, listing.folders, listing.bytes, listing.cut), (2, 1, 3072, false)); + let names: Vec<&str> = listing.entries.iter().map(|(n, _)| n.as_str()).collect(); + assert_eq!(names, ["A.jpg", "b.jpg", "raw/"], "in order, whatever the case, hidden ones left out"); + let n = note(std::slice::from_ref(&a), true, true, usize::MAX); + assert!(n.contains("Attached folder `site photos/` (at "), "{n}"); + assert!(n.contains("2 files, 3 KB in all, and 1 folder."), "{n}"); + assert!(n.contains("Read what you need from it with your own tools"), "{n}"); + assert!(n.contains("In it: A.jpg (1 KB), b.jpg (2 KB), raw/."), "{n}"); + assert!(parts(&[a], true, true).is_empty()); + let empty = d.join("empty"); + std::fs::create_dir_all(&empty).unwrap(); + assert!(note(&[folder(&empty).unwrap()], true, true, usize::MAX).contains("it is empty")); + let many = d.join("many"); + std::fs::create_dir_all(&many).unwrap(); + for i in 0..MAX_FOLDER_NAMED + 5 { + std::fs::write(many.join(format!("p{i:04}.png")), b"x").unwrap(); + } + let m = folder(&many).unwrap(); + let Content::Folder { listing, .. } = &m.content else { panic!("a folder") }; + assert_eq!((listing.files, listing.entries.len()), (MAX_FOLDER_NAMED + 5, MAX_FOLDER_NAMED), "all counted, the first named"); + assert!(note(&[m], true, true, usize::MAX).ends_with("p0199.png (1 bytes), and 5 more.")); + 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); + } + + /// The lines naming files that go by their place take their room before the text files share + /// the budget, so the whole message stays within it. + #[test] + fn named_files_take_their_room_from_the_text_budget() { + let place = Attachment { + id: 0, + name: "big.zip".into(), + content: Content::Reference { path: "/a/big.zip".into(), size: 10, mime: "application/zip", pixels: None }, + thumb: None, + }; + let text = Attachment { id: 0, name: "a.md".into(), content: Content::Text(Arc::new("x".repeat(1000))), thumb: None }; + let files = vec![text, place]; + let named = named_line(&files[1], true).unwrap().chars().count(); + let n = note(&files, true, true, 500 + named); + assert_eq!(n.matches('x').count(), 500, "the text gets what the named file leaves: {n}"); + assert!(n.contains("`big.zip`")); + } + /// 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. #[test] diff --git a/crates/ui-egui/src/agent_chat/mod.rs b/crates/ui-egui/src/agent_chat/mod.rs index ed0cba0ed7f..8b17ea53489 100644 --- a/crates/ui-egui/src/agent_chat/mod.rs +++ b/crates/ui-egui/src/agent_chat/mod.rs @@ -370,6 +370,9 @@ pub(crate) struct Loading { pub id: u64, pub name: String, what: Reading, + /// A folder being listed: it goes by its place, so it doesn't count toward + /// [`attach::MAX_FILES`]. + by_place: bool, } enum Reading { @@ -701,11 +704,18 @@ impl AgentChat { fn files(&self) -> usize { self.attachments.len() + self.loading.len() } - /// Read a file for the next message on a worker thread, in the window's language. + /// Files on the next message whose contents go with it (read or still being read): those that + /// go by their place don't count. + fn files_sent(&self) -> usize { + self.attachments.iter().filter(|f| !f.by_place()).count() + self.loading.iter().filter(|l| !l.by_place).count() + } + /// Read a file for the next message on a worker thread, in the window's language (`by_place`: + /// a folder, which goes by its place). #[cfg(not(target_arch = "wasm32"))] fn load( &mut self, name: String, + by_place: bool, job: impl FnOnce() -> std::result::Result + Send + 'static, ) -> std::result::Result { let (tx, rx) = std::sync::mpsc::channel(); @@ -718,13 +728,13 @@ impl AgentChat { }) .map_err(|e| trf("ui.agent_chat_file_error", &[("name", &name), ("error", &e.to_string())]))?; let id = self.next_file_id(); - self.loading.push(Loading { id, name: name.clone(), what: Reading::File(rx) }); + self.loading.push(Loading { id, name: name.clone(), what: Reading::File(rx), by_place }); Ok(name) } /// A CAD file whose import was asked for: it joins the message once the import is in. fn importing(&mut self, name: String, rx: Receiver) -> String { let id = self.next_file_id(); - self.loading.push(Loading { id, name: name.clone(), what: Reading::Import(rx) }); + self.loading.push(Loading { id, name: name.clone(), what: Reading::Import(rx), by_place: false }); name } @@ -1776,9 +1786,10 @@ 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(); + // One message carries the contents of at most MAX_FILES files, and MAX_ON_MESSAGE files in + // all with those that go by their place; the rest are named, not sent. + let (files, left) = within_caps(files); + if !left.is_empty() { let max = attach::MAX_FILES.to_string(); chat.notice(trf("ui.agent_chat_files_left_out", &[("max", &max), ("files", &left.join(", "))]), true); } @@ -1787,6 +1798,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 +/// [`attach::MAX_FILES`] whose contents go with it, or past [`attach::MAX_ON_MESSAGE`] in all. +fn within_caps(files: Vec) -> (Vec, Vec) { + let (mut kept, mut left, mut sent) = (Vec::new(), Vec::new(), 0); + for f in files { + if kept.len() >= attach::MAX_ON_MESSAGE || (!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) { @@ -1932,13 +1958,46 @@ fn start_turn_with(app: &mut SolveApp, text: String, image: bool, at: Option 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())])); + attach_one(app, path).map(|a| a.name) +} + +/// What attaching one path did. +struct Attached { + name: String, + /// A file past [`attach::MAX_FILES`]: it goes by its place, not in the message. + past_max: bool, +} + +fn attach_one(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); + // A folder: the agent is told where it is and what it holds (listed off the window thread: a + // folder on a network drive can take a while). + if p.is_dir() { + #[cfg(not(target_arch = "wasm32"))] + { + let dir = p.to_path_buf(); + let name = app.agent_chat.load(attach::folder_name(p), true, move || attach::folder(&dir))?; + return Ok(Attached { name, past_max: false }); + } + #[cfg(target_arch = "wasm32")] + { + let file = attach::folder(p)?; + return Ok(Attached { name: app.agent_chat.add_file(file), past_max: false }); + } + } + // Past MAX_FILES files whose contents go with the message, a file goes by its place: the agent + // reads it whole, at full size, with its own tools, and the message stays small. + if app.agent_chat.files_sent() >= attach::MAX_FILES { + let file = attach::reference(p)?; + return Ok(Attached { name: app.agent_chat.add_file(file), past_max: true }); + } let file = if attach::kind(p) == attach::Kind::Cad { if !p.is_file() { return Err(trf("ui.agent_chat_file_not_a_file", &[("name", path)])); @@ -1950,7 +2009,7 @@ pub fn attach_path(app: &mut SolveApp, path: &str) -> std::result::Result std::result::Result 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())])); + if app.agent_chat.files() >= attach::MAX_ON_MESSAGE { + return Err(trf("ui.agent_chat_files_max", &[("max", &attach::MAX_ON_MESSAGE.to_string())])); + } + // A pasted picture has no place to point the agent to: past MAX_FILES it can't go. + 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"); @@ -1981,7 +2045,7 @@ pub fn attach_rgba(app: &mut SolveApp, width: usize, height: usize, rgba: &[u8]) { let rgba = rgba.to_vec(); let named = name.clone(); - app.agent_chat.load(name, move || attach::from_rgba(named, width, height, &rgba)) + app.agent_chat.load(name, false, move || attach::from_rgba(named, width, height, &rgba)) } #[cfg(target_arch = "wasm32")] { @@ -2006,7 +2070,7 @@ pub fn take_drops(app: &mut SolveApp, ctx: &egui::Context) { return; } let files = ctx.input_mut(|i| std::mem::take(&mut i.raw.dropped_files)); - attach_dropped(app, files.iter().map(|f| f.path().to_path_buf())); + attach_paths(app, files.iter().map(|f| f.path().to_path_buf())); } /// Whether files dropped now would be the chat's: the pointer was last seen over it. @@ -2016,16 +2080,22 @@ pub(crate) fn drop_is_ours(chat: &AgentChat, ctx: &egui::Context) -> bool { ctx.input(|i| i.pointer.latest_pos()).is_some_and(|p| rect.contains(p)) } -/// Attach dropped files; a refused one says why in the conversation. -pub(crate) fn attach_dropped(app: &mut SolveApp, paths: impl Iterator) { +/// Attach files and folders dropped or chosen together; a refused one says why in the +/// conversation, and files past [`attach::MAX_FILES`] going by their place are said once. +pub(crate) fn attach_paths(app: &mut SolveApp, paths: impl Iterator) { + let mut past_max = false; for p in paths { if p.as_os_str().is_empty() { continue; } - if let Err(e) = attach_path(app, &p.to_string_lossy()) { - app.agent_chat.notice(e, true); + match attach_one(app, &p.to_string_lossy()) { + Ok(a) => past_max |= a.past_max, + Err(e) => app.agent_chat.notice(e, true), } } + if past_max { + app.agent_chat.notice(trf("ui.agent_chat_files_by_place", &[("max", &attach::MAX_FILES.to_string())]), false); + } } /// Stop: ask the agent to stop the message it is on; requests waiting for approval are declined. diff --git a/crates/ui-egui/src/agent_chat/panel.rs b/crates/ui-egui/src/agent_chat/panel.rs index 64d42e60c20..07ebc840233 100644 --- a/crates/ui-egui/src/agent_chat/panel.rs +++ b/crates/ui-egui/src/agent_chat/panel.rs @@ -71,8 +71,10 @@ pub enum PanelAction { at: Option, }, AttachDropped(Vec), - /// Choose a file to attach. + /// Choose files to attach, one or several. ChooseAttachment, + /// Choose a folder to attach: the agent is told where it is and what it holds. + ChooseFolder, /// Attach the clipboard's picture (desktop only, as the clipboard reader is). #[cfg(not(target_arch = "wasm32"))] PastePicture, @@ -127,14 +129,11 @@ 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::AttachDropped(paths) => attach_paths(app, paths.into_iter()), + PanelAction::ChooseAttachment => app.pick_files(tr("ui.agent_chat_attachable"), &attach::extensions(), |app, paths| { + attach_paths(app, paths.into_iter().map(std::path::PathBuf::from)); }), + PanelAction::ChooseFolder => app.pick_folder(|app, path| attach_paths(app, path.into_iter().map(std::path::PathBuf::from))), #[cfg(not(target_arch = "wasm32"))] PanelAction::PastePicture => { if let Err(e) = paste_picture(app) { @@ -2590,6 +2589,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 place, +/// that place and 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, .. } => format!("{}\n{}", path.display(), tr("ui.agent_chat_file_by_place_tip")), + 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 { @@ -2663,6 +2673,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()); @@ -2684,7 +2704,7 @@ fn chip(ui: &mut egui::Ui, thumbs: &mut std::collections::HashMap = app + .agent_chat + .items + .iter() + .filter_map(|i| if let Item::Notice { text, error } = i { Some((text.as_str(), *error)) } else { None }) + .filter(|(t, _)| t.contains("by their place")) + .collect(); + assert_eq!( + told, + [("Past 8 files, the rest go by their place on disk: the agent reads them with its own tools, at full size", false)], + "said once for the batch" + ); + assert!(attach_rgba(&mut app, 2, 2, &[9; 16]).unwrap_err().contains("save the picture as a file")); + assert!(attach_path(&mut app, &at(&d, "missing.png")).is_err(), "a missing file is still refused"); + assert!(control(&mut app, &ctx, &json!({"remove_file": 11})).is_err(), "no twelfth file to take off"); + control(&mut app, &ctx, &json!({"remove_file": 1})).unwrap(); + assert_eq!(app.agent_chat.attachments.len(), attach::MAX_FILES + 2); + send(&mut app, &ctx, "these".into()); + let sent = &script.prompts()[0]; + let text = text_of(sent); + assert_eq!(pictures_in(sent), 0, "the picture past the eight goes by its place: {text}"); + assert_eq!(text.matches("Attached file `brief.md`:").count(), attach::MAX_FILES - 1, "seven in full: {text}"); + assert!(text.contains("Attached file `target.png` (image/png, 40×30 px, "), "{text}"); + assert_eq!(text.matches("read it with your own tools; it is not in this message").count(), 3, "{text}"); + let more = attach::MAX_ON_MESSAGE - app.agent_chat.files(); + for _ in 0..more { + 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); +} + +/// Choose files… takes several at once from the host's dialog; Choose a folder… attaches the +/// folder by its place, as dropping one does. +#[test] +fn choose_files_takes_several_and_choose_a_folder_one_folder() { + use solidcraft_ui_registry::handle_at; + let d = attachable("choose-many"); + let mut h = narrow_chat(); + let chosen = vec![at(&d, "brief.md"), at(&d, "target.png")]; + h.app.services.pick_files = Some(Box::new(move |_label: &str, _exts: &[&str]| { + let all = chosen.clone(); + Box::pin(async move { all }) + })); + let folder = d.to_string_lossy().to_string(); + h.app.services.pick_folder = Some(Box::new(move || { + let f = folder.clone(); + Box::pin(async move { Some(f) }) + })); + 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 files… in its menu"); + h.call("ui.click", json!({"x": choose.x, "y": choose.y})); + h.frames(2); + settle_chat(&mut h); + assert_eq!(status(&h.app)["attachments"], json!(["brief.md", "target.png"]), "both chosen files"); + h.call("ui.click", json!({"x": plus.x, "y": plus.y})); + h.frames(2); + let choose = handle_at("agent_chat:add_folder").expect("Choose a folder… in its menu"); + h.call("ui.click", json!({"x": choose.x, "y": choose.y})); + h.frames(2); + settle_chat(&mut h); + let name = format!("{}/", d.file_name().unwrap().to_string_lossy()); + assert_eq!(status(&h.app)["attachments"], json!(["brief.md", "target.png", name])); + assert!(h.app.agent_chat.attachments[2].by_place(), "the folder goes by its place"); + // Cancelled: nothing more. + h.app.services.pick_files = Some(Box::new(|_: &str, _: &[&str]| Box::pin(async { Vec::new() }))); + h.call("ui.click", json!({"x": plus.x, "y": plus.y})); + h.frames(2); + let choose = handle_at("agent_chat:add_file").expect("Choose files…"); + h.call("ui.click", json!({"x": choose.x, "y": choose.y})); + settle_chat(&mut h); + assert_eq!(h.app.agent_chat.attachments.len(), 3); + let _ = std::fs::remove_dir_all(&d); +} + +/// A folder attached through the control channel, as a path, is listed off the window thread and +/// goes to the agent as its place and what it holds; a folder doesn't take one of the eight. +#[test] +fn an_attached_folder_tells_the_agent_where_it_is_and_what_it_holds() { + let d = attachable("folder"); + let (mut app, script, ctx) = app_with_script(); + control(&mut app, &ctx, &json!({"attach": d.to_string_lossy()})).unwrap(); + assert_eq!(app.agent_chat.files_sent(), 0, "a folder being listed takes none of the eight"); + settle_files(&mut app, &ctx); + assert_eq!(app.agent_chat.files_sent(), 0); + for _ in 0..attach::MAX_FILES { + attach_path(&mut app, &at(&d, "brief.md")).unwrap(); + } + assert_eq!(app.agent_chat.files_sent(), attach::MAX_FILES, "eight more in full"); + 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("2 files, ") && text.contains("In it: brief.md (") && text.contains("target.png ("), "{text}"); let _ = std::fs::remove_dir_all(&d); } @@ -3163,7 +3263,8 @@ fn a_queued_message_keeps_its_files_through_stop_and_sends_them() { let _ = std::fs::remove_dir_all(&d); } -/// Queued messages go as one prompt with at most eight files; the rest are named, not sent. +/// Queued messages go as one prompt with at most eight files' contents; the rest are named, not +/// sent. Files that go by their place go with it whatever their number. #[test] fn the_queue_sends_at_most_eight_files_and_names_the_rest() { let d = attachable("queue-cap"); @@ -3173,6 +3274,7 @@ fn the_queue_sends_at_most_eight_files_and_names_the_rest() { for _ in 0..4 { attach_path(&mut app, &at(&d, "brief.md")).unwrap(); } + app.agent_chat.add_file(attach::reference(&d.join("target.png")).unwrap()); send(&mut app, &ctx, format!("batch {n}")); } ended(&script, ""); @@ -3180,7 +3282,12 @@ fn the_queue_sends_at_most_eight_files_and_names_the_rest() { let sent = script.prompts(); assert_eq!(sent.len(), 2); assert_eq!(text_of(&sent[1]).matches("Attached file `brief.md`").count(), attach::MAX_FILES); - let told = app.agent_chat.items.iter().any(|i| matches!(i, Item::Notice { text, .. } if text.contains("brief.md") && text.contains('8'))); + assert_eq!(text_of(&sent[1]).matches("Attached file `target.png` (image/png").count(), 3, "every file by its place goes"); + let told = app + .agent_chat + .items + .iter() + .any(|i| matches!(i, Item::Notice { text, .. } if text.contains("brief.md") && text.contains('8') && !text.contains("target.png"))); assert!(told, "the files left out are named"); let _ = std::fs::remove_dir_all(&d); } diff --git a/crates/ui-egui/src/file_picker.rs b/crates/ui-egui/src/file_picker.rs index 9e39391813e..617726dd9fd 100644 --- a/crates/ui-egui/src/file_picker.rs +++ b/crates/ui-egui/src/file_picker.rs @@ -12,11 +12,15 @@ 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 FilesCompletion = Box)>; +/// A picker waiting for its answer: every picker answers with paths, one when it asks for one. pub(crate) struct Pending { - future: FilePickerFuture, - complete: Completion, + future: FilesPickerFuture, + complete: FilesCompletion, } struct Repaint(egui::Context); @@ -62,6 +66,29 @@ impl SolveApp { self.begin_picker(future, Box::new(complete)); } + /// Ask for files of a kind, several at once (the agent chat's files): 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) => self.file_picker = Some(Pending { future: pick(label, extensions), complete: Box::new(complete) }), + None => self.pick_file(label, extensions, move |app, path| complete(app, path.into_iter().collect())), + } + } + + /// Ask for a folder (the agent chat's files). Without a host dialog, the answer is a cancel. + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + pub(crate) fn pick_folder(&mut self, complete: impl FnOnce(&mut SolveApp, Option) + 'static) { + if self.file_picker_busy() { + return; + } + let future = self.services.pick_folder.as_ref().map(|pick| pick()); + self.begin_picker(future, Box::new(complete)); + } + pub(crate) fn pick_save(&mut self, name: &str, extensions: &[&str], complete: impl FnOnce(&mut SolveApp, Option) + 'static) { if self.file_picker_busy() { return; @@ -84,7 +111,10 @@ impl SolveApp { complete(self, None); return; }; - self.file_picker = Some(Pending { future, complete }); + self.file_picker = Some(Pending { + future: Box::pin(async move { future.await.into_iter().collect() }), + complete: Box::new(move |app, paths: Vec| complete(app, paths.into_iter().next())), + }); } pub(crate) fn pick_open_command(&mut self, command: &str, params: Value, extensions: &[&str]) { @@ -123,14 +153,14 @@ impl SolveApp { pub(crate) fn tick(app: &mut SolveApp, ctx: &egui::Context) { let Some(pending) = app.file_picker.as_mut() else { return }; let waker = Waker::from(Arc::new(Repaint(ctx.clone()))); - let Poll::Ready(path) = pending.future.as_mut().poll(&mut Context::from_waker(&waker)) else { + let Poll::Ready(paths) = pending.future.as_mut().poll(&mut Context::from_waker(&waker)) else { // A fallback for native backends that do not wake reliably. Resizing still draws // the ordinary UI in every frame. ctx.request_repaint_after(std::time::Duration::from_millis(50)); return; }; if let Some(pending) = app.file_picker.take() { - (pending.complete)(app, path); + (pending.complete)(app, paths); // Hosts can flush writes or restore native input on the following frame. ctx.request_repaint(); } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 1deb0690d1f..770c876820b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -192,7 +192,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)] @@ -489,6 +489,11 @@ 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>>, + /// The same dialog, allowing several files at once (the agent chat's files). `None`: one + /// file, with `pick_file`. + pub pick_files: Option FilesPickerFuture>>, + /// Open a dialog for a folder (the agent chat attaches one); `None` when the host has none. + pub pick_folder: Option FilePickerFuture>>, /// Open a dialog asking for a program (a slicer); `None` when the host has no such dialog. pub pick_program: Option FilePickerFuture>>, pub show_in_folder: Option>, diff --git a/docs/agent-chat.md b/docs/agent-chat.md index f056bb2b320..950447f343f 100644 --- a/docs/agent-chat.md +++ b/docs/agent-chat.md @@ -125,13 +125,14 @@ 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. - -- **+** next to **Send** has **Choose a file…** (a file dialog for the types below) 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 +A message carries the contents of up to eight files, to show the agent what you mean: a concept +picture, a sketch, a brief, a part to fit around. More files, and folders, go by their place on +disk (below), up to 200 on one message. + +- **+** next to **Send** has **Choose files…** (a file dialog for the types below; pick several at + once), **Choose a folder…** and **Paste a picture** (the picture on the clipboard). +- **Drop files or folders on the chat.** What is dropped on the panel (or its folded strip) + attaches to the next message, and the app doesn't open it 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 pointer was last seen over the chat; **+** always works. - The files show as chips above the text box: a picture's thumbnail, the name, and × to take the @@ -151,6 +152,19 @@ 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). +- **Past eight files**, every further file goes by its place: the message tells the agent its + name, type, size (a picture's size in pixels too) and path, and the agent reads it with its own + tools. Nothing is read, scaled down or copied, so a batch of photos reaches the agent whole, at + full size, however many there are; the chat says so once for the batch. Its chip shows the + file's type instead of a thumbnail, and holding the pointer over it shows its path. A pasted + picture has no place on disk, so past eight it is refused: save it as a file and attach that. +- **A folder** goes by its place too: the message says where it is, how many files and folders it + holds and their size, and names the first 200 entries at its top level (hidden ones left out). + The agent reads the files it needs with its own tools. A folder or a file by its place doesn't + take one of the eight. Files other than the types above (a ZIP, a DXF) also go by their place. + Only a coding agent (Claude Code, Codex, Gemini CLI…) has tools of its own to read them, and it + may ask before it reads outside its working folder; an OpenAI- or Anthropic-compatible endpoint + has only SolidCraft's tools, so it gets the eight files in the message and the others' names. - 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 @@ -160,7 +174,8 @@ 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** +files go with it, the contents of at most eight; the rest are named in the chat and not sent +(files and folders by their place all go). **New chat** clears the files waiting on the chips too. ## Typing while the agent works diff --git a/docs/control-protocol.md b/docs/control-protocol.md index d2d497c02f6..d828aee374b 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -905,7 +905,7 @@ no box selection. | `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)}; 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)}; 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 or folder's path (a picture, a text file or a CAD file, for the next message; CAD files are imported at once; a folder, and any file past the eighth, goes by its place), `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` | | | `app.quit` | `force?` (quit without asking about unsaved designs) | `quitting` (the window closes), `asking` (a "save changes?" prompt is open) | From acdd8d964c4196ca34bd7397a67b7004f0ac250a Mon Sep 17 00:00:00 2001 From: Seth LaForge Date: Fri, 13 Nov 2026 18:48:04 -0800 Subject: [PATCH 02/12] Assistant: the file chips scroll past about three rows, so a large batch keeps the text box in view (#16452) With up to 200 files on a message, the chips above the text box pushed the text box and the conversation out of the panel. The chips now sit in a strip about three and a half rows high that scrolls. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/agent_chat/panel.rs | 41 +++++++++++++++----------- crates/ui-egui/src/agent_chat/tests.rs | 19 ++++++++++++ docs/agent-chat.md | 1 + 3 files changed, 44 insertions(+), 17 deletions(-) diff --git a/crates/ui-egui/src/agent_chat/panel.rs b/crates/ui-egui/src/agent_chat/panel.rs index 07ebc840233..2a72a00ae3a 100644 --- a/crates/ui-egui/src/agent_chat/panel.rs +++ b/crates/ui-egui/src/agent_chat/panel.rs @@ -2378,6 +2378,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, about three and a half rows: more scroll, and the half row shows +/// that there are more. A message holds up to 200 files, which would otherwise push the +/// conversation out of the panel. +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 @@ -2545,6 +2549,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 [`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. @@ -2553,29 +2558,31 @@ 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); + egui::ScrollArea::vertical().id_salt("sc_agent_chat_chips").max_height(CHIPS_MAX_HEIGHT).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() { diff --git a/crates/ui-egui/src/agent_chat/tests.rs b/crates/ui-egui/src/agent_chat/tests.rs index 3a36b4f5921..8af68b715ef 100644 --- a/crates/ui-egui/src/agent_chat/tests.rs +++ b/crates/ui-egui/src/agent_chat/tests.rs @@ -3521,6 +3521,25 @@ fn assert_inside_the_panel(chips: usize) { } } +/// Many files on a message scroll in a strip of chips about three rows high, so the text box stays +/// in the panel; a message holds up to 200 files. +#[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(); + for _ in 0..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] diff --git a/docs/agent-chat.md b/docs/agent-chat.md index 950447f343f..3f50c3dbf9f 100644 --- a/docs/agent-chat.md +++ b/docs/agent-chat.md @@ -138,6 +138,7 @@ disk (below), up to 200 on one message. - The files show as chips above the text box: a picture's thumbnail, the name, and × to take the file off. A picture is read off the window thread, so a large one never stops the window: its chip shows a spinner meanwhile, and **Send** waits for it. **Send** sends files with no text. + Past about three rows, the chips scroll, so the text box and the conversation stay in view. - **Pictures** (PNG, JPEG, GIF, WebP) go to the agent as they are when they are at most 2048 px on the long side and 3.75 MB (a picture's base64 then stays under 5 MB, so eight still fit in a prompt). Otherwise they are scaled down to 2048 px and re-encoded: as PNG when that fits, as From 5634b35a6857f29ec187f5dcbb38f2b429c26a80 Mon Sep 17 00:00:00 2001 From: Seth LaForge Date: Mon, 16 Nov 2026 18:40:24 -0800 Subject: [PATCH 03/12] Merge fix: the file picker hands its chosen paths to the completion The merge of main kept main's `complete(app, path)` in `file_picker::tick`, but this branch renamed the picked value to `paths`, so it didn't compile. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/file_picker.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/src/file_picker.rs b/crates/ui-egui/src/file_picker.rs index c09a779298a..40506822326 100644 --- a/crates/ui-egui/src/file_picker.rs +++ b/crates/ui-egui/src/file_picker.rs @@ -164,7 +164,7 @@ pub(crate) fn tick(app: &mut SolveApp, ctx: &egui::Context) { if let Some(pending) = app.file_picker.take() { // The dialog may have kept a button or modifier release for itself (#16460). crate::window_chrome::mark_input_stale(ctx); - (pending.complete)(app, path); + (pending.complete)(app, paths); // Hosts can flush writes or restore native input on the following frame. ctx.request_repaint(); } From d06780b306b594622f7c3639e705816b0b14d553 Mon Sep 17 00:00:00 2001 From: Seth LaForge Date: Mon, 16 Nov 2026 21:41:20 -0800 Subject: [PATCH 04/12] Assistant: Claude Code can read files sent by path, and the agent is told what is attached and how (#16452) Claude Code's read tools stay off until a message sends a file or folder by path. The first such file on the chips makes the chat say that sending it turns them on for this chat; that message then reopens the same session (session/new with _meta.claudeCode.options.resume) with Read, Glob and Grep on behind a permissions.ask rule. The chat answers a read whose path, links followed, lies inside what was sent by path; any other read waits for Allow or Deny. New chat turns them off again. The message now lists every attachment in order and how it arrives, in a element (the view's picture named first), with each text file in a element instead of a code fence; the selection and SolidCraft's notes go in and , and the system note says these come from SolidCraft. A folder goes as its path only, and a file by path no longer opens to read its pixel size. Co-Authored-By: Claude Opus 5.5 --- .../pending/agent-chat-files-by-place.json | 80 +-- crates/ui-egui/src/agent_chat/acp.rs | 180 +++++- crates/ui-egui/src/agent_chat/acp_client.rs | 68 ++- crates/ui-egui/src/agent_chat/attach.rs | 515 +++++++++--------- crates/ui-egui/src/agent_chat/backend.rs | 11 + crates/ui-egui/src/agent_chat/context.rs | 8 +- crates/ui-egui/src/agent_chat/mod.rs | 176 ++++-- crates/ui-egui/src/agent_chat/panel.rs | 2 +- crates/ui-egui/src/agent_chat/tests.rs | 207 +++++-- docs/agent-chat.md | 58 +- docs/control-protocol.md | 2 +- docs/design/in-app-agent-chat.md | 15 +- 12 files changed, 921 insertions(+), 401 deletions(-) diff --git a/assets/locales/pending/agent-chat-files-by-place.json b/assets/locales/pending/agent-chat-files-by-place.json index e9bf5f27a8c..8d30eded793 100644 --- a/assets/locales/pending/agent-chat-files-by-place.json +++ b/assets/locales/pending/agent-chat-files-by-place.json @@ -1,66 +1,82 @@ { "en": { "ui.agent_chat_add_folder": "Choose a folder…", - "ui.agent_chat_add_folder_tip": "The agent is told where the folder is and what it holds, and reads the files it needs itself, at full size", + "ui.agent_chat_add_folder_tip": "The agent is told where the folder is, and reads the files it needs with its own tools", "ui.agent_chat_file_by_place_tip": "Not in the message: the agent is told where it is and reads it with its own tools", - "ui.agent_chat_files_by_place": "Past {max} files, the rest go by their place on disk: the agent reads them with its own tools, at full size", - "ui.agent_chat_folder_tip": "A folder: the agent is told where it is and what it holds, 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.agent_chat_files_by_place": "Past {max} files, the rest go by their path: the agent reads them 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_reads_warning": "Sending a file or folder by path turns on Claude Code's read tools for this chat: it reads what you send without asking, and asks before reading anything else." }, "ar": { "ui.agent_chat_add_folder": "اختر مجلدًا…", - "ui.agent_chat_add_folder_tip": "يُخبَر الوكيل بمكان المجلد وما يحتويه، ويقرأ بنفسه الملفات التي يحتاجها بحجمها الكامل", + "ui.agent_chat_add_folder_tip": "يُخبَر الوكيل بمكان المجلد، ويقرأ الملفات التي يحتاجها بأدواته الخاصة", "ui.agent_chat_file_by_place_tip": "ليس ضمن الرسالة: يُخبَر الوكيل بمكانه ويقرؤه بأدواته الخاصة", - "ui.agent_chat_files_by_place": "بعد {max} ملفات، تُرسل البقية بمكانها على القرص: يقرؤها الوكيل بأدواته الخاصة بحجمها الكامل", - "ui.agent_chat_folder_tip": "مجلد: يُخبَر الوكيل بمكانه وما يحتويه، ويقرأ الملفات التي يحتاجها بأدواته الخاصة", - "ui.agent_chat_paste_past_max": "يُرسل {max} ملفات كحد أقصى في رسالة واحدة؛ احفظ الصورة في ملف وأرفقه بدلًا منها" + "ui.agent_chat_files_by_place": "بعد {max} ملفات، تُرسل البقية بمساراتها: يقرؤها الوكيل بأدواته الخاصة", + "ui.agent_chat_folder_tip": "مجلد: يُخبَر الوكيل بمكانه، ويقرأ الملفات التي يحتاجها بأدواته الخاصة", + "ui.agent_chat_paste_past_max": "يُرسل {max} ملفات كحد أقصى في رسالة واحدة؛ احفظ الصورة في ملف وأرفقه بدلًا منها", + "ui.ai_auto_attached": "يقرأ شيئًا أرفقته", + "ui.agent_chat_reads_warning": "إرسال ملف أو مجلد بمساره يشغّل أدوات القراءة في Claude Code لهذه المحادثة: يقرأ ما ترسله دون سؤال، ويسأل قبل قراءة أي شيء آخر." }, "de": { "ui.agent_chat_add_folder": "Ordner auswählen…", - "ui.agent_chat_add_folder_tip": "Der Agent erfährt, wo der Ordner liegt und was er enthält, und liest die benötigten Dateien selbst, in voller Größe", + "ui.agent_chat_add_folder_tip": "Der Agent erfährt, wo der Ordner liegt, und liest die benötigten Dateien mit seinen eigenen Werkzeugen", "ui.agent_chat_file_by_place_tip": "Nicht in der Nachricht: Der Agent erfährt, wo die Datei liegt, und liest sie mit seinen eigenen Werkzeugen", - "ui.agent_chat_files_by_place": "Ab {max} Dateien gehen die übrigen über ihren Ort auf der Festplatte: Der Agent liest sie mit seinen eigenen Werkzeugen, in voller Größe", - "ui.agent_chat_folder_tip": "Ein Ordner: Der Agent erfährt, wo er liegt und was er enthält, 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.agent_chat_files_by_place": "Ab {max} Dateien gehen die übrigen über ihren Pfad: Der Agent liest sie 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_reads_warning": "Wenn Sie eine Datei oder einen Ordner über den Pfad senden, schaltet das die Lesewerkzeuge von Claude Code für diesen Chat ein: Es liest, was Sie senden, ohne Rückfrage, und fragt, bevor es etwas anderes liest." }, "he": { "ui.agent_chat_add_folder": "בחירת תיקייה…", - "ui.agent_chat_add_folder_tip": "הסוכן מקבל את מיקום התיקייה ואת תוכנה, וקורא בעצמו את הקבצים שהוא צריך, בגודלם המלא", + "ui.agent_chat_add_folder_tip": "הסוכן מקבל את מיקום התיקייה, וקורא את הקבצים שהוא צריך בכלים שלו", "ui.agent_chat_file_by_place_tip": "לא בתוך ההודעה: הסוכן מקבל את מיקום הקובץ וקורא אותו בכלים שלו", - "ui.agent_chat_files_by_place": "מעבר ל־{max} קבצים, השאר נשלחים לפי מיקומם בדיסק: הסוכן קורא אותם בכלים שלו, בגודלם המלא", - "ui.agent_chat_folder_tip": "תיקייה: הסוכן מקבל את מיקומה ואת תוכנה, וקורא את הקבצים שהוא צריך בכלים שלו", - "ui.agent_chat_paste_past_max": "לכל היותר {max} קבצים בהודעה אחת; יש לשמור את התמונה כקובץ ולצרף אותו במקומה" + "ui.agent_chat_files_by_place": "מעבר ל־{max} קבצים, השאר נשלחים לפי הנתיב שלהם: הסוכן קורא אותם בכלים שלו", + "ui.agent_chat_folder_tip": "תיקייה: הסוכן מקבל את מיקומה, וקורא את הקבצים שהוא צריך בכלים שלו", + "ui.agent_chat_paste_past_max": "לכל היותר {max} קבצים בהודעה אחת; יש לשמור את התמונה כקובץ ולצרף אותו במקומה", + "ui.ai_auto_attached": "הוא קורא משהו שצירפת", + "ui.agent_chat_reads_warning": "שליחת קובץ או תיקייה לפי נתיב מפעילה את כלי הקריאה של Claude Code בצ׳אט הזה: הוא קורא את מה ששלחת בלי לשאול, ושואל לפני שהוא קורא כל דבר אחר." }, "ja": { "ui.agent_chat_add_folder": "フォルダーを選択…", - "ui.agent_chat_add_folder_tip": "フォルダーの場所と中身がエージェントに伝えられ、必要なファイルはエージェントがフルサイズのまま自分で読み込みます", + "ui.agent_chat_add_folder_tip": "フォルダーの場所がエージェントに伝えられ、必要なファイルはエージェントが自分のツールで読み込みます", "ui.agent_chat_file_by_place_tip": "メッセージには含まれません。場所がエージェントに伝えられ、エージェントが自分のツールで読み込みます", - "ui.agent_chat_files_by_place": "{max} 個を超えたファイルはディスク上の場所で渡されます。エージェントが自分のツールでフルサイズのまま読み込みます", - "ui.agent_chat_folder_tip": "フォルダー: 場所と中身がエージェントに伝えられ、必要なファイルはエージェントが自分のツールで読み込みます", - "ui.agent_chat_paste_past_max": "1 つのメッセージで送れるファイルは {max} 個までです。画像をファイルとして保存し、そのファイルを添付してください" + "ui.agent_chat_files_by_place": "{max} 個を超えたファイルはパスで渡されます。エージェントが自分のツールで読み込みます", + "ui.agent_chat_folder_tip": "フォルダー: 場所がエージェントに伝えられ、必要なファイルはエージェントが自分のツールで読み込みます", + "ui.agent_chat_paste_past_max": "1 つのメッセージで送れるファイルは {max} 個までです。画像をファイルとして保存し、そのファイルを添付してください", + "ui.ai_auto_attached": "添付したものを読み込むため", + "ui.agent_chat_reads_warning": "パスでファイルやフォルダーを送ると、このチャットで Claude Code の読み取りツールがオンになります。送ったものは確認なしで読み込み、それ以外を読む前には確認します。" }, "ko": { "ui.agent_chat_add_folder": "폴더 선택…", - "ui.agent_chat_add_folder_tip": "폴더의 위치와 내용이 에이전트에게 전달되고, 에이전트가 필요한 파일을 원래 크기 그대로 직접 읽습니다", + "ui.agent_chat_add_folder_tip": "폴더의 위치가 에이전트에게 전달되고, 에이전트가 필요한 파일을 자체 도구로 읽습니다", "ui.agent_chat_file_by_place_tip": "메시지에 포함되지 않음: 에이전트에게 위치가 전달되고 에이전트가 자체 도구로 읽습니다", - "ui.agent_chat_files_by_place": "{max}개를 넘는 파일은 디스크 위치로 전달됩니다. 에이전트가 자체 도구로 원래 크기 그대로 읽습니다", - "ui.agent_chat_folder_tip": "폴더: 위치와 내용이 에이전트에게 전달되고, 에이전트가 필요한 파일을 자체 도구로 읽습니다", - "ui.agent_chat_paste_past_max": "메시지 하나에는 파일을 최대 {max}개까지 보낼 수 있습니다. 그림을 파일로 저장한 뒤 그 파일을 첨부하세요" + "ui.agent_chat_files_by_place": "{max}개를 넘는 파일은 경로로 전달됩니다. 에이전트가 자체 도구로 읽습니다", + "ui.agent_chat_folder_tip": "폴더: 위치가 에이전트에게 전달되고, 에이전트가 필요한 파일을 자체 도구로 읽습니다", + "ui.agent_chat_paste_past_max": "메시지 하나에는 파일을 최대 {max}개까지 보낼 수 있습니다. 그림을 파일로 저장한 뒤 그 파일을 첨부하세요", + "ui.ai_auto_attached": "첨부한 항목을 읽음", + "ui.agent_chat_reads_warning": "경로로 파일이나 폴더를 보내면 이 채팅에서 Claude Code의 읽기 도구가 켜집니다. 보낸 항목은 묻지 않고 읽고, 그 밖의 항목을 읽기 전에는 묻습니다." }, "vi": { "ui.agent_chat_add_folder": "Chọn một thư mục…", - "ui.agent_chat_add_folder_tip": "AI Agent được cho biết thư mục nằm ở đâu và chứa gì, rồi tự đọc các tệp cần thiết ở kích thước đầy đủ", + "ui.agent_chat_add_folder_tip": "AI Agent được cho biết thư mục 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_file_by_place_tip": "Không nằm trong tin nhắn: AI Agent được cho biết vị trí của tệp và đọc nó bằng công cụ của mình", - "ui.agent_chat_files_by_place": "Quá {max} tệp, các tệp còn lại được gửi theo vị trí trên ổ đĩa: AI Agent đọc chúng bằng công cụ của mình, ở kích thước đầy đủ", - "ui.agent_chat_folder_tip": "Một thư mục: AI Agent được cho biết nó nằm ở đâu và chứa gì, 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.agent_chat_files_by_place": "Quá {max} tệp, các tệp còn lại được gửi theo đường dẫn: AI Agent đọc chúng 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_reads_warning": "Gửi một tệp hoặc thư mục theo đường dẫn sẽ bật các công cụ đọc của Claude Code cho cuộc trò chuyện này: nó đọc những gì bạn gửi mà không hỏi, và hỏi trước khi đọc bất cứ thứ gì khác." }, "zh": { "ui.agent_chat_add_folder": "选择文件夹…", - "ui.agent_chat_add_folder_tip": "智能体会得知文件夹的位置和内容,并自行以原始尺寸读取所需的文件", + "ui.agent_chat_add_folder_tip": "智能体会得知文件夹的位置,并用自己的工具读取所需的文件", "ui.agent_chat_file_by_place_tip": "不在消息中:智能体会得知它的位置,并用自己的工具读取", - "ui.agent_chat_files_by_place": "超过 {max} 个文件后,其余文件按磁盘位置提供:智能体用自己的工具以原始尺寸读取", - "ui.agent_chat_folder_tip": "文件夹:智能体会得知它的位置和内容,并用自己的工具读取所需的文件", - "ui.agent_chat_paste_past_max": "一条消息最多发送 {max} 个文件;请把图片另存为文件,再附加该文件" + "ui.agent_chat_files_by_place": "超过 {max} 个文件后,其余文件按路径提供:智能体用自己的工具读取", + "ui.agent_chat_folder_tip": "文件夹:智能体会得知它的位置,并用自己的工具读取所需的文件", + "ui.agent_chat_paste_past_max": "一条消息最多发送 {max} 个文件;请把图片另存为文件,再附加该文件", + "ui.ai_auto_attached": "它读取的是你附加的内容", + "ui.agent_chat_reads_warning": "按路径发送文件或文件夹会为本次聊天开启 Claude Code 的读取工具:它会直接读取你发送的内容,读取其他任何内容前都会先询问。" } } diff --git a/crates/ui-egui/src/agent_chat/acp.rs b/crates/ui-egui/src/agent_chat/acp.rs index 8d7760aa742..b75483a5d3d 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 @@ -232,8 +277,10 @@ 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. \ -Keep answers short."; +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 or asks you to. In a user message, an element whose \ +tag starts with `solidcraft-` (``, ``, ``) was added by SolidCraft, not typed by \ +the user. Keep answers short."; /// The most of the user's custom instructions (#8220) a session gets, in characters: the /// Preferences field takes no more, and a longer text from an edited settings file is cut here. @@ -252,9 +299,17 @@ 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 ([`CLAUDE_ASK_TOOLS`]) are among them until the conversation sends a file or +/// folder by path ([`turn_on_reads`]). pub const CLAUDE_DISALLOWED_TOOLS: &[&str] = &["Bash", "BashOutput", "KillShell", "Read", "Write", "Edit", "MultiEdit", "NotebookEdit", "Glob", "Grep", "WebFetch", "WebSearch", "Task"]; +/// The Claude Code adapter's read tools. Once the conversation sends a file or folder by path they +/// are on, but every call asks (a `permissions.ask` rule in the session's settings), so the +/// question reaches the panel: the chat answers it by itself for a path the user sent +/// ([`read_path`]), and any other read waits for the user. +pub const CLAUDE_ASK_TOOLS: &[&str] = &["Read", "Glob", "Grep"]; + /// 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`]). @@ -286,6 +341,30 @@ pub fn session_new_params(cwd: &std::path::Path, bridge: Option<&McpBridge>, ini params } +/// `session/new` parameters with Claude Code's read tools on behind an ask rule +/// ([`CLAUDE_ASK_TOOLS`]); with `resume`, the session continues that conversation (the adapter's +/// `_meta.claudeCode.options.resume`), so turning them on mid-chat loses nothing. +pub fn turn_on_reads(params: &mut Value, resume: Option<&str>) { + let Some(options) = params.pointer_mut("/_meta/claudeCode/options").and_then(Value::as_object_mut) else { return }; + if let Some(off) = options.get_mut("disallowedTools").and_then(Value::as_array_mut) { + off.retain(|tool| !tool.as_str().is_some_and(|t| CLAUDE_ASK_TOOLS.contains(&t))); + } + options.insert("settings".into(), json!({"permissions": {"ask": CLAUDE_ASK_TOOLS}})); + if let Some(session) = resume { + options.insert("resume".into(), json!(session)); + } +} + +/// The agent is Claude Code's ACP adapter, the one agent whose read tools SolidCraft turns off and +/// on: 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") + }) +} + /// 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()) @@ -512,6 +591,8 @@ 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 agent says whether it is logged in (an extension both adapters send). AuthStatus(String), @@ -601,7 +682,8 @@ 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); + Some(Incoming::Permission { rpc: id.clone(), title, kind, options, reads }) } (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(""))), @@ -929,9 +1011,9 @@ mod tests { }) ); 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":{}}"#; @@ -1008,4 +1090,92 @@ mod tests { assert_eq!(config_options(&json!({"configOptions":null})), ConfigParse::Invalid); assert_eq!(config_options(&json!({"configOptions":[{"type":"select","id":"broken"}]})), ConfigParse::Invalid); } + + /// A session starts with Claude Code's read tools off, as before. Turned on, they ask before + /// every call and the session resumes the same conversation; its shell, write and web tools + /// stay off either way. + #[test] + fn claudes_read_tools_are_off_until_turned_on_and_then_ask() { + let off = |p: &Value| -> Vec { + p["_meta"]["claudeCode"]["options"]["disallowedTools"] + .as_array() + .map(|t| t.iter().filter_map(Value::as_str).map(str::to_string).collect()) + .unwrap_or_default() + }; + let mut p = session_new_params(std::path::Path::new("/tmp"), None, &json!({}), SYSTEM_NOTE); + for tool in ["Bash", "Write", "Read", "Glob", "Grep"] { + assert!(off(&p).iter().any(|t| t == tool), "{tool} off at first: {:?}", off(&p)); + } + assert!(p["_meta"]["claudeCode"]["options"].get("settings").is_none()); + turn_on_reads(&mut p, Some("s1")); + let options = &p["_meta"]["claudeCode"]["options"]; + for tool in ["Bash", "Write", "Edit", "WebFetch", "WebSearch", "Task"] { + assert!(off(&p).iter().any(|t| t == tool), "{tool} still off: {:?}", off(&p)); + } + for tool in CLAUDE_ASK_TOOLS { + assert!(!off(&p).iter().any(|t| t == tool), "{tool} on: {:?}", off(&p)); + } + assert_eq!(options["settings"]["permissions"]["ask"], json!(["Read", "Glob", "Grep"])); + assert_eq!(options["resume"], "s1", "the same conversation goes on"); + let mut fresh = session_new_params(std::path::Path::new("/tmp"), None, &json!({}), SYSTEM_NOTE); + turn_on_reads(&mut fresh, None); + assert!(fresh["_meta"]["claudeCode"]["options"].get("resume").is_none()); + let mut other = json!({"cwd": "/tmp"}); + turn_on_reads(&mut other, Some("s1")); + assert_eq!(other, json!({"cwd": "/tmp"}), "no Claude options: nothing to change"); + assert!(SYSTEM_NOTE.contains("``") && 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"]))); + } + + /// 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 c5d461d046b..39ccf0eb6e1 100644 --- a/crates/ui-egui/src/agent_chat/acp_client.rs +++ b/crates/ui-egui/src/agent_chat/acp_client.rs @@ -37,6 +37,10 @@ pub struct AcpBackend { init: Value, /// The system note the next session gets ([`acp::system_note`]). note: String, + /// Claude Code's read tools are on (asking), for the next session ([`ChatBackend::set_reads_files`]). + reads_files: bool, + /// The session that is open, or being opened, was asked for with them on. + session_reads: bool, next_id: u64, pending: HashMap, session: Option, @@ -67,6 +71,8 @@ impl AcpBackend { bridge, init: Value::Null, note: acp::SYSTEM_NOTE.to_string(), + reads_files: false, + session_reads: false, next_id: 0, pending: HashMap::new(), session: None, @@ -94,7 +100,19 @@ 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 mut params = acp::session_new_params(&self.cwd, self.bridge.as_ref(), &self.init, &self.note); + if self.reads_files { + acp::turn_on_reads(&mut params, None); + } + self.session_reads = self.reads_files; + self.request(Pending::SessionNew, "session/new", params); + } + + /// The open session again, with Claude Code's read tools on: the same conversation goes on. + fn resume_with_reads(&mut self) { + let mut params = acp::session_new_params(&self.cwd, self.bridge.as_ref(), &self.init, &self.note); + acp::turn_on_reads(&mut params, self.session.as_deref()); + self.session_reads = true; self.request(Pending::SessionNew, "session/new", params); } @@ -123,6 +141,12 @@ impl AcpBackend { out.push(Event::TurnEnded { reason: "cancelled".into() }); } self.session = Some(s.to_string()); + // Read tools were turned on while this session was being opened: open it + // again with them on before saying it is ready. + if self.reads_files && !self.session_reads { + self.resume_with_reads(); + return; + } match acp::config_options(&v) { acp::ConfigParse::Snapshot(options) => { self.modern_config = true; @@ -198,10 +222,10 @@ 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::Plan(p) => out.push(Event::Plan(p)), - Incoming::Permission { rpc, title, kind, options } => { + Incoming::Permission { rpc, title, kind, options, reads } => { 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 }); } Incoming::AuthStatus(s) => out.push(Event::AuthStatus(s)), Incoming::ModeChanged(m) if !self.modern_config => out.push(Event::Modes { current: m, available: Vec::new() }), @@ -295,6 +319,18 @@ impl ChatBackend for AcpBackend { self.note = acp::system_note(text); } + fn set_reads_files(&mut self, on: bool) -> bool { + if on == self.reads_files { + return false; + } + self.reads_files = on; + if on && self.session.is_some() && !self.session_reads && !self.pending.values().any(|p| *p == Pending::SessionNew) { + self.resume_with_reads(); + return true; + } + false + } + fn answer_permission(&mut self, key: u64, option: Option<&str>) { if let Some(rpc) = self.permissions.remove(&key) { self.proc.send(&acp::permission_reply(rpc, option)); @@ -393,6 +429,32 @@ mod tests { Ok(backend) } + /// Turning the read tools on in an open session opens it again (resuming it) before it is ready; + /// turned on while the first session is still being opened, that one is opened again as soon as + /// it answers, so no message goes out without them. + #[test] + fn turning_reads_on_reopens_the_session_before_it_is_ready() { + let mut backend = ready_backend().unwrap(); + assert!(backend.set_reads_files(true), "an open session is opened again"); + assert!(!backend.set_reads_files(true), "once"); + let mut events = Vec::new(); + backend.handle(Incoming::Reply { id: backend.next_id, result: Ok(json!({"sessionId":"s1"})) }, &mut events); + assert!(matches!(events.last(), Some(Event::Ready { .. })), "{events:?}"); + backend.shutdown(true); + + let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) }; + let mut starting = AcpBackend::start(&["sh".into(), "-c".into(), "cat >/dev/null".into()], ctx).unwrap(); + let mut events = Vec::new(); + starting.handle(Incoming::Reply { id: 1, result: Ok(json!({"agentInfo":{"name":"fake"}})) }, &mut events); + assert!(!starting.set_reads_files(true), "no session yet: it opens with them"); + starting.handle(Incoming::Reply { id: 2, result: Ok(json!({"sessionId":"s1"})) }, &mut events); + assert!(!events.iter().any(|e| matches!(e, Event::Ready { .. })), "opened again first: {events:?}"); + assert!(starting.pending.values().any(|p| *p == Pending::SessionNew)); + starting.handle(Incoming::Reply { id: starting.next_id, result: Ok(json!({"sessionId":"s1"})) }, &mut events); + assert!(matches!(events.last(), Some(Event::Ready { .. })), "{events:?}"); + starting.shutdown(true); + } + #[test] fn an_unresponsive_cancel_disconnects_the_agent() { let mut backend = ready_backend().unwrap(); diff --git a/crates/ui-egui/src/agent_chat/attach.rs b/crates/ui-egui/src/agent_chat/attach.rs index 078faf110ba..38c233846a6 100644 --- a/crates/ui-egui/src/agent_chat/attach.rs +++ b/crates/ui-egui/src/agent_chat/attach.rs @@ -1,10 +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. A folder goes by its place -//! too, with what it holds; and past [`MAX_FILES`] files, every further one does, so a batch of -//! photos reaches the agent whole, at full size, 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. +//! and place on this machine) for the agent to read with its own tools. A folder goes by its path +//! too, and past [`MAX_FILES`] files every further one does, so a batch of photos reaches the +//! agent whole however many there are. The agent is told what arrived, in order and how +//! ([`note_for`]). Each file is checked and bounded before it is kept; a refused one says why. use std::path::{Path, PathBuf}; use std::sync::Arc; @@ -25,13 +25,10 @@ fn failed(name: &str, e: impl std::fmt::Display) -> String { } /// Most files whose contents go with one message (pictures, PDFs, text, imported parts); past it, -/// a file goes by its place ([`reference`]). +/// a file goes by its path ([`reference`]). pub const MAX_FILES: usize = 8; -/// Most files and folders on one message, those that go by their place included. +/// Most files and folders on one message, those that go by their path included. pub const MAX_ON_MESSAGE: usize = 200; -/// A folder's entries read to say what it holds, and the most of them named in the message. -const MAX_FOLDER_SCAN: usize = 10_000; -const MAX_FOLDER_NAMED: 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. @@ -107,37 +104,21 @@ pub enum Content { path: PathBuf, text: Option>, }, - /// A file the agent is pointed to, not given: what it is, its size and where it is (and a - /// picture's size in pixels, from its header). + /// A file the agent is pointed to, not given: what it is, its size and where it is. Reference { path: PathBuf, size: u64, mime: &'static str, - pixels: Option<[u32; 2]>, }, - /// A folder the agent is pointed to: where it is and what it holds, none of its files. + /// A folder the 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, - listing: Arc, }, /// A CAD file imported into the design as its own component. Imported, } -/// What a folder holds at its top level, as far as it was read (hidden entries left out). -#[derive(Clone, Debug, Default, PartialEq)] -pub struct Listing { - /// The first [`MAX_FOLDER_NAMED`] names in order, a file's with its size; a folder's ends in - /// `/` and has none. - pub entries: Vec<(String, Option)>, - pub files: usize, - pub folders: usize, - /// The files' sizes together. - pub bytes: u64, - /// Reading stopped at [`MAX_FOLDER_SCAN`] entries: it holds more than counted. - pub cut: bool, -} - /// 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 { @@ -330,12 +311,7 @@ pub fn read(path: &Path) -> Result { 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", pixels: None }, - thumb: None, - }); + return Ok(Attachment { id: 0, name, content: Content::Reference { path, size: meta.len(), mime: "application/pdf" }, thumb: None }); } 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. @@ -344,7 +320,7 @@ pub fn read(path: &Path) -> Result { } Kind::Other if heic(path) => Err(refused("ui.agent_chat_file_heic", &name, &[])), Kind::Other => { - let content = Content::Reference { path: absolute(path), size: meta.len(), mime: mime_of(path), pixels: None }; + let content = Content::Reference { path: absolute(path), size: meta.len(), mime: mime_of(path) }; Ok(Attachment { id: 0, name, content, thumb: None }) } } @@ -355,8 +331,7 @@ fn heic(path: &Path) -> bool { } /// A file the agent is pointed to instead of given, whatever its kind (one past [`MAX_FILES`]): -/// its type, size and place, and a picture's size in pixels, read from its header. Nothing else -/// is read, so the agent gets it whole, at full size, with its own tools. +/// its type, size and path. Nothing of it is read, so the agent gets it whole 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))?; @@ -366,54 +341,24 @@ pub fn reference(path: &Path) -> Result { if heic(path) { return Err(refused("ui.agent_chat_file_heic", &name, &[])); } - let pixels = if kind(path) == Kind::Picture { pixels(path) } else { None }; - let content = Content::Reference { path: absolute(path), size: meta.len(), mime: mime_of(path), pixels }; + let content = Content::Reference { path: absolute(path), size: meta.len(), mime: mime_of(path) }; Ok(Attachment { id: 0, name, content, thumb: None }) } -/// A picture's width and height from its header, without decoding it. -fn pixels(path: &Path) -> Option<[u32; 2]> { - let (w, h) = image::ImageReader::open(path).ok()?.with_guessed_format().ok()?.into_dimensions().ok()?; - Some([w, h]) -} - /// 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 message: the agent is told where it is and what it holds at its top level (up -/// to [`MAX_FOLDER_SCAN`] entries read, [`MAX_FOLDER_NAMED`] named, hidden ones left out), and -/// reads the files it needs with its own tools. None of its files is read here. +/// A folder for a message: the agent is told where it 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 entries = std::fs::read_dir(path).map_err(|e| failed(&name, e))?; - let mut listing = Listing::default(); - for (seen, entry) in entries.enumerate() { - if seen >= MAX_FOLDER_SCAN { - listing.cut = true; - break; - } - let Ok(entry) = entry else { continue }; - let entry_name = entry.file_name().to_string_lossy().to_string(); - if entry_name.starts_with('.') { - continue; - } - // A link counts as what it leads to, as the agent's tools would see it; a broken one is - // left out. - let Ok(meta) = std::fs::metadata(entry.path()) else { continue }; - if meta.is_dir() { - listing.folders += 1; - listing.entries.push((format!("{entry_name}/"), None)); - } else { - listing.files += 1; - listing.bytes = listing.bytes.saturating_add(meta.len()); - listing.entries.push((entry_name, Some(meta.len()))); - } + let meta = std::fs::metadata(path).map_err(|e| failed(&name, e))?; + if !meta.is_dir() { + return Err(failed(&name, "not a folder")); } - listing.entries.sort_by_cached_key(|(n, _)| n.to_lowercase()); - listing.entries.truncate(MAX_FOLDER_NAMED); - Ok(Attachment { id: 0, name, content: Content::Folder { path: absolute(path), listing: Arc::new(listing) }, thumb: None }) + 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. @@ -506,6 +451,12 @@ fn encoded(name: String, img: image::DynamicImage, limit: usize) -> Result Option<[u32; 2]> { + let (w, h) = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?.into_dimensions().ok()?; + Some([w, h]) +} + /// No pixel is see-through (a screenshot or a photo, even when stored with an alpha channel). fn opaque(img: &image::DynamicImage) -> bool { !img.color().has_alpha() || img.to_rgba8().pixels().all(|p| p.0[3] == 255) @@ -517,134 +468,157 @@ fn thumbnail(img: &image::DynamicImage) -> Option> { Some(Arc::new(egui::ColorImage::from_rgba_unmultiplied(size, t.as_raw()))) } -/// Add a file's text to the message under `head`, within the `left` characters shared by the -/// files: whole when it fits; cut, saying how much is missing, when it doesn't; named only when -/// nothing is left. -fn fit(out: &mut String, left: &mut usize, head: &str, text: &str) { +/// How a message reaches this agent: whether it takes pictures and documents, the size of the +/// view's picture when one goes first (Attach view), and whether it has tools of its own to open +/// files by path (a coding agent does; an endpoint has only SolidCraft's). +#[derive(Clone, Copy, Debug)] +pub struct Delivery { + pub pictures: bool, + pub documents: bool, + pub view: Option<[u32; 2]>, + pub file_tools: bool, +} + +/// Text from outside (a file, a name, the design) placed inside SolidCraft's elements: a ` String { + text.replace(" String { + text.replace('&', "&").replace('"', """).replace('<', "<") +} + +/// A file's text in its own element, so a Markdown file's own fences can't end it early; +/// `escaped` says a ` String { + let body = neutralize(text); + *escaped |= body.len() != text.len(); + format!("\n\n{body}\n", attribute(name)) +} + +/// A file's text within the `left` characters the text files share, as its line in the list and +/// its element: whole when it fits; cut, saying how much is missing, when it doesn't; listed only +/// when nothing is left. +fn fit(n: usize, name: &str, what: &str, text: &str, left: &mut usize, escaped: &mut bool) -> (String, String) { let t = text.trim_end(); let len = t.chars().count(); if *left == 0 { - *out += &format!("\n\n{head}: left out, the message is at its size limit."); + (format!("{n}. {what}, left out (the message is at its size limit): `{name}`."), String::new()) } else if len <= *left { - *out += &format!("\n\n{head}:\n```\n{t}\n```"); *left -= len; + (format!("{n}. {what}, complete, below: `{name}`."), file_element(n, name, t, escaped)) } else { let kept: String = t.chars().take(*left).collect(); - *out += &format!("\n\n{head} (cut: {} more characters left out):\n```\n{kept}\n```", len - *left); + let missing = len - *left; *left = 0; + (format!("{n}. {what}, below, cut: `{name}`; its last {missing} characters are left out."), file_element(n, name, &kept, escaped)) } } -/// What the message says about its files, after the person's words: the text files' text, and the -/// pictures and imported parts by name (the agent sees the pictures themselves as images). -/// `pictures_sent` and `documents_sent`: whether this agent takes pictures and PDFs. The text files share `budget` characters -/// in order: one that doesn't fit is cut and says how much is missing, and one past the budget -/// is named only, so the message stays within the prompt cap. The lines that name files (those -/// that go by their place, a folder's listing) take their room from the budget first. -pub fn note(files: &[Attachment], pictures_sent: bool, documents_sent: bool, budget: usize) -> String { - let mut out = String::new(); - let pictures: Vec<&str> = files.iter().filter(|f| f.is_picture()).map(|f| f.name.as_str()).collect(); - if !pictures.is_empty() { - let list = pictures.join(", "); - out += &if pictures_sent { - format!("\n\nAttached pictures: {list}.") - } else { - format!("\n\n(Pictures attached but not sent, this agent takes none: {list}.)") +/// What the message says about its files, after the person's words, in one +/// `` element: every file in the order it arrives, saying how (image *n* +/// of *m*, text below, PDF document, by path, folder by path, imported into the design), the +/// view's picture first when there is one, then each text file's text in a `` element of +/// its own. The text files share `budget` characters in order (a file that doesn't fit is cut and +/// says how much is missing; one past the budget is listed only), after the list takes its room, +/// so the message stays within the prompt cap. Empty when nothing is attached. +pub fn note_for(files: &[Attachment], d: &Delivery, budget: usize) -> String { + if files.is_empty() && d.view.is_none() { + return String::new(); + } + let images = usize::from(d.view.is_some()) + if d.pictures { files.iter().filter(|f| f.is_picture()).count() } else { 0 }; + let mut lines: Vec> = Vec::new(); + let mut image = 0; + if let Some([w, h]) = d.view { + image += 1; + lines.push(Some(format!("1. Image {image} of {images}: a picture of the design's current view (Attach view), {w}×{h} px."))); + } + let first = lines.len() + 1; + let mut by_path = false; + // The lines that need no budget first; a text file's line waits for its share. + for (i, f) in files.iter().enumerate() { + let n = first + i; + let name = &f.name; + let line = match &f.content { + Content::Picture { size: [w, h], .. } if d.pictures => { + image += 1; + Some(format!("{n}. Image {image} of {images}: `{name}`, {w}×{h} px.")) + } + Content::Picture { .. } => Some(format!("{n}. Picture not sent, this agent takes none: `{name}`.")), + Content::Text(_) => None, + Content::Pdf { path, bytes, .. } if d.documents => { + Some(format!("{n}. PDF document, sent with this message: `{name}` ({}) at {}.", size_text(bytes.len() as u64), path.display())) + } + Content::Pdf { text: Some(t), .. } if !t.text.trim().is_empty() => None, + Content::Pdf { path, bytes, text } => { + by_path = true; + let why = if text.is_some() { "no text could be taken from it (scanned or protected)" } else { "its text could not be read" }; + Some(format!("{n}. PDF by path, not in this message: `{name}` ({}) at {}; {why}.", size_text(bytes.len() as u64), path.display())) + } + Content::Reference { path, size, mime } => { + by_path = true; + Some(format!("{n}. By path, not in this message: `{name}` ({mime}, {}) at {}.", size_text(*size), path.display())) + } + Content::Folder { path } => { + by_path = true; + Some(format!("{n}. Folder by path, not in this message: `{name}` at {}.", path.display())) + } + Content::Imported => Some(format!("{n}. Imported into the design as a component of its own: `{name}`.")), }; + lines.push(line); } - let named: usize = files.iter().filter_map(|f| named_line(f, documents_sent)).map(|l| l.chars().count()).sum(); - let mut left = budget.saturating_sub(named); - for f in files { - if let Some(line) = named_line(f, documents_sent) { - out += &line; - continue; - } - match &f.content { - Content::Text(t) => fit(&mut out, &mut left, &format!("Attached file `{}`", f.name), t), - // An agent that takes no documents gets the text (one with none is named instead). - Content::Pdf { path, bytes, text: Some(t) } => { + // The list takes its room (a text file's line estimated) before the text files share the rest. + let listed: usize = lines.iter().flatten().map(|l| l.chars().count() + 1).sum::() + + files.iter().filter(|f| matches!(f.content, Content::Text(_) | Content::Pdf { .. })).map(|f| f.name.chars().count() + 200).sum::(); + let mut left = budget.saturating_sub(listed + 400); + let (mut bodies, mut escaped) = (String::new(), false); + for (i, f) in files.iter().enumerate() { + let n = first + i; + let made = match &f.content { + Content::Text(t) => Some(fit(n, &f.name, &format!("Text ({})", size_text(t.len() as u64)), t, &mut left, &mut escaped)), + Content::Pdf { path, bytes, text: Some(t) } if !d.documents && !t.text.trim().is_empty() => { let cut = if t.cut { "; cut, the rest is in the file" } else { "" }; - let head = format!( - "Attached PDF `{}` ({} pages, {}, at {}): its text only, layout, pictures and fonts are dropped{cut}", - f.name, + let what = format!( + "PDF text ({} pages, {}, at {}; its text only, without layout, pictures or fonts{cut})", t.pages, size_text(bytes.len() as u64), path.display() ); - fit(&mut out, &mut left, &head, &t.text); + Some(fit(n, &f.name, &what, &t.text, &mut left, &mut escaped)) } - _ => {} - } - } - out -} - -/// The line that names a file without its contents: a PDF sent as a document, or one whose text -/// could not be taken; a file or folder that goes by its place; an imported part. `None` for -/// pictures (named together) and for text, which shares the budget. -fn named_line(f: &Attachment, documents_sent: bool) -> Option { - let line = match &f.content { - Content::Pdf { path, bytes, .. } if documents_sent => { - format!("\n\nAttached PDF `{}` ({}, at {}): sent with this message as a document.", f.name, size_text(bytes.len() as u64), path.display()) - } - Content::Pdf { path, bytes, text } if text.as_deref().is_none_or(|t| t.text.trim().is_empty()) => { - let why = if text.is_some() { "no text could be taken from it (scanned or protected)" } else { "its text could not be read" }; - format!( - "\n\nAttached file `{}` (PDF, {}, at {}): {why}; 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, pixels } => { - let pixels = pixels.map(|[w, h]| format!("{w}×{h} px, ")).unwrap_or_default(); - format!( - "\n\nAttached file `{}` ({mime}, {pixels}{}, at {}): read it with your own tools; it is not in this message.", - f.name, - size_text(*size), - path.display() - ) + _ => None, + }; + if let Some((line, body)) = made { + lines[n - 1] = Some(line); + bodies += &body; } - Content::Folder { path, listing } => folder_line(&f.name, path, listing), - Content::Imported => format!("\n\n(I added `{}` to the design as a component of its own.)", f.name), - Content::Text(_) | Content::Pdf { .. } | Content::Picture { .. } => return None, - }; - Some(line) -} - -/// A folder in the message: where it is, what it holds, and the names of the first entries. -fn folder_line(name: &str, path: &Path, l: &Listing) -> String { - let mut out = format!("\n\nAttached folder `{name}` (at {}): ", path.display()); - if l.files + l.folders == 0 { - out += "it is empty (hidden files aside)."; - return out; } - let count = |n: usize, one: &str| if n == 1 { format!("1 {one}") } else { format!("{n} {one}s") }; - out += &format!("{}, {} in all", count(l.files, "file"), size_text(l.bytes)); - if l.folders > 0 { - out += &format!(", and {}", count(l.folders, "folder")); + let mut out = String::from("\n\n\nAttached to this message, in the order they arrive:"); + for line in lines.into_iter().flatten() { + out.push('\n'); + out += &neutralize(&line); } - if l.cut { - out += &format!(" in the first {MAX_FOLDER_SCAN} entries read; it holds more"); + if by_path { + out += if d.file_tools { + "\nOpen what is given by path with your own read tools when you need it." + } else { + "\nYou have no tool that opens a file by its path: if you need one of them, ask the user to attach it as a picture or a text file." + }; } - out += ". Read what you need from it with your own tools; its files are not in this message, and none was scaled down.\nIn it: "; - let names: Vec = l - .entries - .iter() - .map(|(n, size)| match size { - Some(s) => format!("{n} ({})", size_text(*s)), - None => n.clone(), - }) - .collect(); - out += &names.join(", "); - let more = (l.files + l.folders).saturating_sub(l.entries.len()); - if more > 0 || l.cut { - out += &format!(", and {more}{} more", if l.cut { "+" } else { "" }); + if escaped { + out += "\nIn the text below, a `"; out } +/// [`note_for`] for an agent with file tools of its own and no picture of the view. +pub fn note(files: &[Attachment], pictures_sent: bool, documents_sent: bool, budget: usize) -> String { + note_for(files, &Delivery { pictures: pictures_sent, documents: documents_sent, view: None, file_tools: true }, budget) +} + /// The pictures and PDFs as parts of the message, to the agents that take them. pub fn parts(files: &[Attachment], pictures: bool, documents: bool) -> Vec { files @@ -833,37 +807,95 @@ mod tests { /// Review of #1744: eight 256 KB text files took a message to about 2 MB, past the prompt cap /// that only trimmed the typed text. The files' text now gets a budget: a file that doesn't - /// fit is cut and says so, and a file past it is named only. + /// fit is cut and says so, and a file past it is listed only. #[test] fn attached_text_is_kept_within_the_prompt_budget() { - let file = |n: &str, len: usize| Attachment { id: 0, name: n.into(), content: Content::Text(Arc::new("x".repeat(len))), thumb: None }; + let file = |n: &str, len: usize| Attachment { id: 0, name: n.into(), content: Content::Text(Arc::new("q".repeat(len))), thumb: None }; let files = vec![file("a.md", 600), file("b.md", 600), file("c.md", 600)]; - let n = note(&files, true, false, 1000); - assert!(n.contains("`a.md`") && n.contains("`b.md`") && n.contains("`c.md`"), "every file is named: {n}"); - assert!(n.matches('x').count() <= 1000, "the files' text stays within the budget"); - assert!(n.contains("200 more characters"), "a cut file says how much is missing: {n}"); - assert!(n.contains("left out"), "a file past the budget is named only: {n}"); - assert_eq!(note(&files, true, false, usize::MAX).matches('x').count(), 1800, "with room, every file goes whole"); + // The list's room (each text file's line reserved) and the element leave 1000 characters. + let n = note(&files, true, false, 2012); + assert!(n.contains("`a.md`") && n.contains("`b.md`") && n.contains("`c.md`"), "every file is listed: {n}"); + assert!(n.chars().count() <= 2012, "the whole note stays within its budget: {} characters", n.chars().count()); + assert!(n.contains("1. Text (600 bytes), complete, below: `a.md`."), "{n}"); + assert!(n.contains("2. Text (600 bytes), below, cut: `b.md`; its last "), "a cut file says how much is missing: {n}"); + assert!( + n.contains("3. Text (600 bytes), left out (the message is at its size limit): `c.md`."), + "a file past the budget is listed only: {n}" + ); + assert_eq!(note(&files, true, false, usize::MAX).matches('q').count(), 1800, "with room, every file goes whole"); } + /// The note is one element SolidCraft wrote: every file in the order it arrives and how it + /// arrives, then each text file in an element of its own. #[test] - fn the_message_names_its_files_and_carries_the_pictures() { + fn the_message_lists_its_files_in_order_and_carries_the_pictures() { let pic = from_rgba("target.png".into(), 2, 2, &[9; 16]).unwrap(); let text = Attachment { id: 0, name: "brief.md".into(), content: Content::Text(Arc::new("wall 2 mm\n".into())), thumb: None }; let part = Attachment::imported("motor.step".into()); let files = vec![pic, text, part]; let n = note(&files, true, false, usize::MAX); - assert!(n.contains("Attached pictures: target.png."), "{n}"); - assert!(n.contains("Attached file `brief.md`:\n```\nwall 2 mm\n```"), "{n}"); - assert!(n.contains("`motor.step` to the design"), "{n}"); - assert!(note(&files, false, false, usize::MAX).contains("not sent")); + assert!(n.starts_with("\n\n\nAttached to this message, in the order they arrive:\n"), "{n}"); + assert!(n.ends_with("\n"), "{n}"); + assert!(n.contains("\n1. Image 1 of 1: `target.png`, 2×2 px.\n"), "{n}"); + assert!(n.contains("\n2. Text (10 bytes), complete, below: `brief.md`.\n"), "{n}"); + assert!(n.contains("\n3. Imported into the design as a component of its own: `motor.step`."), "{n}"); + assert!(n.contains("\n\nwall 2 mm\n\n"), "{n}"); + assert!(!n.contains("by path"), "nothing goes by path: {n}"); + assert!(note(&files, false, false, usize::MAX).contains("1. Picture not sent, this agent takes none: `target.png`.")); + assert_eq!(note(&[], true, true, usize::MAX), "", "no files, no note"); let p = parts(&files, true, true); assert_eq!(p.len(), 1); 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. + /// The view's picture goes first among the images and is named; an agent with no file tools of + /// its own (an endpoint) is told it can't open what goes by path. + #[test] + fn the_views_picture_comes_first_and_an_endpoint_is_told_what_it_cant_open() { + let pic = from_rgba("target.png".into(), 2, 2, &[9; 16]).unwrap(); + let zip = Attachment { + id: 0, + name: "fixtures.zip".into(), + content: Content::Reference { path: "/a/fixtures.zip".into(), size: 3000, mime: "application/zip" }, + thumb: None, + }; + let files = vec![pic, zip]; + let d = Delivery { pictures: true, documents: false, view: Some([960, 620]), file_tools: true }; + let n = note_for(&files, &d, usize::MAX); + assert!(n.contains("\n1. Image 1 of 2: a picture of the design's current view (Attach view), 960×620 px.\n"), "{n}"); + assert!(n.contains("\n2. Image 2 of 2: `target.png`, 2×2 px.\n"), "{n}"); + assert!(n.contains("\n3. By path, not in this message: `fixtures.zip` (application/zip, 3 KB) at "), "{n}"); + assert!(n.contains("\nOpen what is given by path with your own read tools when you need it."), "{n}"); + let endpoint = note_for(&files, &Delivery { file_tools: false, ..d }, usize::MAX); + assert!(endpoint.contains("You have no tool that opens a file by its path"), "{endpoint}"); + assert!(!endpoint.contains("your own read tools"), "{endpoint}"); + let view_only = note_for(&[], &d, usize::MAX); + assert!(view_only.contains("1. Image 1 of 1: a picture of the design's current view"), "the view alone is still named: {view_only}"); + } + + /// A Markdown file's own code fences stay inside its element, and text that would close + /// SolidCraft's elements (in a file or in a name) is written so it can't. + #[test] + fn a_files_text_cant_end_its_element_early() { + let md = "# Build\n```sh\ncargo run\n```\nThen and as words.\n"; + let a = Attachment { id: 0, name: "README.md".into(), content: Content::Text(Arc::new(md.into())), thumb: None }; + let odd = Attachment { id: 0, name: "a\".md".into(), content: Content::Text(Arc::new("x".into())), thumb: None }; + let n = note(&[a, odd], true, true, usize::MAX); + assert!( + n.contains( + "\n# Build\n```sh\ncargo run\n```\nThen <\\/file> and <\\/solidcraft-attachments> as words.\n" + ), + "{n}" + ); + assert_eq!(n.matches("").count(), 1, "only the real end: {n}"); + assert_eq!(n.matches("").count(), 2, "one end per file: {n}"); + assert!(n.contains("name=\"a"</solidcraft-attachments>.md\""), "{n}"); + assert!(n.contains("a `"), "a <\\/file b <\\/solidcraft-note c

"); + } + + /// Any file that is neither a picture, text, CAD nor a PDF goes by its path (its type, size + /// and place) instead of being refused; the agent reads it with its own tools. #[test] fn other_files_go_by_reference() { crate::i18n::install(); @@ -873,7 +905,7 @@ mod tests { 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") }; + 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"); @@ -883,111 +915,85 @@ mod tests { 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!(n.contains("1. By path, not in this message: `fixtures.zip` (application/zip, 3 KB) at "), "{n}"); + assert!(n.contains("fixtures.zip.\nOpen what is given by path with your own read tools"), "{n}"); assert!(parts(&files, true, true).is_empty(), "a reference sends nothing but the note"); 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); } - /// Past the files whose contents go with a message, a file of any kind goes by its place: - /// nothing is read or scaled, a picture's size in pixels comes from its header, and the - /// message points the agent to it. HEIC is refused here too. + /// Past the files whose contents go with a message, a file of any kind goes by its path: + /// nothing of it is read, and the message points the agent to it. HEIC is refused here too. #[test] - fn a_file_by_its_place_is_left_whole() { + 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(4032, 3024, image::Rgb([90, 90, 90])).save_with_format(&photo, image::ImageFormat::Jpeg).unwrap(); + 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, pixels } = &a.content else { panic!("a reference: {:?}", a.content) }; - assert_eq!((*s, *mime, *pixels), (size, "image/jpeg", Some([4032, 3024])), "its own size, not scaled down"); + 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, 4032×3024 px, "), "{n}"); - assert!(n.contains("read it with your own tools; it is not in this message"), "{n}"); + assert!(n.contains("1. By path, not in this message: `IMG_0001.JPG` (image/jpeg, "), "{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", pixels: None, .. }), - "text goes by its place too" - ); + 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!(reference(&heic).unwrap_err().contains("HEIC")); assert!(reference(&d).unwrap_err().contains("not a file")); assert!(reference(&d.join("missing.jpg")).is_err()); - let fake = d.join("fake.png"); - std::fs::write(&fake, b"not a picture").unwrap(); - assert!(matches!(reference(&fake).unwrap().content, Content::Reference { pixels: None, .. }), "a bad header just has no size"); let _ = std::fs::remove_dir_all(&d); } - /// A folder goes by its place: the message says where it is, how many files and folders it - /// holds and their size, and names its entries in order (hidden ones left out, a long list cut - /// with how many more there are). None of its files is read. + /// 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_place_with_what_it_holds() { + 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("b.jpg"), vec![0u8; 2048]).unwrap(); std::fs::write(photos.join("A.jpg"), vec![0u8; 1024]).unwrap(); - std::fs::write(photos.join(".DS_Store"), b"x").unwrap(); let a = folder(&photos).unwrap(); assert_eq!(a.name, "site photos/"); assert!(a.by_place() && a.mark().is_empty()); - let Content::Folder { path, listing } = &a.content else { panic!("a folder: {:?}", a.content) }; + let Content::Folder { path } = &a.content else { panic!("a folder: {:?}", a.content) }; assert!(path.is_absolute() && path.ends_with("site photos")); - assert_eq!((listing.files, listing.folders, listing.bytes, listing.cut), (2, 1, 3072, false)); - let names: Vec<&str> = listing.entries.iter().map(|(n, _)| n.as_str()).collect(); - assert_eq!(names, ["A.jpg", "b.jpg", "raw/"], "in order, whatever the case, hidden ones left out"); let n = note(std::slice::from_ref(&a), true, true, usize::MAX); - assert!(n.contains("Attached folder `site photos/` (at "), "{n}"); - assert!(n.contains("2 files, 3 KB in all, and 1 folder."), "{n}"); - assert!(n.contains("Read what you need from it with your own tools"), "{n}"); - assert!(n.contains("In it: A.jpg (1 KB), b.jpg (2 KB), raw/."), "{n}"); + assert!(n.contains("1. Folder by path, not in this message: `site photos/` at "), "{n}"); + assert!(n.contains("\nOpen what is given by path with your own read tools"), "{n}"); + assert!(!n.contains("A.jpg") && !n.contains("raw"), "nothing in it is listed: {n}"); assert!(parts(&[a], true, true).is_empty()); - let empty = d.join("empty"); - std::fs::create_dir_all(&empty).unwrap(); - assert!(note(&[folder(&empty).unwrap()], true, true, usize::MAX).contains("it is empty")); - let many = d.join("many"); - std::fs::create_dir_all(&many).unwrap(); - for i in 0..MAX_FOLDER_NAMED + 5 { - std::fs::write(many.join(format!("p{i:04}.png")), b"x").unwrap(); - } - let m = folder(&many).unwrap(); - let Content::Folder { listing, .. } = &m.content else { panic!("a folder") }; - assert_eq!((listing.files, listing.entries.len()), (MAX_FOLDER_NAMED + 5, MAX_FOLDER_NAMED), "all counted, the first named"); - assert!(note(&[m], true, true, usize::MAX).ends_with("p0199.png (1 bytes), and 5 more.")); 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); } - /// The lines naming files that go by their place take their room before the text files share - /// the budget, so the whole message stays within it. + /// With many files by path, the list takes its room before the text files share the rest, so + /// the whole note stays within its budget. #[test] - fn named_files_take_their_room_from_the_text_budget() { - let place = Attachment { + fn the_note_stays_within_its_budget_with_many_files_by_path() { + let place = |i: usize| Attachment { id: 0, - name: "big.zip".into(), - content: Content::Reference { path: "/a/big.zip".into(), size: 10, mime: "application/zip", pixels: None }, + name: format!("photo {i}.jpg"), + content: Content::Reference { path: format!("/site/photos/photo {i}.jpg").into(), size: 3_100_000, mime: "image/jpeg" }, thumb: None, }; - let text = Attachment { id: 0, name: "a.md".into(), content: Content::Text(Arc::new("x".repeat(1000))), thumb: None }; - let files = vec![text, place]; - let named = named_line(&files[1], true).unwrap().chars().count(); - let n = note(&files, true, true, 500 + named); - assert_eq!(n.matches('x').count(), 500, "the text gets what the named file leaves: {n}"); - assert!(n.contains("`big.zip`")); + let text = Attachment { id: 0, name: "a.md".into(), content: Content::Text(Arc::new("q".repeat(20_000))), thumb: None }; + let mut files = vec![text]; + files.extend((0..40).map(place)); + let budget = 8000; + let n = note(&files, true, true, budget); + assert!(n.chars().count() <= budget, "{} characters", n.chars().count()); + assert!(n.contains("`photo 39.jpg`") && n.contains("Text (20 KB), below, cut: `a.md`"), "{n}"); } - /// A PDF goes whole as a document to an agent that takes them (and is named with its place); + /// A PDF goes whole as a document to an agent that takes them (and is named with its path); /// to one that doesn't, and when it is too big to send, the agent is pointed to the file. #[test] fn pdfs_go_as_documents_or_by_reference() { @@ -1003,10 +1009,11 @@ mod tests { assert_eq!((name.as_str(), mime.as_str()), ("brief 1.pdf", "application/pdf")); assert!(uri.starts_with("file://") && uri.ends_with("/brief%201.pdf"), "{uri}"); assert!(base64.starts_with("JVBERi0"), "the PDF's bytes: {base64}"); - assert!(note(&files, false, true, usize::MAX).contains("sent with this message as a document")); + assert!(note(&files, false, true, usize::MAX).contains("1. PDF document, sent with this message: `brief 1.pdf` (15 bytes) at ")); assert!(parts(&files, true, false).is_empty(), "an agent with no documents gets none"); let n = note(&files, true, false, usize::MAX); - assert!(n.contains("(PDF, 15 bytes, at ") && n.contains("read it with your own tools"), "{n}"); + assert!(n.contains("1. PDF by path, not in this message: `brief 1.pdf` (15 bytes) at "), "{n}"); + assert!(n.contains("its text could not be read.\nOpen what is given by path"), "{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(); @@ -1071,12 +1078,12 @@ mod tests { 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}"); + assert!(n.contains("1. PDF text (2 pages, "), "{n}"); + assert!(n.contains("its text only, without layout, pictures or fonts), complete, below: `brief.pdf`.") && 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}"); + assert!(short.contains("left out (the message is at its size limit)"), "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}"); + assert!(with.contains("PDF document, sent with this message") && !with.contains("Wall 2 mm"), "{with}"); let _ = std::fs::remove_dir_all(&d); } diff --git a/crates/ui-egui/src/agent_chat/backend.rs b/crates/ui-egui/src/agent_chat/backend.rs index 34ec089466c..9ca6e8464d8 100644 --- a/crates/ui-egui/src/agent_chat/backend.rs +++ b/crates/ui-egui/src/agent_chat/backend.rs @@ -81,6 +81,9 @@ 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, }, /// It needs the user to sign in; `methods` are its own ways to do so. AuthRequired { @@ -147,6 +150,14 @@ pub trait ChatBackend { /// The user's custom instructions (#8220), added to the system note of every session that /// starts after this call. The panel sets them before the first session and before New chat. fn set_instructions(&mut self, _text: &str) {} + /// Whether the agent's own read tools are on, asking before every read (only Claude Code's can + /// be told): off when a conversation starts, on once it sends a file or folder by path. Turning + /// them on in a running session resumes it with them on (the same conversation); true then, and + /// the panel waits for [`Event::Ready`] before it sends. Otherwise it applies to the next + /// session. + fn set_reads_files(&mut self, _on: bool) -> bool { + false + } /// Answer an [`Event::Permission`] with one of its options (`None`: cancelled). fn answer_permission(&mut self, key: u64, option: Option<&str>); /// Ask the backend to sign in by itself with one of its methods (it opens the browser). diff --git a/crates/ui-egui/src/agent_chat/context.rs b/crates/ui-egui/src/agent_chat/context.rs index 66fbe8f821d..52d287b20de 100644 --- a/crates/ui-egui/src/agent_chat/context.rs +++ b/crates/ui-egui/src/agent_chat/context.rs @@ -360,9 +360,15 @@ pub fn current_sels(session: &Session, entry: &Entry, names: &mut NameCache) -> } /// The message as the agent gets it: the text, then what was selected. +/// The message with what was picked or selected after it, in a `` element: +/// SolidCraft wrote it, not the user (names from the design can't close it). pub fn with_context(text: &str, context: &Context) -> String { let block = context.prompt_block(); - if block.is_empty() { text.to_string() } else { format!("{text}\n\n{block}") } + if block.is_empty() { + text.to_string() + } else { + format!("{text}\n\n\n{}\n", super::attach::neutralize(&block)) + } } /// Describe what the session has selected, as what was clicked: see [`clicked`]. diff --git a/crates/ui-egui/src/agent_chat/mod.rs b/crates/ui-egui/src/agent_chat/mod.rs index 8b17ea53489..9fce413a09a 100644 --- a/crates/ui-egui/src/agent_chat/mod.rs +++ b/crates/ui-egui/src/agent_chat/mod.rs @@ -370,9 +370,6 @@ pub(crate) struct Loading { pub id: u64, pub name: String, what: Reading, - /// A folder being listed: it goes by its place, so it doesn't count toward - /// [`attach::MAX_FILES`]. - by_place: bool, } enum Reading { @@ -491,6 +488,14 @@ 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, + /// This conversation sent a file or folder by path, so Claude Code's read tools are on (asking + /// before each read) for the rest of it; off again after New chat. + reads_files: bool, + /// The chat said that sending by path turns those tools on ([`warn_reads`]). + reads_warned: bool, /// 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` @@ -700,22 +705,44 @@ impl AgentChat { self.attachments.insert(at, file); name } + /// The files and folders of a message being sent that go by their path 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]) { + for f in files { + let path = match &f.content { + attach::Content::Reference { path, .. } | attach::Content::Folder { path } | attach::Content::Pdf { path, .. } => path, + _ => 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 place don't count. + /// go by their path don't count. fn files_sent(&self) -> usize { - self.attachments.iter().filter(|f| !f.by_place()).count() + self.loading.iter().filter(|l| !l.by_place).count() + 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 (`by_place`: - /// a folder, which goes by its place). + /// Read a file for the next message on a worker thread, in the window's language. #[cfg(not(target_arch = "wasm32"))] fn load( &mut self, name: String, - by_place: bool, job: impl FnOnce() -> std::result::Result + Send + 'static, ) -> std::result::Result { let (tx, rx) = std::sync::mpsc::channel(); @@ -728,13 +755,13 @@ impl AgentChat { }) .map_err(|e| trf("ui.agent_chat_file_error", &[("name", &name), ("error", &e.to_string())]))?; let id = self.next_file_id(); - self.loading.push(Loading { id, name: name.clone(), what: Reading::File(rx), by_place }); + self.loading.push(Loading { id, name: name.clone(), what: Reading::File(rx) }); Ok(name) } /// A CAD file whose import was asked for: it joins the message once the import is in. fn importing(&mut self, name: String, rx: Receiver) -> String { let id = self.next_file_id(); - self.loading.push(Loading { id, name: name.clone(), what: Reading::Import(rx), by_place: false }); + self.loading.push(Loading { id, name: name.clone(), what: Reading::Import(rx) }); name } @@ -946,7 +973,7 @@ 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 } => return Some(Outcome::Permission { key, title, kind, options, reads }), Event::Modes { current, available } => { if self.config_options.is_none() && !available.is_empty() { self.modes = available; @@ -1074,7 +1101,7 @@ 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 }, } /// The AI features are on (the master switch in Settings → AI) and this is the desktop app. @@ -1261,6 +1288,7 @@ pub fn connect(app: &mut SolveApp, ctx: &egui::Context) { match started { Ok(mut b) => { b.set_instructions(&app.preferences.agent_instructions); + b.set_reads_files(chat.reads_files); app.preferences.agent_last = entry.id.clone(); chat.backend = Some(b); chat.argv = entry.argv.clone(); @@ -1447,7 +1475,9 @@ pub(crate) fn leave_document(app: &mut SolveApp) { 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.]"; +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; /// Most names one list of [`changed_note`] carries; the rest are counted. const CHANGED_ITEMS: usize = 12; @@ -1751,6 +1781,17 @@ fn submit(app: &mut SolveApp, ctx: &egui::Context, text: String, image: bool, co let at = app.agent_chat.items.len().checked_sub(1); // The agent gets the selection as text after the message; the conversation shows chips. let text = context::with_context(&text, &context); + // The first message that sends a file or folder by path turns Claude Code's read tools on: a + // running session is opened again with them (the same conversation), and the message goes once + // it is ready. + if files.iter().any(attach::Attachment::by_place) && !app.agent_chat.reads_files { + app.agent_chat.reads_files = true; + let restarting = app.agent_chat.backend.as_mut().is_some_and(|b| b.set_reads_files(true)); + if restarting && app.agent_chat.state() == State::Ready { + app.agent_chat.restore_mode = Some(app.agent_chat.mode.clone()).filter(|m| !m.is_empty()); + app.agent_chat.state = Some(State::Starting); + } + } match app.agent_chat.state() { State::Ready => start_turn_with(app, text, image, at, files, interrupted.then_some(INTERRUPT_NOTE)), s => { @@ -1787,7 +1828,7 @@ fn send_queue(app: &mut SolveApp, ctx: &egui::Context, interrupted: bool) { } } // One message carries the contents of at most MAX_FILES files, and MAX_ON_MESSAGE files in - // all with those that go by their place; the rest are named, not sent. + // all with those that go by their path; the rest are named, not sent. let (files, left) = within_caps(files); if !left.is_empty() { let max = attach::MAX_FILES.to_string(); @@ -1848,6 +1889,9 @@ pub fn new_chat(app: &mut SolveApp) { chat.chips_version += 1; chat.pending.clear(); chat.attachments.clear(); + chat.by_path.clear(); + chat.reads_files = false; + chat.reads_warned = false; chat.loading.clear(); chat.pending_edit = None; chat.queued = None; @@ -1864,6 +1908,7 @@ pub fn new_chat(app: &mut SolveApp) { if let Some(b) = chat.backend.as_mut() { // Instructions edited since the last session apply from this one on. b.set_instructions(&app.preferences.agent_instructions); + b.set_reads_files(false); b.new_session(); } } @@ -1904,30 +1949,50 @@ fn start_turn(app: &mut SolveApp, text: String, image: bool, at: Option, } /// Start a message; `note` goes before the text for the agent, not into the conversation, and so -/// does what changed in the design since the agent's last turn ([`changed_note`]). The -/// files are named after the text (text files in full), and pictures go as images to an agent -/// that takes them. `at` is the message's place in the conversation, where its picture is kept. +/// does what changed in the design since the agent's last turn ([`changed_note`]), both in a +/// `` element. The files are listed after the text in a +/// `` element (text files in full), the view's picture first, and pictures +/// go as images to an agent that takes them. `at` is the message's place in the conversation, +/// where its picture is kept. fn start_turn_with(app: &mut SolveApp, text: String, image: bool, at: Option, files: Vec, note: Option<&str>) { let (pictures, documents) = (app.agent_chat.images, app.agent_chat.documents); let seen = app.agent_chat.seen.as_ref().and_then(Revision::get::); let changed = seen.and_then(|seen| changed_note(&seen, &app.session.doc)); let notes: Vec<&str> = note.into_iter().chain(changed.as_deref()).collect(); - let lead = if notes.is_empty() { text.clone() } else { format!("{}\n\n{text}", notes.join("\n")) }; + let lead = if notes.is_empty() { + text.clone() + } else { + format!("\n{}\n\n\n{text}", attach::neutralize(¬es.join("\n"))) + }; + // The view's picture is taken first: the list of what is attached names it as the first image. + let view = if image { + match crate::control::view_png(app, VIEW_IMAGE.0, VIEW_IMAGE.1) { + Ok(png) => Some(png), + Err(e) => { + log::warn!("the view's picture is left out of the prompt: {e}"); + None + } + } + } else { + None + }; + // An endpoint has only SolidCraft's tools: it can't open a file by its path. + let running = app.agent_chat.running_id.clone(); + let file_tools = !agents::entries(app).iter().any(|e| e.id == running && e.kind.is_api()); + let shown = view.as_deref().map(|png| attach::picture_size(png).unwrap_or([VIEW_IMAGE.0, VIEW_IMAGE.1])); + let delivery = attach::Delivery { pictures, documents, view: shown, file_tools }; // 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); - let about_files = attach::note(&files, pictures, documents, budget); + let about_files = attach::note_for(&files, &delivery, budget); let sent: String = format!("{lead}{about_files}").chars().take(MAX_PROMPT).collect(); let mut parts = vec![PromptPart::Text(sent)]; - if image { - match crate::control::view_png(app, VIEW_IMAGE.0, VIEW_IMAGE.1) { - Ok(png) => { - parts.push(PromptPart::Image { mime: "image/png".into(), base64: backend::base64(&png) }); - app.agent_chat.keep_picture(at, png); - } - Err(e) => log::warn!("the view's picture is left out of the prompt: {e}"), - } + if let Some(png) = view { + parts.push(PromptPart::Image { mime: "image/png".into(), base64: backend::base64(&png) }); + app.agent_chat.keep_picture(at, png); } parts.extend(attach::parts(&files, pictures, documents)); + // What goes by path may be read by the agent's own read tools without asking (see `on_permission`). + app.agent_chat.send_by_path(&files); // The undo step is named after the message, or its first file when it has no words. let first_line = text.lines().find(|l| !l.trim().is_empty()).or_else(|| files.first().map(|f| f.name.as_str())).unwrap_or(""); let label: String = first_line.chars().take(48).collect(); @@ -1960,7 +2025,7 @@ fn start_turn_with(app: &mut SolveApp, text: String, image: bool, at: Option std::result::Result { attach_one(app, path).map(|a| a.name) } @@ -1968,7 +2033,7 @@ pub fn attach_path(app: &mut SolveApp, path: &str) -> std::result::Result std::result::Result= attach::MAX_FILES { let file = attach::reference(p)?; + warn_reads(app, &file); return Ok(Attached { name: app.agent_chat.add_file(file), past_max: true }); } let file = if attach::kind(p) == attach::Kind::Cad { @@ -2020,14 +2077,28 @@ fn attach_one(app: &mut SolveApp, path: &str) -> std::result::Result std::result::Result { if app.agent_chat.files() >= attach::MAX_ON_MESSAGE { @@ -2045,7 +2116,7 @@ pub fn attach_rgba(app: &mut SolveApp, width: usize, height: usize, rgba: &[u8]) { let rgba = rgba.to_vec(); let named = name.clone(); - app.agent_chat.load(name, false, move || attach::from_rgba(named, width, height, &rgba)) + app.agent_chat.load(name, move || attach::from_rgba(named, width, height, &rgba)) } #[cfg(target_arch = "wasm32")] { @@ -2081,7 +2152,7 @@ pub(crate) fn drop_is_ours(chat: &AgentChat, ctx: &egui::Context) -> bool { } /// Attach files and folders dropped or chosen together; a refused one says why in the -/// conversation, and files past [`attach::MAX_FILES`] going by their place are said once. +/// conversation, and files past [`attach::MAX_FILES`] going by their path are said once. pub(crate) fn attach_paths(app: &mut SolveApp, paths: impl Iterator) { let mut past_max = false; for p in paths { @@ -2159,14 +2230,17 @@ 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. +fn on_permission(app: &mut SolveApp, key: u64, title: String, kind: Option<&str>, options: Vec, reads: Option<&std::path::Path>) { let agent = app.agent_chat.running_id.clone(); let mode = agents::mode_for(&app.preferences, &agent); let remembered = agents::always_allowed(&app.preferences, &agent, &title); let why = if acp::is_bridge_tool(&title, kind) { Some("ui.ai_auto_ours") + } else if reads.is_some_and(|path| app.agent_chat.attached_by_path(path)) { + Some("ui.ai_auto_attached") } else if remembered { Some("ui.ai_auto_remembered") } else if mode == agents::Mode::All { @@ -2474,7 +2548,9 @@ 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 }) => { + on_permission(app, key, title, kind.as_deref(), options, reads.as_deref()) + } 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 65e81c2fe70..0051f8b2d2f 100644 --- a/crates/ui-egui/src/agent_chat/panel.rs +++ b/crates/ui-egui/src/agent_chat/panel.rs @@ -2621,7 +2621,7 @@ 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 place, +/// What a chip says when the pointer rests on it: the file's name; for one that goes by its path, /// that place and what the agent does with it. #[cfg(not(target_arch = "wasm32"))] pub(super) fn chip_tip(f: &attach::Attachment) -> String { diff --git a/crates/ui-egui/src/agent_chat/tests.rs b/crates/ui-egui/src/agent_chat/tests.rs index 21ee51d0197..5c2b4d22621 100644 --- a/crates/ui-egui/src/agent_chat/tests.rs +++ b/crates/ui-egui/src/agent_chat/tests.rs @@ -809,17 +809,139 @@ fn the_agents_own_questions_are_answered_by_the_mode_or_asked() { PermissionOption { id: "no".into(), name: "Reject".into(), kind: "reject_once".into() }, ] }; - on_permission(&mut app, 1, "mcp__solidcraft-app__batch".into(), Some("other"), opts()); + on_permission(&mut app, 1, "mcp__solidcraft-app__batch".into(), Some("other"), opts(), None); assert!(matches!(app.agent_chat.items.last(), Some(Item::Notice { text, .. }) if text.contains("mcp__solidcraft-app__batch"))); - on_permission(&mut app, 2, "Run ls".into(), None, opts()); + on_permission(&mut app, 2, "Run ls".into(), None, opts(), None); assert!(matches!(app.agent_chat.items.last(), Some(Item::Permission { answer: None, .. }))); let n = app.agent_chat.items.len() - 1; answer_permission(&mut app, n, Some("always")); assert!(agents::always_allowed(&app.preferences, "claude", "Run ls")); - on_permission(&mut app, 3, "Run ls".into(), None, opts()); + on_permission(&mut app, 3, "Run ls".into(), None, opts(), None); assert!(matches!(app.agent_chat.items.last(), Some(Item::Notice { .. })), "remembered"); } +/// Claude Code's read tools are off until a message sends a file or folder by path: then the +/// session is opened again with them on (the same conversation) and the message waits for it to be +/// ready. Later messages don't reopen it; New chat turns them off again. +#[test] +fn the_first_message_sent_by_path_turns_the_read_tools_on() { + let d = attachable("reads-on"); + let (mut app, script, ctx) = app_with_script(); + script.reopens_for_reads.store(true, std::sync::atomic::Ordering::Relaxed); + send(&mut app, &ctx, "hello".into()); + ended(&script, ""); + poll(&mut app, &ctx); + assert!(!script.calls().iter().any(|c| c.starts_with("reads:")), "nothing sent by path yet: {:?}", script.calls()); + attach_path(&mut app, &d.to_string_lossy()).unwrap(); + send(&mut app, &ctx, "look in this folder".into()); + assert_eq!(script.calls().iter().filter(|c| *c == "reads: true").count(), 1, "{:?}", script.calls()); + assert_eq!(script.prompts().len(), 1, "the message waits for the session to open again"); + assert_eq!(app.agent_chat.state(), State::Starting); + script.report(Event::Ready { agent: "Test".into(), images: true }); + poll(&mut app, &ctx); + assert_eq!(script.prompts().len(), 2, "sent once it is ready"); + assert!(text_of(&script.prompts()[1]).starts_with("look in this folder"), "{}", text_of(&script.prompts()[1])); + ended(&script, ""); + poll(&mut app, &ctx); + attach_path(&mut app, &d.to_string_lossy()).unwrap(); + send(&mut app, &ctx, "and again".into()); + assert_eq!(script.prompts().len(), 3, "already on: sent at once"); + assert_eq!(script.calls().iter().filter(|c| c.starts_with("reads: true")).count(), 1); + ended(&script, ""); + poll(&mut app, &ctx); + new_chat(&mut app); + assert!(script.calls().iter().any(|c| c == "reads: false"), "New chat turns them off: {:?}", script.calls()); + let _ = std::fs::remove_dir_all(&d); +} + +/// The first file or folder that goes by its path, in a chat with Claude Code, makes the chat say +/// once that sending it turns Claude Code's read tools on; other agents' own tools are theirs, so +/// nothing is said for them. +#[test] +fn attaching_by_path_warns_once_that_it_turns_claudes_read_tools_on() { + let d = attachable("reads-warn"); + let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); + app.preferences.agents.push(agents::AgentConfig { + id: "codex-test".into(), + name: "Codex".into(), + command: "codex-acp".into(), + ..Default::default() + }); + app.preferences.agents.push(agents::AgentConfig { + id: "claude-test".into(), + name: "Claude Code".into(), + command: "/opt/homebrew/bin/claude-agent-acp".into(), + ..Default::default() + }); + let warnings = |app: &SolveApp| { + app.agent_chat + .items + .iter() + .filter(|i| matches!(i, Item::Notice { text, error: false } if text.contains("turns on Claude Code's read tools"))) + .count() + }; + app.agent_chat.agent_id = Some("codex-test".into()); + attach_path(&mut app, &d.to_string_lossy()).unwrap(); + assert_eq!(warnings(&app), 0, "another agent's tools are its own"); + app.agent_chat.agent_id = Some("claude-test".into()); + attach_path(&mut app, &at(&d, "brief.md")).unwrap(); + assert_eq!(warnings(&app), 0, "a text file goes in the message"); + attach_path(&mut app, &d.to_string_lossy()).unwrap(); + assert_eq!(warnings(&app), 1); + std::fs::write(d.join("fixtures.zip"), [0u8; 10]).unwrap(); + attach_path(&mut app, &at(&d, "fixtures.zip")).unwrap(); + assert_eq!(warnings(&app), 1, "said once"); + let _ = std::fs::remove_dir_all(&d); +} + +/// Claude Code's own read tools ask before every read. A read inside a file or folder sent by +/// path in this conversation is answered at once, and the chat says so; a read before anything +/// was sent, of anything else, through a link in the folder that leads out of it, or after New +/// chat waits for the user. +#[test] +fn reads_of_what_was_sent_by_path_are_allowed_and_others_wait() { + let d = attachable("reads"); + let (photos, outside) = (d.join("photos"), d.join("outside")); + std::fs::create_dir_all(&photos).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + std::fs::write(photos.join("a.jpg"), b"x").unwrap(); + std::fs::write(outside.join("secret.txt"), b"x").unwrap(); + let (mut app, _script, ctx) = app_with_script(); + let opts = || { + vec![ + PermissionOption { id: "allow".into(), name: "Allow".into(), kind: "allow_once".into() }, + PermissionOption { id: "no".into(), name: "Reject".into(), kind: "reject_once".into() }, + ] + }; + let asked = |app: &SolveApp| matches!(app.agent_chat.items.last(), Some(Item::Permission { answer: None, .. })); + let photo = photos.join("a.jpg"); + on_permission(&mut app, 1, "Read photos/a.jpg".into(), Some("read"), opts(), Some(&photo)); + assert!(asked(&app), "nothing was sent by path yet"); + attach_path(&mut app, &photos.to_string_lossy()).unwrap(); + send(&mut app, &ctx, "look at these".into()); + on_permission(&mut app, 2, "Read photos/a.jpg".into(), Some("read"), opts(), Some(&photo)); + assert!( + matches!(app.agent_chat.items.last(), Some(Item::Notice { text, error: false }) if text.contains("Read photos/a.jpg") && text.contains("attached")), + "answered at once" + ); + on_permission(&mut app, 3, "Find photos".into(), Some("search"), opts(), Some(&photos)); + assert!(!asked(&app), "the folder itself"); + on_permission(&mut app, 4, "Read secret.txt".into(), Some("read"), opts(), Some(&outside.join("secret.txt"))); + assert!(asked(&app), "outside what was sent"); + on_permission(&mut app, 5, "Read secret.txt".into(), Some("read"), opts(), Some(&photos.join("../outside/secret.txt"))); + assert!(asked(&app), "stepping out of the folder"); + #[cfg(unix)] + { + std::os::unix::fs::symlink(outside.join("secret.txt"), photos.join("link.txt")).unwrap(); + on_permission(&mut app, 6, "Read link.txt".into(), Some("read"), opts(), Some(&photos.join("link.txt"))); + assert!(asked(&app), "a link in the folder that leads out of it"); + } + new_chat(&mut app); + on_permission(&mut app, 7, "Read photos/a.jpg".into(), Some("read"), opts(), Some(&photo)); + assert!(asked(&app), "a new chat starts with nothing sent"); + let _ = std::fs::remove_dir_all(&d); +} + /// A title that only mentions SolidCraft is no tool of SolidCraft's: in every mode but Allow /// everything the user is asked, and the mode still answers when it says to. #[test] @@ -837,17 +959,17 @@ fn a_title_that_mentions_solidcraft_goes_through_the_users_mode() { for mode in [agents::Mode::Ask, agents::Mode::Edits] { app.preferences.agent_permissions.insert("codex".into(), mode); for (title, kind) in titles { - on_permission(&mut app, 1, title.into(), kind, opts()); + on_permission(&mut app, 1, title.into(), kind, opts(), None); assert!(matches!(app.agent_chat.items.last(), Some(Item::Permission { answer: None, .. })), "{mode:?}: {title}"); app.agent_chat.items.clear(); } // The chat's own tool stays a single question, the gate's. - on_permission(&mut app, 2, "mcp__solidcraft-app__batch".into(), Some("other"), opts()); + on_permission(&mut app, 2, "mcp__solidcraft-app__batch".into(), Some("other"), opts(), None); assert!(matches!(app.agent_chat.items.last(), Some(Item::Notice { .. })), "{mode:?}"); app.agent_chat.items.clear(); } app.preferences.agent_permissions.insert("codex".into(), agents::Mode::All); - on_permission(&mut app, 3, titles[0].0.into(), titles[0].1, opts()); + on_permission(&mut app, 3, titles[0].0.into(), titles[0].1, opts(), None); assert!(matches!(app.agent_chat.items.last(), Some(Item::Notice { .. })), "Allow everything answers it"); } @@ -862,6 +984,9 @@ struct Script { events: Arc>>, /// Every prompt in full (its text and pictures). prompts: Arc>>>, + /// Turning the read tools on opens the session again (as Claude Code's adapter does), so the + /// panel waits for Ready. + reopens_for_reads: Arc, } impl Script { @@ -900,6 +1025,10 @@ impl ChatBackend for Script { fn set_config_option(&mut self, id: &str, value: &str) { self.calls.lock().unwrap().push(format!("set_config_option: {id}={value}")); } + fn set_reads_files(&mut self, on: bool) -> bool { + self.calls.lock().unwrap().push(format!("reads: {on}")); + on && self.reopens_for_reads.load(std::sync::atomic::Ordering::Relaxed) + } fn authenticate(&mut self, _: &str) {} fn shutdown(&mut self, _: bool) {} } @@ -1009,6 +1138,7 @@ 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, }); ended(&script, "auth"); script.report(Event::AuthRequired { methods: Vec::new() }); @@ -1494,7 +1624,14 @@ fn send_now_cancels_then_sends_with_a_note() { assert_eq!(script.calls().len(), 2); ended(&script, "cancelled"); poll(&mut app, &ctx); - assert_eq!(script.calls(), ["prompt: build a gearbox".to_string(), "cancel".into(), format!("prompt: {INTERRUPT_NOTE}\n\nuse 12 teeth instead")]); + assert_eq!( + script.calls(), + [ + "prompt: build a gearbox".to_string(), + "cancel".into(), + format!("prompt: \n{INTERRUPT_NOTE}\n\n\nuse 12 teeth instead") + ] + ); assert!(matches!(app.agent_chat.items.last(), Some(Item::User { text, .. }) if text == "use 12 teeth instead")); // Stop after Send now wins: nothing more is sent by itself. send(&mut app, &ctx, "one more".into()); @@ -1580,9 +1717,13 @@ fn a_change_by_hand_between_messages_is_told_to_the_agent() { let sent = text_of(script.prompts().last().unwrap()); // The new box may bring parameters of its own after `w`. let new = expr(&app); - assert!(sent.starts_with(&format!("[The user changed the design by hand since your last reply (parameters: w {old} -> {new}")), "{sent}"); + assert!( + sent.starts_with(&format!("\n[The user changed the design by hand since your last reply (parameters: w {old} -> {new}")), + "{sent}" + ); + assert!(sent.contains("\n\nchamfer it"), "the note stands before the words: {sent}"); assert!(sent.contains(&format!("; features: {added} (new)). Read it again before")), "{sent}"); - assert!(sent.ends_with("chat.]\n\nchamfer it"), "{sent}"); + assert!(sent.ends_with("chat.]\n\n\nchamfer it"), "{sent}"); assert!( matches!(app.agent_chat.items.iter().rev().find(|i| matches!(i, Item::User { .. })), Some(Item::User { text, .. }) if text == "chamfer it") ); @@ -1680,7 +1821,7 @@ done "session/new".into(), "session/prompt: slow job".into(), "session/cancel".into(), - format!("session/prompt: {INTERRUPT_NOTE}\n\ndo this instead"), + format!("session/prompt: \n{INTERRUPT_NOTE}\n\n\ndo this instead"), ] ); disconnect(&mut app); @@ -1701,7 +1842,7 @@ fn new_chat_clears_everything_and_keeps_the_agent_and_mode() { send(&mut app, &ctx, "queued".into()); assert!(new_chat_needs_confirm(&app), "a running message and a queue ask first"); new_chat(&mut app); - assert_eq!(script.calls(), ["prompt: first", "cancel", "new_session"]); + assert_eq!(script.calls(), ["prompt: first", "cancel", "reads: false", "new_session"], "New chat starts with the read tools off"); assert!(app.agent_chat.items.is_empty() && app.agent_chat.pending.is_empty()); assert_eq!(app.agent_chat.state(), State::Starting); assert_eq!(app.agent_chat.agent_id.as_deref(), Some("claude")); @@ -3032,7 +3173,8 @@ fn a_message_carries_its_files() { assert_eq!(sent.len(), 1); let text = text_of(&sent[0]); assert!(text.starts_with("make the case like this"), "{text}"); - assert!(text.contains("Attached pictures: target.png.") && text.contains("wall 2 mm, Pi 5 inside"), "{text}"); + assert!(text.contains("1. Image 1 of 1: `target.png`, 40×30 px.") && text.contains("wall 2 mm, Pi 5 inside"), "{text}"); + assert!(text.contains("") && text.trim_end().ends_with(""), "{text}"); assert_eq!(sent[0].iter().filter(|p| matches!(p, PromptPart::Image { mime, .. } if mime == "image/png")).count(), 1); assert!(app.agent_chat.attachments.is_empty(), "the files went with the message"); // The picture shows as a thumbnail with the viewer (its name is the note); the text file by name. @@ -3139,13 +3281,9 @@ fn past_eight_files_the_rest_go_by_their_place() { .items .iter() .filter_map(|i| if let Item::Notice { text, error } = i { Some((text.as_str(), *error)) } else { None }) - .filter(|(t, _)| t.contains("by their place")) + .filter(|(t, _)| t.contains("by their path")) .collect(); - assert_eq!( - told, - [("Past 8 files, the rest go by their place on disk: the agent reads them with its own tools, at full size", false)], - "said once for the batch" - ); + assert_eq!(told, [("Past 8 files, the rest go by their path: the agent reads them with its own tools", false)], "said once for the batch"); assert!(attach_rgba(&mut app, 2, 2, &[9; 16]).unwrap_err().contains("save the picture as a file")); assert!(attach_path(&mut app, &at(&d, "missing.png")).is_err(), "a missing file is still refused"); assert!(control(&mut app, &ctx, &json!({"remove_file": 11})).is_err(), "no twelfth file to take off"); @@ -3155,9 +3293,10 @@ fn past_eight_files_the_rest_go_by_their_place() { let sent = &script.prompts()[0]; let text = text_of(sent); assert_eq!(pictures_in(sent), 0, "the picture past the eight goes by its place: {text}"); - assert_eq!(text.matches("Attached file `brief.md`:").count(), attach::MAX_FILES - 1, "seven in full: {text}"); - assert!(text.contains("Attached file `target.png` (image/png, 40×30 px, "), "{text}"); - assert_eq!(text.matches("read it with your own tools; it is not in this message").count(), 3, "{text}"); + assert_eq!(text.matches("complete, below: `brief.md`.").count(), attach::MAX_FILES - 1, "seven in full: {text}"); + assert!(text.contains("By path, not in this message: `target.png` (image/png, "), "{text}"); + assert_eq!(text.matches("By path, not in this message: ").count(), 3, "{text}"); + assert!(text.contains("Open what is given by path with your own read tools"), "{text}"); let more = attach::MAX_ON_MESSAGE - app.agent_chat.files(); for _ in 0..more { attach_path(&mut app, &at(&d, "brief.md")).unwrap(); @@ -3215,21 +3354,20 @@ fn choose_files_takes_several_and_choose_a_folder_one_folder() { /// A folder attached through the control channel, as a path, is listed off the window thread and /// goes to the agent as its place and what it holds; a folder doesn't take one of the eight. #[test] -fn an_attached_folder_tells_the_agent_where_it_is_and_what_it_holds() { +fn an_attached_folder_tells_the_agent_where_it_is() { let d = attachable("folder"); let (mut app, script, ctx) = app_with_script(); control(&mut app, &ctx, &json!({"attach": d.to_string_lossy()})).unwrap(); - assert_eq!(app.agent_chat.files_sent(), 0, "a folder being listed takes none of the eight"); - settle_files(&mut app, &ctx); - assert_eq!(app.agent_chat.files_sent(), 0); + assert!(app.agent_chat.loading.is_empty(), "nothing in it is read"); + assert_eq!(app.agent_chat.files_sent(), 0, "a folder takes none of the eight"); for _ in 0..attach::MAX_FILES { attach_path(&mut app, &at(&d, "brief.md")).unwrap(); } assert_eq!(app.agent_chat.files_sent(), attach::MAX_FILES, "eight more in full"); 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("2 files, ") && text.contains("In it: brief.md (") && text.contains("target.png ("), "{text}"); + assert!(text.contains(&format!("1. Folder by path, not in this message: `{}/` 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); } @@ -3258,7 +3396,7 @@ fn a_queued_message_keeps_its_files_through_stop_and_sends_them() { let last = sent.last().expect("the queue went"); let text = text_of(last); assert!(text.starts_with("like this") && !text.contains("\n\n\n\n"), "a message of files alone adds no empty paragraph: {text:?}"); - assert!(text.contains("Attached pictures: target.png.") && text.contains("wall 2 mm"), "{text}"); + assert!(text.contains("Image 1 of 1: `target.png`") && text.contains("wall 2 mm"), "{text}"); assert_eq!(pictures_in(last), 1); let sent = status(&app)["items"].as_array().and_then(|i| i.last()).cloned().unwrap_or_default(); assert_eq!((sent["files"].clone(), sent["pictures"].clone()), (json!(["brief.md"]), json!(1))); @@ -3283,8 +3421,8 @@ fn the_queue_sends_at_most_eight_files_and_names_the_rest() { poll(&mut app, &ctx); let sent = script.prompts(); assert_eq!(sent.len(), 2); - assert_eq!(text_of(&sent[1]).matches("Attached file `brief.md`").count(), attach::MAX_FILES); - assert_eq!(text_of(&sent[1]).matches("Attached file `target.png` (image/png").count(), 3, "every file by its place goes"); + assert_eq!(text_of(&sent[1]).matches("complete, below: `brief.md`.").count(), attach::MAX_FILES); + assert_eq!(text_of(&sent[1]).matches("By path, not in this message: `target.png` (image/png").count(), 3, "every file by its path goes"); let told = app .agent_chat .items @@ -3719,7 +3857,7 @@ fn a_cad_file_joins_the_message_once_its_import_is_in() { h.call("ui.agent_chat", json!({"send": "fit around this"})); h.frames(2); let text = text_of(&script.prompts()[0]); - assert!(text.contains("`block.stl` to the design") && !text.contains("broken.stl"), "{text}"); + assert!(text.contains("Imported into the design as a component of its own: `block.stl`.") && !text.contains("broken.stl"), "{text}"); let _ = std::fs::remove_dir_all(&d); } @@ -3892,7 +4030,8 @@ fn an_attached_selection_goes_as_text_for_the_agent_and_as_chips_in_the_conversa app.agent_chat.attach_selection = true; send(&mut app, &ctx, "round this".into()); let prompt = script.calls().pop().expect("a prompt"); - assert!(prompt.starts_with("prompt: round this\n\n[Selected in SolidCraft"), "{prompt}"); + assert!(prompt.starts_with("prompt: round this\n\n\n[Selected in SolidCraft"), "{prompt}"); + assert!(prompt.trim_end().ends_with(""), "{prompt}"); for want in ["Elements:", "- Flat face ", "planar", "area ", "- Edge ", "length ", "name ", "Features:", "feature id", "Bodies:", "- Body1"] { assert!(prompt.contains(want), "{want:?} missing from {prompt}"); } @@ -3925,7 +4064,7 @@ fn queued_messages_keep_the_selection_they_were_typed_with() { ended(&script, ""); poll(&mut app, &ctx); let prompt = script.calls().pop().expect("the queue went"); - assert!(prompt.starts_with("prompt: second\n\nthird\n\n[Selected"), "{prompt}"); + assert!(prompt.starts_with("prompt: second\n\nthird\n\n\n[Selected"), "{prompt}"); assert!(prompt.contains("- Alpha") && prompt.contains("- Beta"), "{prompt}"); let Some(Item::User { context, .. }) = app.agent_chat.items.last() else { panic!("a sent message") }; assert_eq!(context.items.iter().map(|i| i.label.as_str()).collect::>(), ["Alpha", "Beta"]); @@ -4485,7 +4624,7 @@ fn picks_reach_the_agent_at_the_place_they_were_made() { send(&mut app, &ctx, text); let prompt = script.calls().pop().expect("a prompt"); assert!(prompt.starts_with("prompt: make «1: Flat face"), "the face picked second stands first and is 1: {prompt}"); - assert!(prompt.contains(" match «2: Body1» \n\n[Selected"), "the body's mark follows 'match': {prompt}"); + assert!(prompt.contains(" match «2: Body1» \n\n\n[Selected"), "the body's mark follows 'match': {prompt}"); let block = &prompt[prompt.find("[Selected in SolidCraft").expect("the block")..]; assert!(block.contains("stands for the numbered group below"), "{block}"); let g1 = block.find("\n«1: ").expect("group 1"); diff --git a/docs/agent-chat.md b/docs/agent-chat.md index 271cb7a47ad..6f16b101e40 100644 --- a/docs/agent-chat.md +++ b/docs/agent-chat.md @@ -126,8 +126,8 @@ turn limit. Queue, Send now and Stop keep their existing behavior. ## Files and pictures A message carries the contents of up to eight files, to show the agent what you mean: a concept -picture, a sketch, a brief, a part to fit around. More files, and folders, go by their place on -disk (below), up to 200 on one message. +picture, a sketch, a brief, a part to fit around. More files, and folders, go by their path +(below), up to 200 on one message. - **+** next to **Send** has **Choose files…** (a file dialog for the types below; pick several at once), **Choose a folder…** and **Paste a picture** (the picture on the clipboard). @@ -153,19 +153,32 @@ disk (below), up to 200 on one message. 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). -- **Past eight files**, every further file goes by its place: the message tells the agent its - name, type, size (a picture's size in pixels too) and path, and the agent reads it with its own - tools. Nothing is read, scaled down or copied, so a batch of photos reaches the agent whole, at - full size, however many there are; the chat says so once for the batch. Its chip shows the - file's type instead of a thumbnail, and holding the pointer over it shows its path. A pasted - picture has no place on disk, so past eight it is refused: save it as a file and attach that. -- **A folder** goes by its place too: the message says where it is, how many files and folders it - holds and their size, and names the first 200 entries at its top level (hidden ones left out). - The agent reads the files it needs with its own tools. A folder or a file by its place doesn't - take one of the eight. Files other than the types above (a ZIP, a DXF) also go by their place. - Only a coding agent (Claude Code, Codex, Gemini CLI…) has tools of its own to read them, and it - may ask before it reads outside its working folder; an OpenAI- or Anthropic-compatible endpoint - has only SolidCraft's tools, so it gets the eight files in the message and the others' names. +- **Past eight files**, every further file goes by its path: the message tells the agent its + name, type, size and path, and the agent reads it with its own read tools. SolidCraft reads + nothing of it, so a batch of photos reaches the agent however many there are; the chat says so + once for the batch. Its chip shows the file's type instead of a thumbnail, and holding the + pointer over it shows its path. A pasted picture has no path, so past eight it is refused: save + it as a file and attach that. +- **A folder** goes by its path too, and only its path: nothing in it is listed, counted or read + (on a network share that would keep the message waiting). The agent lists it and reads the + files it needs with its own read tools. A folder or a file by its path doesn't take one of the + eight. Files other than the types above (a ZIP, a DXF) also go by their path. +- **Who can read files by path.** A coding agent (Codex, Gemini CLI…) reads them with its own + tools. Claude Code's read tools are off until a message sends a file or folder by path; the first + time one lands on the chips, the chat says that sending it turns them on for this chat. Then they + ask before every read, and the chat answers them by itself for what you sent by path + (*Auto-allowed* in the chat): any other read waits for **Allow** or **Deny** (see + [What it can't do](#what-it-cant-do)). An OpenAI- or Anthropic-compatible endpoint has only + SolidCraft's tools: it gets the eight files in the message, and the message tells it that it + can't open the others. +- **What the agent is told.** After your words, in a `` element (SolidCraft's + note tells the agent that such elements come from SolidCraft, not from you), the message lists + every file in the order it arrives and how: image *n* of *m* (the picture of the view first, when + **Attach view** is ticked), text below, PDF document, by path, folder by path, imported into the + design. Each text file follows in a `` element of its own, so a Markdown file's own code + fences can't end it early. The selection goes in a `` element, and notes + such as "the design changed since your last turn" in a `` element before your + words. - 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 @@ -176,7 +189,7 @@ disk (below), up to 200 on one message. 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, the contents of at most eight; the rest are named in the chat and not sent -(files and folders by their place all go). **New chat** +(files and folders by their path all go). **New chat** clears the files waiting on the chips too. ## Typing while the agent works @@ -544,7 +557,8 @@ 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 +and notes it in the chat as *Auto-allowed*. So it does when Claude Code reads something you sent +by path in this conversation (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 the agent yourself. With **Allow everything**, or after **Always allow**, those questions are answered the same way and noted too. @@ -571,7 +585,15 @@ 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 to turn off its shell, file and web tools for the session. + Code adapter to turn off its shell, file-writing and web tools for the session. +- **Claude Code reads only what you sent, unless you allow more.** Its read tools (Read, Glob, + Grep) are off until a message sends a file or folder by path. Then the chat turns them on for the + rest of the conversation (it opens the same session again with them on, so the agent loses + nothing), and they ask before every read. The chat answers a read of a file or folder you sent by + path; any other read waits for **Allow** or **Deny**, as does a search whose pattern starts at a + root or your home folder or steps up with `..`. A path counts once links are followed, so a link + in a folder you sent that leads out of it still asks. **New chat** turns them off again; + **Allow everything** lets every read through. 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 7f6802603d4..95d83055fec 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -958,7 +958,7 @@ no box selection. | `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)}; 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 or folder's path (a picture, a text file or a CAD file, for the next message; CAD files are imported at once; a folder, and any file past the eighth, goes by its place), `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)}; 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 or folder's path (a picture, a text file or a CAD file, for the next message; CAD files are imported at once; a folder, and any file past the eighth, 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` | | | `app.quit` | `force?` (quit without asking about unsaved designs) | `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 3816542bcc0..2e58761e66d 100644 --- a/docs/design/in-app-agent-chat.md +++ b/docs/design/in-app-agent-chat.md @@ -227,8 +227,19 @@ ACP lets the client offer a file system and a terminal; the chat offers neither, agent in an empty working folder of SolidCraft's own (`/agent-chat/work`), not the design's folder. The Claude Code adapter has shell, file and web tools of its own anyway: the session asks it to turn them off (`_meta.claudeCode.options.disallowedTools`) and not to offer -"bypass permissions". Other agents' own permission requests appear in the panel with their -options. +"bypass permissions". Once a message sends a file or folder by path, its read tools (Read, Glob, +Grep) come on behind a `permissions.ask` rule (`_meta.claudeCode.options.settings`): a running +session is opened again with `session/new` and `_meta.claudeCode.options.resume` set to its id, +which keeps the conversation (`acp::turn_on_reads`), and the message waits for its Ready. The +first such file on the chips makes the chat say so. Every read then 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 with the tools turned off again), and asks the user otherwise. Checked with +`claude-agent-acp` 0.107.0: without the rule these tools read any path without asking, and a +resumed session keeps what was said before. Other agents' own permission requests appear in the +panel with their options. ### Processes From b97e2cb2143a5319df12d151e4916664853117cc Mon Sep 17 00:00:00 2001 From: Seth LaForge Date: Tue, 17 Nov 2026 13:02:33 -0800 Subject: [PATCH 05/12] Assistant: the + menu picks several files and folders of any type, in one item on macOS (#16452) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On macOS the + menu has one Choose files or folders…: its open panel chooses both. Windows' and Linux's dialogs choose files or folders but not both, so there it has Choose files… and Choose folders…, each taking several at once. The dialog no longer filters by type. On macOS the filter let only the listed types be chosen (rfd sends every filter's extensions as one allowed list, and "All files" `*` is no wildcard there), so files that go by path, like ZIP and DXF, could be dropped but not chosen. The unused "Pictures, PDFs, text and CAD files" message goes from the catalogs. Co-Authored-By: Claude Opus 5.5 --- apps/solidcraft/src/main.rs | 33 +++++-- assets/locales/ar.json | 1 - assets/locales/bg.json | 1 - assets/locales/bs.json | 1 - assets/locales/ca.json | 1 - assets/locales/cs.json | 1 - assets/locales/da.json | 1 - assets/locales/de.json | 1 - assets/locales/en.json | 1 - assets/locales/es.json | 1 - assets/locales/fi.json | 1 - assets/locales/fr.json | 1 - assets/locales/gl.json | 1 - assets/locales/he.json | 1 - assets/locales/hr.json | 1 - assets/locales/hu.json | 1 - assets/locales/id.json | 1 - assets/locales/it.json | 1 - assets/locales/ja.json | 1 - assets/locales/ka.json | 1 - assets/locales/ko.json | 1 - assets/locales/lv.json | 1 - assets/locales/ms.json | 1 - assets/locales/nb.json | 1 - assets/locales/nl.json | 1 - .../pending/agent-chat-files-by-place.json | 48 +++++----- assets/locales/pl.json | 1 - assets/locales/pt-BR.json | 1 - assets/locales/ro.json | 1 - assets/locales/ru.json | 1 - assets/locales/sr.json | 1 - assets/locales/sv.json | 1 - assets/locales/tr.json | 1 - assets/locales/uk.json | 1 - assets/locales/vi.json | 1 - assets/locales/zh-TW.json | 1 - assets/locales/zh.json | 1 - crates/ui-egui/src/agent_chat/attach.rs | 12 --- crates/ui-egui/src/agent_chat/panel.rs | 75 ++++++++-------- crates/ui-egui/src/agent_chat/tests.rs | 89 ++++++++++--------- crates/ui-egui/src/file_picker.rs | 40 ++++++++- crates/ui-egui/src/lib.rs | 13 ++- docs/agent-chat.md | 7 +- 43 files changed, 191 insertions(+), 161 deletions(-) diff --git a/apps/solidcraft/src/main.rs b/apps/solidcraft/src/main.rs index 564c25f539b..59f6cb892f3 100644 --- a/apps/solidcraft/src/main.rs +++ b/apps/solidcraft/src/main.rs @@ -764,9 +764,14 @@ fn services(cc: &eframe::CreationContext<'_>, folder: &DialogFolder) -> Services 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) = (folder.clone(), folder.clone(), folder.clone()); - let files_folder = 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). @@ -810,14 +815,30 @@ fn services(cc: &eframe::CreationContext<'_>, folder: &DialogFolder) -> Services let folder = file_folder.clone(); Box::pin(async move { folder.answer(future.await) }) })), - // The same, several files at once (the agent chat's attachments: a batch of photos). - pick_files: Some(Box::new(move |label: &str, exts: &[&str]| { - let all = any_case(exts); - let all: Vec<&str> = all.iter().map(String::as_str).collect(); - let future = files_folder.start(files_parent.clone()).add_filter(label, &all).add_filter("All files", &["*"]).pick_files(); + // Several files of any type at once (the agent chat's attachments: a batch of photos). No + // filter: what the chat can't read goes to the agent by path. (On macOS a filter lists the + // only types that can be chosen, and its "All files" `*` is no wildcard.) + pick_files: Some(Box::new(move || { + let future = files_folder.start(files_parent.clone()).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(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(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, // A folder: the document library's, or one the agent chat attaches. pick_folder: Some(Box::new(move || { let future = folder_parent.clone().set_title("Choose a folder").pick_folder(); diff --git a/assets/locales/ar.json b/assets/locales/ar.json index 2593551bf10..f86c85fda42 100644 --- a/assets/locales/ar.json +++ b/assets/locales/ar.json @@ -5513,7 +5513,6 @@ "ui.agent_chat_attach_selection_tip": "إرسال ما هو محدد في النموذج (أوجه وحواف وميزات وأجسام) مع الرسالة، ليعرف الوكيل ما تقصده", "ui.agent_chat_attach_view": "إرفاق العرض", "ui.agent_chat_attach_view_tip": "إرسال صورة للعرض الحالي مع الرسالة", - "ui.agent_chat_attachable": "صور وملفات PDF ونصوص وملفات CAD", "ui.agent_chat_auth_agent": "تسجيل الدخول باستخدام {name}", "ui.agent_chat_auth_env": "اضبط {vars} في بيئة النظام وأعد تشغيل SolidCraft.", "ui.agent_chat_auth_needed": "يطلب الوكيل منك تسجيل الدخول. تسجّل الدخول عبر الوكيل نفسه؛ ولا يرى SolidCraft كلمة مرورك أو مفاتيحك أبدًا.", diff --git a/assets/locales/bg.json b/assets/locales/bg.json index 079e505bc0d..a2bb0458aec 100644 --- a/assets/locales/bg.json +++ b/assets/locales/bg.json @@ -2727,7 +2727,6 @@ "ui.agent_chat_attach_selection_tip": "Send what is selected in the model (faces, edges, features, bodies) with the message, so the agent knows what you mean", "ui.agent_chat_attach_view": "Attach view", "ui.agent_chat_attach_view_tip": "Send a picture of the current view with the message", - "ui.agent_chat_attachable": "Pictures, PDFs, text and CAD files", "ui.agent_chat_auth_agent": "Sign in with {name}", "ui.agent_chat_auth_env": "Set {vars} in your environment and restart SolidCraft.", "ui.agent_chat_auth_needed": "The agent asks you to sign in. You sign in with the agent itself; SolidCraft never sees your password or keys.", diff --git a/assets/locales/bs.json b/assets/locales/bs.json index 8d15f2818f7..a50dab94561 100644 --- a/assets/locales/bs.json +++ b/assets/locales/bs.json @@ -4114,7 +4114,6 @@ "ui.agent_chat_attach_selection_tip": "Pošalji s porukom ono što je izabrano u modelu (lica, ivice, operacije, tijela), da agent zna na šta mislite", "ui.agent_chat_attach_view": "Priloži prikaz", "ui.agent_chat_attach_view_tip": "Pošalji sliku trenutnog prikaza s porukom", - "ui.agent_chat_attachable": "Slike, PDF-ovi, tekst i CAD datoteke", "ui.agent_chat_auth_agent": "Prijavi se pomoću {name}", "ui.agent_chat_auth_env": "Postavite {vars} u svom okruženju i ponovo pokrenite SolidCraft.", "ui.agent_chat_auth_needed": "Agent traži da se prijavite. Prijavljujete se kod samog agenta; SolidCraft nikad ne vidi vašu lozinku ni ključeve.", diff --git a/assets/locales/ca.json b/assets/locales/ca.json index b8fd7079508..791173aecb6 100644 --- a/assets/locales/ca.json +++ b/assets/locales/ca.json @@ -5289,7 +5289,6 @@ "ui.agent_chat_attach_selection_tip": "Envia amb el missatge el que estigui seleccionat al model (cares, arestes, operacions, cossos) perquè l'agent sàpiga a què us referiu", "ui.agent_chat_attach_view": "Adjuntar la vista", "ui.agent_chat_attach_view_tip": "Enviar una imatge de la vista actual amb el missatge", - "ui.agent_chat_attachable": "Imatges, PDF, text i fitxers CAD", "ui.agent_chat_auth_agent": "Iniciar sessió amb {name}", "ui.agent_chat_auth_env": "Definiu {vars} a l'entorn i reinicieu SolidCraft.", "ui.agent_chat_auth_needed": "L'agent us demana que inicieu sessió. L'inici de sessió es fa amb l'agent mateix; SolidCraft no veu mai la vostra contrasenya ni les vostres claus.", diff --git a/assets/locales/cs.json b/assets/locales/cs.json index 98b65efa59d..68f107ff800 100644 --- a/assets/locales/cs.json +++ b/assets/locales/cs.json @@ -4848,7 +4848,6 @@ "ui.agent_chat_attach_selection_tip": "Odešle se zprávou to, co je v modelu vybráno (plochy, hrany, prvky, tělesa), aby agent věděl, co máte na mysli", "ui.agent_chat_attach_view": "Přiložit pohled", "ui.agent_chat_attach_view_tip": "Odeslat se zprávou obrázek aktuálního pohledu", - "ui.agent_chat_attachable": "Obrázky, PDF, text a soubory CAD", "ui.agent_chat_auth_agent": "Přihlásit se přes {name}", "ui.agent_chat_auth_env": "Nastavte {vars} v proměnných prostředí a restartujte SolidCraft.", "ui.agent_chat_auth_needed": "Agent žádá o přihlášení. Přihlašujete se přímo u agenta; SolidCraft vaše heslo ani klíče nikdy nevidí.", diff --git a/assets/locales/da.json b/assets/locales/da.json index 97e8a57b27d..dbb9fa30212 100644 --- a/assets/locales/da.json +++ b/assets/locales/da.json @@ -4117,7 +4117,6 @@ "ui.agent_chat_attach_selection_tip": "Send det, der er markeret i modellen (flader, kanter, features, emner), sammen med beskeden, så agenten ved, hvad du mener", "ui.agent_chat_attach_view": "Vedhæft visning", "ui.agent_chat_attach_view_tip": "Send et billede af den aktuelle visning sammen med beskeden", - "ui.agent_chat_attachable": "Billeder, PDF-filer, tekst og CAD-filer", "ui.agent_chat_auth_agent": "Log ind med {name}", "ui.agent_chat_auth_env": "Indstil {vars} i dit miljø, og genstart SolidCraft.", "ui.agent_chat_auth_needed": "Agenten beder dig logge ind. Du logger ind hos agenten selv; SolidCraft ser aldrig din adgangskode eller dine nøgler.", diff --git a/assets/locales/de.json b/assets/locales/de.json index 994ad9bfeff..ca98b2d6fd9 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -5131,7 +5131,6 @@ "ui.agent_chat_attach_selection_tip": "Das im Modell Ausgewählte (Flächen, Kanten, Merkmale, Körper) mit der Nachricht senden, damit der Agent weiß, was Sie meinen", "ui.agent_chat_attach_view": "Ansicht anhängen", "ui.agent_chat_attach_view_tip": "Ein Bild der aktuellen Ansicht mit der Nachricht senden", - "ui.agent_chat_attachable": "Bilder, PDFs, Text- und CAD-Dateien", "ui.agent_chat_auth_agent": "Mit {name} anmelden", "ui.agent_chat_auth_env": "Setzen Sie {vars} in Ihrer Umgebung und starten Sie SolidCraft neu.", "ui.agent_chat_auth_needed": "Der Agent bittet Sie, sich anzumelden. Sie melden sich beim Agenten selbst an; SolidCraft sieht Ihr Passwort oder Ihre Schlüssel nie.", diff --git a/assets/locales/en.json b/assets/locales/en.json index 859aa6b9aa4..c752ef2d001 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -5513,7 +5513,6 @@ "ui.agent_chat_attach_selection_tip": "Send what is selected in the model (faces, edges, features, bodies) with the message, so the agent knows what you mean", "ui.agent_chat_attach_view": "Attach view", "ui.agent_chat_attach_view_tip": "Send a picture of the current view with the message", - "ui.agent_chat_attachable": "Pictures, PDFs, text and CAD files", "ui.agent_chat_auth_agent": "Sign in with {name}", "ui.agent_chat_auth_env": "Set {vars} in your environment and restart SolidCraft.", "ui.agent_chat_auth_needed": "The agent asks you to sign in. You sign in with the agent itself; SolidCraft never sees your password or keys.", diff --git a/assets/locales/es.json b/assets/locales/es.json index bf1ff08e68f..90d5800927f 100644 --- a/assets/locales/es.json +++ b/assets/locales/es.json @@ -5308,7 +5308,6 @@ "ui.agent_chat_attach_selection_tip": "Envía con el mensaje lo que esté seleccionado en el modelo (caras, aristas, operaciones, cuerpos) para que el agente sepa a qué te refieres", "ui.agent_chat_attach_view": "Adjuntar vista", "ui.agent_chat_attach_view_tip": "Enviar una imagen de la vista actual con el mensaje", - "ui.agent_chat_attachable": "Imágenes, PDF, texto y archivos CAD", "ui.agent_chat_auth_agent": "Iniciar sesión con {name}", "ui.agent_chat_auth_env": "Configura {vars} en las variables de entorno y reinicia SolidCraft.", "ui.agent_chat_auth_needed": "El agente te pide que inicies sesión. El inicio de sesión se realiza con el propio agente; SolidCraft nunca ve tu contraseña ni tus claves.", diff --git a/assets/locales/fi.json b/assets/locales/fi.json index b290f551434..d76e99a8c55 100644 --- a/assets/locales/fi.json +++ b/assets/locales/fi.json @@ -4871,7 +4871,6 @@ "ui.agent_chat_attach_selection_tip": "Lähetä mallista valitut kohteet (pinnat, särmät, piirteet, kappaleet) viestin mukana, jotta agentti tietää, mitä tarkoitat", "ui.agent_chat_attach_view": "Liitä näkymä", "ui.agent_chat_attach_view_tip": "Lähetä kuva nykyisestä näkymästä viestin mukana", - "ui.agent_chat_attachable": "Kuvat, PDF:t, teksti- ja CAD-tiedostot", "ui.agent_chat_auth_agent": "Kirjaudu palvelulla {name}", "ui.agent_chat_auth_env": "Aseta {vars} ympäristöösi ja käynnistä SolidCraft uudelleen.", "ui.agent_chat_auth_needed": "Agentti pyytää sinua kirjautumaan. Kirjaudut agentin itsensä kautta; SolidCraft ei koskaan näe salasanaasi tai avaimiasi.", diff --git a/assets/locales/fr.json b/assets/locales/fr.json index 496c69ff262..c7b67fc10f8 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -4445,7 +4445,6 @@ "ui.agent_chat_attach_selection_tip": "Envoyer ce qui est sélectionné dans le modèle (faces, arêtes, fonctions, corps) avec le message, pour que l'agent sache de quoi vous parlez", "ui.agent_chat_attach_view": "Joindre la vue", "ui.agent_chat_attach_view_tip": "Envoyer une image de la vue actuelle avec le message", - "ui.agent_chat_attachable": "Images, PDF, textes et fichiers de CAO", "ui.agent_chat_auth_agent": "S'authentifier avec {name}", "ui.agent_chat_auth_env": "Définir {vars} dans votre environnement, puis redémarrer SolidCraft.", "ui.agent_chat_auth_needed": "L'agent demande une authentification. Vous vous authentifiez auprès de l'agent lui-même ; SolidCraft ne voit jamais votre mot de passe ni vos clés.", diff --git a/assets/locales/gl.json b/assets/locales/gl.json index 2127ca0d704..e5fd3bae60c 100644 --- a/assets/locales/gl.json +++ b/assets/locales/gl.json @@ -4117,7 +4117,6 @@ "ui.agent_chat_attach_selection_tip": "Envía coa mensaxe o que está seleccionado no modelo (caras, arestas, operacións, corpos), para que o axente saiba a que te refires", "ui.agent_chat_attach_view": "Achegar a vista", "ui.agent_chat_attach_view_tip": "Envía unha imaxe da vista actual coa mensaxe", - "ui.agent_chat_attachable": "Imaxes, PDF, texto e ficheiros CAD", "ui.agent_chat_auth_agent": "Iniciar sesión con {name}", "ui.agent_chat_auth_env": "Define {vars} no teu contorno e reinicia SolidCraft.", "ui.agent_chat_auth_needed": "O axente pídeche que inicies sesión. Inicias sesión co propio axente; SolidCraft nunca ve o teu contrasinal nin as túas claves.", diff --git a/assets/locales/he.json b/assets/locales/he.json index 4d4c1caa8c3..3728cabeb72 100644 --- a/assets/locales/he.json +++ b/assets/locales/he.json @@ -5513,7 +5513,6 @@ "ui.agent_chat_attach_selection_tip": "שליחת מה שנבחר במודל (פאות, מקצועות, פיצ'רים, גופים) עם ההודעה, כדי שהסוכן יבין למה הכוונה", "ui.agent_chat_attach_view": "צירוף התצוגה", "ui.agent_chat_attach_view_tip": "שליחת תמונה של התצוגה הנוכחית עם ההודעה", - "ui.agent_chat_attachable": "תמונות, PDF, טקסט וקובצי CAD", "ui.agent_chat_auth_agent": "התחברות עם {name}", "ui.agent_chat_auth_env": "יש להגדיר את {vars} בסביבה ולהפעיל מחדש את SolidCraft.", "ui.agent_chat_auth_needed": "הסוכן מבקש להתחבר. ההתחברות נעשית מול הסוכן עצמו; SolidCraft לעולם אינו רואה את הסיסמה או המפתחות.", diff --git a/assets/locales/hr.json b/assets/locales/hr.json index da34ae5340c..5c57fcc529b 100644 --- a/assets/locales/hr.json +++ b/assets/locales/hr.json @@ -4116,7 +4116,6 @@ "ui.agent_chat_attach_selection_tip": "Pošalji s porukom ono što je odabrano u modelu (lica, bridove, značajke, tijela), kako bi agent znao na što mislite", "ui.agent_chat_attach_view": "Priloži prikaz", "ui.agent_chat_attach_view_tip": "Pošalji sliku trenutnog prikaza s porukom", - "ui.agent_chat_attachable": "Slike, PDF-ovi, tekst i CAD datoteke", "ui.agent_chat_auth_agent": "Prijavi se pomoću {name}", "ui.agent_chat_auth_env": "Postavite {vars} u svom okruženju i ponovno pokrenite SolidCraft.", "ui.agent_chat_auth_needed": "Agent traži da se prijavite. Prijavljujete se kod samog agenta; SolidCraft nikad ne vidi vašu lozinku ni ključeve.", diff --git a/assets/locales/hu.json b/assets/locales/hu.json index 5fff04e91cc..be69e1eb7b8 100644 --- a/assets/locales/hu.json +++ b/assets/locales/hu.json @@ -4117,7 +4117,6 @@ "ui.agent_chat_attach_selection_tip": "A modellben kijelölt elemeket (lapok, élek, elemek, testek) elküldi az üzenettel együtt, hogy az ügynök tudja, mire gondol", "ui.agent_chat_attach_view": "Nézet csatolása", "ui.agent_chat_attach_view_tip": "Az aktuális nézet képének küldése az üzenettel", - "ui.agent_chat_attachable": "Képek, PDF-ek, szöveg- és CAD-fájlok", "ui.agent_chat_auth_agent": "Bejelentkezés: {name}", "ui.agent_chat_auth_env": "Állítsa be a(z) {vars} változót a környezetében, és indítsa újra a SolidCraftot.", "ui.agent_chat_auth_needed": "Az ügynök bejelentkezést kér. Magával az ügynökkel jelentkezik be; a SolidCraft soha nem látja a jelszavát vagy kulcsait.", diff --git a/assets/locales/id.json b/assets/locales/id.json index ea60a5b4868..c66b8249648 100644 --- a/assets/locales/id.json +++ b/assets/locales/id.json @@ -4117,7 +4117,6 @@ "ui.agent_chat_attach_selection_tip": "Kirim apa yang dipilih di model (muka, tepi, fitur, bodi) bersama pesan, agar agen tahu maksud Anda", "ui.agent_chat_attach_view": "Lampirkan tampilan", "ui.agent_chat_attach_view_tip": "Kirim gambar tampilan saat ini bersama pesan", - "ui.agent_chat_attachable": "Gambar, PDF, teks, dan file CAD", "ui.agent_chat_auth_agent": "Masuk dengan {name}", "ui.agent_chat_auth_env": "Atur {vars} di environment Anda dan mulai ulang SolidCraft.", "ui.agent_chat_auth_needed": "Agen meminta Anda masuk. Anda masuk melalui agen itu sendiri; SolidCraft tidak pernah melihat kata sandi atau key Anda.", diff --git a/assets/locales/it.json b/assets/locales/it.json index dd22ace572a..33d57108265 100644 --- a/assets/locales/it.json +++ b/assets/locales/it.json @@ -4882,7 +4882,6 @@ "ui.agent_chat_attach_selection_tip": "Invia con il messaggio ciò che è selezionato nel modello (facce, spigoli, lavorazioni, corpi), così l'agente capisce a cosa ti riferisci", "ui.agent_chat_attach_view": "Allega vista", "ui.agent_chat_attach_view_tip": "Invia un'immagine della vista corrente insieme al messaggio", - "ui.agent_chat_attachable": "Immagini, PDF, testo e file CAD", "ui.agent_chat_auth_agent": "Accedi con {name}", "ui.agent_chat_auth_env": "Imposta {vars} nell'ambiente e riavvia SolidCraft.", "ui.agent_chat_auth_needed": "L'agente richiede l'accesso. L'accesso avviene tramite l'agente stesso; SolidCraft non vede mai password o chiavi.", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index e959fc10269..7b6079a8d76 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -5513,7 +5513,6 @@ "ui.agent_chat_attach_selection_tip": "モデルで選択中のもの(面、エッジ、フィーチャ、ボディ)をメッセージと一緒に送り、何を指しているかをエージェントに伝えます", "ui.agent_chat_attach_view": "ビューを添付", "ui.agent_chat_attach_view_tip": "現在のビューの画像をメッセージと一緒に送ります", - "ui.agent_chat_attachable": "画像・PDF・テキスト・CAD ファイル", "ui.agent_chat_auth_agent": "{name} でサインイン", "ui.agent_chat_auth_env": "環境変数 {vars} を設定して SolidCraft を再起動してください。", "ui.agent_chat_auth_needed": "エージェントがサインインを求めています。サインインはエージェント自身で行います。SolidCraft がパスワードやキーを見ることはありません。", diff --git a/assets/locales/ka.json b/assets/locales/ka.json index d458a25e15b..b3499229498 100644 --- a/assets/locales/ka.json +++ b/assets/locales/ka.json @@ -4225,7 +4225,6 @@ "ui.agent_chat_attach_selection_tip": "შეტყობინებასთან ერთად მოდელში მონიშნულის (წახნაგების, წიბოების, ოპერაციების, სხეულების) გაგზავნა, რომ აგენტმა იცოდეს, რას გულისხმობთ", "ui.agent_chat_attach_view": "ხედის მიმაგრება", "ui.agent_chat_attach_view_tip": "შეტყობინებასთან ერთად მიმდინარე ხედის სურათის გაგზავნა", - "ui.agent_chat_attachable": "სურათები, PDF-ები, ტექსტი და CAD ფაილები", "ui.agent_chat_auth_agent": "შესვლა {name}-ით", "ui.agent_chat_auth_env": "დააყენეთ {vars} თქვენს გარემოში და გადატვირთეთ SolidCraft.", "ui.agent_chat_auth_needed": "აგენტი გთხოვთ, შეხვიდეთ სისტემაში. შედიხართ თავად აგენტით; SolidCraft ვერასოდეს ხედავს თქვენს პაროლს ან გასაღებებს.", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index 6a8c8acac65..50e9829f2c0 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -4590,7 +4590,6 @@ "ui.agent_chat_attach_selection_tip": "모델에서 선택한 항목(면, 모서리, 피처, 바디)을 메시지와 함께 보내 에이전트가 무엇을 말하는지 알 수 있게 합니다", "ui.agent_chat_attach_view": "뷰 첨부", "ui.agent_chat_attach_view_tip": "현재 뷰의 이미지를 메시지와 함께 보냅니다", - "ui.agent_chat_attachable": "이미지, PDF, 텍스트 및 CAD 파일", "ui.agent_chat_auth_agent": "{name}(으)로 로그인", "ui.agent_chat_auth_env": "환경 변수 {vars}을(를) 설정하고 SolidCraft를 다시 시작하세요.", "ui.agent_chat_auth_needed": "에이전트가 로그인을 요청합니다. 로그인은 에이전트에서 직접 하며, SolidCraft는 비밀번호나 키를 보지 않습니다.", diff --git a/assets/locales/lv.json b/assets/locales/lv.json index 74ed5af8ddc..7faa9d90435 100644 --- a/assets/locales/lv.json +++ b/assets/locales/lv.json @@ -4924,7 +4924,6 @@ "ui.agent_chat_attach_selection_tip": "Nosūtīt kopā ar ziņu to, kas modelī atlasīts (skaldnes, šķautnes, operācijas, ķermeņus), lai aģents zinātu, ko jūs domājat", "ui.agent_chat_attach_view": "Pievienot skatu", "ui.agent_chat_attach_view_tip": "Nosūtīt kopā ar ziņu pašreizējā skata attēlu", - "ui.agent_chat_attachable": "Attēli, PDF, teksts un CAD faili", "ui.agent_chat_auth_agent": "Pierakstīties ar {name}", "ui.agent_chat_auth_env": "Iestatiet {vars} savā vidē un restartējiet SolidCraft.", "ui.agent_chat_auth_needed": "Aģents lūdz jums pierakstīties. Jūs pierakstāties pašā aģentā; SolidCraft nekad neredz jūsu paroli vai atslēgas.", diff --git a/assets/locales/ms.json b/assets/locales/ms.json index 4401a613a2f..cafee8651bc 100644 --- a/assets/locales/ms.json +++ b/assets/locales/ms.json @@ -4117,7 +4117,6 @@ "ui.agent_chat_attach_selection_tip": "Hantar apa yang dipilih dalam model (muka, tepi, ciri, jasad) bersama mesej, supaya ejen tahu apa yang anda maksudkan", "ui.agent_chat_attach_view": "Lampirkan paparan", "ui.agent_chat_attach_view_tip": "Hantar imej pandangan semasa bersama mesej", - "ui.agent_chat_attachable": "Gambar, PDF, teks dan fail CAD", "ui.agent_chat_auth_agent": "Log masuk dengan {name}", "ui.agent_chat_auth_env": "Tetapkan {vars} dalam persekitaran, kemudian mula semula SolidCraft.", "ui.agent_chat_auth_needed": "Ejen memerlukan anda log masuk melalui ejen itu sendiri. SolidCraft tidak dapat melihat kata laluan atau kunci anda.", diff --git a/assets/locales/nb.json b/assets/locales/nb.json index cc15128e562..35831b2ef9a 100644 --- a/assets/locales/nb.json +++ b/assets/locales/nb.json @@ -4116,7 +4116,6 @@ "ui.agent_chat_attach_selection_tip": "Send det som er valgt i modellen (flater, kanter, funksjoner, kropper) sammen med meldingen, så agenten vet hva du mener", "ui.agent_chat_attach_view": "Legg ved visning", "ui.agent_chat_attach_view_tip": "Send et bilde av gjeldende visning med meldingen", - "ui.agent_chat_attachable": "Bilder, PDF-er, tekst og CAD-filer", "ui.agent_chat_auth_agent": "Logg inn med {name}", "ui.agent_chat_auth_env": "Angi miljøvariablene {vars} og start SolidCraft på nytt.", "ui.agent_chat_auth_needed": "Agenten ber deg logge inn. Du logger inn med agenten selv; SolidCraft ser aldri passordet eller nøklene dine.", diff --git a/assets/locales/nl.json b/assets/locales/nl.json index 6f4882a7c47..ced17143493 100644 --- a/assets/locales/nl.json +++ b/assets/locales/nl.json @@ -4128,7 +4128,6 @@ "ui.agent_chat_attach_selection_tip": "Verstuur wat in het model is geselecteerd (vlakken, randen, kenmerken, lichamen) met het bericht mee, zodat de agent weet wat je bedoelt", "ui.agent_chat_attach_view": "Weergave bijvoegen", "ui.agent_chat_attach_view_tip": "Een afbeelding van de huidige weergave met het bericht meesturen", - "ui.agent_chat_attachable": "Afbeeldingen, pdf's, tekst en CAD-bestanden", "ui.agent_chat_auth_agent": "Aanmelden met {name}", "ui.agent_chat_auth_env": "Stel {vars} in uw omgeving in en start SolidCraft opnieuw.", "ui.agent_chat_auth_needed": "De agent vraagt u zich aan te melden. U meldt zich aan bij de agent zelf; SolidCraft ziet nooit uw wachtwoord of sleutels.", diff --git a/assets/locales/pending/agent-chat-files-by-place.json b/assets/locales/pending/agent-chat-files-by-place.json index 8d30eded793..a4d910efb90 100644 --- a/assets/locales/pending/agent-chat-files-by-place.json +++ b/assets/locales/pending/agent-chat-files-by-place.json @@ -1,82 +1,90 @@ { "en": { - "ui.agent_chat_add_folder": "Choose a folder…", - "ui.agent_chat_add_folder_tip": "The agent is told where the folder is, and reads the files it needs with its own tools", + "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_file_by_place_tip": "Not in the message: the agent is told where it is and reads it with its own tools", "ui.agent_chat_files_by_place": "Past {max} files, the rest go by their path: the agent reads them 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_reads_warning": "Sending a file or folder by path turns on Claude Code's read tools for this chat: it reads what you send without asking, and asks before reading anything else." + "ui.agent_chat_reads_warning": "Sending a file or folder by path turns on Claude Code's read tools for this chat: it reads what you send without asking, and asks before reading anything else.", + "ui.agent_chat_add_any": "Choose files or folders…" }, "ar": { - "ui.agent_chat_add_folder": "اختر مجلدًا…", - "ui.agent_chat_add_folder_tip": "يُخبَر الوكيل بمكان المجلد، ويقرأ الملفات التي يحتاجها بأدواته الخاصة", + "ui.agent_chat_add_folder": "اختر مجلدات…", + "ui.agent_chat_add_folder_tip": "يُرسل المجلد إلى الوكيل بمساره: يقرأ الوكيل الملفات التي يحتاجها بأدواته الخاصة", "ui.agent_chat_file_by_place_tip": "ليس ضمن الرسالة: يُخبَر الوكيل بمكانه ويقرؤه بأدواته الخاصة", "ui.agent_chat_files_by_place": "بعد {max} ملفات، تُرسل البقية بمساراتها: يقرؤها الوكيل بأدواته الخاصة", "ui.agent_chat_folder_tip": "مجلد: يُخبَر الوكيل بمكانه، ويقرأ الملفات التي يحتاجها بأدواته الخاصة", "ui.agent_chat_paste_past_max": "يُرسل {max} ملفات كحد أقصى في رسالة واحدة؛ احفظ الصورة في ملف وأرفقه بدلًا منها", "ui.ai_auto_attached": "يقرأ شيئًا أرفقته", - "ui.agent_chat_reads_warning": "إرسال ملف أو مجلد بمساره يشغّل أدوات القراءة في Claude Code لهذه المحادثة: يقرأ ما ترسله دون سؤال، ويسأل قبل قراءة أي شيء آخر." + "ui.agent_chat_reads_warning": "إرسال ملف أو مجلد بمساره يشغّل أدوات القراءة في Claude Code لهذه المحادثة: يقرأ ما ترسله دون سؤال، ويسأل قبل قراءة أي شيء آخر.", + "ui.agent_chat_add_any": "اختر ملفات أو مجلدات…" }, "de": { "ui.agent_chat_add_folder": "Ordner auswählen…", - "ui.agent_chat_add_folder_tip": "Der Agent erfährt, wo der Ordner liegt, und liest die benötigten Dateien mit seinen eigenen Werkzeugen", + "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_file_by_place_tip": "Nicht in der Nachricht: Der Agent erfährt, wo die Datei liegt, und liest sie mit seinen eigenen Werkzeugen", "ui.agent_chat_files_by_place": "Ab {max} Dateien gehen die übrigen über ihren Pfad: Der Agent liest sie 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_reads_warning": "Wenn Sie eine Datei oder einen Ordner über den Pfad senden, schaltet das die Lesewerkzeuge von Claude Code für diesen Chat ein: Es liest, was Sie senden, ohne Rückfrage, und fragt, bevor es etwas anderes liest." + "ui.agent_chat_reads_warning": "Wenn Sie eine Datei oder einen Ordner über den Pfad senden, schaltet das die Lesewerkzeuge von Claude Code für diesen Chat ein: Es liest, was Sie senden, ohne Rückfrage, und fragt, bevor es etwas anderes liest.", + "ui.agent_chat_add_any": "Dateien oder Ordner auswählen…" }, "he": { - "ui.agent_chat_add_folder": "בחירת תיקייה…", - "ui.agent_chat_add_folder_tip": "הסוכן מקבל את מיקום התיקייה, וקורא את הקבצים שהוא צריך בכלים שלו", + "ui.agent_chat_add_folder": "בחירת תיקיות…", + "ui.agent_chat_add_folder_tip": "תיקייה נשלחת לסוכן לפי הנתיב שלה: הסוכן קורא את הקבצים שהוא צריך בכלים שלו", "ui.agent_chat_file_by_place_tip": "לא בתוך ההודעה: הסוכן מקבל את מיקום הקובץ וקורא אותו בכלים שלו", "ui.agent_chat_files_by_place": "מעבר ל־{max} קבצים, השאר נשלחים לפי הנתיב שלהם: הסוכן קורא אותם בכלים שלו", "ui.agent_chat_folder_tip": "תיקייה: הסוכן מקבל את מיקומה, וקורא את הקבצים שהוא צריך בכלים שלו", "ui.agent_chat_paste_past_max": "לכל היותר {max} קבצים בהודעה אחת; יש לשמור את התמונה כקובץ ולצרף אותו במקומה", "ui.ai_auto_attached": "הוא קורא משהו שצירפת", - "ui.agent_chat_reads_warning": "שליחת קובץ או תיקייה לפי נתיב מפעילה את כלי הקריאה של Claude Code בצ׳אט הזה: הוא קורא את מה ששלחת בלי לשאול, ושואל לפני שהוא קורא כל דבר אחר." + "ui.agent_chat_reads_warning": "שליחת קובץ או תיקייה לפי נתיב מפעילה את כלי הקריאה של Claude Code בצ׳אט הזה: הוא קורא את מה ששלחת בלי לשאול, ושואל לפני שהוא קורא כל דבר אחר.", + "ui.agent_chat_add_any": "בחירת קבצים או תיקיות…" }, "ja": { "ui.agent_chat_add_folder": "フォルダーを選択…", - "ui.agent_chat_add_folder_tip": "フォルダーの場所がエージェントに伝えられ、必要なファイルはエージェントが自分のツールで読み込みます", + "ui.agent_chat_add_folder_tip": "フォルダーはパスとしてエージェントに渡されます。必要なファイルはエージェントが自分のツールで読み込みます", "ui.agent_chat_file_by_place_tip": "メッセージには含まれません。場所がエージェントに伝えられ、エージェントが自分のツールで読み込みます", "ui.agent_chat_files_by_place": "{max} 個を超えたファイルはパスで渡されます。エージェントが自分のツールで読み込みます", "ui.agent_chat_folder_tip": "フォルダー: 場所がエージェントに伝えられ、必要なファイルはエージェントが自分のツールで読み込みます", "ui.agent_chat_paste_past_max": "1 つのメッセージで送れるファイルは {max} 個までです。画像をファイルとして保存し、そのファイルを添付してください", "ui.ai_auto_attached": "添付したものを読み込むため", - "ui.agent_chat_reads_warning": "パスでファイルやフォルダーを送ると、このチャットで Claude Code の読み取りツールがオンになります。送ったものは確認なしで読み込み、それ以外を読む前には確認します。" + "ui.agent_chat_reads_warning": "パスでファイルやフォルダーを送ると、このチャットで Claude Code の読み取りツールがオンになります。送ったものは確認なしで読み込み、それ以外を読む前には確認します。", + "ui.agent_chat_add_any": "ファイルまたはフォルダーを選択…" }, "ko": { "ui.agent_chat_add_folder": "폴더 선택…", - "ui.agent_chat_add_folder_tip": "폴더의 위치가 에이전트에게 전달되고, 에이전트가 필요한 파일을 자체 도구로 읽습니다", + "ui.agent_chat_add_folder_tip": "폴더는 경로로 에이전트에게 전달됩니다. 에이전트가 필요한 파일을 자체 도구로 읽습니다", "ui.agent_chat_file_by_place_tip": "메시지에 포함되지 않음: 에이전트에게 위치가 전달되고 에이전트가 자체 도구로 읽습니다", "ui.agent_chat_files_by_place": "{max}개를 넘는 파일은 경로로 전달됩니다. 에이전트가 자체 도구로 읽습니다", "ui.agent_chat_folder_tip": "폴더: 위치가 에이전트에게 전달되고, 에이전트가 필요한 파일을 자체 도구로 읽습니다", "ui.agent_chat_paste_past_max": "메시지 하나에는 파일을 최대 {max}개까지 보낼 수 있습니다. 그림을 파일로 저장한 뒤 그 파일을 첨부하세요", "ui.ai_auto_attached": "첨부한 항목을 읽음", - "ui.agent_chat_reads_warning": "경로로 파일이나 폴더를 보내면 이 채팅에서 Claude Code의 읽기 도구가 켜집니다. 보낸 항목은 묻지 않고 읽고, 그 밖의 항목을 읽기 전에는 묻습니다." + "ui.agent_chat_reads_warning": "경로로 파일이나 폴더를 보내면 이 채팅에서 Claude Code의 읽기 도구가 켜집니다. 보낸 항목은 묻지 않고 읽고, 그 밖의 항목을 읽기 전에는 묻습니다.", + "ui.agent_chat_add_any": "파일 또는 폴더 선택…" }, "vi": { - "ui.agent_chat_add_folder": "Chọn một thư mục…", - "ui.agent_chat_add_folder_tip": "AI Agent được cho biết thư mục 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_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_file_by_place_tip": "Không nằm trong tin nhắn: AI Agent được cho biết vị trí của tệp và đọc nó bằng công cụ của mình", "ui.agent_chat_files_by_place": "Quá {max} tệp, các tệp còn lại được gửi theo đường dẫn: AI Agent đọc chúng 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_reads_warning": "Gửi một tệp hoặc thư mục theo đường dẫn sẽ bật các công cụ đọc của Claude Code cho cuộc trò chuyện này: nó đọc những gì bạn gửi mà không hỏi, và hỏi trước khi đọc bất cứ thứ gì khác." + "ui.agent_chat_reads_warning": "Gửi một tệp hoặc thư mục theo đường dẫn sẽ bật các công cụ đọc của Claude Code cho cuộc trò chuyện này: nó đọc những gì bạn gửi mà không hỏi, và hỏi trước khi đọc bất cứ thứ gì khác.", + "ui.agent_chat_add_any": "Chọn tệp hoặc thư mục…" }, "zh": { "ui.agent_chat_add_folder": "选择文件夹…", - "ui.agent_chat_add_folder_tip": "智能体会得知文件夹的位置,并用自己的工具读取所需的文件", + "ui.agent_chat_add_folder_tip": "文件夹以路径形式交给智能体:智能体用自己的工具读取所需的文件", "ui.agent_chat_file_by_place_tip": "不在消息中:智能体会得知它的位置,并用自己的工具读取", "ui.agent_chat_files_by_place": "超过 {max} 个文件后,其余文件按路径提供:智能体用自己的工具读取", "ui.agent_chat_folder_tip": "文件夹:智能体会得知它的位置,并用自己的工具读取所需的文件", "ui.agent_chat_paste_past_max": "一条消息最多发送 {max} 个文件;请把图片另存为文件,再附加该文件", "ui.ai_auto_attached": "它读取的是你附加的内容", - "ui.agent_chat_reads_warning": "按路径发送文件或文件夹会为本次聊天开启 Claude Code 的读取工具:它会直接读取你发送的内容,读取其他任何内容前都会先询问。" + "ui.agent_chat_reads_warning": "按路径发送文件或文件夹会为本次聊天开启 Claude Code 的读取工具:它会直接读取你发送的内容,读取其他任何内容前都会先询问。", + "ui.agent_chat_add_any": "选择文件或文件夹…" } } diff --git a/assets/locales/pl.json b/assets/locales/pl.json index 4cf6cd327df..7d380db7d3e 100644 --- a/assets/locales/pl.json +++ b/assets/locales/pl.json @@ -5410,7 +5410,6 @@ "ui.agent_chat_attach_selection_tip": "Wyślij z wiadomością to, co zaznaczono w modelu (ściany, krawędzie, operacje, bryły), aby agent wiedział, o co chodzi", "ui.agent_chat_attach_view": "Dołącz widok", "ui.agent_chat_attach_view_tip": "Wyślij z wiadomością obraz bieżącego widoku", - "ui.agent_chat_attachable": "Obrazy, pliki PDF, tekstowe i CAD", "ui.agent_chat_auth_agent": "Zaloguj się przez {name}", "ui.agent_chat_auth_env": "Ustaw {vars} w swoim środowisku i uruchom ponownie SolidCraft.", "ui.agent_chat_auth_needed": "Agent prosi o zalogowanie. Logujesz się w samym agencie; SolidCraft nigdy nie widzi twojego hasła ani kluczy.", diff --git a/assets/locales/pt-BR.json b/assets/locales/pt-BR.json index 38b48d32dba..49b3e32248d 100644 --- a/assets/locales/pt-BR.json +++ b/assets/locales/pt-BR.json @@ -4936,7 +4936,6 @@ "ui.agent_chat_attach_selection_tip": "Enviar o que está selecionado no modelo (faces, arestas, recursos, corpos) com a mensagem, para que o agente saiba do que você está falando", "ui.agent_chat_attach_view": "Anexar vista", "ui.agent_chat_attach_view_tip": "Enviar uma imagem da vista atual com a mensagem", - "ui.agent_chat_attachable": "Imagens, PDFs, texto e arquivos CAD", "ui.agent_chat_auth_agent": "Entrar com {name}", "ui.agent_chat_auth_env": "Defina {vars} no seu ambiente e reinicie o SolidCraft.", "ui.agent_chat_auth_needed": "O agente pede que você entre. Você entra no próprio agente; o SolidCraft nunca vê sua senha ou chaves.", diff --git a/assets/locales/ro.json b/assets/locales/ro.json index 2d3ab80205b..944b29a8f20 100644 --- a/assets/locales/ro.json +++ b/assets/locales/ro.json @@ -4117,7 +4117,6 @@ "ui.agent_chat_attach_selection_tip": "Trimite împreună cu mesajul ce este selectat în model (fețe, muchii, operații, corpuri), astfel încât agentul să știe la ce vă referiți", "ui.agent_chat_attach_view": "Atașează vizualizarea", "ui.agent_chat_attach_view_tip": "Trimite o imagine a vizualizării curente împreună cu mesajul", - "ui.agent_chat_attachable": "Imagini, PDF-uri, text și fișiere CAD", "ui.agent_chat_auth_agent": "Autentificare cu {name}", "ui.agent_chat_auth_env": "Setați {vars} în mediul dumneavoastră și reporniți SolidCraft.", "ui.agent_chat_auth_needed": "Agentul vă cere să vă autentificați. Vă autentificați chiar în agent; SolidCraft nu vă vede niciodată parola sau cheile.", diff --git a/assets/locales/ru.json b/assets/locales/ru.json index e0e9434d905..3641fb37ffa 100644 --- a/assets/locales/ru.json +++ b/assets/locales/ru.json @@ -4073,7 +4073,6 @@ "ui.agent_chat_attach_selection_tip": "Отправить с сообщением выделенное в модели (грани, рёбра, операции, тела), чтобы агент понимал, что вы имеете в виду", "ui.agent_chat_attach_view": "Прикрепить вид", "ui.agent_chat_attach_view_tip": "Отправить с сообщением изображение текущего вида", - "ui.agent_chat_attachable": "Изображения, PDF, текст и файлы CAD", "ui.agent_chat_auth_agent": "Войти через {name}", "ui.agent_chat_auth_env": "Задайте {vars} в окружении и перезапустите SolidCraft.", "ui.agent_chat_auth_needed": "Агент просит войти в систему. Вход выполняется через самого агента; SolidCraft никогда не видит ваш пароль или ключи.", diff --git a/assets/locales/sr.json b/assets/locales/sr.json index 36d76c4dbb3..0fd03c91c47 100644 --- a/assets/locales/sr.json +++ b/assets/locales/sr.json @@ -4114,7 +4114,6 @@ "ui.agent_chat_attach_selection_tip": "Пошаљи са поруком оно што је изабрано у моделу (лица, ивице, операције, тела), да агент зна на шта мислите", "ui.agent_chat_attach_view": "Приложи приказ", "ui.agent_chat_attach_view_tip": "Пошаљи слику тренутног приказа са поруком", - "ui.agent_chat_attachable": "Слике, ПДФ-ови, текст и CAD датотеке", "ui.agent_chat_auth_agent": "Пријави се помоћу {name}", "ui.agent_chat_auth_env": "Подесите {vars} у свом окружењу и поново покрените SolidCraft.", "ui.agent_chat_auth_needed": "Агент тражи да се пријавите. Пријављујете се код самог агента; SolidCraft никад не види вашу лозинку ни кључеве.", diff --git a/assets/locales/sv.json b/assets/locales/sv.json index 5eb0762f24e..8e6c5a2e912 100644 --- a/assets/locales/sv.json +++ b/assets/locales/sv.json @@ -4118,7 +4118,6 @@ "ui.agent_chat_attach_selection_tip": "Skicka det som är markerat i modellen (ytor, kanter, funktioner, kroppar) med meddelandet, så att agenten vet vad du menar", "ui.agent_chat_attach_view": "Bifoga vy", "ui.agent_chat_attach_view_tip": "Skicka en bild av den aktuella vyn med meddelandet", - "ui.agent_chat_attachable": "Bilder, PDF-filer, text och CAD-filer", "ui.agent_chat_auth_agent": "Logga in med {name}", "ui.agent_chat_auth_env": "Ange {vars} i din miljö och starta om SolidCraft.", "ui.agent_chat_auth_needed": "Agenten ber dig logga in. Du loggar in hos agenten själv; SolidCraft ser aldrig ditt lösenord eller dina nycklar.", diff --git a/assets/locales/tr.json b/assets/locales/tr.json index 57cf55620d5..030bcdb6354 100644 --- a/assets/locales/tr.json +++ b/assets/locales/tr.json @@ -4117,7 +4117,6 @@ "ui.agent_chat_attach_selection_tip": "Modelde seçili olanı (yüzler, kenarlar, özellikler, gövdeler) mesajla birlikte gönderin; ajan ne kastettiğinizi bilsin", "ui.agent_chat_attach_view": "Görünümü ekle", "ui.agent_chat_attach_view_tip": "Geçerli görünümün bir resmini mesajla birlikte gönder", - "ui.agent_chat_attachable": "Görseller, PDF'ler, metin ve CAD dosyaları", "ui.agent_chat_auth_agent": "{name} ile oturum aç", "ui.agent_chat_auth_env": "{vars} ortam değişkenlerini ayarlayın ve SolidCraft'ı yeniden başlatın.", "ui.agent_chat_auth_needed": "Ajan oturum açmanızı istiyor. Oturumu ajanın kendisinde açarsınız; SolidCraft parolanızı veya anahtarlarınızı asla görmez.", diff --git a/assets/locales/uk.json b/assets/locales/uk.json index 0c9a0a945f7..e085fed2558 100644 --- a/assets/locales/uk.json +++ b/assets/locales/uk.json @@ -5294,7 +5294,6 @@ "ui.agent_chat_attach_selection_tip": "Надіслати разом із повідомленням, що виділено в моделі (грані, ребра, операції, тіла), щоб агент розумів, що ви маєте на увазі", "ui.agent_chat_attach_view": "Прикріпити вид", "ui.agent_chat_attach_view_tip": "Надіслати знімок поточного виду разом із повідомленням", - "ui.agent_chat_attachable": "Зображення, текст і CAD-файли", "ui.agent_chat_auth_agent": "Увійти через {name}", "ui.agent_chat_auth_env": "Задайте {vars} у своєму середовищі та перезапустіть SolidCraft.", "ui.agent_chat_auth_needed": "Агент просить вас увійти. Ви входите через сам агент; SolidCraft ніколи не бачить вашого пароля чи ключів.", diff --git a/assets/locales/vi.json b/assets/locales/vi.json index bff3d029cd8..3ab576d973f 100644 --- a/assets/locales/vi.json +++ b/assets/locales/vi.json @@ -5513,7 +5513,6 @@ "ui.agent_chat_attach_selection_tip": "Gửi các đối tượng đang chọn trong mô hình (mặt, cạnh, tính năng, khối) kèm tin nhắn để trợ lý hiểu rõ đối tượng bạn muốn xử lý", "ui.agent_chat_attach_view": "Đính kèm góc nhìn", "ui.agent_chat_attach_view_tip": "Gửi kèm hình ảnh góc nhìn hiện tại trong tin nhắn", - "ui.agent_chat_attachable": "Hình ảnh, PDF, văn bản và tệp CAD", "ui.agent_chat_auth_agent": "Đăng nhập với {name}", "ui.agent_chat_auth_env": "Thiết lập {vars} trong biến môi trường của bạn rồi khởi động lại SolidCraft.", "ui.agent_chat_auth_needed": "AI Agent yêu cầu bạn đăng nhập. Bạn đăng nhập trực tiếp với dịch vụ của AI; SolidCraft không bao giờ thấy mật khẩu hay khóa API của bạn.", diff --git a/assets/locales/zh-TW.json b/assets/locales/zh-TW.json index b73738f05da..d05c3504046 100644 --- a/assets/locales/zh-TW.json +++ b/assets/locales/zh-TW.json @@ -4942,7 +4942,6 @@ "ui.agent_chat_attach_selection_tip": "隨消息發送模型中目前選中的內容(面、邊、特徵、實體),讓智能體知道你指的是什麼", "ui.agent_chat_attach_view": "附加視圖", "ui.agent_chat_attach_view_tip": "隨消息發送目前視圖的圖片", - "ui.agent_chat_attachable": "圖片、PDF、文本和 CAD 檔案", "ui.agent_chat_auth_agent": "使用 {name} 登錄", "ui.agent_chat_auth_env": "請在環境中設置 {vars},然後重啟 SolidCraft。", "ui.agent_chat_auth_needed": "智能體要求你登錄。登錄在智能體本身完成;SolidCraft 從不接觸你的密碼或密鑰。", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index ca4d8d391f9..e1bb05517e4 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -5513,7 +5513,6 @@ "ui.agent_chat_attach_selection_tip": "随消息发送模型中当前选中的内容(面、边、特征、实体),让智能体知道你指的是什么", "ui.agent_chat_attach_view": "附加视图", "ui.agent_chat_attach_view_tip": "随消息发送当前视图的图片", - "ui.agent_chat_attachable": "图片、PDF、文本和 CAD 文件", "ui.agent_chat_auth_agent": "使用 {name} 登录", "ui.agent_chat_auth_env": "请在环境中设置 {vars},然后重启 SolidCraft。", "ui.agent_chat_auth_needed": "智能体要求你登录。登录在智能体本身完成;SolidCraft 从不接触你的密码或密钥。", diff --git a/crates/ui-egui/src/agent_chat/attach.rs b/crates/ui-egui/src/agent_chat/attach.rs index 38c233846a6..cf39214f54a 100644 --- a/crates/ui-egui/src/agent_chat/attach.rs +++ b/crates/ui-egui/src/agent_chat/attach.rs @@ -56,15 +56,6 @@ const THUMB: u32 = 64; const PICTURE_EXTS: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "bmp", "tif", "tiff"]; /// Text sent in full; SVG goes as its source, which the agents read well. const TEXT_EXTS: &[&str] = &["svg", "txt", "md", "markdown", "json", "csv", "tsv", "yaml", "yml", "toml", "xml", "log", "ini", "cfg"]; -/// CAD files and meshes, imported into the design (the file picker's list; [`kind`] asks the -/// importers themselves). -const CAD_EXTS: &[&str] = &["step", "stp", "igs", "iges", "FCStd", "3dm", "stl", "3mf", "obj", "glb", "gltf"]; - -/// Every extension the file picker lists first, pictures first (any other file can be chosen too). -pub fn extensions() -> Vec<&'static str> { - PICTURE_EXTS.iter().chain(TEXT_EXTS).chain(CAD_EXTS).chain(&["pdf"]).copied().collect() -} - /// What a file is, by its extension. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Kind { @@ -799,9 +790,6 @@ mod tests { let heic = d.join("photo.HEIC"); std::fs::write(&heic, b"....ftypheic").unwrap(); assert!(read(&heic).unwrap_err().contains("HEIC")); - for ext in ["png", "jpg", "jpeg", "gif", "webp", "bmp", "tiff", "svg", "md", "txt", "step", "FCStd", "3dm", "stl", "3mf", "obj", "glb"] { - assert!(extensions().contains(&ext), "{ext} can be chosen"); - } let _ = std::fs::remove_dir_all(&d); } diff --git a/crates/ui-egui/src/agent_chat/panel.rs b/crates/ui-egui/src/agent_chat/panel.rs index 0051f8b2d2f..e37b0c183a4 100644 --- a/crates/ui-egui/src/agent_chat/panel.rs +++ b/crates/ui-egui/src/agent_chat/panel.rs @@ -71,10 +71,12 @@ pub enum PanelAction { at: Option, }, AttachDropped(Vec), - /// Choose files to attach, one or several. + /// Choose files of any type to attach, one or several. ChooseAttachment, - /// Choose a folder to attach: the agent is told where it is and what it holds. + /// Choose folders to attach, one or several: the agent is told where each is. ChooseFolder, + /// Choose files and folders in one dialog, 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, @@ -130,10 +132,9 @@ 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_paths(app, paths.into_iter()), - PanelAction::ChooseAttachment => app.pick_files(tr("ui.agent_chat_attachable"), &attach::extensions(), |app, paths| { - attach_paths(app, paths.into_iter().map(std::path::PathBuf::from)); - }), - PanelAction::ChooseFolder => app.pick_folder(|app, path| attach_paths(app, path.into_iter().map(std::path::PathBuf::from))), + PanelAction::ChooseAttachment => app.pick_files(|app, paths| attach_paths(app, paths.into_iter().map(std::path::PathBuf::from))), + PanelAction::ChooseFolder => app.pick_folders(|app, paths| attach_paths(app, paths.into_iter().map(std::path::PathBuf::from))), + PanelAction::ChooseAny => app.pick_files_or_folders(|app, paths| attach_paths(app, paths.into_iter().map(std::path::PathBuf::from))), #[cfg(not(target_arch = "wasm32"))] PanelAction::PastePicture => { if let Err(e) = paste_picture(app) { @@ -223,6 +224,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 one + /// Choose files or folders… instead of Choose files… and Choose folders…. + pub mixed_picker: bool, } impl PanelView { @@ -252,6 +256,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(), } } } @@ -1189,7 +1194,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.mixed_picker, ui); let mode = view.permission; let permissions = ui .allocate_ui(vec2(Tokens::get().space_24 * 4.0, Tokens::get().control_height), |ui| { @@ -2751,42 +2756,37 @@ fn chip(ui: &mut egui::Ui, thumbs: &mut std::collections::HashMap::new())); - let seen = asked.clone(); - h.app.services.pick_file = Some(Box::new(move |_label: &str, exts: &[&str]| { - *seen.borrow_mut() = exts.iter().map(|e| e.to_string()).collect(); + h.app.services.pick_files = Some(Box::new(move || { let p = chosen.clone(); - Box::pin(async move { Some(p) }) + Box::pin(async move { vec![p] }) })); + h.app.services.pick_file = Some(Box::new(|_: &str, _: &[&str]| panic!("the filtered one-file dialog is not the chat's"))); 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"); h.call("ui.click", json!({"x": choose.x, "y": choose.y})); h.frames(4); assert_eq!(status(&h.app)["attachments"], json!(["brief.md"])); - let exts = asked.borrow().clone(); - for ext in ["png", "jpg", "gif", "webp", "svg", "md", "step", "stl"] { - assert!(exts.iter().any(|e| e == ext), "{ext} in {exts:?}"); - } - assert!(!exts.iter().any(|e| e == "solidcraft")); attach_rgba(&mut h.app, 4, 3, &[200; 48]).unwrap(); attach_rgba(&mut h.app, 4, 3, &[200; 47]).unwrap(); settle_chat(&mut h); diff --git a/crates/ui-egui/src/file_picker.rs b/crates/ui-egui/src/file_picker.rs index e81f9753005..d53d833503c 100644 --- a/crates/ui-egui/src/file_picker.rs +++ b/crates/ui-egui/src/file_picker.rs @@ -84,19 +84,51 @@ impl SolveApp { self.begin_picker(future, Box::new(complete)); } - /// Ask for files of a kind, several at once (the agent chat's files): the host's dialog for + /// Ask for files of any type, several at once (the agent chat's files): 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) { + pub(crate) fn pick_files(&mut self, 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); + let future = pick(); self.begin_file_task(future, complete); } - None => self.pick_file(label, extensions, move |app, path| complete(app, path.into_iter().collect())), + None => self.pick_file("", &[], 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()), } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 2f9efb89b2e..4bbba3e4b7a 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -511,9 +511,16 @@ 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>>, - /// The same dialog, allowing several files at once (the agent chat's files). `None`: one - /// file, with `pick_file`. - pub pick_files: Option FilesPickerFuture>>, + /// Open a dialog for several files of any type at once (the agent chat's files: whatever it + /// can't read goes to the agent by path, so nothing is filtered out). `None`: one file, with + /// `pick_file`. + pub pick_files: Option FilesPickerFuture>>, + /// Open a dialog for several folders at once (the agent chat's files). `None`: one, with + /// `pick_folder`. + pub pick_folders: 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 program (a slicer); `None` when the host has no such dialog. pub pick_program: Option FilePickerFuture>>, /// Open a dialog for a folder: the local document library root, or a folder the agent chat diff --git a/docs/agent-chat.md b/docs/agent-chat.md index 6f16b101e40..c85834f247d 100644 --- a/docs/agent-chat.md +++ b/docs/agent-chat.md @@ -129,8 +129,11 @@ A message carries the contents of up to eight files, to show the agent what you picture, a sketch, a brief, a part to fit around. More files, and folders, go by their path (below), up to 200 on one message. -- **+** next to **Send** has **Choose files…** (a file dialog for the types below; pick several at - once), **Choose a folder…** and **Paste a picture** (the picture on the clipboard). +- **+** next to **Send** has **Paste a picture** (the picture on the clipboard) and a way to choose + files and folders, several at once and of any type. On macOS it is one item, **Choose files or + folders…**. Windows' and Linux's file dialogs choose files or folders but not both, so there it + is **Choose files…** and **Choose folders…**. What happens to each file depends on its type + (below). - **Drop files or folders on the chat.** What is dropped on the panel (or its folded strip) attaches to the next message, and the app doesn't open it 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 From 3c5e8fa9a905559b5f5fca60c1afb9dfcba16f83 Mon Sep 17 00:00:00 2001 From: Seth LaForge Date: Tue, 17 Nov 2026 13:41:22 -0800 Subject: [PATCH 06/12] Assistant: turning Claude Code's read tools on no longer loses a first message (#16452) When the first message that sends a file or folder by path went to a Claude Code session that had had no message yet, the chat resumed that session with read tools on. Claude Code keeps no conversation until the first message, so it answered "Resource not found"; the chat marked the agent failed and the message never reached it. A session that has had no message is now opened fresh with the read tools on (it has nothing to keep). A session that has is resumed as before, and if the resume fails, a fresh session with them follows, the chat says the earlier conversation couldn't be carried over, and the message still goes. Co-Authored-By: Claude Opus 5.5 --- .../pending/agent-chat-files-by-place.json | 24 +++++--- crates/ui-egui/src/agent_chat/acp_client.rs | 60 ++++++++++++++++--- crates/ui-egui/src/agent_chat/backend.rs | 2 + crates/ui-egui/src/agent_chat/mod.rs | 1 + 4 files changed, 70 insertions(+), 17 deletions(-) diff --git a/assets/locales/pending/agent-chat-files-by-place.json b/assets/locales/pending/agent-chat-files-by-place.json index a4d910efb90..b5192e56341 100644 --- a/assets/locales/pending/agent-chat-files-by-place.json +++ b/assets/locales/pending/agent-chat-files-by-place.json @@ -8,7 +8,8 @@ "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_reads_warning": "Sending a file or folder by path turns on Claude Code's read tools for this chat: it reads what you send without asking, and asks before reading anything else.", - "ui.agent_chat_add_any": "Choose files or folders…" + "ui.agent_chat_add_any": "Choose files or folders…", + "ui.agent_chat_reads_fresh_session": "Claude Code couldn't carry the earlier conversation over when its read tools came on, so it starts again from this message." }, "ar": { "ui.agent_chat_add_folder": "اختر مجلدات…", @@ -19,7 +20,8 @@ "ui.agent_chat_paste_past_max": "يُرسل {max} ملفات كحد أقصى في رسالة واحدة؛ احفظ الصورة في ملف وأرفقه بدلًا منها", "ui.ai_auto_attached": "يقرأ شيئًا أرفقته", "ui.agent_chat_reads_warning": "إرسال ملف أو مجلد بمساره يشغّل أدوات القراءة في Claude Code لهذه المحادثة: يقرأ ما ترسله دون سؤال، ويسأل قبل قراءة أي شيء آخر.", - "ui.agent_chat_add_any": "اختر ملفات أو مجلدات…" + "ui.agent_chat_add_any": "اختر ملفات أو مجلدات…", + "ui.agent_chat_reads_fresh_session": "تعذّر على Claude Code نقل المحادثة السابقة عند تشغيل أدوات القراءة، لذا يبدأ من جديد من هذه الرسالة." }, "de": { "ui.agent_chat_add_folder": "Ordner auswählen…", @@ -30,7 +32,8 @@ "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_reads_warning": "Wenn Sie eine Datei oder einen Ordner über den Pfad senden, schaltet das die Lesewerkzeuge von Claude Code für diesen Chat ein: Es liest, was Sie senden, ohne Rückfrage, und fragt, bevor es etwas anderes liest.", - "ui.agent_chat_add_any": "Dateien oder Ordner auswählen…" + "ui.agent_chat_add_any": "Dateien oder Ordner auswählen…", + "ui.agent_chat_reads_fresh_session": "Claude Code konnte das bisherige Gespräch beim Einschalten seiner Lesewerkzeuge nicht übernehmen und beginnt deshalb neu mit dieser Nachricht." }, "he": { "ui.agent_chat_add_folder": "בחירת תיקיות…", @@ -41,7 +44,8 @@ "ui.agent_chat_paste_past_max": "לכל היותר {max} קבצים בהודעה אחת; יש לשמור את התמונה כקובץ ולצרף אותו במקומה", "ui.ai_auto_attached": "הוא קורא משהו שצירפת", "ui.agent_chat_reads_warning": "שליחת קובץ או תיקייה לפי נתיב מפעילה את כלי הקריאה של Claude Code בצ׳אט הזה: הוא קורא את מה ששלחת בלי לשאול, ושואל לפני שהוא קורא כל דבר אחר.", - "ui.agent_chat_add_any": "בחירת קבצים או תיקיות…" + "ui.agent_chat_add_any": "בחירת קבצים או תיקיות…", + "ui.agent_chat_reads_fresh_session": "Claude Code לא הצליח להעביר את השיחה הקודמת כשכלי הקריאה שלו הופעלו, ולכן הוא מתחיל מחדש מההודעה הזו." }, "ja": { "ui.agent_chat_add_folder": "フォルダーを選択…", @@ -52,7 +56,8 @@ "ui.agent_chat_paste_past_max": "1 つのメッセージで送れるファイルは {max} 個までです。画像をファイルとして保存し、そのファイルを添付してください", "ui.ai_auto_attached": "添付したものを読み込むため", "ui.agent_chat_reads_warning": "パスでファイルやフォルダーを送ると、このチャットで Claude Code の読み取りツールがオンになります。送ったものは確認なしで読み込み、それ以外を読む前には確認します。", - "ui.agent_chat_add_any": "ファイルまたはフォルダーを選択…" + "ui.agent_chat_add_any": "ファイルまたはフォルダーを選択…", + "ui.agent_chat_reads_fresh_session": "読み取りツールをオンにする際に Claude Code がそれまでの会話を引き継げなかったため、このメッセージから新しく始めます。" }, "ko": { "ui.agent_chat_add_folder": "폴더 선택…", @@ -63,7 +68,8 @@ "ui.agent_chat_paste_past_max": "메시지 하나에는 파일을 최대 {max}개까지 보낼 수 있습니다. 그림을 파일로 저장한 뒤 그 파일을 첨부하세요", "ui.ai_auto_attached": "첨부한 항목을 읽음", "ui.agent_chat_reads_warning": "경로로 파일이나 폴더를 보내면 이 채팅에서 Claude Code의 읽기 도구가 켜집니다. 보낸 항목은 묻지 않고 읽고, 그 밖의 항목을 읽기 전에는 묻습니다.", - "ui.agent_chat_add_any": "파일 또는 폴더 선택…" + "ui.agent_chat_add_any": "파일 또는 폴더 선택…", + "ui.agent_chat_reads_fresh_session": "읽기 도구를 켜는 동안 Claude Code가 이전 대화를 이어받지 못해 이 메시지부터 새로 시작합니다." }, "vi": { "ui.agent_chat_add_folder": "Chọn thư mục…", @@ -74,7 +80,8 @@ "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_reads_warning": "Gửi một tệp hoặc thư mục theo đường dẫn sẽ bật các công cụ đọc của Claude Code cho cuộc trò chuyện này: nó đọc những gì bạn gửi mà không hỏi, và hỏi trước khi đọc bất cứ thứ gì khác.", - "ui.agent_chat_add_any": "Chọn tệp hoặc thư mục…" + "ui.agent_chat_add_any": "Chọn tệp hoặc thư mục…", + "ui.agent_chat_reads_fresh_session": "Claude Code không thể chuyển cuộc trò chuyện trước khi bật công cụ đọc, nên bắt đầu lại từ tin nhắn này." }, "zh": { "ui.agent_chat_add_folder": "选择文件夹…", @@ -85,6 +92,7 @@ "ui.agent_chat_paste_past_max": "一条消息最多发送 {max} 个文件;请把图片另存为文件,再附加该文件", "ui.ai_auto_attached": "它读取的是你附加的内容", "ui.agent_chat_reads_warning": "按路径发送文件或文件夹会为本次聊天开启 Claude Code 的读取工具:它会直接读取你发送的内容,读取其他任何内容前都会先询问。", - "ui.agent_chat_add_any": "选择文件或文件夹…" + "ui.agent_chat_add_any": "选择文件或文件夹…", + "ui.agent_chat_reads_fresh_session": "开启读取工具时 Claude Code 无法沿用之前的对话,因此从这条消息重新开始。" } } diff --git a/crates/ui-egui/src/agent_chat/acp_client.rs b/crates/ui-egui/src/agent_chat/acp_client.rs index 39ccf0eb6e1..de9477fcb4d 100644 --- a/crates/ui-egui/src/agent_chat/acp_client.rs +++ b/crates/ui-egui/src/agent_chat/acp_client.rs @@ -15,6 +15,8 @@ use super::process::{AgentProcess, FromAgent}; enum Pending { Initialize, SessionNew, + /// `session/new` resuming the open session with Claude Code's read tools on. + SessionResume, Prompt, Authenticate, SetMode, @@ -41,6 +43,10 @@ pub struct AcpBackend { reads_files: bool, /// The session that is open, or being opened, was asked for with them on. session_reads: bool, + /// The open session has had a message: Claude Code has its conversation on disk, so it can be + /// resumed. A session that has had none can't be ("Resource not found"), and has nothing to + /// keep. + prompted: bool, next_id: u64, pending: HashMap, session: Option, @@ -73,6 +79,7 @@ impl AcpBackend { note: acp::SYSTEM_NOTE.to_string(), reads_files: false, session_reads: false, + prompted: false, next_id: 0, pending: HashMap::new(), session: None, @@ -105,15 +112,22 @@ impl AcpBackend { acp::turn_on_reads(&mut params, None); } self.session_reads = self.reads_files; + self.prompted = false; self.request(Pending::SessionNew, "session/new", params); } - /// The open session again, with Claude Code's read tools on: the same conversation goes on. + /// The open session again, with Claude Code's read tools on: resumed when it has had a message, + /// so the same conversation goes on; a fresh one when it hasn't, as there is nothing to keep + /// (and Claude Code can't resume it). fn resume_with_reads(&mut self) { + if !self.prompted { + self.new_session(); + return; + } let mut params = acp::session_new_params(&self.cwd, self.bridge.as_ref(), &self.init, &self.note); acp::turn_on_reads(&mut params, self.session.as_deref()); self.session_reads = true; - self.request(Pending::SessionNew, "session/new", params); + self.request(Pending::SessionResume, "session/new", params); } fn handle(&mut self, msg: Incoming, out: &mut Vec) { @@ -132,7 +146,14 @@ impl AcpBackend { self.init = v; self.new_session(); } - (Pending::SessionNew, Ok(v)) => match v.get("sessionId").and_then(Value::as_str) { + // Resuming with the read tools on failed: a fresh session with them, so the + // message that turned them on still goes, and the chat says what was lost. + (Pending::SessionResume, Err((code, message))) => { + log::warn!("Claude Code did not resume its session with read tools on ({code}): {message}"); + self.new_session(); + out.push(Event::Notice(solidcraft_ui_text::tr("ui.agent_chat_reads_fresh_session").to_string())); + } + (Pending::SessionNew | Pending::SessionResume, Ok(v)) => match v.get("sessionId").and_then(Value::as_str) { Some(s) => { // New chat has opened successfully: retire the old turn before Ready. // Its late reply and cancellation deadline must not end the new turn. @@ -285,6 +306,7 @@ impl ChatBackend for AcpBackend { fn prompt(&mut self, parts: &[PromptPart]) { if let Some(s) = self.session.clone() { + self.prompted = true; self.request(Pending::Prompt, "session/prompt", acp::prompt_params(&s, parts)); } } @@ -324,7 +346,8 @@ impl ChatBackend for AcpBackend { return false; } self.reads_files = on; - if on && self.session.is_some() && !self.session_reads && !self.pending.values().any(|p| *p == Pending::SessionNew) { + let opening = self.pending.values().any(|p| matches!(p, Pending::SessionNew | Pending::SessionResume)); + if on && self.session.is_some() && !self.session_reads && !opening { self.resume_with_reads(); return true; } @@ -429,19 +452,38 @@ mod tests { Ok(backend) } - /// Turning the read tools on in an open session opens it again (resuming it) before it is ready; - /// turned on while the first session is still being opened, that one is opened again as soon as - /// it answers, so no message goes out without them. + /// Turning the read tools on in an open session opens it again before it is ready: resumed when + /// it has had a message (the same conversation goes on), fresh when it hasn't (Claude Code + /// answers "Resource not found" to resuming such a session, and there is nothing to keep). + /// Turned on while the first session is still being opened, that one is opened again as soon + /// as it answers, so no message goes out without them. A resume that fails still ends in a + /// session with them, and says so. #[test] fn turning_reads_on_reopens_the_session_before_it_is_ready() { let mut backend = ready_backend().unwrap(); assert!(backend.set_reads_files(true), "an open session is opened again"); assert!(!backend.set_reads_files(true), "once"); + assert!(backend.pending.values().any(|p| *p == Pending::SessionNew), "no message yet: a fresh session, not a resume"); let mut events = Vec::new(); - backend.handle(Incoming::Reply { id: backend.next_id, result: Ok(json!({"sessionId":"s1"})) }, &mut events); + backend.handle(Incoming::Reply { id: backend.next_id, result: Ok(json!({"sessionId":"s2"})) }, &mut events); assert!(matches!(events.last(), Some(Event::Ready { .. })), "{events:?}"); backend.shutdown(true); + let mut talked = ready_backend().unwrap(); + talked.prompt(&[PromptPart::Text("hello".into())]); + let mut events = Vec::new(); + talked.handle(Incoming::Reply { id: talked.next_id, result: Ok(json!({"stopReason":"end_turn"})) }, &mut events); + assert!(talked.set_reads_files(true)); + assert!(talked.pending.values().any(|p| *p == Pending::SessionResume), "a session that has had a message is resumed"); + events.clear(); + talked.handle(Incoming::Reply { id: talked.next_id, result: Err((-32002, "Resource not found".into())) }, &mut events); + assert!(matches!(events.as_slice(), [Event::Notice(_)]), "a failed resume is said, not an error: {events:?}"); + assert!(talked.pending.values().any(|p| *p == Pending::SessionNew), "and a fresh session with them follows"); + events.clear(); + talked.handle(Incoming::Reply { id: talked.next_id, result: Ok(json!({"sessionId":"s3"})) }, &mut events); + assert!(matches!(events.last(), Some(Event::Ready { .. })), "{events:?}"); + talked.shutdown(true); + let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) }; let mut starting = AcpBackend::start(&["sh".into(), "-c".into(), "cat >/dev/null".into()], ctx).unwrap(); let mut events = Vec::new(); @@ -449,7 +491,7 @@ mod tests { assert!(!starting.set_reads_files(true), "no session yet: it opens with them"); starting.handle(Incoming::Reply { id: 2, result: Ok(json!({"sessionId":"s1"})) }, &mut events); assert!(!events.iter().any(|e| matches!(e, Event::Ready { .. })), "opened again first: {events:?}"); - assert!(starting.pending.values().any(|p| *p == Pending::SessionNew)); + assert!(starting.pending.values().any(|p| *p == Pending::SessionNew), "fresh: it has had no message"); starting.handle(Incoming::Reply { id: starting.next_id, result: Ok(json!({"sessionId":"s1"})) }, &mut events); assert!(matches!(events.last(), Some(Event::Ready { .. })), "{events:?}"); starting.shutdown(true); diff --git a/crates/ui-egui/src/agent_chat/backend.rs b/crates/ui-egui/src/agent_chat/backend.rs index 9ca6e8464d8..fdc405bef78 100644 --- a/crates/ui-egui/src/agent_chat/backend.rs +++ b/crates/ui-egui/src/agent_chat/backend.rs @@ -117,6 +117,8 @@ pub enum Event { }, /// Something failed; the backend is still running unless [`Event::Exited`] follows. Error(String), + /// Something the user should know that is no error: the chat goes on. + Notice(String), /// It ended; its last error output. Exited { tail: Vec, diff --git a/crates/ui-egui/src/agent_chat/mod.rs b/crates/ui-egui/src/agent_chat/mod.rs index 9fce413a09a..b2415884908 100644 --- a/crates/ui-egui/src/agent_chat/mod.rs +++ b/crates/ui-egui/src/agent_chat/mod.rs @@ -1066,6 +1066,7 @@ impl AgentChat { } return Some(Outcome::TurnEnd); } + Event::Notice(text) => self.notice(text, false), Event::Error(e) => { self.notice(e, true); match self.state() { From ff6a3ccefcbb769497bcaeef06668bbb0b41deb9 Mon Sep 17 00:00:00 2001 From: Seth LaForge Date: Tue, 17 Nov 2026 20:22:36 -0800 Subject: [PATCH 07/12] Assistant: attachments by agent kind; endpoints get PDFs as documents (#16452) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit What a file attached to a message becomes now depends on the agent. An OpenAI- or Anthropic-compatible endpoint has only SolidCraft's tools, so it keeps main's attachments and main's wording: at most eight files, pictures and text in the message, CAD files imported. A PDF (up to 12 MB) now goes whole as a document (an OpenAI `file` part, an Anthropic `document` block, and each OpenCode Go family's own), so the model sees its drawings; PDF text extraction and lopdf are gone. Any other file type is refused, saying what can go, as a path is of no use to an endpoint, and the + menu's Choose files… lists only those types. Every picture and PDF of the message being sent now reaches the endpoint: the history trim kept only the two newest pictures in the whole conversation, so eight attached photos arrived as two. A coding agent reads with its own tools, so every file and folder goes to it by path, up to 200 on one message, of any type, with nothing read, scaled or imported. Its + menu chooses files and folders (one item on macOS). Claude Code's read tools, the warning and the auto-allowed reads are unchanged. Main's code and wording come back where this branch had changed them: the attachment note, the selection and interrupt notes, and the dialog label. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 226 +------ apps/solidcraft/src/main.rs | 21 +- assets/locales/ar.json | 1 + assets/locales/bg.json | 1 + assets/locales/bs.json | 1 + assets/locales/ca.json | 1 + assets/locales/cs.json | 1 + assets/locales/da.json | 1 + assets/locales/de.json | 1 + assets/locales/en.json | 1 + assets/locales/es.json | 1 + assets/locales/fi.json | 1 + assets/locales/fr.json | 1 + assets/locales/gl.json | 1 + assets/locales/he.json | 1 + assets/locales/hr.json | 1 + assets/locales/hu.json | 1 + assets/locales/id.json | 1 + assets/locales/it.json | 1 + assets/locales/ja.json | 1 + assets/locales/ka.json | 1 + assets/locales/ko.json | 1 + assets/locales/lv.json | 1 + assets/locales/ms.json | 1 + assets/locales/nb.json | 1 + assets/locales/nl.json | 1 + .../pending/agent-chat-files-by-place.json | 48 +- assets/locales/pl.json | 1 + assets/locales/pt-BR.json | 1 + assets/locales/ro.json | 1 + assets/locales/ru.json | 1 + assets/locales/sr.json | 1 + assets/locales/sv.json | 1 + assets/locales/tr.json | 1 + assets/locales/uk.json | 1 + assets/locales/vi.json | 1 + assets/locales/zh-TW.json | 1 + assets/locales/zh.json | 1 + crates/ui-egui/Cargo.toml | 1 - crates/ui-egui/src/agent_chat/acp.rs | 6 +- crates/ui-egui/src/agent_chat/api_client.rs | 148 +++-- crates/ui-egui/src/agent_chat/attach.rs | 591 ++++-------------- crates/ui-egui/src/agent_chat/context.rs | 8 +- crates/ui-egui/src/agent_chat/mod.rs | 155 ++--- crates/ui-egui/src/agent_chat/panel.rs | 42 +- crates/ui-egui/src/agent_chat/tests.rs | 231 +++---- crates/ui-egui/src/file_picker.rs | 11 +- crates/ui-egui/src/lib.rs | 8 +- docs/agent-chat.md | 81 ++- docs/control-protocol.md | 2 +- docs/design/in-app-agent-chat.md | 26 +- 51 files changed, 631 insertions(+), 1009 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ebddc4f02c8..3f8c615c104 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]] @@ -938,7 +893,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3264e2574e9ef2b53ce6f536dea83a69ac0bc600b762d1523ff83fe07230ce30" dependencies = [ "byteorder", - "cipher 0.4.4", + "cipher", ] [[package]] @@ -977,7 +932,7 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "26b07d673db1ccf000e90f54b819db9e75a8348d6eb056e9b8ab53231b7a9911" dependencies = [ - "cipher 0.4.4", + "cipher", ] [[package]] @@ -998,16 +953,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]] @@ -1028,7 +974,7 @@ version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "738b8d467867f80a71351933f70461f5b56f24d5c93e0cf216e59229c968d330" dependencies = [ - "cipher 0.4.4", + "cipher", ] [[package]] @@ -1121,17 +1067,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]] @@ -1149,7 +1085,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", ] @@ -1304,12 +1240,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" @@ -1589,7 +1519,7 @@ version = "0.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" dependencies = [ - "cipher 0.4.4", + "cipher", ] [[package]] @@ -1703,9 +1633,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", @@ -1786,7 +1716,7 @@ version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ffdd80ce8ce993de27e9f063a444a4d53ce8e8db4c1f00cc03af5ad5a9867a1e" dependencies = [ - "cipher 0.4.4", + "cipher", ] [[package]] @@ -1906,21 +1836,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" @@ -2635,7 +2556,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" dependencies = [ "color_quant", - "weezl 0.1.12", + "weezl", ] [[package]] @@ -3073,7 +2994,7 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "075557004419d7f2031b8bb7f44bb43e55a83ca7b63076a8fb8fe75753836477" dependencies = [ - "cipher 0.4.4", + "cipher", ] [[package]] @@ -3156,20 +3077,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" @@ -3519,33 +3430,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" @@ -3568,16 +3452,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" @@ -4240,7 +4114,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c196e0276c471c843dd5777e7543a36a298a4be942a2a688d8111cd43390dedb" dependencies = [ "aead", - "cipher 0.4.4", + "cipher", "ctr", "subtle", ] @@ -4435,13 +4309,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", @@ -4449,7 +4323,7 @@ dependencies = [ "camellia", "cast5", "cfb-mode", - "cipher 0.4.4", + "cipher", "const-oid 0.9.6", "crc24", "curve25519-dalek", @@ -4471,7 +4345,7 @@ dependencies = [ "idea", "k256", "log", - "md-5 0.10.6", + "md-5", "memchr", "nom", "num-bigint-dig", @@ -4860,7 +4734,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", ] @@ -4905,12 +4778,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,8 +5273,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", @@ -6247,7 +6114,7 @@ dependencies = [ "solidcraft-viewport", "sysinfo", "web-time", - "weezl 0.1.12", + "weezl", ] [[package]] @@ -6308,7 +6175,6 @@ dependencies = [ "egui-wgpu", "image", "log", - "lopdf", "minisign-verify", "nix 0.31.3", "pollster 0.4.0", @@ -6507,17 +6373,6 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731" -[[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" @@ -6691,7 +6546,7 @@ dependencies = [ "flate2", "half", "quick-error", - "weezl 0.1.12", + "weezl", "zune-jpeg", ] @@ -6730,12 +6585,6 @@ dependencies = [ "zerovec", ] -[[package]] -name = "tinyvec" -version = "1.13.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" - [[package]] name = "tokio" version = "1.53.2" @@ -6870,7 +6719,7 @@ version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a78e83a30223c757c3947cd144a31014ff04298d8719ae10d03c31c0448c8013" dependencies = [ - "cipher 0.4.4", + "cipher", ] [[package]] @@ -6941,15 +6790,6 @@ version = "1.0.26" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" -[[package]] -name = "unicode-normalization" -version = "0.1.26" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" -dependencies = [ - "tinyvec", -] - [[package]] name = "unicode-properties" version = "0.1.5" @@ -7671,12 +7511,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.1" diff --git a/apps/solidcraft/src/main.rs b/apps/solidcraft/src/main.rs index 59f6cb892f3..3e7a887a98c 100644 --- a/apps/solidcraft/src/main.rs +++ b/apps/solidcraft/src/main.rs @@ -804,9 +804,8 @@ fn services(cc: &eframe::CreationContext<'_>, folder: &DialogFolder) -> Services let folder = open_folder.clone(); Box::pin(async move { folder.answer(future.await) }) })), - // One kind of file (a plug-in, 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). + // 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 all = any_case(exts); let all: Vec<&str> = all.iter().map(String::as_str).collect(); @@ -815,11 +814,17 @@ fn services(cc: &eframe::CreationContext<'_>, folder: &DialogFolder) -> Services let folder = file_folder.clone(); Box::pin(async move { folder.answer(future.await) }) })), - // Several files of any type at once (the agent chat's attachments: a batch of photos). No - // filter: what the chat can't read goes to the agent by path. (On macOS a filter lists the - // only types that can be chosen, and its "All files" `*` is no wildcard.) - pick_files: Some(Box::new(move || { - let future = files_folder.start(files_parent.clone()).pick_files(); + // 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(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) }) })), diff --git a/assets/locales/ar.json b/assets/locales/ar.json index f86c85fda42..2593551bf10 100644 --- a/assets/locales/ar.json +++ b/assets/locales/ar.json @@ -5513,6 +5513,7 @@ "ui.agent_chat_attach_selection_tip": "إرسال ما هو محدد في النموذج (أوجه وحواف وميزات وأجسام) مع الرسالة، ليعرف الوكيل ما تقصده", "ui.agent_chat_attach_view": "إرفاق العرض", "ui.agent_chat_attach_view_tip": "إرسال صورة للعرض الحالي مع الرسالة", + "ui.agent_chat_attachable": "صور وملفات PDF ونصوص وملفات CAD", "ui.agent_chat_auth_agent": "تسجيل الدخول باستخدام {name}", "ui.agent_chat_auth_env": "اضبط {vars} في بيئة النظام وأعد تشغيل SolidCraft.", "ui.agent_chat_auth_needed": "يطلب الوكيل منك تسجيل الدخول. تسجّل الدخول عبر الوكيل نفسه؛ ولا يرى SolidCraft كلمة مرورك أو مفاتيحك أبدًا.", diff --git a/assets/locales/bg.json b/assets/locales/bg.json index a2bb0458aec..079e505bc0d 100644 --- a/assets/locales/bg.json +++ b/assets/locales/bg.json @@ -2727,6 +2727,7 @@ "ui.agent_chat_attach_selection_tip": "Send what is selected in the model (faces, edges, features, bodies) with the message, so the agent knows what you mean", "ui.agent_chat_attach_view": "Attach view", "ui.agent_chat_attach_view_tip": "Send a picture of the current view with the message", + "ui.agent_chat_attachable": "Pictures, PDFs, text and CAD files", "ui.agent_chat_auth_agent": "Sign in with {name}", "ui.agent_chat_auth_env": "Set {vars} in your environment and restart SolidCraft.", "ui.agent_chat_auth_needed": "The agent asks you to sign in. You sign in with the agent itself; SolidCraft never sees your password or keys.", diff --git a/assets/locales/bs.json b/assets/locales/bs.json index a50dab94561..8d15f2818f7 100644 --- a/assets/locales/bs.json +++ b/assets/locales/bs.json @@ -4114,6 +4114,7 @@ "ui.agent_chat_attach_selection_tip": "Pošalji s porukom ono što je izabrano u modelu (lica, ivice, operacije, tijela), da agent zna na šta mislite", "ui.agent_chat_attach_view": "Priloži prikaz", "ui.agent_chat_attach_view_tip": "Pošalji sliku trenutnog prikaza s porukom", + "ui.agent_chat_attachable": "Slike, PDF-ovi, tekst i CAD datoteke", "ui.agent_chat_auth_agent": "Prijavi se pomoću {name}", "ui.agent_chat_auth_env": "Postavite {vars} u svom okruženju i ponovo pokrenite SolidCraft.", "ui.agent_chat_auth_needed": "Agent traži da se prijavite. Prijavljujete se kod samog agenta; SolidCraft nikad ne vidi vašu lozinku ni ključeve.", diff --git a/assets/locales/ca.json b/assets/locales/ca.json index 791173aecb6..b8fd7079508 100644 --- a/assets/locales/ca.json +++ b/assets/locales/ca.json @@ -5289,6 +5289,7 @@ "ui.agent_chat_attach_selection_tip": "Envia amb el missatge el que estigui seleccionat al model (cares, arestes, operacions, cossos) perquè l'agent sàpiga a què us referiu", "ui.agent_chat_attach_view": "Adjuntar la vista", "ui.agent_chat_attach_view_tip": "Enviar una imatge de la vista actual amb el missatge", + "ui.agent_chat_attachable": "Imatges, PDF, text i fitxers CAD", "ui.agent_chat_auth_agent": "Iniciar sessió amb {name}", "ui.agent_chat_auth_env": "Definiu {vars} a l'entorn i reinicieu SolidCraft.", "ui.agent_chat_auth_needed": "L'agent us demana que inicieu sessió. L'inici de sessió es fa amb l'agent mateix; SolidCraft no veu mai la vostra contrasenya ni les vostres claus.", diff --git a/assets/locales/cs.json b/assets/locales/cs.json index 68f107ff800..98b65efa59d 100644 --- a/assets/locales/cs.json +++ b/assets/locales/cs.json @@ -4848,6 +4848,7 @@ "ui.agent_chat_attach_selection_tip": "Odešle se zprávou to, co je v modelu vybráno (plochy, hrany, prvky, tělesa), aby agent věděl, co máte na mysli", "ui.agent_chat_attach_view": "Přiložit pohled", "ui.agent_chat_attach_view_tip": "Odeslat se zprávou obrázek aktuálního pohledu", + "ui.agent_chat_attachable": "Obrázky, PDF, text a soubory CAD", "ui.agent_chat_auth_agent": "Přihlásit se přes {name}", "ui.agent_chat_auth_env": "Nastavte {vars} v proměnných prostředí a restartujte SolidCraft.", "ui.agent_chat_auth_needed": "Agent žádá o přihlášení. Přihlašujete se přímo u agenta; SolidCraft vaše heslo ani klíče nikdy nevidí.", diff --git a/assets/locales/da.json b/assets/locales/da.json index dbb9fa30212..97e8a57b27d 100644 --- a/assets/locales/da.json +++ b/assets/locales/da.json @@ -4117,6 +4117,7 @@ "ui.agent_chat_attach_selection_tip": "Send det, der er markeret i modellen (flader, kanter, features, emner), sammen med beskeden, så agenten ved, hvad du mener", "ui.agent_chat_attach_view": "Vedhæft visning", "ui.agent_chat_attach_view_tip": "Send et billede af den aktuelle visning sammen med beskeden", + "ui.agent_chat_attachable": "Billeder, PDF-filer, tekst og CAD-filer", "ui.agent_chat_auth_agent": "Log ind med {name}", "ui.agent_chat_auth_env": "Indstil {vars} i dit miljø, og genstart SolidCraft.", "ui.agent_chat_auth_needed": "Agenten beder dig logge ind. Du logger ind hos agenten selv; SolidCraft ser aldrig din adgangskode eller dine nøgler.", diff --git a/assets/locales/de.json b/assets/locales/de.json index ca98b2d6fd9..994ad9bfeff 100644 --- a/assets/locales/de.json +++ b/assets/locales/de.json @@ -5131,6 +5131,7 @@ "ui.agent_chat_attach_selection_tip": "Das im Modell Ausgewählte (Flächen, Kanten, Merkmale, Körper) mit der Nachricht senden, damit der Agent weiß, was Sie meinen", "ui.agent_chat_attach_view": "Ansicht anhängen", "ui.agent_chat_attach_view_tip": "Ein Bild der aktuellen Ansicht mit der Nachricht senden", + "ui.agent_chat_attachable": "Bilder, PDFs, Text- und CAD-Dateien", "ui.agent_chat_auth_agent": "Mit {name} anmelden", "ui.agent_chat_auth_env": "Setzen Sie {vars} in Ihrer Umgebung und starten Sie SolidCraft neu.", "ui.agent_chat_auth_needed": "Der Agent bittet Sie, sich anzumelden. Sie melden sich beim Agenten selbst an; SolidCraft sieht Ihr Passwort oder Ihre Schlüssel nie.", diff --git a/assets/locales/en.json b/assets/locales/en.json index c752ef2d001..859aa6b9aa4 100644 --- a/assets/locales/en.json +++ b/assets/locales/en.json @@ -5513,6 +5513,7 @@ "ui.agent_chat_attach_selection_tip": "Send what is selected in the model (faces, edges, features, bodies) with the message, so the agent knows what you mean", "ui.agent_chat_attach_view": "Attach view", "ui.agent_chat_attach_view_tip": "Send a picture of the current view with the message", + "ui.agent_chat_attachable": "Pictures, PDFs, text and CAD files", "ui.agent_chat_auth_agent": "Sign in with {name}", "ui.agent_chat_auth_env": "Set {vars} in your environment and restart SolidCraft.", "ui.agent_chat_auth_needed": "The agent asks you to sign in. You sign in with the agent itself; SolidCraft never sees your password or keys.", diff --git a/assets/locales/es.json b/assets/locales/es.json index 90d5800927f..bf1ff08e68f 100644 --- a/assets/locales/es.json +++ b/assets/locales/es.json @@ -5308,6 +5308,7 @@ "ui.agent_chat_attach_selection_tip": "Envía con el mensaje lo que esté seleccionado en el modelo (caras, aristas, operaciones, cuerpos) para que el agente sepa a qué te refieres", "ui.agent_chat_attach_view": "Adjuntar vista", "ui.agent_chat_attach_view_tip": "Enviar una imagen de la vista actual con el mensaje", + "ui.agent_chat_attachable": "Imágenes, PDF, texto y archivos CAD", "ui.agent_chat_auth_agent": "Iniciar sesión con {name}", "ui.agent_chat_auth_env": "Configura {vars} en las variables de entorno y reinicia SolidCraft.", "ui.agent_chat_auth_needed": "El agente te pide que inicies sesión. El inicio de sesión se realiza con el propio agente; SolidCraft nunca ve tu contraseña ni tus claves.", diff --git a/assets/locales/fi.json b/assets/locales/fi.json index d76e99a8c55..b290f551434 100644 --- a/assets/locales/fi.json +++ b/assets/locales/fi.json @@ -4871,6 +4871,7 @@ "ui.agent_chat_attach_selection_tip": "Lähetä mallista valitut kohteet (pinnat, särmät, piirteet, kappaleet) viestin mukana, jotta agentti tietää, mitä tarkoitat", "ui.agent_chat_attach_view": "Liitä näkymä", "ui.agent_chat_attach_view_tip": "Lähetä kuva nykyisestä näkymästä viestin mukana", + "ui.agent_chat_attachable": "Kuvat, PDF:t, teksti- ja CAD-tiedostot", "ui.agent_chat_auth_agent": "Kirjaudu palvelulla {name}", "ui.agent_chat_auth_env": "Aseta {vars} ympäristöösi ja käynnistä SolidCraft uudelleen.", "ui.agent_chat_auth_needed": "Agentti pyytää sinua kirjautumaan. Kirjaudut agentin itsensä kautta; SolidCraft ei koskaan näe salasanaasi tai avaimiasi.", diff --git a/assets/locales/fr.json b/assets/locales/fr.json index c7b67fc10f8..496c69ff262 100644 --- a/assets/locales/fr.json +++ b/assets/locales/fr.json @@ -4445,6 +4445,7 @@ "ui.agent_chat_attach_selection_tip": "Envoyer ce qui est sélectionné dans le modèle (faces, arêtes, fonctions, corps) avec le message, pour que l'agent sache de quoi vous parlez", "ui.agent_chat_attach_view": "Joindre la vue", "ui.agent_chat_attach_view_tip": "Envoyer une image de la vue actuelle avec le message", + "ui.agent_chat_attachable": "Images, PDF, textes et fichiers de CAO", "ui.agent_chat_auth_agent": "S'authentifier avec {name}", "ui.agent_chat_auth_env": "Définir {vars} dans votre environnement, puis redémarrer SolidCraft.", "ui.agent_chat_auth_needed": "L'agent demande une authentification. Vous vous authentifiez auprès de l'agent lui-même ; SolidCraft ne voit jamais votre mot de passe ni vos clés.", diff --git a/assets/locales/gl.json b/assets/locales/gl.json index e5fd3bae60c..2127ca0d704 100644 --- a/assets/locales/gl.json +++ b/assets/locales/gl.json @@ -4117,6 +4117,7 @@ "ui.agent_chat_attach_selection_tip": "Envía coa mensaxe o que está seleccionado no modelo (caras, arestas, operacións, corpos), para que o axente saiba a que te refires", "ui.agent_chat_attach_view": "Achegar a vista", "ui.agent_chat_attach_view_tip": "Envía unha imaxe da vista actual coa mensaxe", + "ui.agent_chat_attachable": "Imaxes, PDF, texto e ficheiros CAD", "ui.agent_chat_auth_agent": "Iniciar sesión con {name}", "ui.agent_chat_auth_env": "Define {vars} no teu contorno e reinicia SolidCraft.", "ui.agent_chat_auth_needed": "O axente pídeche que inicies sesión. Inicias sesión co propio axente; SolidCraft nunca ve o teu contrasinal nin as túas claves.", diff --git a/assets/locales/he.json b/assets/locales/he.json index 3728cabeb72..4d4c1caa8c3 100644 --- a/assets/locales/he.json +++ b/assets/locales/he.json @@ -5513,6 +5513,7 @@ "ui.agent_chat_attach_selection_tip": "שליחת מה שנבחר במודל (פאות, מקצועות, פיצ'רים, גופים) עם ההודעה, כדי שהסוכן יבין למה הכוונה", "ui.agent_chat_attach_view": "צירוף התצוגה", "ui.agent_chat_attach_view_tip": "שליחת תמונה של התצוגה הנוכחית עם ההודעה", + "ui.agent_chat_attachable": "תמונות, PDF, טקסט וקובצי CAD", "ui.agent_chat_auth_agent": "התחברות עם {name}", "ui.agent_chat_auth_env": "יש להגדיר את {vars} בסביבה ולהפעיל מחדש את SolidCraft.", "ui.agent_chat_auth_needed": "הסוכן מבקש להתחבר. ההתחברות נעשית מול הסוכן עצמו; SolidCraft לעולם אינו רואה את הסיסמה או המפתחות.", diff --git a/assets/locales/hr.json b/assets/locales/hr.json index 5c57fcc529b..da34ae5340c 100644 --- a/assets/locales/hr.json +++ b/assets/locales/hr.json @@ -4116,6 +4116,7 @@ "ui.agent_chat_attach_selection_tip": "Pošalji s porukom ono što je odabrano u modelu (lica, bridove, značajke, tijela), kako bi agent znao na što mislite", "ui.agent_chat_attach_view": "Priloži prikaz", "ui.agent_chat_attach_view_tip": "Pošalji sliku trenutnog prikaza s porukom", + "ui.agent_chat_attachable": "Slike, PDF-ovi, tekst i CAD datoteke", "ui.agent_chat_auth_agent": "Prijavi se pomoću {name}", "ui.agent_chat_auth_env": "Postavite {vars} u svom okruženju i ponovno pokrenite SolidCraft.", "ui.agent_chat_auth_needed": "Agent traži da se prijavite. Prijavljujete se kod samog agenta; SolidCraft nikad ne vidi vašu lozinku ni ključeve.", diff --git a/assets/locales/hu.json b/assets/locales/hu.json index be69e1eb7b8..5fff04e91cc 100644 --- a/assets/locales/hu.json +++ b/assets/locales/hu.json @@ -4117,6 +4117,7 @@ "ui.agent_chat_attach_selection_tip": "A modellben kijelölt elemeket (lapok, élek, elemek, testek) elküldi az üzenettel együtt, hogy az ügynök tudja, mire gondol", "ui.agent_chat_attach_view": "Nézet csatolása", "ui.agent_chat_attach_view_tip": "Az aktuális nézet képének küldése az üzenettel", + "ui.agent_chat_attachable": "Képek, PDF-ek, szöveg- és CAD-fájlok", "ui.agent_chat_auth_agent": "Bejelentkezés: {name}", "ui.agent_chat_auth_env": "Állítsa be a(z) {vars} változót a környezetében, és indítsa újra a SolidCraftot.", "ui.agent_chat_auth_needed": "Az ügynök bejelentkezést kér. Magával az ügynökkel jelentkezik be; a SolidCraft soha nem látja a jelszavát vagy kulcsait.", diff --git a/assets/locales/id.json b/assets/locales/id.json index c66b8249648..ea60a5b4868 100644 --- a/assets/locales/id.json +++ b/assets/locales/id.json @@ -4117,6 +4117,7 @@ "ui.agent_chat_attach_selection_tip": "Kirim apa yang dipilih di model (muka, tepi, fitur, bodi) bersama pesan, agar agen tahu maksud Anda", "ui.agent_chat_attach_view": "Lampirkan tampilan", "ui.agent_chat_attach_view_tip": "Kirim gambar tampilan saat ini bersama pesan", + "ui.agent_chat_attachable": "Gambar, PDF, teks, dan file CAD", "ui.agent_chat_auth_agent": "Masuk dengan {name}", "ui.agent_chat_auth_env": "Atur {vars} di environment Anda dan mulai ulang SolidCraft.", "ui.agent_chat_auth_needed": "Agen meminta Anda masuk. Anda masuk melalui agen itu sendiri; SolidCraft tidak pernah melihat kata sandi atau key Anda.", diff --git a/assets/locales/it.json b/assets/locales/it.json index 33d57108265..dd22ace572a 100644 --- a/assets/locales/it.json +++ b/assets/locales/it.json @@ -4882,6 +4882,7 @@ "ui.agent_chat_attach_selection_tip": "Invia con il messaggio ciò che è selezionato nel modello (facce, spigoli, lavorazioni, corpi), così l'agente capisce a cosa ti riferisci", "ui.agent_chat_attach_view": "Allega vista", "ui.agent_chat_attach_view_tip": "Invia un'immagine della vista corrente insieme al messaggio", + "ui.agent_chat_attachable": "Immagini, PDF, testo e file CAD", "ui.agent_chat_auth_agent": "Accedi con {name}", "ui.agent_chat_auth_env": "Imposta {vars} nell'ambiente e riavvia SolidCraft.", "ui.agent_chat_auth_needed": "L'agente richiede l'accesso. L'accesso avviene tramite l'agente stesso; SolidCraft non vede mai password o chiavi.", diff --git a/assets/locales/ja.json b/assets/locales/ja.json index 7b6079a8d76..e959fc10269 100644 --- a/assets/locales/ja.json +++ b/assets/locales/ja.json @@ -5513,6 +5513,7 @@ "ui.agent_chat_attach_selection_tip": "モデルで選択中のもの(面、エッジ、フィーチャ、ボディ)をメッセージと一緒に送り、何を指しているかをエージェントに伝えます", "ui.agent_chat_attach_view": "ビューを添付", "ui.agent_chat_attach_view_tip": "現在のビューの画像をメッセージと一緒に送ります", + "ui.agent_chat_attachable": "画像・PDF・テキスト・CAD ファイル", "ui.agent_chat_auth_agent": "{name} でサインイン", "ui.agent_chat_auth_env": "環境変数 {vars} を設定して SolidCraft を再起動してください。", "ui.agent_chat_auth_needed": "エージェントがサインインを求めています。サインインはエージェント自身で行います。SolidCraft がパスワードやキーを見ることはありません。", diff --git a/assets/locales/ka.json b/assets/locales/ka.json index b3499229498..d458a25e15b 100644 --- a/assets/locales/ka.json +++ b/assets/locales/ka.json @@ -4225,6 +4225,7 @@ "ui.agent_chat_attach_selection_tip": "შეტყობინებასთან ერთად მოდელში მონიშნულის (წახნაგების, წიბოების, ოპერაციების, სხეულების) გაგზავნა, რომ აგენტმა იცოდეს, რას გულისხმობთ", "ui.agent_chat_attach_view": "ხედის მიმაგრება", "ui.agent_chat_attach_view_tip": "შეტყობინებასთან ერთად მიმდინარე ხედის სურათის გაგზავნა", + "ui.agent_chat_attachable": "სურათები, PDF-ები, ტექსტი და CAD ფაილები", "ui.agent_chat_auth_agent": "შესვლა {name}-ით", "ui.agent_chat_auth_env": "დააყენეთ {vars} თქვენს გარემოში და გადატვირთეთ SolidCraft.", "ui.agent_chat_auth_needed": "აგენტი გთხოვთ, შეხვიდეთ სისტემაში. შედიხართ თავად აგენტით; SolidCraft ვერასოდეს ხედავს თქვენს პაროლს ან გასაღებებს.", diff --git a/assets/locales/ko.json b/assets/locales/ko.json index 50e9829f2c0..6a8c8acac65 100644 --- a/assets/locales/ko.json +++ b/assets/locales/ko.json @@ -4590,6 +4590,7 @@ "ui.agent_chat_attach_selection_tip": "모델에서 선택한 항목(면, 모서리, 피처, 바디)을 메시지와 함께 보내 에이전트가 무엇을 말하는지 알 수 있게 합니다", "ui.agent_chat_attach_view": "뷰 첨부", "ui.agent_chat_attach_view_tip": "현재 뷰의 이미지를 메시지와 함께 보냅니다", + "ui.agent_chat_attachable": "이미지, PDF, 텍스트 및 CAD 파일", "ui.agent_chat_auth_agent": "{name}(으)로 로그인", "ui.agent_chat_auth_env": "환경 변수 {vars}을(를) 설정하고 SolidCraft를 다시 시작하세요.", "ui.agent_chat_auth_needed": "에이전트가 로그인을 요청합니다. 로그인은 에이전트에서 직접 하며, SolidCraft는 비밀번호나 키를 보지 않습니다.", diff --git a/assets/locales/lv.json b/assets/locales/lv.json index 7faa9d90435..74ed5af8ddc 100644 --- a/assets/locales/lv.json +++ b/assets/locales/lv.json @@ -4924,6 +4924,7 @@ "ui.agent_chat_attach_selection_tip": "Nosūtīt kopā ar ziņu to, kas modelī atlasīts (skaldnes, šķautnes, operācijas, ķermeņus), lai aģents zinātu, ko jūs domājat", "ui.agent_chat_attach_view": "Pievienot skatu", "ui.agent_chat_attach_view_tip": "Nosūtīt kopā ar ziņu pašreizējā skata attēlu", + "ui.agent_chat_attachable": "Attēli, PDF, teksts un CAD faili", "ui.agent_chat_auth_agent": "Pierakstīties ar {name}", "ui.agent_chat_auth_env": "Iestatiet {vars} savā vidē un restartējiet SolidCraft.", "ui.agent_chat_auth_needed": "Aģents lūdz jums pierakstīties. Jūs pierakstāties pašā aģentā; SolidCraft nekad neredz jūsu paroli vai atslēgas.", diff --git a/assets/locales/ms.json b/assets/locales/ms.json index cafee8651bc..4401a613a2f 100644 --- a/assets/locales/ms.json +++ b/assets/locales/ms.json @@ -4117,6 +4117,7 @@ "ui.agent_chat_attach_selection_tip": "Hantar apa yang dipilih dalam model (muka, tepi, ciri, jasad) bersama mesej, supaya ejen tahu apa yang anda maksudkan", "ui.agent_chat_attach_view": "Lampirkan paparan", "ui.agent_chat_attach_view_tip": "Hantar imej pandangan semasa bersama mesej", + "ui.agent_chat_attachable": "Gambar, PDF, teks dan fail CAD", "ui.agent_chat_auth_agent": "Log masuk dengan {name}", "ui.agent_chat_auth_env": "Tetapkan {vars} dalam persekitaran, kemudian mula semula SolidCraft.", "ui.agent_chat_auth_needed": "Ejen memerlukan anda log masuk melalui ejen itu sendiri. SolidCraft tidak dapat melihat kata laluan atau kunci anda.", diff --git a/assets/locales/nb.json b/assets/locales/nb.json index 35831b2ef9a..cc15128e562 100644 --- a/assets/locales/nb.json +++ b/assets/locales/nb.json @@ -4116,6 +4116,7 @@ "ui.agent_chat_attach_selection_tip": "Send det som er valgt i modellen (flater, kanter, funksjoner, kropper) sammen med meldingen, så agenten vet hva du mener", "ui.agent_chat_attach_view": "Legg ved visning", "ui.agent_chat_attach_view_tip": "Send et bilde av gjeldende visning med meldingen", + "ui.agent_chat_attachable": "Bilder, PDF-er, tekst og CAD-filer", "ui.agent_chat_auth_agent": "Logg inn med {name}", "ui.agent_chat_auth_env": "Angi miljøvariablene {vars} og start SolidCraft på nytt.", "ui.agent_chat_auth_needed": "Agenten ber deg logge inn. Du logger inn med agenten selv; SolidCraft ser aldri passordet eller nøklene dine.", diff --git a/assets/locales/nl.json b/assets/locales/nl.json index ced17143493..6f4882a7c47 100644 --- a/assets/locales/nl.json +++ b/assets/locales/nl.json @@ -4128,6 +4128,7 @@ "ui.agent_chat_attach_selection_tip": "Verstuur wat in het model is geselecteerd (vlakken, randen, kenmerken, lichamen) met het bericht mee, zodat de agent weet wat je bedoelt", "ui.agent_chat_attach_view": "Weergave bijvoegen", "ui.agent_chat_attach_view_tip": "Een afbeelding van de huidige weergave met het bericht meesturen", + "ui.agent_chat_attachable": "Afbeeldingen, pdf's, tekst en CAD-bestanden", "ui.agent_chat_auth_agent": "Aanmelden met {name}", "ui.agent_chat_auth_env": "Stel {vars} in uw omgeving in en start SolidCraft opnieuw.", "ui.agent_chat_auth_needed": "De agent vraagt u zich aan te melden. U meldt zich aan bij de agent zelf; SolidCraft ziet nooit uw wachtwoord of sleutels.", diff --git a/assets/locales/pending/agent-chat-files-by-place.json b/assets/locales/pending/agent-chat-files-by-place.json index b5192e56341..82dd2e76054 100644 --- a/assets/locales/pending/agent-chat-files-by-place.json +++ b/assets/locales/pending/agent-chat-files-by-place.json @@ -2,97 +2,97 @@ "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_file_by_place_tip": "Not in the message: the agent is told where it is and reads it with its own tools", - "ui.agent_chat_files_by_place": "Past {max} files, the rest go by their path: the agent reads them 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_reads_warning": "Sending a file or folder by path turns on Claude Code's read tools for this chat: it reads what you send without asking, and asks before reading anything else.", "ui.agent_chat_add_any": "Choose files or folders…", - "ui.agent_chat_reads_fresh_session": "Claude Code couldn't carry the earlier conversation over when its read tools came on, so it starts again from this message." + "ui.agent_chat_reads_fresh_session": "Claude Code couldn't carry the earlier conversation over when its read tools came on, so it starts again from this message.", + "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" }, "ar": { "ui.agent_chat_add_folder": "اختر مجلدات…", "ui.agent_chat_add_folder_tip": "يُرسل المجلد إلى الوكيل بمساره: يقرأ الوكيل الملفات التي يحتاجها بأدواته الخاصة", - "ui.agent_chat_file_by_place_tip": "ليس ضمن الرسالة: يُخبَر الوكيل بمكانه ويقرؤه بأدواته الخاصة", - "ui.agent_chat_files_by_place": "بعد {max} ملفات، تُرسل البقية بمساراتها: يقرؤها الوكيل بأدواته الخاصة", "ui.agent_chat_folder_tip": "مجلد: يُخبَر الوكيل بمكانه، ويقرأ الملفات التي يحتاجها بأدواته الخاصة", "ui.agent_chat_paste_past_max": "يُرسل {max} ملفات كحد أقصى في رسالة واحدة؛ احفظ الصورة في ملف وأرفقه بدلًا منها", "ui.ai_auto_attached": "يقرأ شيئًا أرفقته", "ui.agent_chat_reads_warning": "إرسال ملف أو مجلد بمساره يشغّل أدوات القراءة في Claude Code لهذه المحادثة: يقرأ ما ترسله دون سؤال، ويسأل قبل قراءة أي شيء آخر.", "ui.agent_chat_add_any": "اختر ملفات أو مجلدات…", - "ui.agent_chat_reads_fresh_session": "تعذّر على Claude Code نقل المحادثة السابقة عند تشغيل أدوات القراءة، لذا يبدأ من جديد من هذه الرسالة." + "ui.agent_chat_reads_fresh_session": "تعذّر على Claude Code نقل المحادثة السابقة عند تشغيل أدوات القراءة، لذا يبدأ من جديد من هذه الرسالة.", + "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} ميغابايت على الأكثر" }, "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_file_by_place_tip": "Nicht in der Nachricht: Der Agent erfährt, wo die Datei liegt, und liest sie mit seinen eigenen Werkzeugen", - "ui.agent_chat_files_by_place": "Ab {max} Dateien gehen die übrigen über ihren Pfad: Der Agent liest sie 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_reads_warning": "Wenn Sie eine Datei oder einen Ordner über den Pfad senden, schaltet das die Lesewerkzeuge von Claude Code für diesen Chat ein: Es liest, was Sie senden, ohne Rückfrage, und fragt, bevor es etwas anderes liest.", "ui.agent_chat_add_any": "Dateien oder Ordner auswählen…", - "ui.agent_chat_reads_fresh_session": "Claude Code konnte das bisherige Gespräch beim Einschalten seiner Lesewerkzeuge nicht übernehmen und beginnt deshalb neu mit dieser Nachricht." + "ui.agent_chat_reads_fresh_session": "Claude Code konnte das bisherige Gespräch beim Einschalten seiner Lesewerkzeuge nicht übernehmen und beginnt deshalb neu mit dieser Nachricht.", + "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" }, "he": { "ui.agent_chat_add_folder": "בחירת תיקיות…", "ui.agent_chat_add_folder_tip": "תיקייה נשלחת לסוכן לפי הנתיב שלה: הסוכן קורא את הקבצים שהוא צריך בכלים שלו", - "ui.agent_chat_file_by_place_tip": "לא בתוך ההודעה: הסוכן מקבל את מיקום הקובץ וקורא אותו בכלים שלו", - "ui.agent_chat_files_by_place": "מעבר ל־{max} קבצים, השאר נשלחים לפי הנתיב שלהם: הסוכן קורא אותם בכלים שלו", "ui.agent_chat_folder_tip": "תיקייה: הסוכן מקבל את מיקומה, וקורא את הקבצים שהוא צריך בכלים שלו", "ui.agent_chat_paste_past_max": "לכל היותר {max} קבצים בהודעה אחת; יש לשמור את התמונה כקובץ ולצרף אותו במקומה", "ui.ai_auto_attached": "הוא קורא משהו שצירפת", "ui.agent_chat_reads_warning": "שליחת קובץ או תיקייה לפי נתיב מפעילה את כלי הקריאה של Claude Code בצ׳אט הזה: הוא קורא את מה ששלחת בלי לשאול, ושואל לפני שהוא קורא כל דבר אחר.", "ui.agent_chat_add_any": "בחירת קבצים או תיקיות…", - "ui.agent_chat_reads_fresh_session": "Claude Code לא הצליח להעביר את השיחה הקודמת כשכלי הקריאה שלו הופעלו, ולכן הוא מתחיל מחדש מההודעה הזו." + "ui.agent_chat_reads_fresh_session": "Claude Code לא הצליח להעביר את השיחה הקודמת כשכלי הקריאה שלו הופעלו, ולכן הוא מתחיל מחדש מההודעה הזו.", + "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" }, "ja": { "ui.agent_chat_add_folder": "フォルダーを選択…", "ui.agent_chat_add_folder_tip": "フォルダーはパスとしてエージェントに渡されます。必要なファイルはエージェントが自分のツールで読み込みます", - "ui.agent_chat_file_by_place_tip": "メッセージには含まれません。場所がエージェントに伝えられ、エージェントが自分のツールで読み込みます", - "ui.agent_chat_files_by_place": "{max} 個を超えたファイルはパスで渡されます。エージェントが自分のツールで読み込みます", "ui.agent_chat_folder_tip": "フォルダー: 場所がエージェントに伝えられ、必要なファイルはエージェントが自分のツールで読み込みます", "ui.agent_chat_paste_past_max": "1 つのメッセージで送れるファイルは {max} 個までです。画像をファイルとして保存し、そのファイルを添付してください", "ui.ai_auto_attached": "添付したものを読み込むため", "ui.agent_chat_reads_warning": "パスでファイルやフォルダーを送ると、このチャットで Claude Code の読み取りツールがオンになります。送ったものは確認なしで読み込み、それ以外を読む前には確認します。", "ui.agent_chat_add_any": "ファイルまたはフォルダーを選択…", - "ui.agent_chat_reads_fresh_session": "読み取りツールをオンにする際に Claude Code がそれまでの会話を引き継げなかったため、このメッセージから新しく始めます。" + "ui.agent_chat_reads_fresh_session": "読み取りツールをオンにする際に Claude Code がそれまでの会話を引き継げなかったため、このメッセージから新しく始めます。", + "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 までです" }, "ko": { "ui.agent_chat_add_folder": "폴더 선택…", "ui.agent_chat_add_folder_tip": "폴더는 경로로 에이전트에게 전달됩니다. 에이전트가 필요한 파일을 자체 도구로 읽습니다", - "ui.agent_chat_file_by_place_tip": "메시지에 포함되지 않음: 에이전트에게 위치가 전달되고 에이전트가 자체 도구로 읽습니다", - "ui.agent_chat_files_by_place": "{max}개를 넘는 파일은 경로로 전달됩니다. 에이전트가 자체 도구로 읽습니다", "ui.agent_chat_folder_tip": "폴더: 위치가 에이전트에게 전달되고, 에이전트가 필요한 파일을 자체 도구로 읽습니다", "ui.agent_chat_paste_past_max": "메시지 하나에는 파일을 최대 {max}개까지 보낼 수 있습니다. 그림을 파일로 저장한 뒤 그 파일을 첨부하세요", "ui.ai_auto_attached": "첨부한 항목을 읽음", "ui.agent_chat_reads_warning": "경로로 파일이나 폴더를 보내면 이 채팅에서 Claude Code의 읽기 도구가 켜집니다. 보낸 항목은 묻지 않고 읽고, 그 밖의 항목을 읽기 전에는 묻습니다.", "ui.agent_chat_add_any": "파일 또는 폴더 선택…", - "ui.agent_chat_reads_fresh_session": "읽기 도구를 켜는 동안 Claude Code가 이전 대화를 이어받지 못해 이 메시지부터 새로 시작합니다." + "ui.agent_chat_reads_fresh_session": "읽기 도구를 켜는 동안 Claude Code가 이전 대화를 이어받지 못해 이 메시지부터 새로 시작합니다.", + "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까지입니다" }, "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_file_by_place_tip": "Không nằm trong tin nhắn: AI Agent được cho biết vị trí của tệp và đọc nó bằng công cụ của mình", - "ui.agent_chat_files_by_place": "Quá {max} tệp, các tệp còn lại được gửi theo đường dẫn: AI Agent đọc chúng 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_reads_warning": "Gửi một tệp hoặc thư mục theo đường dẫn sẽ bật các công cụ đọc của Claude Code cho cuộc trò chuyện này: nó đọc những gì bạn gửi mà không hỏi, và hỏi trước khi đọc bất cứ thứ gì khác.", "ui.agent_chat_add_any": "Chọn tệp hoặc thư mục…", - "ui.agent_chat_reads_fresh_session": "Claude Code không thể chuyển cuộc trò chuyện trước khi bật công cụ đọc, nên bắt đầu lại từ tin nhắn này." + "ui.agent_chat_reads_fresh_session": "Claude Code không thể chuyển cuộc trò chuyện trước khi bật công cụ đọc, nên bắt đầu lại từ tin nhắn này.", + "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" }, "zh": { "ui.agent_chat_add_folder": "选择文件夹…", "ui.agent_chat_add_folder_tip": "文件夹以路径形式交给智能体:智能体用自己的工具读取所需的文件", - "ui.agent_chat_file_by_place_tip": "不在消息中:智能体会得知它的位置,并用自己的工具读取", - "ui.agent_chat_files_by_place": "超过 {max} 个文件后,其余文件按路径提供:智能体用自己的工具读取", "ui.agent_chat_folder_tip": "文件夹:智能体会得知它的位置,并用自己的工具读取所需的文件", "ui.agent_chat_paste_past_max": "一条消息最多发送 {max} 个文件;请把图片另存为文件,再附加该文件", "ui.ai_auto_attached": "它读取的是你附加的内容", "ui.agent_chat_reads_warning": "按路径发送文件或文件夹会为本次聊天开启 Claude Code 的读取工具:它会直接读取你发送的内容,读取其他任何内容前都会先询问。", "ui.agent_chat_add_any": "选择文件或文件夹…", - "ui.agent_chat_reads_fresh_session": "开启读取工具时 Claude Code 无法沿用之前的对话,因此从这条消息重新开始。" + "ui.agent_chat_reads_fresh_session": "开启读取工具时 Claude Code 无法沿用之前的对话,因此从这条消息重新开始。", + "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" } } diff --git a/assets/locales/pl.json b/assets/locales/pl.json index 7d380db7d3e..4cf6cd327df 100644 --- a/assets/locales/pl.json +++ b/assets/locales/pl.json @@ -5410,6 +5410,7 @@ "ui.agent_chat_attach_selection_tip": "Wyślij z wiadomością to, co zaznaczono w modelu (ściany, krawędzie, operacje, bryły), aby agent wiedział, o co chodzi", "ui.agent_chat_attach_view": "Dołącz widok", "ui.agent_chat_attach_view_tip": "Wyślij z wiadomością obraz bieżącego widoku", + "ui.agent_chat_attachable": "Obrazy, pliki PDF, tekstowe i CAD", "ui.agent_chat_auth_agent": "Zaloguj się przez {name}", "ui.agent_chat_auth_env": "Ustaw {vars} w swoim środowisku i uruchom ponownie SolidCraft.", "ui.agent_chat_auth_needed": "Agent prosi o zalogowanie. Logujesz się w samym agencie; SolidCraft nigdy nie widzi twojego hasła ani kluczy.", diff --git a/assets/locales/pt-BR.json b/assets/locales/pt-BR.json index 49b3e32248d..38b48d32dba 100644 --- a/assets/locales/pt-BR.json +++ b/assets/locales/pt-BR.json @@ -4936,6 +4936,7 @@ "ui.agent_chat_attach_selection_tip": "Enviar o que está selecionado no modelo (faces, arestas, recursos, corpos) com a mensagem, para que o agente saiba do que você está falando", "ui.agent_chat_attach_view": "Anexar vista", "ui.agent_chat_attach_view_tip": "Enviar uma imagem da vista atual com a mensagem", + "ui.agent_chat_attachable": "Imagens, PDFs, texto e arquivos CAD", "ui.agent_chat_auth_agent": "Entrar com {name}", "ui.agent_chat_auth_env": "Defina {vars} no seu ambiente e reinicie o SolidCraft.", "ui.agent_chat_auth_needed": "O agente pede que você entre. Você entra no próprio agente; o SolidCraft nunca vê sua senha ou chaves.", diff --git a/assets/locales/ro.json b/assets/locales/ro.json index 944b29a8f20..2d3ab80205b 100644 --- a/assets/locales/ro.json +++ b/assets/locales/ro.json @@ -4117,6 +4117,7 @@ "ui.agent_chat_attach_selection_tip": "Trimite împreună cu mesajul ce este selectat în model (fețe, muchii, operații, corpuri), astfel încât agentul să știe la ce vă referiți", "ui.agent_chat_attach_view": "Atașează vizualizarea", "ui.agent_chat_attach_view_tip": "Trimite o imagine a vizualizării curente împreună cu mesajul", + "ui.agent_chat_attachable": "Imagini, PDF-uri, text și fișiere CAD", "ui.agent_chat_auth_agent": "Autentificare cu {name}", "ui.agent_chat_auth_env": "Setați {vars} în mediul dumneavoastră și reporniți SolidCraft.", "ui.agent_chat_auth_needed": "Agentul vă cere să vă autentificați. Vă autentificați chiar în agent; SolidCraft nu vă vede niciodată parola sau cheile.", diff --git a/assets/locales/ru.json b/assets/locales/ru.json index 3641fb37ffa..e0e9434d905 100644 --- a/assets/locales/ru.json +++ b/assets/locales/ru.json @@ -4073,6 +4073,7 @@ "ui.agent_chat_attach_selection_tip": "Отправить с сообщением выделенное в модели (грани, рёбра, операции, тела), чтобы агент понимал, что вы имеете в виду", "ui.agent_chat_attach_view": "Прикрепить вид", "ui.agent_chat_attach_view_tip": "Отправить с сообщением изображение текущего вида", + "ui.agent_chat_attachable": "Изображения, PDF, текст и файлы CAD", "ui.agent_chat_auth_agent": "Войти через {name}", "ui.agent_chat_auth_env": "Задайте {vars} в окружении и перезапустите SolidCraft.", "ui.agent_chat_auth_needed": "Агент просит войти в систему. Вход выполняется через самого агента; SolidCraft никогда не видит ваш пароль или ключи.", diff --git a/assets/locales/sr.json b/assets/locales/sr.json index 0fd03c91c47..36d76c4dbb3 100644 --- a/assets/locales/sr.json +++ b/assets/locales/sr.json @@ -4114,6 +4114,7 @@ "ui.agent_chat_attach_selection_tip": "Пошаљи са поруком оно што је изабрано у моделу (лица, ивице, операције, тела), да агент зна на шта мислите", "ui.agent_chat_attach_view": "Приложи приказ", "ui.agent_chat_attach_view_tip": "Пошаљи слику тренутног приказа са поруком", + "ui.agent_chat_attachable": "Слике, ПДФ-ови, текст и CAD датотеке", "ui.agent_chat_auth_agent": "Пријави се помоћу {name}", "ui.agent_chat_auth_env": "Подесите {vars} у свом окружењу и поново покрените SolidCraft.", "ui.agent_chat_auth_needed": "Агент тражи да се пријавите. Пријављујете се код самог агента; SolidCraft никад не види вашу лозинку ни кључеве.", diff --git a/assets/locales/sv.json b/assets/locales/sv.json index 8e6c5a2e912..5eb0762f24e 100644 --- a/assets/locales/sv.json +++ b/assets/locales/sv.json @@ -4118,6 +4118,7 @@ "ui.agent_chat_attach_selection_tip": "Skicka det som är markerat i modellen (ytor, kanter, funktioner, kroppar) med meddelandet, så att agenten vet vad du menar", "ui.agent_chat_attach_view": "Bifoga vy", "ui.agent_chat_attach_view_tip": "Skicka en bild av den aktuella vyn med meddelandet", + "ui.agent_chat_attachable": "Bilder, PDF-filer, text och CAD-filer", "ui.agent_chat_auth_agent": "Logga in med {name}", "ui.agent_chat_auth_env": "Ange {vars} i din miljö och starta om SolidCraft.", "ui.agent_chat_auth_needed": "Agenten ber dig logga in. Du loggar in hos agenten själv; SolidCraft ser aldrig ditt lösenord eller dina nycklar.", diff --git a/assets/locales/tr.json b/assets/locales/tr.json index 030bcdb6354..57cf55620d5 100644 --- a/assets/locales/tr.json +++ b/assets/locales/tr.json @@ -4117,6 +4117,7 @@ "ui.agent_chat_attach_selection_tip": "Modelde seçili olanı (yüzler, kenarlar, özellikler, gövdeler) mesajla birlikte gönderin; ajan ne kastettiğinizi bilsin", "ui.agent_chat_attach_view": "Görünümü ekle", "ui.agent_chat_attach_view_tip": "Geçerli görünümün bir resmini mesajla birlikte gönder", + "ui.agent_chat_attachable": "Görseller, PDF'ler, metin ve CAD dosyaları", "ui.agent_chat_auth_agent": "{name} ile oturum aç", "ui.agent_chat_auth_env": "{vars} ortam değişkenlerini ayarlayın ve SolidCraft'ı yeniden başlatın.", "ui.agent_chat_auth_needed": "Ajan oturum açmanızı istiyor. Oturumu ajanın kendisinde açarsınız; SolidCraft parolanızı veya anahtarlarınızı asla görmez.", diff --git a/assets/locales/uk.json b/assets/locales/uk.json index e085fed2558..0c9a0a945f7 100644 --- a/assets/locales/uk.json +++ b/assets/locales/uk.json @@ -5294,6 +5294,7 @@ "ui.agent_chat_attach_selection_tip": "Надіслати разом із повідомленням, що виділено в моделі (грані, ребра, операції, тіла), щоб агент розумів, що ви маєте на увазі", "ui.agent_chat_attach_view": "Прикріпити вид", "ui.agent_chat_attach_view_tip": "Надіслати знімок поточного виду разом із повідомленням", + "ui.agent_chat_attachable": "Зображення, текст і CAD-файли", "ui.agent_chat_auth_agent": "Увійти через {name}", "ui.agent_chat_auth_env": "Задайте {vars} у своєму середовищі та перезапустіть SolidCraft.", "ui.agent_chat_auth_needed": "Агент просить вас увійти. Ви входите через сам агент; SolidCraft ніколи не бачить вашого пароля чи ключів.", diff --git a/assets/locales/vi.json b/assets/locales/vi.json index 3ab576d973f..bff3d029cd8 100644 --- a/assets/locales/vi.json +++ b/assets/locales/vi.json @@ -5513,6 +5513,7 @@ "ui.agent_chat_attach_selection_tip": "Gửi các đối tượng đang chọn trong mô hình (mặt, cạnh, tính năng, khối) kèm tin nhắn để trợ lý hiểu rõ đối tượng bạn muốn xử lý", "ui.agent_chat_attach_view": "Đính kèm góc nhìn", "ui.agent_chat_attach_view_tip": "Gửi kèm hình ảnh góc nhìn hiện tại trong tin nhắn", + "ui.agent_chat_attachable": "Hình ảnh, PDF, văn bản và tệp CAD", "ui.agent_chat_auth_agent": "Đăng nhập với {name}", "ui.agent_chat_auth_env": "Thiết lập {vars} trong biến môi trường của bạn rồi khởi động lại SolidCraft.", "ui.agent_chat_auth_needed": "AI Agent yêu cầu bạn đăng nhập. Bạn đăng nhập trực tiếp với dịch vụ của AI; SolidCraft không bao giờ thấy mật khẩu hay khóa API của bạn.", diff --git a/assets/locales/zh-TW.json b/assets/locales/zh-TW.json index d05c3504046..b73738f05da 100644 --- a/assets/locales/zh-TW.json +++ b/assets/locales/zh-TW.json @@ -4942,6 +4942,7 @@ "ui.agent_chat_attach_selection_tip": "隨消息發送模型中目前選中的內容(面、邊、特徵、實體),讓智能體知道你指的是什麼", "ui.agent_chat_attach_view": "附加視圖", "ui.agent_chat_attach_view_tip": "隨消息發送目前視圖的圖片", + "ui.agent_chat_attachable": "圖片、PDF、文本和 CAD 檔案", "ui.agent_chat_auth_agent": "使用 {name} 登錄", "ui.agent_chat_auth_env": "請在環境中設置 {vars},然後重啟 SolidCraft。", "ui.agent_chat_auth_needed": "智能體要求你登錄。登錄在智能體本身完成;SolidCraft 從不接觸你的密碼或密鑰。", diff --git a/assets/locales/zh.json b/assets/locales/zh.json index e1bb05517e4..ca4d8d391f9 100644 --- a/assets/locales/zh.json +++ b/assets/locales/zh.json @@ -5513,6 +5513,7 @@ "ui.agent_chat_attach_selection_tip": "随消息发送模型中当前选中的内容(面、边、特征、实体),让智能体知道你指的是什么", "ui.agent_chat_attach_view": "附加视图", "ui.agent_chat_attach_view_tip": "随消息发送当前视图的图片", + "ui.agent_chat_attachable": "图片、PDF、文本和 CAD 文件", "ui.agent_chat_auth_agent": "使用 {name} 登录", "ui.agent_chat_auth_env": "请在环境中设置 {vars},然后重启 SolidCraft。", "ui.agent_chat_auth_needed": "智能体要求你登录。登录在智能体本身完成;SolidCraft 从不接触你的密码或密钥。", diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 394df164249..de66c6044ce 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -77,7 +77,6 @@ proc-macro2 = { workspace = true } # egui-winit's clipboard. [target.'cfg(not(target_arch = "wasm32"))'.dependencies] arboard = { version = "3.6", default-features = false, features = ["image-data"] } -lopdf = { version = "0.45", default-features = false } [target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] wat = "1" diff --git a/crates/ui-egui/src/agent_chat/acp.rs b/crates/ui-egui/src/agent_chat/acp.rs index b75483a5d3d..afb28db2eb3 100644 --- a/crates/ui-egui/src/agent_chat/acp.rs +++ b/crates/ui-egui/src/agent_chat/acp.rs @@ -278,9 +278,7 @@ measure or inspect_design. Before building anything beyond one primitive, read ` 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 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 or asks you to. In a user message, an element whose \ -tag starts with `solidcraft-` (``, ``, ``) was added by SolidCraft, not typed by \ -the user. Keep answers short."; +tools. Read a file or folder with your own read tools only when the user attached it by path or asks you to. Keep answers short."; /// The most of the user's custom instructions (#8220) a session gets, in characters: the /// Preferences field takes no more, and a longer text from an edited settings file is cut here. @@ -1123,7 +1121,7 @@ mod tests { let mut other = json!({"cwd": "/tmp"}); turn_on_reads(&mut other, Some("s1")); assert_eq!(other, json!({"cwd": "/tmp"}), "no Claude options: nothing to change"); - assert!(SYSTEM_NOTE.contains("``") && SYSTEM_NOTE.contains("attached it by path"), "{SYSTEM_NOTE}"); + 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"]))); diff --git a/crates/ui-egui/src/agent_chat/api_client.rs b/crates/ui-egui/src/agent_chat/api_client.rs index 0e5b2fa5ff4..3f7564be848 100644 --- a/crates/ui-egui/src/agent_chat/api_client.rs +++ b/crates/ui-egui/src/agent_chat/api_client.rs @@ -27,12 +27,15 @@ const MAX_TOOL_TEXT: usize = 20_000; const MODEL_NAME_CAP: usize = 256; /// Messages kept in the conversation (the system note stays). const MAX_HISTORY: usize = 240; -/// Pictures of the view kept in the conversation. The whole history goes with every request -/// (up to `MAX_REQUESTS_PER_TURN` per message), so older views are swapped for a short note: -/// otherwise each attached view makes every later request bigger, until the endpoint refuses it. +/// Pictures, and PDFs, kept from earlier messages in the conversation (the newest message keeps +/// all of its own). The whole history goes with every request (up to `MAX_REQUESTS_PER_TURN` per +/// message), so older ones are swapped for a short note: otherwise each attached view or file +/// makes every later request bigger, until the endpoint refuses it. const MAX_HISTORY_IMAGES: usize = 2; /// What an older view becomes in the history. const DROPPED_VIEW_NOTE: &str = "[an earlier picture of the view, removed to keep the request small]"; +/// What an older PDF becomes in the history. +const DROPPED_DOCUMENT_NOTE: &str = "[an earlier PDF, removed to keep the request small]"; const DROPPED_THINKING_NOTE: &str = "[earlier reasoning, removed with older history]"; /// How long one tool call may take (it may wait for the user's Allow, declined after four /// minutes). It does not depend on the endpoint's request timeout: a tool call is SolidCraft's own @@ -296,6 +299,11 @@ fn openai_part_image_url(p: &Value) -> 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 +326,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)); } } } @@ -370,6 +382,8 @@ fn go_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})) } @@ -457,7 +471,7 @@ fn go_gemini_contents(history: &[Value], sigs: &std::collections::HashMap) -> 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}) @@ -1527,22 +1551,26 @@ fn anthropic_reply(body: &Value) -> Reply { Reply { text, calls, assistant, stop } } -/// Keeps the newest `keep` pictures of the view in the history 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 or Anthropic `image` blocks, depending on the endpoint. True when -/// a picture was swapped. +/// Keeps every picture and PDF of the newest message (the one being sent, which may carry several) +/// and the newest `keep` pictures and `keep` PDFs before it, 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 or Anthropic `image` blocks, 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).unwrap_or(history.len()); + let (mut pictures, mut documents) = (0, 0); let mut dropped = false; - for msg in history.iter_mut().rev() { + for msg in history[..newest].iter_mut().rev() { let Some(content) = msg.get_mut("content").and_then(Value::as_array_mut) else { continue }; for part in content.iter_mut().rev() { - if !matches!(part.get("type").and_then(Value::as_str), Some("image_url" | "image")) { - continue; - } - seen += 1; - if seen > keep { - *part = json!({"type": "text", "text": DROPPED_VIEW_NOTE}); + 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), + _ => continue, + }; + *seen += 1; + if *seen > keep { + *part = json!({"type": "text", "text": note}); dropped = true; } } @@ -1851,8 +1879,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})); @@ -1873,8 +1902,50 @@ 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!( + go_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] @@ -1885,11 +1956,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})); } @@ -3086,10 +3157,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); @@ -3098,10 +3172,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."}])); diff --git a/crates/ui-egui/src/agent_chat/attach.rs b/crates/ui-egui/src/agent_chat/attach.rs index cf39214f54a..5300c06d230 100644 --- a/crates/ui-egui/src/agent_chat/attach.rs +++ b/crates/ui-egui/src/agent_chat/attach.rs @@ -1,10 +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. A folder goes by its path -//! too, and past [`MAX_FILES`] files every further one does, so a batch of photos reaches the -//! agent whole however many there are. The agent is told what arrived, in order and how -//! ([`note_for`]). 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; @@ -24,22 +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 whose contents go with one message (pictures, PDFs, text, imported parts); past it, -/// a file goes by its path ([`reference`]). +/// Most files whose contents go with one message. pub const MAX_FILES: usize = 8; -/// Most files and folders on one message, those that go by their path included. +/// 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, @@ -56,6 +50,15 @@ const THUMB: u32 = 64; const PICTURE_EXTS: &[&str] = &["png", "jpg", "jpeg", "gif", "webp", "bmp", "tif", "tiff"]; /// Text sent in full; SVG goes as its source, which the agents read well. const TEXT_EXTS: &[&str] = &["svg", "txt", "md", "markdown", "json", "csv", "tsv", "yaml", "yml", "toml", "xml", "log", "ini", "cfg"]; +/// CAD files and meshes, imported into the design (the file picker's list; [`kind`] asks the +/// importers themselves). +const CAD_EXTS: &[&str] = &["step", "stp", "igs", "iges", "FCStd", "3dm", "stl", "3mf", "obj", "glb", "gltf"]; + +/// Every extension the file picker lists first, pictures first (any other file can be chosen too). +pub fn extensions() -> Vec<&'static str> { + PICTURE_EXTS.iter().chain(TEXT_EXTS).chain(CAD_EXTS).chain(&["pdf"]).copied().collect() +} + /// What a file is, by its extension. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Kind { @@ -63,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, } @@ -89,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 { @@ -101,8 +103,8 @@ pub enum Content { size: u64, mime: &'static str, }, - /// A folder the 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). + /// 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, }, @@ -110,60 +112,6 @@ pub enum Content { 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 @@ -206,6 +154,7 @@ fn mime_of(path: &Path) -> &'static str { "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", @@ -274,7 +223,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))?; @@ -300,40 +251,28 @@ 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())])); } 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 heic(path) => Err(refused("ui.agent_chat_file_heic", &name, &[])), - Kind::Other => { - let content = Content::Reference { path: absolute(path), size: meta.len(), mime: mime_of(path) }; - Ok(Attachment { id: 0, name, content, 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 => Err(refused("ui.agent_chat_file_kinds_endpoint", &name, &[])), } } -fn heic(path: &Path) -> bool { - matches!(path.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).as_deref(), Some("heic" | "heif")) -} - -/// A file the agent is pointed to instead of given, whatever its kind (one past [`MAX_FILES`]): -/// its type, size and path. Nothing of it is read, so the agent gets it whole with its own tools. +/// 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, &[])); } - if heic(path) { - return Err(refused("ui.agent_chat_file_heic", &name, &[])); - } - let content = Content::Reference { path: absolute(path), size: meta.len(), mime: mime_of(path) }; - Ok(Attachment { id: 0, name, content, thumb: None }) + 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. @@ -341,8 +280,8 @@ pub(crate) fn folder_name(path: &Path) -> String { format!("{}/", name_of(path).trim_end_matches(['/', '\\'])) } -/// A folder for a message: the agent is told where it is and lists it with its own tools. Nothing -/// in it is read here. +/// 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))?; @@ -442,12 +381,6 @@ fn encoded(name: String, img: image::DynamicImage, limit: usize) -> Result Option<[u32; 2]> { - let (w, h) = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?.into_dimensions().ok()?; - Some([w, h]) -} - /// No pixel is see-through (a screenshot or a photo, even when stored with an alpha channel). fn opaque(img: &image::DynamicImage) -> bool { !img.color().has_alpha() || img.to_rgba8().pixels().all(|p| p.0[3] == 255) @@ -459,157 +392,83 @@ fn thumbnail(img: &image::DynamicImage) -> Option> { Some(Arc::new(egui::ColorImage::from_rgba_unmultiplied(size, t.as_raw()))) } -/// How a message reaches this agent: whether it takes pictures and documents, the size of the -/// view's picture when one goes first (Attach view), and whether it has tools of its own to open -/// files by path (a coding agent does; an endpoint has only SolidCraft's). -#[derive(Clone, Copy, Debug)] -pub struct Delivery { - pub pictures: bool, - pub documents: bool, - pub view: Option<[u32; 2]>, - pub file_tools: bool, -} - -/// Text from outside (a file, a name, the design) placed inside SolidCraft's elements: a ` String { - text.replace(" String { - text.replace('&', "&").replace('"', """).replace('<', "<") -} - -/// A file's text in its own element, so a Markdown file's own fences can't end it early; -/// `escaped` says a ` String { - let body = neutralize(text); - *escaped |= body.len() != text.len(); - format!("\n\n{body}\n", attribute(name)) -} - -/// A file's text within the `left` characters the text files share, as its line in the list and -/// its element: whole when it fits; cut, saying how much is missing, when it doesn't; listed only -/// when nothing is left. -fn fit(n: usize, name: &str, what: &str, text: &str, left: &mut usize, escaped: &mut bool) -> (String, String) { +/// Add a file's text to the message under `head`, within the `left` characters shared by the +/// files: whole when it fits; cut, saying how much is missing, when it doesn't; named only when +/// nothing is left. +fn fit(out: &mut String, left: &mut usize, head: &str, text: &str) { let t = text.trim_end(); let len = t.chars().count(); if *left == 0 { - (format!("{n}. {what}, left out (the message is at its size limit): `{name}`."), String::new()) + *out += &format!("\n\n{head}: left out, the message is at its size limit."); } else if len <= *left { + *out += &format!("\n\n{head}:\n```\n{t}\n```"); *left -= len; - (format!("{n}. {what}, complete, below: `{name}`."), file_element(n, name, t, escaped)) } else { let kept: String = t.chars().take(*left).collect(); - let missing = len - *left; + *out += &format!("\n\n{head} (cut: {} more characters left out):\n```\n{kept}\n```", len - *left); *left = 0; - (format!("{n}. {what}, below, cut: `{name}`; its last {missing} characters are left out."), file_element(n, name, &kept, escaped)) } } -/// What the message says about its files, after the person's words, in one -/// `` element: every file in the order it arrives, saying how (image *n* -/// of *m*, text below, PDF document, by path, folder by path, imported into the design), the -/// view's picture first when there is one, then each text file's text in a `` element of -/// its own. The text files share `budget` characters in order (a file that doesn't fit is cut and -/// says how much is missing; one past the budget is listed only), after the list takes its room, -/// so the message stays within the prompt cap. Empty when nothing is attached. -pub fn note_for(files: &[Attachment], d: &Delivery, budget: usize) -> String { - if files.is_empty() && d.view.is_none() { - return String::new(); - } - let images = usize::from(d.view.is_some()) + if d.pictures { files.iter().filter(|f| f.is_picture()).count() } else { 0 }; - let mut lines: Vec> = Vec::new(); - let mut image = 0; - if let Some([w, h]) = d.view { - image += 1; - lines.push(Some(format!("1. Image {image} of {images}: a picture of the design's current view (Attach view), {w}×{h} px."))); +/// What the message says about its files, after the person's words: the text files' text, and the +/// pictures and imported parts by name (the agent sees the pictures themselves as images). +/// `pictures_sent` and `documents_sent`: whether this agent takes pictures and PDFs. The text files share `budget` characters +/// in order: one that doesn't fit is cut and says how much is missing, and one past the budget +/// is named only, so the message stays within the prompt cap. +pub fn note(files: &[Attachment], pictures_sent: bool, documents_sent: bool, budget: usize) -> String { + let mut out = String::new(); + let pictures: Vec<&str> = files.iter().filter(|f| f.is_picture()).map(|f| f.name.as_str()).collect(); + if !pictures.is_empty() { + let list = pictures.join(", "); + out += &if pictures_sent { + format!("\n\nAttached pictures: {list}.") + } else { + format!("\n\n(Pictures attached but not sent, this agent takes none: {list}.)") + }; } - let first = lines.len() + 1; - let mut by_path = false; - // The lines that need no budget first; a text file's line waits for its share. - for (i, f) in files.iter().enumerate() { - let n = first + i; - let name = &f.name; - let line = match &f.content { - Content::Picture { size: [w, h], .. } if d.pictures => { - image += 1; - Some(format!("{n}. Image {image} of {images}: `{name}`, {w}×{h} px.")) - } - Content::Picture { .. } => Some(format!("{n}. Picture not sent, this agent takes none: `{name}`.")), - Content::Text(_) => None, - Content::Pdf { path, bytes, .. } if d.documents => { - Some(format!("{n}. PDF document, sent with this message: `{name}` ({}) at {}.", size_text(bytes.len() as u64), path.display())) + let mut left = budget; + for f in files { + match &f.content { + Content::Text(t) => fit(&mut out, &mut left, &format!("Attached file `{}`", f.name), t), + Content::Pdf { path, bytes, .. } if documents_sent => { + out += &format!( + "\n\nAttached PDF `{}` ({}, at {}): sent with this message as a document.", + f.name, + size_text(bytes.len() as u64), + path.display() + ); } - Content::Pdf { text: Some(t), .. } if !t.text.trim().is_empty() => None, - Content::Pdf { path, bytes, text } => { - by_path = true; - let why = if text.is_some() { "no text could be taken from it (scanned or protected)" } else { "its text could not be read" }; - Some(format!("{n}. PDF by path, not in this message: `{name}` ({}) at {}; {why}.", size_text(bytes.len() as u64), 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 } => { - by_path = true; - Some(format!("{n}. By path, not in this message: `{name}` ({mime}, {}) at {}.", size_text(*size), path.display())) + out += &format!( + "\n\nAttached file `{}` ({mime}, {}, at {}): read it with your own tools; it is not in this message.", + f.name, + size_text(*size), + path.display() + ); } Content::Folder { path } => { - by_path = true; - Some(format!("{n}. Folder by path, not in this message: `{name}` at {}.", path.display())) - } - Content::Imported => Some(format!("{n}. Imported into the design as a component of its own: `{name}`.")), - }; - lines.push(line); - } - // The list takes its room (a text file's line estimated) before the text files share the rest. - let listed: usize = lines.iter().flatten().map(|l| l.chars().count() + 1).sum::() - + files.iter().filter(|f| matches!(f.content, Content::Text(_) | Content::Pdf { .. })).map(|f| f.name.chars().count() + 200).sum::(); - let mut left = budget.saturating_sub(listed + 400); - let (mut bodies, mut escaped) = (String::new(), false); - for (i, f) in files.iter().enumerate() { - let n = first + i; - let made = match &f.content { - Content::Text(t) => Some(fit(n, &f.name, &format!("Text ({})", size_text(t.len() as u64)), t, &mut left, &mut escaped)), - Content::Pdf { path, bytes, text: Some(t) } if !d.documents && !t.text.trim().is_empty() => { - let cut = if t.cut { "; cut, the rest is in the file" } else { "" }; - let what = format!( - "PDF text ({} pages, {}, at {}; its text only, without layout, pictures or fonts{cut})", - t.pages, - size_text(bytes.len() as u64), + out += &format!( + "\n\nAttached folder `{}` (at {}): read it with your own tools; its files are not in this message.", + f.name, path.display() ); - Some(fit(n, &f.name, &what, &t.text, &mut left, &mut escaped)) } - _ => None, - }; - if let Some((line, body)) = made { - lines[n - 1] = Some(line); - bodies += &body; + Content::Imported => out += &format!("\n\n(I added `{}` to the design as a component of its own.)", f.name), + Content::Picture { .. } => {} } } - let mut out = String::from("\n\n\nAttached to this message, in the order they arrive:"); - for line in lines.into_iter().flatten() { - out.push('\n'); - out += &neutralize(&line); - } - if by_path { - out += if d.file_tools { - "\nOpen what is given by path with your own read tools when you need it." - } else { - "\nYou have no tool that opens a file by its path: if you need one of them, ask the user to attach it as a picture or a text file." - }; - } - if escaped { - out += "\nIn the text below, a `"; out } -/// [`note_for`] for an agent with file tools of its own and no picture of the view. -pub fn note(files: &[Attachment], pictures_sent: bool, documents_sent: bool, budget: usize) -> String { - note_for(files, &Delivery { pictures: pictures_sent, documents: documents_sent, view: None, file_tools: true }, budget) -} - /// The pictures and PDFs as parts of the message, to the agents that take them. pub fn parts(files: &[Attachment], pictures: bool, documents: bool) -> Vec { files @@ -790,129 +649,68 @@ mod tests { let heic = d.join("photo.HEIC"); std::fs::write(&heic, b"....ftypheic").unwrap(); assert!(read(&heic).unwrap_err().contains("HEIC")); + for ext in ["png", "jpg", "jpeg", "gif", "webp", "bmp", "tiff", "svg", "md", "txt", "step", "FCStd", "3dm", "stl", "3mf", "obj", "glb"] { + assert!(extensions().contains(&ext), "{ext} can be chosen"); + } let _ = std::fs::remove_dir_all(&d); } /// Review of #1744: eight 256 KB text files took a message to about 2 MB, past the prompt cap /// that only trimmed the typed text. The files' text now gets a budget: a file that doesn't - /// fit is cut and says so, and a file past it is listed only. + /// fit is cut and says so, and a file past it is named only. #[test] fn attached_text_is_kept_within_the_prompt_budget() { - let file = |n: &str, len: usize| Attachment { id: 0, name: n.into(), content: Content::Text(Arc::new("q".repeat(len))), thumb: None }; + let file = |n: &str, len: usize| Attachment { id: 0, name: n.into(), content: Content::Text(Arc::new("x".repeat(len))), thumb: None }; let files = vec![file("a.md", 600), file("b.md", 600), file("c.md", 600)]; - // The list's room (each text file's line reserved) and the element leave 1000 characters. - let n = note(&files, true, false, 2012); - assert!(n.contains("`a.md`") && n.contains("`b.md`") && n.contains("`c.md`"), "every file is listed: {n}"); - assert!(n.chars().count() <= 2012, "the whole note stays within its budget: {} characters", n.chars().count()); - assert!(n.contains("1. Text (600 bytes), complete, below: `a.md`."), "{n}"); - assert!(n.contains("2. Text (600 bytes), below, cut: `b.md`; its last "), "a cut file says how much is missing: {n}"); - assert!( - n.contains("3. Text (600 bytes), left out (the message is at its size limit): `c.md`."), - "a file past the budget is listed only: {n}" - ); - assert_eq!(note(&files, true, false, usize::MAX).matches('q').count(), 1800, "with room, every file goes whole"); + let n = note(&files, true, false, 1000); + assert!(n.contains("`a.md`") && n.contains("`b.md`") && n.contains("`c.md`"), "every file is named: {n}"); + assert!(n.matches('x').count() <= 1000, "the files' text stays within the budget"); + assert!(n.contains("200 more characters"), "a cut file says how much is missing: {n}"); + assert!(n.contains("left out"), "a file past the budget is named only: {n}"); + assert_eq!(note(&files, true, false, usize::MAX).matches('x').count(), 1800, "with room, every file goes whole"); } - /// The note is one element SolidCraft wrote: every file in the order it arrives and how it - /// arrives, then each text file in an element of its own. #[test] - fn the_message_lists_its_files_in_order_and_carries_the_pictures() { + fn the_message_names_its_files_and_carries_the_pictures() { let pic = from_rgba("target.png".into(), 2, 2, &[9; 16]).unwrap(); let text = Attachment { id: 0, name: "brief.md".into(), content: Content::Text(Arc::new("wall 2 mm\n".into())), thumb: None }; let part = Attachment::imported("motor.step".into()); let files = vec![pic, text, part]; let n = note(&files, true, false, usize::MAX); - assert!(n.starts_with("\n\n\nAttached to this message, in the order they arrive:\n"), "{n}"); - assert!(n.ends_with("\n"), "{n}"); - assert!(n.contains("\n1. Image 1 of 1: `target.png`, 2×2 px.\n"), "{n}"); - assert!(n.contains("\n2. Text (10 bytes), complete, below: `brief.md`.\n"), "{n}"); - assert!(n.contains("\n3. Imported into the design as a component of its own: `motor.step`."), "{n}"); - assert!(n.contains("\n\nwall 2 mm\n\n"), "{n}"); - assert!(!n.contains("by path"), "nothing goes by path: {n}"); - assert!(note(&files, false, false, usize::MAX).contains("1. Picture not sent, this agent takes none: `target.png`.")); - assert_eq!(note(&[], true, true, usize::MAX), "", "no files, no note"); + assert!(n.contains("Attached pictures: target.png."), "{n}"); + assert!(n.contains("Attached file `brief.md`:\n```\nwall 2 mm\n```"), "{n}"); + assert!(n.contains("`motor.step` to the design"), "{n}"); + assert!(note(&files, false, false, usize::MAX).contains("not sent")); let p = parts(&files, true, true); assert_eq!(p.len(), 1); assert!(matches!(&p[0], PromptPart::Image { mime, base64 } if mime == "image/png" && base64.starts_with("iVBORw0KGgo"))); } - /// The view's picture goes first among the images and is named; an agent with no file tools of - /// its own (an endpoint) is told it can't open what goes by path. + /// 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 the_views_picture_comes_first_and_an_endpoint_is_told_what_it_cant_open() { - let pic = from_rgba("target.png".into(), 2, 2, &[9; 16]).unwrap(); - let zip = Attachment { - id: 0, - name: "fixtures.zip".into(), - content: Content::Reference { path: "/a/fixtures.zip".into(), size: 3000, mime: "application/zip" }, - thumb: None, - }; - let files = vec![pic, zip]; - let d = Delivery { pictures: true, documents: false, view: Some([960, 620]), file_tools: true }; - let n = note_for(&files, &d, usize::MAX); - assert!(n.contains("\n1. Image 1 of 2: a picture of the design's current view (Attach view), 960×620 px.\n"), "{n}"); - assert!(n.contains("\n2. Image 2 of 2: `target.png`, 2×2 px.\n"), "{n}"); - assert!(n.contains("\n3. By path, not in this message: `fixtures.zip` (application/zip, 3 KB) at "), "{n}"); - assert!(n.contains("\nOpen what is given by path with your own read tools when you need it."), "{n}"); - let endpoint = note_for(&files, &Delivery { file_tools: false, ..d }, usize::MAX); - assert!(endpoint.contains("You have no tool that opens a file by its path"), "{endpoint}"); - assert!(!endpoint.contains("your own read tools"), "{endpoint}"); - let view_only = note_for(&[], &d, usize::MAX); - assert!(view_only.contains("1. Image 1 of 1: a picture of the design's current view"), "the view alone is still named: {view_only}"); - } - - /// A Markdown file's own code fences stay inside its element, and text that would close - /// SolidCraft's elements (in a file or in a name) is written so it can't. - #[test] - fn a_files_text_cant_end_its_element_early() { - let md = "# Build\n```sh\ncargo run\n```\nThen and as words.\n"; - let a = Attachment { id: 0, name: "README.md".into(), content: Content::Text(Arc::new(md.into())), thumb: None }; - let odd = Attachment { id: 0, name: "a\".md".into(), content: Content::Text(Arc::new("x".into())), thumb: None }; - let n = note(&[a, odd], true, true, usize::MAX); - assert!( - n.contains( - "\n# Build\n```sh\ncargo run\n```\nThen <\\/file> and <\\/solidcraft-attachments> as words.\n" - ), - "{n}" - ); - assert_eq!(n.matches("").count(), 1, "only the real end: {n}"); - assert_eq!(n.matches("").count(), 2, "one end per file: {n}"); - assert!(n.contains("name=\"a"</solidcraft-attachments>.md\""), "{n}"); - assert!(n.contains("a `"), "a <\\/file b <\\/solidcraft-note c

"); - } - - /// Any file that is neither a picture, text, CAD nor a PDF goes by its path (its type, size - /// and place) instead of being refused; the agent reads it with its own tools. - #[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("1. By path, not in this message: `fixtures.zip` (application/zip, 3 KB) at "), "{n}"); - assert!(n.contains("fixtures.zip.\nOpen what is given by path with your own read 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); } - /// Past the files whose contents go with a message, a file of any kind goes by its path: - /// nothing of it is read, and the message points the agent to it. HEIC is refused here too. + /// 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 a_file_by_its_path_is_left_whole() { crate::i18n::install(); @@ -925,14 +723,25 @@ mod tests { 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("1. By path, not in this message: `IMG_0001.JPG` (image/jpeg, "), "{n}"); + 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!(reference(&heic).unwrap_err().contains("HEIC")); + 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); @@ -953,8 +762,8 @@ mod tests { 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("1. Folder by path, not in this message: `site photos/` at "), "{n}"); - assert!(n.contains("\nOpen what is given by path with your own read tools"), "{n}"); + 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"); @@ -962,29 +771,11 @@ mod tests { let _ = std::fs::remove_dir_all(&d); } - /// With many files by path, the list takes its room before the text files share the rest, so - /// the whole note stays within its budget. + /// 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 the_note_stays_within_its_budget_with_many_files_by_path() { - let place = |i: usize| Attachment { - id: 0, - name: format!("photo {i}.jpg"), - content: Content::Reference { path: format!("/site/photos/photo {i}.jpg").into(), size: 3_100_000, mime: "image/jpeg" }, - thumb: None, - }; - let text = Attachment { id: 0, name: "a.md".into(), content: Content::Text(Arc::new("q".repeat(20_000))), thumb: None }; - let mut files = vec![text]; - files.extend((0..40).map(place)); - let budget = 8000; - let n = note(&files, true, true, budget); - assert!(n.chars().count() <= budget, "{} characters", n.chars().count()); - assert!(n.contains("`photo 39.jpg`") && n.contains("Text (20 KB), below, cut: `a.md`"), "{n}"); - } - - /// A PDF goes whole as a document to an agent that takes them (and is named with its path); - /// to one that doesn't, and when it is too big to send, the agent is pointed to the file. - #[test] - fn pdfs_go_as_documents_or_by_reference() { + 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(); @@ -997,16 +788,13 @@ mod tests { assert_eq!((name.as_str(), mime.as_str()), ("brief 1.pdf", "application/pdf")); assert!(uri.starts_with("file://") && uri.ends_with("/brief%201.pdf"), "{uri}"); assert!(base64.starts_with("JVBERi0"), "the PDF's bytes: {base64}"); - assert!(note(&files, false, true, usize::MAX).contains("1. PDF document, sent with this message: `brief 1.pdf` (15 bytes) at ")); + assert!(note(&files, false, true, usize::MAX).contains("sent with this message as a document")); assert!(parts(&files, true, false).is_empty(), "an agent with no documents gets none"); let n = note(&files, true, false, usize::MAX); - assert!(n.contains("1. PDF by path, not in this message: `brief 1.pdf` (15 bytes) at "), "{n}"); - assert!(n.contains("its text could not be read.\nOpen what is given by path"), "{n}"); + 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 _ = std::fs::remove_dir_all(&d); } @@ -1017,107 +805,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("1. PDF text (2 pages, "), "{n}"); - assert!(n.contains("its text only, without layout, pictures or fonts), complete, below: `brief.pdf`.") && n.contains("Wall 2 mm"), "{n}"); - let short = note(&files, false, false, 5); - assert!(short.contains("left out (the message is at its size limit)"), "the text shares the message's budget: {short}"); - let with = note(&files, false, true, usize::MAX); - assert!(with.contains("PDF document, sent with this message") && !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/context.rs b/crates/ui-egui/src/agent_chat/context.rs index 52d287b20de..66fbe8f821d 100644 --- a/crates/ui-egui/src/agent_chat/context.rs +++ b/crates/ui-egui/src/agent_chat/context.rs @@ -360,15 +360,9 @@ pub fn current_sels(session: &Session, entry: &Entry, names: &mut NameCache) -> } /// The message as the agent gets it: the text, then what was selected. -/// The message with what was picked or selected after it, in a `` element: -/// SolidCraft wrote it, not the user (names from the design can't close it). pub fn with_context(text: &str, context: &Context) -> String { let block = context.prompt_block(); - if block.is_empty() { - text.to_string() - } else { - format!("{text}\n\n\n{}\n", super::attach::neutralize(&block)) - } + if block.is_empty() { text.to_string() } else { format!("{text}\n\n{block}") } } /// Describe what the session has selected, as what was clicked: see [`clicked`]. diff --git a/crates/ui-egui/src/agent_chat/mod.rs b/crates/ui-egui/src/agent_chat/mod.rs index b2415884908..fa56e9017b5 100644 --- a/crates/ui-egui/src/agent_chat/mod.rs +++ b/crates/ui-egui/src/agent_chat/mod.rs @@ -1476,7 +1476,7 @@ pub(crate) fn leave_document(app: &mut SolveApp) { 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."; +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; /// Most names one list of [`changed_note`] carries; the rest are counted. @@ -1809,6 +1809,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() { @@ -1828,11 +1829,11 @@ fn send_queue(app: &mut SolveApp, ctx: &egui::Context, interrupted: bool) { texts.push(pills::shift(&p.text, by)); } } - // One message carries the contents of at most MAX_FILES files, and MAX_ON_MESSAGE files in - // all with those that go by their path; the rest are named, not sent. - let (files, left) = within_caps(files); + // 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 = attach::MAX_FILES.to_string(); + 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"); @@ -1840,12 +1841,12 @@ 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 -/// [`attach::MAX_FILES`] whose contents go with it, or past [`attach::MAX_ON_MESSAGE`] in all. -fn within_caps(files: Vec) -> (Vec, Vec) { +/// 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() >= attach::MAX_ON_MESSAGE || (!f.by_place() && sent >= attach::MAX_FILES) { + if kept.len() >= max || (!f.by_place() && sent >= attach::MAX_FILES) { left.push(f.name); continue; } @@ -1950,46 +1951,28 @@ fn start_turn(app: &mut SolveApp, text: String, image: bool, at: Option, } /// Start a message; `note` goes before the text for the agent, not into the conversation, and so -/// does what changed in the design since the agent's last turn ([`changed_note`]), both in a -/// `` element. The files are listed after the text in a -/// `` element (text files in full), the view's picture first, and pictures -/// go as images to an agent that takes them. `at` is the message's place in the conversation, -/// where its picture is kept. +/// does what changed in the design since the agent's last turn ([`changed_note`]). The +/// files are named after the text (text files in full), and pictures go as images to an agent +/// that takes them. `at` is the message's place in the conversation, where its picture is kept. fn start_turn_with(app: &mut SolveApp, text: String, image: bool, at: Option, files: Vec, note: Option<&str>) { let (pictures, documents) = (app.agent_chat.images, app.agent_chat.documents); let seen = app.agent_chat.seen.as_ref().and_then(Revision::get::); let changed = seen.and_then(|seen| changed_note(&seen, &app.session.doc)); let notes: Vec<&str> = note.into_iter().chain(changed.as_deref()).collect(); - let lead = if notes.is_empty() { - text.clone() - } else { - format!("\n{}\n\n\n{text}", attach::neutralize(¬es.join("\n"))) - }; - // The view's picture is taken first: the list of what is attached names it as the first image. - let view = if image { - match crate::control::view_png(app, VIEW_IMAGE.0, VIEW_IMAGE.1) { - Ok(png) => Some(png), - Err(e) => { - log::warn!("the view's picture is left out of the prompt: {e}"); - None - } - } - } else { - None - }; - // An endpoint has only SolidCraft's tools: it can't open a file by its path. - let running = app.agent_chat.running_id.clone(); - let file_tools = !agents::entries(app).iter().any(|e| e.id == running && e.kind.is_api()); - let shown = view.as_deref().map(|png| attach::picture_size(png).unwrap_or([VIEW_IMAGE.0, VIEW_IMAGE.1])); - let delivery = attach::Delivery { pictures, documents, view: shown, file_tools }; + 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); - let about_files = attach::note_for(&files, &delivery, budget); + let about_files = attach::note(&files, pictures, documents, budget); let sent: String = format!("{lead}{about_files}").chars().take(MAX_PROMPT).collect(); let mut parts = vec![PromptPart::Text(sent)]; - if let Some(png) = view { - parts.push(PromptPart::Image { mime: "image/png".into(), base64: backend::base64(&png) }); - app.agent_chat.keep_picture(at, png); + if image { + match crate::control::view_png(app, VIEW_IMAGE.0, VIEW_IMAGE.1) { + Ok(png) => { + parts.push(PromptPart::Image { mime: "image/png".into(), base64: backend::base64(&png) }); + app.agent_chat.keep_picture(at, png); + } + Err(e) => log::warn!("the view's picture is left out of the prompt: {e}"), + } } parts.extend(attach::parts(&files, pictures, documents)); // What goes by path may be read by the agent's own read tools without asking (see `on_permission`). @@ -2024,38 +2007,17 @@ fn start_turn_with(app: &mut SolveApp, text: String, image: bool, at: Option std::result::Result { - attach_one(app, path).map(|a| a.name) -} - -/// What attaching one path did. -struct Attached { - name: String, - /// A file past [`attach::MAX_FILES`]: it goes by its path, not in the message. - past_max: bool, -} - -fn attach_one(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())])); + if takes_paths(app) { + return attach_by_path(app, path); } - let p = std::path::Path::new(path); - // A folder: the agent is told where it is, and lists it with its own tools. - if p.is_dir() { - let file = attach::folder(p)?; - warn_reads(app, &file); - return Ok(Attached { name: app.agent_chat.add_file(file), past_max: false }); - } - // Past MAX_FILES files whose contents go with the message, a file goes by its path: the agent - // reads it whole, at full size, with its own tools, and the message stays small. - if app.agent_chat.files_sent() >= attach::MAX_FILES { - let file = attach::reference(p)?; - warn_reads(app, &file); - return Ok(Attached { name: app.agent_chat.add_file(file), past_max: true }); + if app.agent_chat.files() >= attach::MAX_FILES { + return Err(trf("ui.agent_chat_files_max", &[("max", &attach::MAX_FILES.to_string())])); } + let p = std::path::Path::new(path); let file = if attach::kind(p) == attach::Kind::Cad { if !p.is_file() { return Err(trf("ui.agent_chat_file_not_a_file", &[("name", path)])); @@ -2067,7 +2029,7 @@ fn attach_one(app: &mut SolveApp, path: &str) -> std::result::Result 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)? }; + warn_reads(app); + Ok(app.agent_chat.add_file(file)) } /// The first file or folder on the chips that goes by its path, in a conversation with Claude Code /// whose read tools are still off: the chat says, once, that sending it turns them on for the rest /// of the chat (asking before every read, and reading what was sent without asking). -fn warn_reads(app: &mut SolveApp, file: &attach::Attachment) { - if !file.by_place() || app.agent_chat.reads_files || app.agent_chat.reads_warned { +fn warn_reads(app: &mut SolveApp) { + if app.agent_chat.reads_files || app.agent_chat.reads_warned { return; } if agents::current(app).is_some_and(|entry| acp::is_claude_adapter(&entry.argv)) { @@ -2100,12 +2078,13 @@ fn warn_reads(app: &mut SolveApp, file: &attach::Attachment) { } } -/// Add a picture from the clipboard (RGBA rows, as the system gives them) to the next message. +/// 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_ON_MESSAGE { - return Err(trf("ui.agent_chat_files_max", &[("max", &attach::MAX_ON_MESSAGE.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())])); } - // A pasted picture has no place to point the agent to: past MAX_FILES it can't go. if app.agent_chat.files_sent() >= attach::MAX_FILES { return Err(trf("ui.agent_chat_paste_past_max", &[("max", &attach::MAX_FILES.to_string())])); } @@ -2142,7 +2121,7 @@ pub fn take_drops(app: &mut SolveApp, ctx: &egui::Context) { return; } let files = ctx.input_mut(|i| std::mem::take(&mut i.raw.dropped_files)); - attach_paths(app, files.iter().map(|f| f.path().to_path_buf())); + attach_dropped(app, files.iter().map(|f| f.path().to_path_buf())); } /// Whether files dropped now would be the chat's: the pointer was last seen over it. @@ -2152,22 +2131,16 @@ pub(crate) fn drop_is_ours(chat: &AgentChat, ctx: &egui::Context) -> bool { ctx.input(|i| i.pointer.latest_pos()).is_some_and(|p| rect.contains(p)) } -/// Attach files and folders dropped or chosen together; a refused one says why in the -/// conversation, and files past [`attach::MAX_FILES`] going by their path are said once. -pub(crate) fn attach_paths(app: &mut SolveApp, paths: impl Iterator) { - let mut past_max = false; +/// Attach dropped files; a refused one says why in the conversation. +pub(crate) fn attach_dropped(app: &mut SolveApp, paths: impl Iterator) { for p in paths { if p.as_os_str().is_empty() { continue; } - match attach_one(app, &p.to_string_lossy()) { - Ok(a) => past_max |= a.past_max, - Err(e) => app.agent_chat.notice(e, true), + if let Err(e) = attach_path(app, &p.to_string_lossy()) { + app.agent_chat.notice(e, true); } } - if past_max { - app.agent_chat.notice(trf("ui.agent_chat_files_by_place", &[("max", &attach::MAX_FILES.to_string())]), false); - } } /// Stop: ask the agent to stop the message it is on; requests waiting for approval are declined. diff --git a/crates/ui-egui/src/agent_chat/panel.rs b/crates/ui-egui/src/agent_chat/panel.rs index e37b0c183a4..3e06016b7bc 100644 --- a/crates/ui-egui/src/agent_chat/panel.rs +++ b/crates/ui-egui/src/agent_chat/panel.rs @@ -71,11 +71,13 @@ pub enum PanelAction { at: Option, }, AttachDropped(Vec), - /// Choose files of any type to attach, one or several. + /// 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: the agent is told where each is. + /// 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, where the host's dialog can (macOS). + /// 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"))] @@ -131,10 +133,14 @@ 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_paths(app, paths.into_iter()), - PanelAction::ChooseAttachment => app.pick_files(|app, paths| attach_paths(app, paths.into_iter().map(std::path::PathBuf::from))), - PanelAction::ChooseFolder => app.pick_folders(|app, paths| attach_paths(app, paths.into_iter().map(std::path::PathBuf::from))), - PanelAction::ChooseAny => app.pick_files_or_folders(|app, paths| attach_paths(app, paths.into_iter().map(std::path::PathBuf::from))), + PanelAction::AttachDropped(paths) => attach_dropped(app, paths.into_iter()), + 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) { @@ -224,8 +230,8 @@ 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 one - /// Choose files or folders… instead of Choose files… and Choose folders…. + /// 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, } @@ -1194,7 +1200,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, view.mixed_picker, 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| { @@ -2627,11 +2633,11 @@ 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 what the agent does with it. +/// 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, .. } => format!("{}\n{}", path.display(), tr("ui.agent_chat_file_by_place_tip")), + 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(), } @@ -2756,13 +2762,17 @@ 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() }); } @@ -1624,14 +1630,7 @@ fn send_now_cancels_then_sends_with_a_note() { assert_eq!(script.calls().len(), 2); ended(&script, "cancelled"); poll(&mut app, &ctx); - assert_eq!( - script.calls(), - [ - "prompt: build a gearbox".to_string(), - "cancel".into(), - format!("prompt: \n{INTERRUPT_NOTE}\n\n\nuse 12 teeth instead") - ] - ); + assert_eq!(script.calls(), ["prompt: build a gearbox".to_string(), "cancel".into(), format!("prompt: {INTERRUPT_NOTE}\n\nuse 12 teeth instead")]); assert!(matches!(app.agent_chat.items.last(), Some(Item::User { text, .. }) if text == "use 12 teeth instead")); // Stop after Send now wins: nothing more is sent by itself. send(&mut app, &ctx, "one more".into()); @@ -1717,13 +1716,9 @@ fn a_change_by_hand_between_messages_is_told_to_the_agent() { let sent = text_of(script.prompts().last().unwrap()); // The new box may bring parameters of its own after `w`. let new = expr(&app); - assert!( - sent.starts_with(&format!("\n[The user changed the design by hand since your last reply (parameters: w {old} -> {new}")), - "{sent}" - ); - assert!(sent.contains("\n\nchamfer it"), "the note stands before the words: {sent}"); + assert!(sent.starts_with(&format!("[The user changed the design by hand since your last reply (parameters: w {old} -> {new}")), "{sent}"); assert!(sent.contains(&format!("; features: {added} (new)). Read it again before")), "{sent}"); - assert!(sent.ends_with("chat.]\n\n\nchamfer it"), "{sent}"); + assert!(sent.ends_with("chat.]\n\nchamfer it"), "{sent}"); assert!( matches!(app.agent_chat.items.iter().rev().find(|i| matches!(i, Item::User { .. })), Some(Item::User { text, .. }) if text == "chamfer it") ); @@ -1821,7 +1816,7 @@ done "session/new".into(), "session/prompt: slow job".into(), "session/cancel".into(), - format!("session/prompt: \n{INTERRUPT_NOTE}\n\n\ndo this instead"), + format!("session/prompt: {INTERRUPT_NOTE}\n\ndo this instead"), ] ); disconnect(&mut app); @@ -3173,8 +3168,7 @@ fn a_message_carries_its_files() { assert_eq!(sent.len(), 1); let text = text_of(&sent[0]); assert!(text.starts_with("make the case like this"), "{text}"); - assert!(text.contains("1. Image 1 of 1: `target.png`, 40×30 px.") && text.contains("wall 2 mm, Pi 5 inside"), "{text}"); - assert!(text.contains("") && text.trim_end().ends_with(""), "{text}"); + assert!(text.contains("Attached pictures: target.png.") && text.contains("wall 2 mm, Pi 5 inside"), "{text}"); assert_eq!(sent[0].iter().filter(|p| matches!(p, PromptPart::Image { mime, .. } if mime == "image/png")).count(), 1); assert!(app.agent_chat.attachments.is_empty(), "the files went with the message"); // The picture shows as a thumbnail with the viewer (its name is the note); the text file by name. @@ -3258,56 +3252,86 @@ fn files_wait_with_their_message_and_pictures_skip_an_agent_that_takes_none() { let _ = std::fs::remove_dir_all(&d); } -/// The contents of at most eight files go with a message; past them a file goes by its place -/// (the agent reads it with its own tools, whole), up to MAX_ON_MESSAGE in all. A pasted picture -/// has no place, so past eight it is refused and says what to do. Files that go by their place -/// don't take one of the eight. #[test] -fn past_eight_files_the_rest_go_by_their_place() { +fn at_most_eight_files_on_a_message() { let d = attachable("eight"); - let (mut app, script, ctx) = app_with_script(); - std::fs::write(d.join("fixtures.zip"), [0u8; 10]).unwrap(); - attach_path(&mut app, &at(&d, "fixtures.zip")).unwrap(); + let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); for _ in 0..attach::MAX_FILES { attach_path(&mut app, &at(&d, "brief.md")).unwrap(); } - assert!(app.agent_chat.attachments.iter().skip(1).all(|f| matches!(f.content, attach::Content::Text(_))), "the zip took none of the eight"); - attach_paths(&mut app, [at(&d, "target.png"), at(&d, "brief.md")].into_iter().map(std::path::PathBuf::from)); - assert_eq!(app.agent_chat.attachments.len(), attach::MAX_FILES + 3, "nothing refused"); - assert!(app.agent_chat.loading.is_empty(), "a file by its place is not read"); - assert!(app.agent_chat.attachments[attach::MAX_FILES + 1..].iter().all(attach::Attachment::by_place)); - let told: Vec<(&str, bool)> = app - .agent_chat - .items - .iter() - .filter_map(|i| if let Item::Notice { text, error } = i { Some((text.as_str(), *error)) } else { None }) - .filter(|(t, _)| t.contains("by their path")) - .collect(); - assert_eq!(told, [("Past 8 files, the rest go by their path: the agent reads them with its own tools", false)], "said once for the batch"); - assert!(attach_rgba(&mut app, 2, 2, &[9; 16]).unwrap_err().contains("save the picture as a file")); + assert!(attach_path(&mut app, &at(&d, "brief.md")).unwrap_err().contains('8')); + assert!(attach_rgba(&mut app, 2, 2, &[9; 16]).is_err()); + assert_eq!(app.agent_chat.attachments.len(), attach::MAX_FILES); + let ctx = egui::Context::default(); + assert!(control(&mut app, &ctx, &json!({"remove_file": 8})).is_err(), "no ninth file to take off"); + control(&mut app, &ctx, &json!({"remove_file": 0})).unwrap(); + assert_eq!(app.agent_chat.attachments.len(), attach::MAX_FILES - 1); + 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"); - assert!(control(&mut app, &ctx, &json!({"remove_file": 11})).is_err(), "no twelfth file to take off"); - control(&mut app, &ctx, &json!({"remove_file": 1})).unwrap(); - assert_eq!(app.agent_chat.attachments.len(), attach::MAX_FILES + 2); send(&mut app, &ctx, "these".into()); let sent = &script.prompts()[0]; let text = text_of(sent); - assert_eq!(pictures_in(sent), 0, "the picture past the eight goes by its place: {text}"); - assert_eq!(text.matches("complete, below: `brief.md`.").count(), attach::MAX_FILES - 1, "seven in full: {text}"); - assert!(text.contains("By path, not in this message: `target.png` (image/png, "), "{text}"); - assert_eq!(text.matches("By path, not in this message: ").count(), 3, "{text}"); - assert!(text.contains("Open what is given by path with your own read tools"), "{text}"); - let more = attach::MAX_ON_MESSAGE - app.agent_chat.files(); - for _ in 0..more { + 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); } -/// Where the host's dialogs choose files or folders but not both (Windows, Linux), the + menu has -/// Choose files… and Choose folders…, each taking several at once; where one dialog mixes them -/// (macOS), one Choose files or folders… takes both. Folders go by their path, as dropped ones do. +/// 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; @@ -3316,8 +3340,10 @@ fn the_plus_menu_chooses_several_files_and_folders() { 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 || { + 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 }) })); @@ -3341,9 +3367,9 @@ fn the_plus_menu_chooses_several_files_and_folders() { 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[2..].iter().all(attach::Attachment::by_place), "folders go by their path"); + 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(|| Box::pin(async { Vec::new() }))); + 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. @@ -3363,26 +3389,6 @@ fn the_plus_menu_chooses_several_files_and_folders() { let _ = std::fs::remove_dir_all(&d); } -/// A folder attached through the control channel, as a path, is listed off the window thread and -/// goes to the agent as its place and what it holds; a folder doesn't take one of the eight. -#[test] -fn an_attached_folder_tells_the_agent_where_it_is() { - let d = attachable("folder"); - let (mut app, script, ctx) = app_with_script(); - control(&mut app, &ctx, &json!({"attach": d.to_string_lossy()})).unwrap(); - assert!(app.agent_chat.loading.is_empty(), "nothing in it is read"); - assert_eq!(app.agent_chat.files_sent(), 0, "a folder takes none of the eight"); - for _ in 0..attach::MAX_FILES { - attach_path(&mut app, &at(&d, "brief.md")).unwrap(); - } - assert_eq!(app.agent_chat.files_sent(), attach::MAX_FILES, "eight more in full"); - send(&mut app, &ctx, "look in here".into()); - let text = text_of(&script.prompts()[0]); - assert!(text.contains(&format!("1. Folder by path, not in this message: `{}/` 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); -} - /// While the agent works, a message queues with its files: the queue shows them, Stop keeps /// them, and they go with the queue. #[test] @@ -3408,15 +3414,14 @@ fn a_queued_message_keeps_its_files_through_stop_and_sends_them() { let last = sent.last().expect("the queue went"); let text = text_of(last); assert!(text.starts_with("like this") && !text.contains("\n\n\n\n"), "a message of files alone adds no empty paragraph: {text:?}"); - assert!(text.contains("Image 1 of 1: `target.png`") && text.contains("wall 2 mm"), "{text}"); + assert!(text.contains("Attached pictures: target.png.") && text.contains("wall 2 mm"), "{text}"); assert_eq!(pictures_in(last), 1); let sent = status(&app)["items"].as_array().and_then(|i| i.last()).cloned().unwrap_or_default(); assert_eq!((sent["files"].clone(), sent["pictures"].clone()), (json!(["brief.md"]), json!(1))); let _ = std::fs::remove_dir_all(&d); } -/// Queued messages go as one prompt with at most eight files' contents; the rest are named, not -/// sent. Files that go by their place go with it whatever their number. +/// Queued messages go as one prompt with at most eight files; the rest are named, not sent. #[test] fn the_queue_sends_at_most_eight_files_and_names_the_rest() { let d = attachable("queue-cap"); @@ -3426,20 +3431,14 @@ fn the_queue_sends_at_most_eight_files_and_names_the_rest() { for _ in 0..4 { attach_path(&mut app, &at(&d, "brief.md")).unwrap(); } - app.agent_chat.add_file(attach::reference(&d.join("target.png")).unwrap()); send(&mut app, &ctx, format!("batch {n}")); } ended(&script, ""); poll(&mut app, &ctx); let sent = script.prompts(); assert_eq!(sent.len(), 2); - assert_eq!(text_of(&sent[1]).matches("complete, below: `brief.md`.").count(), attach::MAX_FILES); - assert_eq!(text_of(&sent[1]).matches("By path, not in this message: `target.png` (image/png").count(), 3, "every file by its path goes"); - let told = app - .agent_chat - .items - .iter() - .any(|i| matches!(i, Item::Notice { text, .. } if text.contains("brief.md") && text.contains('8') && !text.contains("target.png"))); + assert_eq!(text_of(&sent[1]).matches("Attached file `brief.md`").count(), attach::MAX_FILES); + let told = app.agent_chat.items.iter().any(|i| matches!(i, Item::Notice { text, .. } if text.contains("brief.md") && text.contains('8'))); assert!(told, "the files left out are named"); let _ = std::fs::remove_dir_all(&d); } @@ -3673,13 +3672,14 @@ fn assert_inside_the_panel(chips: usize) { } } -/// Many files on a message scroll in a strip of chips about three rows high, so the text box stays -/// in the panel; a message holds up to 200 files. +/// 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. #[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..40 { attach_path(&mut h.app, &at(&d, "brief.md")).unwrap(); } @@ -3751,29 +3751,39 @@ fn each_file_has_its_own_id_and_thumbnail() { let _ = std::fs::remove_dir_all(&d); } -/// The + button: "Choose files…" asks the app's dialog for files of any type (no filter: what -/// the chat can't read goes by path) 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; let d = attachable("plus"); let mut h = narrow_chat(); let chosen = at(&d, "brief.md"); - h.app.services.pick_files = Some(Box::new(move || { + let asked = std::rc::Rc::new(std::cell::RefCell::new(Vec::::new())); + let seen = asked.clone(); + 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 { vec![p] }) })); - h.app.services.pick_file = Some(Box::new(|_: &str, _: &[&str]| panic!("the filtered one-file dialog is not the chat's"))); + 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 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"])); + let exts = asked.borrow().clone(); + for ext in ["png", "jpg", "gif", "webp", "svg", "md", "step", "stl"] { + assert!(exts.iter().any(|e| e == ext), "{ext} in {exts:?}"); + } + assert!(!exts.iter().any(|e| e == "solidcraft")); attach_rgba(&mut h.app, 4, 3, &[200; 48]).unwrap(); attach_rgba(&mut h.app, 4, 3, &[200; 47]).unwrap(); settle_chat(&mut h); @@ -3862,7 +3872,7 @@ fn a_cad_file_joins_the_message_once_its_import_is_in() { h.call("ui.agent_chat", json!({"send": "fit around this"})); h.frames(2); let text = text_of(&script.prompts()[0]); - assert!(text.contains("Imported into the design as a component of its own: `block.stl`.") && !text.contains("broken.stl"), "{text}"); + assert!(text.contains("`block.stl` to the design") && !text.contains("broken.stl"), "{text}"); let _ = std::fs::remove_dir_all(&d); } @@ -4035,8 +4045,7 @@ fn an_attached_selection_goes_as_text_for_the_agent_and_as_chips_in_the_conversa app.agent_chat.attach_selection = true; send(&mut app, &ctx, "round this".into()); let prompt = script.calls().pop().expect("a prompt"); - assert!(prompt.starts_with("prompt: round this\n\n\n[Selected in SolidCraft"), "{prompt}"); - assert!(prompt.trim_end().ends_with(""), "{prompt}"); + assert!(prompt.starts_with("prompt: round this\n\n[Selected in SolidCraft"), "{prompt}"); for want in ["Elements:", "- Flat face ", "planar", "area ", "- Edge ", "length ", "name ", "Features:", "feature id", "Bodies:", "- Body1"] { assert!(prompt.contains(want), "{want:?} missing from {prompt}"); } @@ -4069,7 +4078,7 @@ fn queued_messages_keep_the_selection_they_were_typed_with() { ended(&script, ""); poll(&mut app, &ctx); let prompt = script.calls().pop().expect("the queue went"); - assert!(prompt.starts_with("prompt: second\n\nthird\n\n\n[Selected"), "{prompt}"); + assert!(prompt.starts_with("prompt: second\n\nthird\n\n[Selected"), "{prompt}"); assert!(prompt.contains("- Alpha") && prompt.contains("- Beta"), "{prompt}"); let Some(Item::User { context, .. }) = app.agent_chat.items.last() else { panic!("a sent message") }; assert_eq!(context.items.iter().map(|i| i.label.as_str()).collect::>(), ["Alpha", "Beta"]); @@ -4629,7 +4638,7 @@ fn picks_reach_the_agent_at_the_place_they_were_made() { send(&mut app, &ctx, text); let prompt = script.calls().pop().expect("a prompt"); assert!(prompt.starts_with("prompt: make «1: Flat face"), "the face picked second stands first and is 1: {prompt}"); - assert!(prompt.contains(" match «2: Body1» \n\n\n[Selected"), "the body's mark follows 'match': {prompt}"); + assert!(prompt.contains(" match «2: Body1» \n\n[Selected"), "the body's mark follows 'match': {prompt}"); let block = &prompt[prompt.find("[Selected in SolidCraft").expect("the block")..]; assert!(block.contains("stands for the numbered group below"), "{block}"); let g1 = block.find("\n«1: ").expect("group 1"); diff --git a/crates/ui-egui/src/file_picker.rs b/crates/ui-egui/src/file_picker.rs index d53d833503c..d3f422c8d8f 100644 --- a/crates/ui-egui/src/file_picker.rs +++ b/crates/ui-egui/src/file_picker.rs @@ -84,19 +84,20 @@ impl SolveApp { self.begin_picker(future, Box::new(complete)); } - /// Ask for files of any type, several at once (the agent chat's files): the host's dialog for - /// several, else one file as [`Self::pick_file`] asks. + /// 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, complete: impl FnOnce(&mut SolveApp, Vec) + 'static) { + 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(); + let future = pick(label, extensions); self.begin_file_task(future, complete); } - None => self.pick_file("", &[], move |app, path| complete(app, path.into_iter().collect())), + None => self.pick_file(label, extensions, move |app, path| complete(app, path.into_iter().collect())), } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 4bbba3e4b7a..9e9a8a98f74 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -511,10 +511,10 @@ 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 for several files of any type at once (the agent chat's files: whatever it - /// can't read goes to the agent by path, so nothing is filtered out). `None`: one file, with - /// `pick_file`. - pub pick_files: Option FilesPickerFuture>>, + /// 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 a dialog for several folders at once (the agent chat's files). `None`: one, with /// `pick_folder`. pub pick_folders: Option FilesPickerFuture>>, diff --git a/docs/agent-chat.md b/docs/agent-chat.md index c85834f247d..60b37a83f99 100644 --- a/docs/agent-chat.md +++ b/docs/agent-chat.md @@ -125,23 +125,21 @@ turn limit. Queue, Send now and Stop keep their existing behavior. ## Files and pictures -A message carries the contents of up to eight files, to show the agent what you mean: a concept -picture, a sketch, a brief, a part to fit around. More files, and folders, go by their path -(below), up to 200 on one message. - -- **+** next to **Send** has **Paste a picture** (the picture on the clipboard) and a way to choose - files and folders, several at once and of any type. On macOS it is one item, **Choose files or - folders…**. Windows' and Linux's file dialogs choose files or folders but not both, so there it - is **Choose files…** and **Choose folders…**. What happens to each file depends on its type - (below). -- **Drop files or folders on the chat.** What is dropped on the panel (or its folded strip) - attaches to the next message, and the app doesn't open it too. While files are dragged over the chat, it says +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. 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 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 pointer was last seen over the chat; **+** always works. - The files show as chips above the text box: a picture's thumbnail, the name, and × to take the file off. A picture is read off the window thread, so a large one never stops the window: its chip shows a spinner meanwhile, and **Send** waits for it. **Send** sends files with no text. - Past about three rows, the chips scroll, so the text box and the conversation stay in view. - **Pictures** (PNG, JPEG, GIF, WebP) go to the agent as they are when they are at most 2048 px on the long side and 3.75 MB (a picture's base64 then stays under 5 MB, so eight still fit in a prompt). Otherwise they are scaled down to 2048 px and re-encoded: as PNG when that fits, as @@ -156,32 +154,12 @@ picture, a sketch, a brief, a part to fit around. More files, and folders, go by 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). -- **Past eight files**, every further file goes by its path: the message tells the agent its - name, type, size and path, and the agent reads it with its own read tools. SolidCraft reads - nothing of it, so a batch of photos reaches the agent however many there are; the chat says so - once for the batch. Its chip shows the file's type instead of a thumbnail, and holding the - pointer over it shows its path. A pasted picture has no path, so past eight it is refused: save - it as a file and attach that. -- **A folder** goes by its path too, and only its path: nothing in it is listed, counted or read - (on a network share that would keep the message waiting). The agent lists it and reads the - files it needs with its own read tools. A folder or a file by its path doesn't take one of the - eight. Files other than the types above (a ZIP, a DXF) also go by their path. -- **Who can read files by path.** A coding agent (Codex, Gemini CLI…) reads them with its own - tools. Claude Code's read tools are off until a message sends a file or folder by path; the first - time one lands on the chips, the chat says that sending it turns them on for this chat. Then they - ask before every read, and the chat answers them by itself for what you sent by path - (*Auto-allowed* in the chat): any other read waits for **Allow** or **Deny** (see - [What it can't do](#what-it-cant-do)). An OpenAI- or Anthropic-compatible endpoint has only - SolidCraft's tools: it gets the eight files in the message, and the message tells it that it - can't open the others. -- **What the agent is told.** After your words, in a `` element (SolidCraft's - note tells the agent that such elements come from SolidCraft, not from you), the message lists - every file in the order it arrives and how: image *n* of *m* (the picture of the view first, when - **Attach view** is ticked), text below, PDF document, by path, folder by path, imported into the - design. Each text file follows in a `` element of its own, so a Markdown file's own code - fences can't end it early. The selection goes in a `` element, and notes - such as "the design changed since your last turn" in a `` element before your - words. +- **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. - 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 @@ -191,9 +169,30 @@ picture, a sketch, a brief, a part to fit around. More files, and folders, go by 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, the contents of at most eight; the rest are named in the chat and not sent -(files and folders by their path all go). **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. +- Claude Code's read tools are off until a message sends a file or folder by path; the first one + on the chips makes the chat say that sending it turns them on for this chat. Then they ask + before every read, and the chat answers them by itself for what you sent + (*Auto-allowed* in the chat); any other read waits for **Allow** or **Deny** (see + [What it can't do](#what-it-cant-do)). ## Typing while the agent works diff --git a/docs/control-protocol.md b/docs/control-protocol.md index f750e26f9b7..260f8fbee64 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -958,7 +958,7 @@ no box selection. | `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)}; 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 or folder's path (a picture, a text file or a CAD file, for the next message; CAD files are imported at once; a folder, and any file past the eighth, 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.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)}; 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` | | | `app.quit` | `force?` (quit without asking about unsaved designs) | `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 2e58761e66d..3b22f5ddd50 100644 --- a/docs/design/in-app-agent-chat.md +++ b/docs/design/in-app-agent-chat.md @@ -230,16 +230,22 @@ session asks it to turn them off (`_meta.claudeCode.options.disallowedTools`) an "bypass permissions". Once a message sends a file or folder by path, its read tools (Read, Glob, Grep) come on behind a `permissions.ask` rule (`_meta.claudeCode.options.settings`): a running session is opened again with `session/new` and `_meta.claudeCode.options.resume` set to its id, -which keeps the conversation (`acp::turn_on_reads`), and the message waits for its Ready. The -first such file on the chips makes the chat say so. Every read then 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 with the tools turned off again), and asks the user otherwise. Checked with -`claude-agent-acp` 0.107.0: without the rule these tools read any path without asking, and a -resumed session keeps what was said before. Other agents' own permission requests appear in the -panel with their options. +which keeps the conversation (`acp::turn_on_reads`), and the message waits for its Ready. A +session that has had no message yet can't be resumed ("Resource not found"), and has nothing to +keep, so it is opened fresh. The first such file on the chips makes the chat say so. Every read +then 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 with the tools turned off again), and asks +the user otherwise. Checked with `claude-agent-acp` 0.107.0: without the rule these tools read any +path without asking, and a resumed session keeps what was said before. 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 From 0f93d19fbae1e37f49203938cf92646fed70b541 Mon Sep 17 00:00:00 2001 From: Seth LaForge Date: Tue, 17 Nov 2026 21:34:08 -0800 Subject: [PATCH 08/12] Assistant: format the endpoint attachments test (#16452) Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/agent_chat/api_client.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/agent_chat/api_client.rs b/crates/ui-egui/src/agent_chat/api_client.rs index 3f7564be848..9ae0e62d4f0 100644 --- a/crates/ui-egui/src/agent_chat/api_client.rs +++ b/crates/ui-egui/src/agent_chat/api_client.rs @@ -1911,7 +1911,8 @@ mod tests { /// 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 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)); @@ -1926,7 +1927,8 @@ mod tests { 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(); + 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); From 9a649e7a8297585846329b5f3a884423b270d69a Mon Sep 17 00:00:00 2001 From: Seth LaForge Date: Tue, 17 Nov 2026 22:44:57 -0800 Subject: [PATCH 09/12] Assistant: New chat replaces a reopening session; only named paths read freely (#16452) Review fixes from CodeRabbit: - New chat while Claude Code's session is being opened again with its read tools on (the chat waits in Starting then) now replaces that session too, with the tools off. A fresh session drops any session request still pending, so the reopen's late reply can't bring back the old conversation. - Only a file or folder the message names may be read without asking. The lines naming files by path get their room before text files share the message's cap, and a line the cap still cuts off doesn't count. - The chip strip scrolls only past eight files; eight or fewer show whole, as on main. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/agent_chat/acp_client.rs | 22 ++++++++- crates/ui-egui/src/agent_chat/mod.rs | 32 +++++++++---- crates/ui-egui/src/agent_chat/panel.rs | 11 +++-- crates/ui-egui/src/agent_chat/tests.rs | 53 ++++++++++++++++++++- 4 files changed, 101 insertions(+), 17 deletions(-) diff --git a/crates/ui-egui/src/agent_chat/acp_client.rs b/crates/ui-egui/src/agent_chat/acp_client.rs index de9477fcb4d..8661a78f1be 100644 --- a/crates/ui-egui/src/agent_chat/acp_client.rs +++ b/crates/ui-egui/src/agent_chat/acp_client.rs @@ -106,7 +106,9 @@ impl AcpBackend { fn new_session(&mut self) { self.config_pending = None; - self.pending.retain(|_, request| *request != Pending::SetConfig); + // A session still being opened (or opened again with the read tools) is dropped too: its + // late reply must not bring back the conversation New chat cleared. + self.pending.retain(|_, request| !matches!(request, Pending::SetConfig | Pending::SessionNew | Pending::SessionResume)); let mut params = acp::session_new_params(&self.cwd, self.bridge.as_ref(), &self.init, &self.note); if self.reads_files { acp::turn_on_reads(&mut params, None); @@ -495,6 +497,24 @@ mod tests { starting.handle(Incoming::Reply { id: starting.next_id, result: Ok(json!({"sessionId":"s1"})) }, &mut events); assert!(matches!(events.last(), Some(Event::Ready { .. })), "{events:?}"); starting.shutdown(true); + + // New chat while the session is being opened again: that opening's late reply is + // dropped, so the old conversation can't come back, and the new session has them off. + let mut cleared = ready_backend().unwrap(); + cleared.prompt(&[PromptPart::Text("hello".into())]); + let mut events = Vec::new(); + cleared.handle(Incoming::Reply { id: cleared.next_id, result: Ok(json!({"stopReason":"end_turn"})) }, &mut events); + assert!(cleared.set_reads_files(true)); + let resume = cleared.next_id; + cleared.set_reads_files(false); + ChatBackend::new_session(&mut cleared); + events.clear(); + cleared.handle(Incoming::Reply { id: resume, result: Ok(json!({"sessionId":"old"})) }, &mut events); + assert!(events.is_empty(), "the reopened session's reply is dropped: {events:?}"); + cleared.handle(Incoming::Reply { id: cleared.next_id, result: Ok(json!({"sessionId":"new"})) }, &mut events); + assert!(matches!(events.last(), Some(Event::Ready { .. })), "{events:?}"); + assert_eq!((cleared.session.as_deref(), cleared.session_reads), (Some("new"), false)); + cleared.shutdown(true); } #[test] diff --git a/crates/ui-egui/src/agent_chat/mod.rs b/crates/ui-egui/src/agent_chat/mod.rs index fa56e9017b5..dfb18b01439 100644 --- a/crates/ui-egui/src/agent_chat/mod.rs +++ b/crates/ui-egui/src/agent_chat/mod.rs @@ -496,6 +496,9 @@ pub struct AgentChat { reads_files: bool, /// The chat said that sending by path turns those tools on ([`warn_reads`]). reads_warned: bool, + /// The session is being opened again with Claude Code's read tools on ([`submit`]): New chat + /// replaces it, or its reply would bring back the conversation New chat cleared. + reads_reopening: bool, /// 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` @@ -705,15 +708,18 @@ impl AgentChat { self.attachments.insert(at, file); name } - /// The files and folders of a message being sent that go by their path 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]) { + /// 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) { @@ -911,6 +917,7 @@ impl AgentChat { self.agent = agent; self.images = images; self.state = Some(State::Ready); + self.reads_reopening = false; self.picking = Some(false); // Keep the mode across a new chat. if self.config_options.is_none() @@ -1290,6 +1297,7 @@ pub fn connect(app: &mut SolveApp, ctx: &egui::Context) { Ok(mut b) => { b.set_instructions(&app.preferences.agent_instructions); b.set_reads_files(chat.reads_files); + chat.reads_reopening = false; app.preferences.agent_last = entry.id.clone(); chat.backend = Some(b); chat.argv = entry.argv.clone(); @@ -1791,6 +1799,7 @@ fn submit(app: &mut SolveApp, ctx: &egui::Context, text: String, image: bool, co if restarting && app.agent_chat.state() == State::Ready { app.agent_chat.restore_mode = Some(app.agent_chat.mode.clone()).filter(|m| !m.is_empty()); app.agent_chat.state = Some(State::Starting); + app.agent_chat.reads_reopening = true; } } match app.agent_chat.state() { @@ -1904,7 +1913,9 @@ pub fn new_chat(app: &mut SolveApp) { chat.seen = None; chat.discard_end = running; chat.model_revert = None; - if matches!(chat.state(), State::Ready | State::Busy) { + // A session being opened again with the read tools on is replaced as a ready one is. + let reopening = std::mem::take(&mut chat.reads_reopening) && chat.state() == State::Starting; + if matches!(chat.state(), State::Ready | State::Busy) || reopening { chat.restore_mode = Some(chat.mode.clone()).filter(|m| !m.is_empty()); chat.state = Some(State::Starting); if let Some(b) = chat.backend.as_mut() { @@ -1960,10 +1971,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) { @@ -1975,8 +1991,6 @@ fn start_turn_with(app: &mut SolveApp, text: String, image: bool, at: Option(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, about three and a half rows: more scroll, and the half row shows -/// that there are more. A message holds up to 200 files, which would otherwise push the -/// conversation out of the panel. +/// 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 @@ -2585,7 +2585,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 [`CHIPS_MAX_HEIGHT`] the rows scroll. +/// 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. @@ -2598,7 +2598,8 @@ fn attachment_chips(chat: &mut AgentChat, ui: &mut egui::Ui) { // 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(); - egui::ScrollArea::vertical().id_salt("sc_agent_chat_chips").max_height(CHIPS_MAX_HEIGHT).auto_shrink([false, true]).show(ui, |ui| { + 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); diff --git a/crates/ui-egui/src/agent_chat/tests.rs b/crates/ui-egui/src/agent_chat/tests.rs index f32ab36f581..5855053a404 100644 --- a/crates/ui-egui/src/agent_chat/tests.rs +++ b/crates/ui-egui/src/agent_chat/tests.rs @@ -855,6 +855,48 @@ fn the_first_message_sent_by_path_turns_the_read_tools_on() { let _ = std::fs::remove_dir_all(&d); } +/// New chat while the session is being opened again with Claude Code's read tools on replaces it +/// too, with them off, so that opening's reply can't bring back the conversation (Review: the +/// chat waits in Starting then, which New chat used to leave to the agent). +#[test] +fn new_chat_while_the_read_tools_come_on_starts_afresh() { + let d = attachable("reads-new-chat"); + let (mut app, script, ctx) = app_with_script(); + with_coding_agent(&mut app); + script.reopens_for_reads.store(true, std::sync::atomic::Ordering::Relaxed); + attach_path(&mut app, &d.to_string_lossy()).unwrap(); + send(&mut app, &ctx, "look in this folder".into()); + assert_eq!(app.agent_chat.state(), State::Starting, "the session is being opened again"); + new_chat(&mut app); + let calls = script.calls(); + assert!(calls.ends_with(&["reads: false".to_string(), "new_session".to_string()]), "{calls:?}"); + assert!(app.agent_chat.pending.is_empty() && app.agent_chat.items.is_empty()); + script.report(Event::Ready { agent: "Test".into(), images: true }); + poll(&mut app, &ctx); + assert!(script.prompts().is_empty(), "the cleared message isn't sent"); + let _ = std::fs::remove_dir_all(&d); +} + +/// A file whose line the message's cap cut off was never named to the agent, so its reads still +/// ask (Review: every file sent by path was taken as named). +#[test] +fn a_path_cut_off_by_the_cap_is_not_read_without_asking() { + let d = attachable("cut-path"); + let (mut app, script, ctx) = app_with_script(); + with_coding_agent(&mut app); + attach_path(&mut app, &at(&d, "brief.md")).unwrap(); + send(&mut app, &ctx, "x".repeat(MAX_PROMPT)); + assert!(!text_of(&script.prompts()[0]).contains("brief.md"), "cut off by the cap"); + assert!(!app.agent_chat.attached_by_path(&d.join("brief.md"))); + ended(&script, ""); + poll(&mut app, &ctx); + attach_path(&mut app, &at(&d, "brief.md")).unwrap(); + send(&mut app, &ctx, "now this".into()); + assert!(text_of(&script.prompts()[1]).contains("brief.md")); + assert!(app.agent_chat.attached_by_path(&d.join("brief.md"))); + let _ = std::fs::remove_dir_all(&d); +} + /// The first file or folder attached in a chat with Claude Code makes the chat say once that /// sending it turns Claude Code's read tools on; other agents' own tools are theirs, so nothing is /// said for them. @@ -3673,14 +3715,21 @@ 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. +/// 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..40 { + 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); From 851ce53ff7998b9512276a8d1e53bc110e34da80 Mon Sep 17 00:00:00 2001 From: Seth LaForge Date: Thu, 19 Nov 2026 16:45:59 -0800 Subject: [PATCH 10/12] Assistant: note that Claude Code's Glob and Grep don't follow links out of an attached folder (#16452) The chat sees only where a Glob or Grep starts, so a link inside an attached folder that points out of it is safe only because Claude Code's walk doesn't follow links. Record the check (claude-agent-acp 0.107.0) and that it should be repeated when the adapter's version moves. Co-Authored-By: Claude Opus 5.5 --- docs/design/in-app-agent-chat.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/docs/design/in-app-agent-chat.md b/docs/design/in-app-agent-chat.md index 3b22f5ddd50..869b913afe2 100644 --- a/docs/design/in-app-agent-chat.md +++ b/docs/design/in-app-agent-chat.md @@ -239,7 +239,13 @@ accepts only that form, with an absolute path and a pattern that can't leave it; 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 with the tools turned off again), and asks the user otherwise. Checked with `claude-agent-acp` 0.107.0: without the rule these tools read any -path without asking, and a resumed session keeps what was said before. Other agents' own +path without asking, and a resumed session keeps what was said before. 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`, From 12429b4ce36c1a94ea3c6e7408b162a54feb83d1 Mon Sep 17 00:00:00 2001 From: Seth LaForge Date: Fri, 20 Nov 2026 11:39:13 -0800 Subject: [PATCH 11/12] Assistant chat: Claude Code's read tools are on from the start; reads of what wasn't sent are declined The earlier design turned Claude Code's Read, Glob and Grep on only after the first file was sent by path, by reopening the session. That added too many edge cases (New chat during the reopen, a session still opening, a resume that fails) and did nothing for other coding agents. Turning the read tools on from the start behind the ask rule, and declining without asking any read outside what was sent by path, gives the same result much more simply. Also from review: - a PDF is read with its 12 MB limit applied to the bytes actually read; - a message whose pictures or PDFs the endpoint refuses before replying is taken out of the conversation, so later messages don't send it again; - one endpoint request carries at most 18 MB of pictures and PDFs: older ones are dropped first, and a message whose own files are over it is not sent. Co-Authored-By: Claude Opus 5.5 --- .../pending/agent-chat-files-by-place.json | 56 ++++--- crates/ui-egui/src/agent_chat/acp.rs | 75 +++------ crates/ui-egui/src/agent_chat/acp_client.rs | 130 +-------------- crates/ui-egui/src/agent_chat/api_client.rs | 147 ++++++++++++++++- crates/ui-egui/src/agent_chat/attach.rs | 11 +- crates/ui-egui/src/agent_chat/backend.rs | 10 -- crates/ui-egui/src/agent_chat/mod.rs | 65 +++----- crates/ui-egui/src/agent_chat/tests.rs | 152 +++++------------- docs/agent-chat.md | 35 ++-- docs/design/in-app-agent-chat.md | 29 ++-- 10 files changed, 308 insertions(+), 402 deletions(-) diff --git a/assets/locales/pending/agent-chat-files-by-place.json b/assets/locales/pending/agent-chat-files-by-place.json index 82dd2e76054..d6ade096c99 100644 --- a/assets/locales/pending/agent-chat-files-by-place.json +++ b/assets/locales/pending/agent-chat-files-by-place.json @@ -5,11 +5,12 @@ "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_reads_warning": "Sending a file or folder by path turns on Claude Code's read tools for this chat: it reads what you send without asking, and asks before reading anything else.", "ui.agent_chat_add_any": "Choose files or folders…", - "ui.agent_chat_reads_fresh_session": "Claude Code couldn't carry the earlier conversation over when its read tools came on, so it starts again from this message.", "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.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" }, "ar": { "ui.agent_chat_add_folder": "اختر مجلدات…", @@ -17,11 +18,12 @@ "ui.agent_chat_folder_tip": "مجلد: يُخبَر الوكيل بمكانه، ويقرأ الملفات التي يحتاجها بأدواته الخاصة", "ui.agent_chat_paste_past_max": "يُرسل {max} ملفات كحد أقصى في رسالة واحدة؛ احفظ الصورة في ملف وأرفقه بدلًا منها", "ui.ai_auto_attached": "يقرأ شيئًا أرفقته", - "ui.agent_chat_reads_warning": "إرسال ملف أو مجلد بمساره يشغّل أدوات القراءة في Claude Code لهذه المحادثة: يقرأ ما ترسله دون سؤال، ويسأل قبل قراءة أي شيء آخر.", "ui.agent_chat_add_any": "اختر ملفات أو مجلدات…", - "ui.agent_chat_reads_fresh_session": "تعذّر على Claude Code نقل المحادثة السابقة عند تشغيل أدوات القراءة، لذا يبدأ من جديد من هذه الرسالة.", "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.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": "أُزيلت هذه الرسالة وملفاتها من المحادثة؛ أرسلها مرة أخرى لإعادة المحاولة" }, "de": { "ui.agent_chat_add_folder": "Ordner auswählen…", @@ -29,11 +31,12 @@ "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_reads_warning": "Wenn Sie eine Datei oder einen Ordner über den Pfad senden, schaltet das die Lesewerkzeuge von Claude Code für diesen Chat ein: Es liest, was Sie senden, ohne Rückfrage, und fragt, bevor es etwas anderes liest.", "ui.agent_chat_add_any": "Dateien oder Ordner auswählen…", - "ui.agent_chat_reads_fresh_session": "Claude Code konnte das bisherige Gespräch beim Einschalten seiner Lesewerkzeuge nicht übernehmen und beginnt deshalb neu mit dieser Nachricht.", "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.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" }, "he": { "ui.agent_chat_add_folder": "בחירת תיקיות…", @@ -41,11 +44,12 @@ "ui.agent_chat_folder_tip": "תיקייה: הסוכן מקבל את מיקומה, וקורא את הקבצים שהוא צריך בכלים שלו", "ui.agent_chat_paste_past_max": "לכל היותר {max} קבצים בהודעה אחת; יש לשמור את התמונה כקובץ ולצרף אותו במקומה", "ui.ai_auto_attached": "הוא קורא משהו שצירפת", - "ui.agent_chat_reads_warning": "שליחת קובץ או תיקייה לפי נתיב מפעילה את כלי הקריאה של Claude Code בצ׳אט הזה: הוא קורא את מה ששלחת בלי לשאול, ושואל לפני שהוא קורא כל דבר אחר.", "ui.agent_chat_add_any": "בחירת קבצים או תיקיות…", - "ui.agent_chat_reads_fresh_session": "Claude Code לא הצליח להעביר את השיחה הקודמת כשכלי הקריאה שלו הופעלו, ולכן הוא מתחיל מחדש מההודעה הזו.", "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.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": "ההודעה הזו והקבצים שלה הוצאו מהשיחה; שלח אותה שוב כדי לנסות שוב" }, "ja": { "ui.agent_chat_add_folder": "フォルダーを選択…", @@ -53,11 +57,12 @@ "ui.agent_chat_folder_tip": "フォルダー: 場所がエージェントに伝えられ、必要なファイルはエージェントが自分のツールで読み込みます", "ui.agent_chat_paste_past_max": "1 つのメッセージで送れるファイルは {max} 個までです。画像をファイルとして保存し、そのファイルを添付してください", "ui.ai_auto_attached": "添付したものを読み込むため", - "ui.agent_chat_reads_warning": "パスでファイルやフォルダーを送ると、このチャットで Claude Code の読み取りツールがオンになります。送ったものは確認なしで読み込み、それ以外を読む前には確認します。", "ui.agent_chat_add_any": "ファイルまたはフォルダーを選択…", - "ui.agent_chat_reads_fresh_session": "読み取りツールをオンにする際に Claude Code がそれまでの会話を引き継げなかったため、このメッセージから新しく始めます。", "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.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": "このメッセージとそのファイルは会話から外されました。もう一度送ると再試行できます" }, "ko": { "ui.agent_chat_add_folder": "폴더 선택…", @@ -65,11 +70,12 @@ "ui.agent_chat_folder_tip": "폴더: 위치가 에이전트에게 전달되고, 에이전트가 필요한 파일을 자체 도구로 읽습니다", "ui.agent_chat_paste_past_max": "메시지 하나에는 파일을 최대 {max}개까지 보낼 수 있습니다. 그림을 파일로 저장한 뒤 그 파일을 첨부하세요", "ui.ai_auto_attached": "첨부한 항목을 읽음", - "ui.agent_chat_reads_warning": "경로로 파일이나 폴더를 보내면 이 채팅에서 Claude Code의 읽기 도구가 켜집니다. 보낸 항목은 묻지 않고 읽고, 그 밖의 항목을 읽기 전에는 묻습니다.", "ui.agent_chat_add_any": "파일 또는 폴더 선택…", - "ui.agent_chat_reads_fresh_session": "읽기 도구를 켜는 동안 Claude Code가 이전 대화를 이어받지 못해 이 메시지부터 새로 시작합니다.", "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.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": "이 메시지와 파일은 대화에서 빠졌습니다. 다시 시도하려면 다시 보내세요" }, "vi": { "ui.agent_chat_add_folder": "Chọn thư mục…", @@ -77,11 +83,12 @@ "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_reads_warning": "Gửi một tệp hoặc thư mục theo đường dẫn sẽ bật các công cụ đọc của Claude Code cho cuộc trò chuyện này: nó đọc những gì bạn gửi mà không hỏi, và hỏi trước khi đọc bất cứ thứ gì khác.", "ui.agent_chat_add_any": "Chọn tệp hoặc thư mục…", - "ui.agent_chat_reads_fresh_session": "Claude Code không thể chuyển cuộc trò chuyện trước khi bật công cụ đọc, nên bắt đầu lại từ tin nhắn này.", "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.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" }, "zh": { "ui.agent_chat_add_folder": "选择文件夹…", @@ -89,10 +96,11 @@ "ui.agent_chat_folder_tip": "文件夹:智能体会得知它的位置,并用自己的工具读取所需的文件", "ui.agent_chat_paste_past_max": "一条消息最多发送 {max} 个文件;请把图片另存为文件,再附加该文件", "ui.ai_auto_attached": "它读取的是你附加的内容", - "ui.agent_chat_reads_warning": "按路径发送文件或文件夹会为本次聊天开启 Claude Code 的读取工具:它会直接读取你发送的内容,读取其他任何内容前都会先询问。", "ui.agent_chat_add_any": "选择文件或文件夹…", - "ui.agent_chat_reads_fresh_session": "开启读取工具时 Claude Code 无法沿用之前的对话,因此从这条消息重新开始。", "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.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": "这条消息及其文件已从对话中移除;重新发送即可重试" } } diff --git a/crates/ui-egui/src/agent_chat/acp.rs b/crates/ui-egui/src/agent_chat/acp.rs index afb28db2eb3..4a3bf4d20ce 100644 --- a/crates/ui-egui/src/agent_chat/acp.rs +++ b/crates/ui-egui/src/agent_chat/acp.rs @@ -278,7 +278,7 @@ measure or inspect_design. Before building anything beyond one primitive, read ` 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 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 or asks you to. Keep answers short."; +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. Keep answers short."; /// The most of the user's custom instructions (#8220) a session gets, in characters: the /// Preferences field takes no more, and a longer text from an edited settings file is cut here. @@ -297,15 +297,14 @@ 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 ([`CLAUDE_ASK_TOOLS`]) are among them until the conversation sends a file or -/// folder by path ([`turn_on_reads`]). +/// Its read tools are not among them: 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. Once the conversation sends a file or folder by path they -/// are on, but every call asks (a `permissions.ask` rule in the session's settings), so the -/// question reaches the panel: the chat answers it by itself for a path the user sent -/// ([`read_path`]), and any other read waits for the user. +/// The Claude Code adapter's read tools. They are on in every session, but 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. pub const CLAUDE_ASK_TOOLS: &[&str] = &["Read", "Glob", "Grep"]; /// The `session/new` parameters. `init` is the agent's `initialize` reply: agents read the system @@ -318,8 +317,13 @@ pub fn session_new_params(cwd: &std::path::Path, bridge: Option<&McpBridge>, ini "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. - "claudeCode": {"options": {"allowDangerouslySkipPermissions": false, "disallowedTools": CLAUDE_DISALLOWED_TOOLS}}, + // 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. + "claudeCode": {"options": { + "allowDangerouslySkipPermissions": false, + "disallowedTools": CLAUDE_DISALLOWED_TOOLS, + "settings": {"permissions": {"ask": CLAUDE_ASK_TOOLS}}, + }}, }); if takes_antigravity_note(init) && let Some(meta) = meta.as_object_mut() @@ -339,22 +343,8 @@ pub fn session_new_params(cwd: &std::path::Path, bridge: Option<&McpBridge>, ini params } -/// `session/new` parameters with Claude Code's read tools on behind an ask rule -/// ([`CLAUDE_ASK_TOOLS`]); with `resume`, the session continues that conversation (the adapter's -/// `_meta.claudeCode.options.resume`), so turning them on mid-chat loses nothing. -pub fn turn_on_reads(params: &mut Value, resume: Option<&str>) { - let Some(options) = params.pointer_mut("/_meta/claudeCode/options").and_then(Value::as_object_mut) else { return }; - if let Some(off) = options.get_mut("disallowedTools").and_then(Value::as_array_mut) { - off.retain(|tool| !tool.as_str().is_some_and(|t| CLAUDE_ASK_TOOLS.contains(&t))); - } - options.insert("settings".into(), json!({"permissions": {"ask": CLAUDE_ASK_TOOLS}})); - if let Some(session) = resume { - options.insert("resume".into(), json!(session)); - } -} - -/// The agent is Claude Code's ACP adapter, the one agent whose read tools SolidCraft turns off and -/// on: its program (or the package `npx` starts) is `claude-agent-acp` or the older +/// 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| { @@ -1089,38 +1079,21 @@ mod tests { assert_eq!(config_options(&json!({"configOptions":[{"type":"select","id":"broken"}]})), ConfigParse::Invalid); } - /// A session starts with Claude Code's read tools off, as before. Turned on, they ask before - /// every call and the session resumes the same conversation; its shell, write and web tools - /// stay off either way. + /// Claude Code's read tools are on in every session and ask before every call; its shell, + /// write and web tools stay off. #[test] - fn claudes_read_tools_are_off_until_turned_on_and_then_ask() { - let off = |p: &Value| -> Vec { - p["_meta"]["claudeCode"]["options"]["disallowedTools"] - .as_array() - .map(|t| t.iter().filter_map(Value::as_str).map(str::to_string).collect()) - .unwrap_or_default() - }; - let mut p = session_new_params(std::path::Path::new("/tmp"), None, &json!({}), SYSTEM_NOTE); - for tool in ["Bash", "Write", "Read", "Glob", "Grep"] { - assert!(off(&p).iter().any(|t| t == tool), "{tool} off at first: {:?}", off(&p)); - } - assert!(p["_meta"]["claudeCode"]["options"].get("settings").is_none()); - turn_on_reads(&mut p, Some("s1")); + 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); 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(&p).iter().any(|t| t == tool), "{tool} still off: {:?}", off(&p)); + assert!(off.contains(&tool), "{tool} off: {off:?}"); } for tool in CLAUDE_ASK_TOOLS { - assert!(!off(&p).iter().any(|t| t == tool), "{tool} on: {:?}", off(&p)); + assert!(!off.contains(tool), "{tool} on: {off:?}"); } assert_eq!(options["settings"]["permissions"]["ask"], json!(["Read", "Glob", "Grep"])); - assert_eq!(options["resume"], "s1", "the same conversation goes on"); - let mut fresh = session_new_params(std::path::Path::new("/tmp"), None, &json!({}), SYSTEM_NOTE); - turn_on_reads(&mut fresh, None); - assert!(fresh["_meta"]["claudeCode"]["options"].get("resume").is_none()); - let mut other = json!({"cwd": "/tmp"}); - turn_on_reads(&mut other, Some("s1")); - assert_eq!(other, json!({"cwd": "/tmp"}), "no Claude options: nothing to change"); + 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"]))); diff --git a/crates/ui-egui/src/agent_chat/acp_client.rs b/crates/ui-egui/src/agent_chat/acp_client.rs index 8661a78f1be..b3dbdb7163f 100644 --- a/crates/ui-egui/src/agent_chat/acp_client.rs +++ b/crates/ui-egui/src/agent_chat/acp_client.rs @@ -15,8 +15,6 @@ use super::process::{AgentProcess, FromAgent}; enum Pending { Initialize, SessionNew, - /// `session/new` resuming the open session with Claude Code's read tools on. - SessionResume, Prompt, Authenticate, SetMode, @@ -39,14 +37,6 @@ pub struct AcpBackend { init: Value, /// The system note the next session gets ([`acp::system_note`]). note: String, - /// Claude Code's read tools are on (asking), for the next session ([`ChatBackend::set_reads_files`]). - reads_files: bool, - /// The session that is open, or being opened, was asked for with them on. - session_reads: bool, - /// The open session has had a message: Claude Code has its conversation on disk, so it can be - /// resumed. A session that has had none can't be ("Resource not found"), and has nothing to - /// keep. - prompted: bool, next_id: u64, pending: HashMap, session: Option, @@ -77,9 +67,6 @@ impl AcpBackend { bridge, init: Value::Null, note: acp::SYSTEM_NOTE.to_string(), - reads_files: false, - session_reads: false, - prompted: false, next_id: 0, pending: HashMap::new(), session: None, @@ -106,32 +93,11 @@ impl AcpBackend { fn new_session(&mut self) { self.config_pending = None; - // A session still being opened (or opened again with the read tools) is dropped too: its - // late reply must not bring back the conversation New chat cleared. - self.pending.retain(|_, request| !matches!(request, Pending::SetConfig | Pending::SessionNew | Pending::SessionResume)); - let mut params = acp::session_new_params(&self.cwd, self.bridge.as_ref(), &self.init, &self.note); - if self.reads_files { - acp::turn_on_reads(&mut params, None); - } - self.session_reads = self.reads_files; - self.prompted = false; + self.pending.retain(|_, request| *request != Pending::SetConfig); + let params = acp::session_new_params(&self.cwd, self.bridge.as_ref(), &self.init, &self.note); self.request(Pending::SessionNew, "session/new", params); } - /// The open session again, with Claude Code's read tools on: resumed when it has had a message, - /// so the same conversation goes on; a fresh one when it hasn't, as there is nothing to keep - /// (and Claude Code can't resume it). - fn resume_with_reads(&mut self) { - if !self.prompted { - self.new_session(); - return; - } - let mut params = acp::session_new_params(&self.cwd, self.bridge.as_ref(), &self.init, &self.note); - acp::turn_on_reads(&mut params, self.session.as_deref()); - self.session_reads = true; - self.request(Pending::SessionResume, "session/new", params); - } - fn handle(&mut self, msg: Incoming, out: &mut Vec) { match msg { Incoming::Reply { id, result } => { @@ -148,14 +114,7 @@ impl AcpBackend { self.init = v; self.new_session(); } - // Resuming with the read tools on failed: a fresh session with them, so the - // message that turned them on still goes, and the chat says what was lost. - (Pending::SessionResume, Err((code, message))) => { - log::warn!("Claude Code did not resume its session with read tools on ({code}): {message}"); - self.new_session(); - out.push(Event::Notice(solidcraft_ui_text::tr("ui.agent_chat_reads_fresh_session").to_string())); - } - (Pending::SessionNew | Pending::SessionResume, Ok(v)) => match v.get("sessionId").and_then(Value::as_str) { + (Pending::SessionNew, Ok(v)) => match v.get("sessionId").and_then(Value::as_str) { Some(s) => { // New chat has opened successfully: retire the old turn before Ready. // Its late reply and cancellation deadline must not end the new turn. @@ -164,12 +123,6 @@ impl AcpBackend { out.push(Event::TurnEnded { reason: "cancelled".into() }); } self.session = Some(s.to_string()); - // Read tools were turned on while this session was being opened: open it - // again with them on before saying it is ready. - if self.reads_files && !self.session_reads { - self.resume_with_reads(); - return; - } match acp::config_options(&v) { acp::ConfigParse::Snapshot(options) => { self.modern_config = true; @@ -308,7 +261,6 @@ impl ChatBackend for AcpBackend { fn prompt(&mut self, parts: &[PromptPart]) { if let Some(s) = self.session.clone() { - self.prompted = true; self.request(Pending::Prompt, "session/prompt", acp::prompt_params(&s, parts)); } } @@ -343,19 +295,6 @@ impl ChatBackend for AcpBackend { self.note = acp::system_note(text); } - fn set_reads_files(&mut self, on: bool) -> bool { - if on == self.reads_files { - return false; - } - self.reads_files = on; - let opening = self.pending.values().any(|p| matches!(p, Pending::SessionNew | Pending::SessionResume)); - if on && self.session.is_some() && !self.session_reads && !opening { - self.resume_with_reads(); - return true; - } - false - } - fn answer_permission(&mut self, key: u64, option: Option<&str>) { if let Some(rpc) = self.permissions.remove(&key) { self.proc.send(&acp::permission_reply(rpc, option)); @@ -454,69 +393,6 @@ mod tests { Ok(backend) } - /// Turning the read tools on in an open session opens it again before it is ready: resumed when - /// it has had a message (the same conversation goes on), fresh when it hasn't (Claude Code - /// answers "Resource not found" to resuming such a session, and there is nothing to keep). - /// Turned on while the first session is still being opened, that one is opened again as soon - /// as it answers, so no message goes out without them. A resume that fails still ends in a - /// session with them, and says so. - #[test] - fn turning_reads_on_reopens_the_session_before_it_is_ready() { - let mut backend = ready_backend().unwrap(); - assert!(backend.set_reads_files(true), "an open session is opened again"); - assert!(!backend.set_reads_files(true), "once"); - assert!(backend.pending.values().any(|p| *p == Pending::SessionNew), "no message yet: a fresh session, not a resume"); - let mut events = Vec::new(); - backend.handle(Incoming::Reply { id: backend.next_id, result: Ok(json!({"sessionId":"s2"})) }, &mut events); - assert!(matches!(events.last(), Some(Event::Ready { .. })), "{events:?}"); - backend.shutdown(true); - - let mut talked = ready_backend().unwrap(); - talked.prompt(&[PromptPart::Text("hello".into())]); - let mut events = Vec::new(); - talked.handle(Incoming::Reply { id: talked.next_id, result: Ok(json!({"stopReason":"end_turn"})) }, &mut events); - assert!(talked.set_reads_files(true)); - assert!(talked.pending.values().any(|p| *p == Pending::SessionResume), "a session that has had a message is resumed"); - events.clear(); - talked.handle(Incoming::Reply { id: talked.next_id, result: Err((-32002, "Resource not found".into())) }, &mut events); - assert!(matches!(events.as_slice(), [Event::Notice(_)]), "a failed resume is said, not an error: {events:?}"); - assert!(talked.pending.values().any(|p| *p == Pending::SessionNew), "and a fresh session with them follows"); - events.clear(); - talked.handle(Incoming::Reply { id: talked.next_id, result: Ok(json!({"sessionId":"s3"})) }, &mut events); - assert!(matches!(events.last(), Some(Event::Ready { .. })), "{events:?}"); - talked.shutdown(true); - - let ctx = StartContext { cwd: std::env::temp_dir(), bridge: None, tools: None, wake: Box::new(|| {}) }; - let mut starting = AcpBackend::start(&["sh".into(), "-c".into(), "cat >/dev/null".into()], ctx).unwrap(); - let mut events = Vec::new(); - starting.handle(Incoming::Reply { id: 1, result: Ok(json!({"agentInfo":{"name":"fake"}})) }, &mut events); - assert!(!starting.set_reads_files(true), "no session yet: it opens with them"); - starting.handle(Incoming::Reply { id: 2, result: Ok(json!({"sessionId":"s1"})) }, &mut events); - assert!(!events.iter().any(|e| matches!(e, Event::Ready { .. })), "opened again first: {events:?}"); - assert!(starting.pending.values().any(|p| *p == Pending::SessionNew), "fresh: it has had no message"); - starting.handle(Incoming::Reply { id: starting.next_id, result: Ok(json!({"sessionId":"s1"})) }, &mut events); - assert!(matches!(events.last(), Some(Event::Ready { .. })), "{events:?}"); - starting.shutdown(true); - - // New chat while the session is being opened again: that opening's late reply is - // dropped, so the old conversation can't come back, and the new session has them off. - let mut cleared = ready_backend().unwrap(); - cleared.prompt(&[PromptPart::Text("hello".into())]); - let mut events = Vec::new(); - cleared.handle(Incoming::Reply { id: cleared.next_id, result: Ok(json!({"stopReason":"end_turn"})) }, &mut events); - assert!(cleared.set_reads_files(true)); - let resume = cleared.next_id; - cleared.set_reads_files(false); - ChatBackend::new_session(&mut cleared); - events.clear(); - cleared.handle(Incoming::Reply { id: resume, result: Ok(json!({"sessionId":"old"})) }, &mut events); - assert!(events.is_empty(), "the reopened session's reply is dropped: {events:?}"); - cleared.handle(Incoming::Reply { id: cleared.next_id, result: Ok(json!({"sessionId":"new"})) }, &mut events); - assert!(matches!(events.last(), Some(Event::Ready { .. })), "{events:?}"); - assert_eq!((cleared.session.as_deref(), cleared.session_reads), (Some("new"), false)); - cleared.shutdown(true); - } - #[test] fn an_unresponsive_cancel_disconnects_the_agent() { let mut backend = ready_backend().unwrap(); diff --git a/crates/ui-egui/src/agent_chat/api_client.rs b/crates/ui-egui/src/agent_chat/api_client.rs index 9ae0e62d4f0..8685c2ec1f8 100644 --- a/crates/ui-egui/src/agent_chat/api_client.rs +++ b/crates/ui-egui/src/agent_chat/api_client.rs @@ -37,6 +37,10 @@ const DROPPED_VIEW_NOTE: &str = "[an earlier picture of the view, removed to kee /// What an older PDF becomes in the history. const DROPPED_DOCUMENT_NOTE: &str = "[an earlier PDF, removed to keep the request small]"; const DROPPED_THINKING_NOTE: &str = "[earlier reasoning, removed with older history]"; +/// The pictures and PDFs one request may carry, as sent (base64): 18 MB of files. It leaves room +/// for the words under Anthropic's 32 MB request limit and OpenAI's 32 MB of files per request. +/// Older ones go first; a message whose own are over it is refused before it is sent. +const MAX_REQUEST_MEDIA: usize = 24 * 1024 * 1024; /// How long one tool call may take (it may wait for the user's Allow, declined after four /// minutes). It does not depend on the endpoint's request timeout: a tool call is SolidCraft's own /// work and the user's answer, never a wait for the model, so a longer request timeout does not @@ -932,11 +936,30 @@ impl Worker { fn turn(&mut self, parts: Vec) { self.history.push(user_message(self.cfg.protocol, &parts)); - let dropped = drop_old_views(&mut self.history, MAX_HISTORY_IMAGES); + let mut dropped = drop_old_views(&mut self.history, MAX_HISTORY_IMAGES); + // The whole request has to fit: older pictures and PDFs go first, one kind-pair at a time. + let mut keep = MAX_HISTORY_IMAGES; + while keep > 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 @@ -958,12 +981,22 @@ impl Worker { self.emit(Event::TurnEnded { reason: "cancelled".into() }); return; } + // 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 }); } @@ -1578,6 +1611,25 @@ fn drop_old_views(history: &mut [Value], keep: usize) -> bool { 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 @@ -3188,6 +3240,99 @@ 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(), + }; + 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(); diff --git a/crates/ui-egui/src/agent_chat/attach.rs b/crates/ui-egui/src/agent_chat/attach.rs index 5300c06d230..c8016906821 100644 --- a/crates/ui-egui/src/agent_chat/attach.rs +++ b/crates/ui-egui/src/agent_chat/attach.rs @@ -254,7 +254,13 @@ pub fn read(path: &Path) -> Result { if meta.len() > 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))?; + // 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())])); + } 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")) => { @@ -795,6 +801,9 @@ mod tests { let big = d.join("drawing set.pdf"); std::fs::write(&big, vec![b'x'; usize::try_from(MAX_PDF_BYTES).unwrap() + 1]).unwrap(); 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); } diff --git a/crates/ui-egui/src/agent_chat/backend.rs b/crates/ui-egui/src/agent_chat/backend.rs index fdc405bef78..087102dd1ba 100644 --- a/crates/ui-egui/src/agent_chat/backend.rs +++ b/crates/ui-egui/src/agent_chat/backend.rs @@ -117,8 +117,6 @@ pub enum Event { }, /// Something failed; the backend is still running unless [`Event::Exited`] follows. Error(String), - /// Something the user should know that is no error: the chat goes on. - Notice(String), /// It ended; its last error output. Exited { tail: Vec, @@ -152,14 +150,6 @@ pub trait ChatBackend { /// The user's custom instructions (#8220), added to the system note of every session that /// starts after this call. The panel sets them before the first session and before New chat. fn set_instructions(&mut self, _text: &str) {} - /// Whether the agent's own read tools are on, asking before every read (only Claude Code's can - /// be told): off when a conversation starts, on once it sends a file or folder by path. Turning - /// them on in a running session resumes it with them on (the same conversation); true then, and - /// the panel waits for [`Event::Ready`] before it sends. Otherwise it applies to the next - /// session. - fn set_reads_files(&mut self, _on: bool) -> bool { - false - } /// Answer an [`Event::Permission`] with one of its options (`None`: cancelled). fn answer_permission(&mut self, key: u64, option: Option<&str>); /// Ask the backend to sign in by itself with one of its methods (it opens the browser). diff --git a/crates/ui-egui/src/agent_chat/mod.rs b/crates/ui-egui/src/agent_chat/mod.rs index dfb18b01439..baac0434239 100644 --- a/crates/ui-egui/src/agent_chat/mod.rs +++ b/crates/ui-egui/src/agent_chat/mod.rs @@ -491,14 +491,6 @@ pub struct AgentChat { /// 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, - /// This conversation sent a file or folder by path, so Claude Code's read tools are on (asking - /// before each read) for the rest of it; off again after New chat. - reads_files: bool, - /// The chat said that sending by path turns those tools on ([`warn_reads`]). - reads_warned: bool, - /// The session is being opened again with Claude Code's read tools on ([`submit`]): New chat - /// replaces it, or its reply would bring back the conversation New chat cleared. - reads_reopening: bool, /// 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` @@ -917,7 +909,6 @@ impl AgentChat { self.agent = agent; self.images = images; self.state = Some(State::Ready); - self.reads_reopening = false; self.picking = Some(false); // Keep the mode across a new chat. if self.config_options.is_none() @@ -1073,7 +1064,6 @@ impl AgentChat { } return Some(Outcome::TurnEnd); } - Event::Notice(text) => self.notice(text, false), Event::Error(e) => { self.notice(e, true); match self.state() { @@ -1296,8 +1286,6 @@ pub fn connect(app: &mut SolveApp, ctx: &egui::Context) { match started { Ok(mut b) => { b.set_instructions(&app.preferences.agent_instructions); - b.set_reads_files(chat.reads_files); - chat.reads_reopening = false; app.preferences.agent_last = entry.id.clone(); chat.backend = Some(b); chat.argv = entry.argv.clone(); @@ -1790,18 +1778,6 @@ fn submit(app: &mut SolveApp, ctx: &egui::Context, text: String, image: bool, co let at = app.agent_chat.items.len().checked_sub(1); // The agent gets the selection as text after the message; the conversation shows chips. let text = context::with_context(&text, &context); - // The first message that sends a file or folder by path turns Claude Code's read tools on: a - // running session is opened again with them (the same conversation), and the message goes once - // it is ready. - if files.iter().any(attach::Attachment::by_place) && !app.agent_chat.reads_files { - app.agent_chat.reads_files = true; - let restarting = app.agent_chat.backend.as_mut().is_some_and(|b| b.set_reads_files(true)); - if restarting && app.agent_chat.state() == State::Ready { - app.agent_chat.restore_mode = Some(app.agent_chat.mode.clone()).filter(|m| !m.is_empty()); - app.agent_chat.state = Some(State::Starting); - app.agent_chat.reads_reopening = true; - } - } match app.agent_chat.state() { State::Ready => start_turn_with(app, text, image, at, files, interrupted.then_some(INTERRUPT_NOTE)), s => { @@ -1901,8 +1877,6 @@ pub fn new_chat(app: &mut SolveApp) { chat.pending.clear(); chat.attachments.clear(); chat.by_path.clear(); - chat.reads_files = false; - chat.reads_warned = false; chat.loading.clear(); chat.pending_edit = None; chat.queued = None; @@ -1913,15 +1887,12 @@ pub fn new_chat(app: &mut SolveApp) { chat.seen = None; chat.discard_end = running; chat.model_revert = None; - // A session being opened again with the read tools on is replaced as a ready one is. - let reopening = std::mem::take(&mut chat.reads_reopening) && chat.state() == State::Starting; - if matches!(chat.state(), State::Ready | State::Busy) || reopening { + if matches!(chat.state(), State::Ready | State::Busy) { chat.restore_mode = Some(chat.mode.clone()).filter(|m| !m.is_empty()); chat.state = Some(State::Starting); if let Some(b) = chat.backend.as_mut() { // Instructions edited since the last session apply from this one on. b.set_instructions(&app.preferences.agent_instructions); - b.set_reads_files(false); b.new_session(); } } @@ -2075,23 +2046,9 @@ fn attach_by_path(app: &mut SolveApp, path: &str) -> std::result::Result std::result::Result { @@ -2222,12 +2179,24 @@ pub fn answer_permission(app: &mut SolveApp, index: usize, option: Option<&str>) /// [`acp::read_path`]); 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, reads: Option<&std::path::Path>) { + let attached = reads.is_some_and(|path| app.agent_chat.attached_by_path(path)); + // Claude Code's read tools are on in every session, but read 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. + if !attached && matches!(kind, Some("read" | "search")) && !acp::is_bridge_tool(&title, kind) && runs_claude_code(app) { + 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_for(&app.preferences, &agent); let remembered = agents::always_allowed(&app.preferences, &agent, &title); let why = if acp::is_bridge_tool(&title, kind) { Some("ui.ai_auto_ours") - } else if reads.is_some_and(|path| app.agent_chat.attached_by_path(path)) { + } else if attached { Some("ui.ai_auto_attached") } else if remembered { Some("ui.ai_auto_remembered") @@ -2250,6 +2219,12 @@ fn on_permission(app: &mut SolveApp, key: u64, title: String, kind: Option<&str> } } +/// The running agent is Claude Code's ACP adapter. +fn runs_claude_code(app: &SolveApp) -> bool { + let running = &app.agent_chat.running_id; + 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 }; diff --git a/crates/ui-egui/src/agent_chat/tests.rs b/crates/ui-egui/src/agent_chat/tests.rs index 5855053a404..cce9f3831b1 100644 --- a/crates/ui-egui/src/agent_chat/tests.rs +++ b/crates/ui-egui/src/agent_chat/tests.rs @@ -820,65 +820,8 @@ fn the_agents_own_questions_are_answered_by_the_mode_or_asked() { assert!(matches!(app.agent_chat.items.last(), Some(Item::Notice { .. })), "remembered"); } -/// Claude Code's read tools are off until a message sends a file or folder by path: then the -/// session is opened again with them on (the same conversation) and the message waits for it to be -/// ready. Later messages don't reopen it; New chat turns them off again. -#[test] -fn the_first_message_sent_by_path_turns_the_read_tools_on() { - let d = attachable("reads-on"); - let (mut app, script, ctx) = app_with_script(); - with_coding_agent(&mut app); - script.reopens_for_reads.store(true, std::sync::atomic::Ordering::Relaxed); - send(&mut app, &ctx, "hello".into()); - ended(&script, ""); - poll(&mut app, &ctx); - assert!(!script.calls().iter().any(|c| c.starts_with("reads:")), "nothing sent by path yet: {:?}", script.calls()); - attach_path(&mut app, &d.to_string_lossy()).unwrap(); - send(&mut app, &ctx, "look in this folder".into()); - assert_eq!(script.calls().iter().filter(|c| *c == "reads: true").count(), 1, "{:?}", script.calls()); - assert_eq!(script.prompts().len(), 1, "the message waits for the session to open again"); - assert_eq!(app.agent_chat.state(), State::Starting); - script.report(Event::Ready { agent: "Test".into(), images: true }); - poll(&mut app, &ctx); - assert_eq!(script.prompts().len(), 2, "sent once it is ready"); - assert!(text_of(&script.prompts()[1]).starts_with("look in this folder"), "{}", text_of(&script.prompts()[1])); - ended(&script, ""); - poll(&mut app, &ctx); - attach_path(&mut app, &d.to_string_lossy()).unwrap(); - send(&mut app, &ctx, "and again".into()); - assert_eq!(script.prompts().len(), 3, "already on: sent at once"); - assert_eq!(script.calls().iter().filter(|c| c.starts_with("reads: true")).count(), 1); - ended(&script, ""); - poll(&mut app, &ctx); - new_chat(&mut app); - assert!(script.calls().iter().any(|c| c == "reads: false"), "New chat turns them off: {:?}", script.calls()); - let _ = std::fs::remove_dir_all(&d); -} - -/// New chat while the session is being opened again with Claude Code's read tools on replaces it -/// too, with them off, so that opening's reply can't bring back the conversation (Review: the -/// chat waits in Starting then, which New chat used to leave to the agent). -#[test] -fn new_chat_while_the_read_tools_come_on_starts_afresh() { - let d = attachable("reads-new-chat"); - let (mut app, script, ctx) = app_with_script(); - with_coding_agent(&mut app); - script.reopens_for_reads.store(true, std::sync::atomic::Ordering::Relaxed); - attach_path(&mut app, &d.to_string_lossy()).unwrap(); - send(&mut app, &ctx, "look in this folder".into()); - assert_eq!(app.agent_chat.state(), State::Starting, "the session is being opened again"); - new_chat(&mut app); - let calls = script.calls(); - assert!(calls.ends_with(&["reads: false".to_string(), "new_session".to_string()]), "{calls:?}"); - assert!(app.agent_chat.pending.is_empty() && app.agent_chat.items.is_empty()); - script.report(Event::Ready { agent: "Test".into(), images: true }); - poll(&mut app, &ctx); - assert!(script.prompts().is_empty(), "the cleared message isn't sent"); - let _ = std::fs::remove_dir_all(&d); -} - -/// A file whose line the message's cap cut off was never named to the agent, so its reads still -/// ask (Review: every file sent by path was taken as named). +/// A file whose line the message's cap cut off was never named to the agent, so it doesn't count +/// as attached (Review: every file sent by path was taken as named). #[test] fn a_path_cut_off_by_the_cap_is_not_read_without_asking() { let d = attachable("cut-path"); @@ -897,84 +840,70 @@ fn a_path_cut_off_by_the_cap_is_not_read_without_asking() { let _ = std::fs::remove_dir_all(&d); } -/// The first file or folder attached in a chat with Claude Code makes the chat say once that -/// sending it turns Claude Code's read tools on; other agents' own tools are theirs, so nothing is -/// said for them. -#[test] -fn attaching_by_path_warns_once_that_it_turns_claudes_read_tools_on() { - let d = attachable("reads-warn"); - let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default()); - app.preferences.agents.push(agents::AgentConfig { - id: "codex-test".into(), - name: "Codex".into(), - command: "codex-acp".into(), - ..Default::default() - }); - with_coding_agent(&mut app); - let warnings = |app: &SolveApp| { - app.agent_chat - .items - .iter() - .filter(|i| matches!(i, Item::Notice { text, error: false } if text.contains("turns on Claude Code's read tools"))) - .count() - }; - app.agent_chat.agent_id = Some("codex-test".into()); - attach_path(&mut app, &d.to_string_lossy()).unwrap(); - assert_eq!(warnings(&app), 0, "another agent's tools are its own"); - app.agent_chat.agent_id = Some("claude-test".into()); - attach_path(&mut app, &at(&d, "brief.md")).unwrap(); - assert_eq!(warnings(&app), 1, "a file goes by its path too"); - attach_path(&mut app, &d.to_string_lossy()).unwrap(); - assert_eq!(warnings(&app), 1, "said once"); - let _ = std::fs::remove_dir_all(&d); -} - /// Claude Code's own read tools ask before every read. A read inside a file or folder sent by -/// path in this conversation is answered at once, and the chat says so; a read before anything -/// was sent, of anything else, through a link in the folder that leads out of it, or after New -/// chat waits for the user. +/// path in this conversation is answered at once, and the chat says so. Any other is declined +/// without asking, even under Allow everything with the title remembered: a read before anything +/// was sent, of anything else, stepping out of the folder, through a link in it that leads out, +/// or after New chat. Another agent's reads are its own, and go through the user's mode. #[test] -fn reads_of_what_was_sent_by_path_are_allowed_and_others_wait() { +fn claude_code_reads_only_what_was_sent_by_path() { let d = attachable("reads"); let (photos, outside) = (d.join("photos"), d.join("outside")); std::fs::create_dir_all(&photos).unwrap(); std::fs::create_dir_all(&outside).unwrap(); std::fs::write(photos.join("a.jpg"), b"x").unwrap(); std::fs::write(outside.join("secret.txt"), b"x").unwrap(); - let (mut app, _script, ctx) = app_with_script(); + let (mut app, script, ctx) = app_with_script(); with_coding_agent(&mut app); + app.agent_chat.running_id = "claude-test".into(); + app.preferences.agent_permissions.insert("claude-test".into(), agents::Mode::All); let opts = || { vec![ PermissionOption { id: "allow".into(), name: "Allow".into(), kind: "allow_once".into() }, + PermissionOption { id: "always".into(), name: "Always".into(), kind: "allow_always".into() }, PermissionOption { id: "no".into(), name: "Reject".into(), kind: "reject_once".into() }, ] }; - let asked = |app: &SolveApp| matches!(app.agent_chat.items.last(), Some(Item::Permission { answer: None, .. })); + let answer = |key: u64| script.calls().into_iter().rev().find(|c| c.starts_with(&format!("permission: {key} "))); + let declined = |key: u64| answer(key).as_deref() == Some(&*format!("permission: {key} Some(\"no\")")); let photo = photos.join("a.jpg"); + let secret = outside.join("secret.txt"); on_permission(&mut app, 1, "Read photos/a.jpg".into(), Some("read"), opts(), Some(&photo)); - assert!(asked(&app), "nothing was sent by path yet"); + assert!(declined(1), "nothing was sent by path yet: {:?}", script.calls()); + assert!(matches!(app.agent_chat.items.last(), Some(Item::Notice { text, error: false }) if text.contains("Read photos/a.jpg"))); attach_path(&mut app, &photos.to_string_lossy()).unwrap(); send(&mut app, &ctx, "look at these".into()); on_permission(&mut app, 2, "Read photos/a.jpg".into(), Some("read"), opts(), Some(&photo)); + assert_eq!(answer(2).as_deref(), Some("permission: 2 Some(\"allow\")")); assert!( matches!(app.agent_chat.items.last(), Some(Item::Notice { text, error: false }) if text.contains("Read photos/a.jpg") && text.contains("attached")), "answered at once" ); on_permission(&mut app, 3, "Find photos".into(), Some("search"), opts(), Some(&photos)); - assert!(!asked(&app), "the folder itself"); - on_permission(&mut app, 4, "Read secret.txt".into(), Some("read"), opts(), Some(&outside.join("secret.txt"))); - assert!(asked(&app), "outside what was sent"); + assert_eq!(answer(3).as_deref(), Some("permission: 3 Some(\"allow\")"), "the folder itself"); + agents::remember(&mut app.preferences, "claude-test", "Read secret.txt"); + on_permission(&mut app, 4, "Read secret.txt".into(), Some("read"), opts(), Some(&secret)); + assert!(declined(4), "outside what was sent, though remembered and under Allow everything"); on_permission(&mut app, 5, "Read secret.txt".into(), Some("read"), opts(), Some(&photos.join("../outside/secret.txt"))); - assert!(asked(&app), "stepping out of the folder"); + assert!(declined(5), "stepping out of the folder"); + on_permission(&mut app, 6, "Find /".into(), Some("search"), opts(), None); + assert!(declined(6), "a pattern that can't be checked"); #[cfg(unix)] { - std::os::unix::fs::symlink(outside.join("secret.txt"), photos.join("link.txt")).unwrap(); - on_permission(&mut app, 6, "Read link.txt".into(), Some("read"), opts(), Some(&photos.join("link.txt"))); - assert!(asked(&app), "a link in the folder that leads out of it"); + std::os::unix::fs::symlink(&secret, photos.join("link.txt")).unwrap(); + on_permission(&mut app, 7, "Read link.txt".into(), Some("read"), opts(), Some(&photos.join("link.txt"))); + assert!(declined(7), "a link in the folder that leads out of it"); } + assert!(!app.agent_chat.items.iter().any(|i| matches!(i, Item::Permission { .. })), "nothing waits for the user"); new_chat(&mut app); - on_permission(&mut app, 7, "Read photos/a.jpg".into(), Some("read"), opts(), Some(&photo)); - assert!(asked(&app), "a new chat starts with nothing sent"); + on_permission(&mut app, 8, "Read photos/a.jpg".into(), Some("read"), opts(), Some(&photo)); + assert!(declined(8), "a new chat starts with nothing sent"); + + app.agent_chat.running_id = "codex".into(); + app.preferences.agent_permissions.insert("codex".into(), agents::Mode::Ask); + app.agent_chat.items.clear(); + on_permission(&mut app, 9, "Read secret.txt".into(), Some("read"), opts(), Some(&secret)); + assert!(matches!(app.agent_chat.items.last(), Some(Item::Permission { answer: None, .. })), "another agent's read goes to the user"); let _ = std::fs::remove_dir_all(&d); } @@ -1020,9 +949,6 @@ struct Script { events: Arc>>, /// Every prompt in full (its text and pictures). prompts: Arc>>>, - /// Turning the read tools on opens the session again (as Claude Code's adapter does), so the - /// panel waits for Ready. - reopens_for_reads: Arc, } impl Script { @@ -1061,10 +987,6 @@ impl ChatBackend for Script { fn set_config_option(&mut self, id: &str, value: &str) { self.calls.lock().unwrap().push(format!("set_config_option: {id}={value}")); } - fn set_reads_files(&mut self, on: bool) -> bool { - self.calls.lock().unwrap().push(format!("reads: {on}")); - on && self.reopens_for_reads.load(std::sync::atomic::Ordering::Relaxed) - } fn authenticate(&mut self, _: &str) {} fn shutdown(&mut self, _: bool) {} } @@ -1879,7 +1801,7 @@ fn new_chat_clears_everything_and_keeps_the_agent_and_mode() { send(&mut app, &ctx, "queued".into()); assert!(new_chat_needs_confirm(&app), "a running message and a queue ask first"); new_chat(&mut app); - assert_eq!(script.calls(), ["prompt: first", "cancel", "reads: false", "new_session"], "New chat starts with the read tools off"); + assert_eq!(script.calls(), ["prompt: first", "cancel", "new_session"]); assert!(app.agent_chat.items.is_empty() && app.agent_chat.pending.is_empty()); assert_eq!(app.agent_chat.state(), State::Starting); assert_eq!(app.agent_chat.agent_id.as_deref(), Some("claude")); diff --git a/docs/agent-chat.md b/docs/agent-chat.md index 60b37a83f99..72e50dbee2a 100644 --- a/docs/agent-chat.md +++ b/docs/agent-chat.md @@ -159,7 +159,11 @@ files with its own tools: it gets every file and folder by its path instead 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. + 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 @@ -188,11 +192,12 @@ file and folder by its path, up to 200 on one message, whatever their type: - 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. -- Claude Code's read tools are off until a message sends a file or folder by path; the first one - on the chips makes the chat say that sending it turns them on for this chat. Then they ask - before every read, and the chat answers them by itself for what you sent - (*Auto-allowed* in the chat); any other read waits for **Allow** or **Deny** (see - [What it can't do](#what-it-cant-do)). +- 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 @@ -560,7 +565,8 @@ follow the agent's own mode, which you pick in the panel's header. When an agent 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*. So it does when Claude Code reads something you sent -by path in this conversation (see below). Any other question appears in the panel, including +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 the agent yourself. With **Allow everything**, or after **Always allow**, those questions are answered the same way and noted too. @@ -588,14 +594,13 @@ saves, opens or inserts. A sweep's or pattern's `path` (curve ids) and an occurr - **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 to turn off its shell, file-writing and web tools for the session. -- **Claude Code reads only what you sent, unless you allow more.** Its read tools (Read, Glob, - Grep) are off until a message sends a file or folder by path. Then the chat turns them on for the - rest of the conversation (it opens the same session again with them on, so the agent loses - nothing), and they ask before every read. The chat answers a read of a file or folder you sent by - path; any other read waits for **Allow** or **Deny**, as does a search whose pattern starts at a - root or your home folder or steps up with `..`. A path counts once links are followed, so a link - in a folder you sent that leads out of it still asks. **New chat** turns them off again; - **Allow everything** lets every read through. +- **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. 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/design/in-app-agent-chat.md b/docs/design/in-app-agent-chat.md index 869b913afe2..394bdf5991a 100644 --- a/docs/design/in-app-agent-chat.md +++ b/docs/design/in-app-agent-chat.md @@ -227,19 +227,22 @@ ACP lets the client offer a file system and a terminal; the chat offers neither, agent in an empty working folder of SolidCraft's own (`/agent-chat/work`), not the design's folder. The Claude Code adapter has shell, file and web tools of its own anyway: the session asks it to turn them off (`_meta.claudeCode.options.disallowedTools`) and not to offer -"bypass permissions". Once a message sends a file or folder by path, its read tools (Read, Glob, -Grep) come on behind a `permissions.ask` rule (`_meta.claudeCode.options.settings`): a running -session is opened again with `session/new` and `_meta.claudeCode.options.resume` set to its id, -which keeps the conversation (`acp::turn_on_reads`), and the message waits for its Ready. A -session that has had no message yet can't be resumed ("Resource not found"), and has nothing to -keep, so it is opened fresh. The first such file on the chips makes the chat say so. Every read -then 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 with the tools turned off again), and asks -the user otherwise. Checked with `claude-agent-acp` 0.107.0: without the rule these tools read any -path without asking, and a resumed session keeps what was said before. The chat sees only the +"bypass permissions". Its read tools (Read, Glob, Grep) are on in every session, 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. + +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 From 8e110697b230e3a16b9a19303278b8021c9008f3 Mon Sep 17 00:00:00 2001 From: Seth LaForge Date: Mon, 23 Nov 2026 10:02:14 -0800 Subject: [PATCH 12/12] Assistant: Claude Code's read tools fail closed when its adapter isn't recognised (#16458 review) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The read tools (Read, Glob, Grep) are on only in a session for an agent whose command names the Claude adapter, decided once when it starts; any other session keeps them in disallowedTools, so the adapter run through a wrapper script or `node …/dist/index.js` can't read at all. - The backend learns which of Claude Code's tools each call is from the adapter's `_meta.claudeCode.toolName` on its updates, and a question names its call: a question about one of its read tools is declined unless it reads what was sent, whatever command started the agent and whatever the mode. - A Claude Code read that completes without having asked (an adapter that no longer honours the session's ask rule) stops the message with an error, so the rule can't be lost quietly. Co-Authored-By: Claude Opus 5.5 --- .../pending/agent-chat-files-by-place.json | 24 ++- crates/ui-egui/src/agent_chat/acp.rs | 157 +++++++++++++++--- crates/ui-egui/src/agent_chat/acp_client.rs | 29 +++- crates/ui-egui/src/agent_chat/backend.rs | 13 ++ crates/ui-egui/src/agent_chat/mod.rs | 59 +++++-- crates/ui-egui/src/agent_chat/tests.rs | 75 +++++++-- docs/agent-chat.md | 5 +- docs/design/in-app-agent-chat.md | 11 +- 8 files changed, 312 insertions(+), 61 deletions(-) diff --git a/assets/locales/pending/agent-chat-files-by-place.json b/assets/locales/pending/agent-chat-files-by-place.json index d6ade096c99..84cfffebbfd 100644 --- a/assets/locales/pending/agent-chat-files-by-place.json +++ b/assets/locales/pending/agent-chat-files-by-place.json @@ -10,7 +10,8 @@ "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_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": "اختر مجلدات…", @@ -23,7 +24,8 @@ "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_media_message_dropped": "أُزيلت هذه الرسالة وملفاتها من المحادثة؛ أرسلها مرة أخرى لإعادة المحاولة", + "ui.ai_unasked_read": "أُوقف: شغّل Claude Code الأداة {tool} دون أن يسأل أولًا، فلم تتمكن الدردشة من التحقق مما قرأه. ربما تغيّر محوّله؛ يُرجى الإبلاغ عن ذلك." }, "de": { "ui.agent_chat_add_folder": "Ordner auswählen…", @@ -36,7 +38,8 @@ "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_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": "בחירת תיקיות…", @@ -49,7 +52,8 @@ "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_media_message_dropped": "ההודעה הזו והקבצים שלה הוצאו מהשיחה; שלח אותה שוב כדי לנסות שוב", + "ui.ai_unasked_read": "נעצר: Claude Code הפעיל את {tool} בלי לשאול קודם, ולכן הצ'אט לא יכול היה לבדוק מה הוא קרא. ייתכן שהמתאם שלו השתנה; נא לדווח על כך." }, "ja": { "ui.agent_chat_add_folder": "フォルダーを選択…", @@ -62,7 +66,8 @@ "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_media_message_dropped": "このメッセージとそのファイルは会話から外されました。もう一度送ると再試行できます", + "ui.ai_unasked_read": "停止しました: Claude Code が先に確認せずに {tool} を実行したため、チャットは読み取った内容を確認できませんでした。アダプターが変更された可能性があります。報告してください。" }, "ko": { "ui.agent_chat_add_folder": "폴더 선택…", @@ -75,7 +80,8 @@ "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_media_message_dropped": "이 메시지와 파일은 대화에서 빠졌습니다. 다시 시도하려면 다시 보내세요", + "ui.ai_unasked_read": "중지됨: Claude Code가 먼저 묻지 않고 {tool}을(를) 실행해서 채팅이 무엇을 읽었는지 확인할 수 없었습니다. 어댑터가 바뀌었을 수 있으니 신고해 주세요." }, "vi": { "ui.agent_chat_add_folder": "Chọn thư mục…", @@ -88,7 +94,8 @@ "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_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": "选择文件夹…", @@ -101,6 +108,7 @@ "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_media_message_dropped": "这条消息及其文件已从对话中移除;重新发送即可重试", + "ui.ai_unasked_read": "已停止:Claude Code 未先询问就运行了 {tool},因此聊天无法检查它读取了什么。它的适配器可能已更改;请报告此问题。" } } diff --git a/crates/ui-egui/src/agent_chat/acp.rs b/crates/ui-egui/src/agent_chat/acp.rs index fca5ab7ff32..0e65a2ece74 100644 --- a/crates/ui-egui/src/agent_chat/acp.rs +++ b/crates/ui-egui/src/agent_chat/acp.rs @@ -301,31 +301,39 @@ 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: they ask instead ([`CLAUDE_ASK_TOOLS`]). +/// 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", "Write", "Edit", "MultiEdit", "NotebookEdit", "WebFetch", "WebSearch", "Task"]; -/// The Claude Code adapter's read tools. They are on in every session, but 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. +/// 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 `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 off: Vec<&str> = + if claude { CLAUDE_DISALLOWED_TOOLS.to_vec() } else { 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 write tools are off: the agent works through SolidCraft's tools. Its - // read tools ask, so the chat sees every read. + // read tools ask, so the chat sees every read, or are off too when the adapter wasn't + // recognised. "claudeCode": {"options": { "allowDangerouslySkipPermissions": false, - "disallowedTools": CLAUDE_DISALLOWED_TOOLS, + "disallowedTools": off, "settings": {"permissions": {"ask": CLAUDE_ASK_TOOLS}}, }}, }); @@ -357,6 +365,55 @@ pub fn is_claude_adapter(argv: &[String]) -> bool { }) } +/// 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()) @@ -573,6 +630,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(Vec<(String, String)>), @@ -585,6 +645,11 @@ pub enum Incoming { 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), @@ -675,7 +740,9 @@ pub fn parse(line: &str) -> Option { }) .unwrap_or_default(); let reads = call.and_then(read_path); - Some(Incoming::Permission { rpc: id.clone(), title, kind, options, reads }) + 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(""))), @@ -702,6 +769,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, }, @@ -871,14 +939,14 @@ 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 }; - 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"])); let text = p.to_string(); assert!(!text.contains("allow-any-path") && !text.contains("TOKEN") && !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!([])); } /// #9811: the note goes by the routes an agent's `initialize` reply offers, and the standard @@ -887,7 +955,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": {}}}})); @@ -949,7 +1017,7 @@ mod tests { assert_eq!(wsl(r"\\server\share\x"), r"\\server\share\x"); let b = McpBridge { cli: r"C:\Program Files\SolidCraft\solidcraft-cli.exe".into(), port: 41234 }; - 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"])); @@ -1010,11 +1078,12 @@ 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, reads }) = 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, reads), (None, None)); assert_eq!(permission_reply(rpc.clone(), Some("allow"))["result"]["outcome"], json!({"outcome": "selected", "optionId": "allow"})); @@ -1094,11 +1163,11 @@ mod tests { assert_eq!(config_options(&json!({"configOptions":[{"type":"select","id":"broken"}]})), ConfigParse::Invalid); } - /// Claude Code's read tools are on in every session and ask before every call; its shell, - /// write and web tools stay off. + /// 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); + 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"] { @@ -1117,6 +1186,56 @@ mod tests { 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] diff --git a/crates/ui-egui/src/agent_chat/acp_client.rs b/crates/ui-egui/src/agent_chat/acp_client.rs index e491397f4dd..c2b61a45166 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,12 +250,19 @@ 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 }); + } + } Incoming::Plan(p) => out.push(Event::Plan(p)), - Incoming::Permission { rpc, title, kind, options, reads } => { + 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, reads }); + 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() }), @@ -331,6 +345,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)); } @@ -430,6 +445,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); @@ -479,7 +498,7 @@ pub fn test_agent(argv: &[String], cwd: &std::path::Path) -> Result, + /// 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 { @@ -167,6 +175,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 58863836c5f..ecf91cf5cee 100644 --- a/crates/ui-egui/src/agent_chat/mod.rs +++ b/crates/ui-egui/src/agent_chat/mod.rs @@ -1034,7 +1034,10 @@ impl AgentChat { self.push(Item::Plan(entries)); } } - Event::Permission { key, title, kind, options, reads } => return Some(Outcome::Permission { key, title, kind, options, reads }), + 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; @@ -1162,7 +1165,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, reads: Option }, + 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. @@ -2247,13 +2259,26 @@ pub fn answer_permission(app: &mut SolveApp, index: usize, option: Option<&str>) /// SolidCraft's gate, so they're allowed here (no double question, see [`acp::is_bridge_tool`]); /// 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. -fn on_permission(app: &mut SolveApp, key: u64, title: String, kind: Option<&str>, options: Vec, reads: Option<&std::path::Path>) { +/// 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's read tools are on in every session, but read 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. - if !attached && matches!(kind, Some("read" | "search")) && !acp::is_bridge_tool(&title, kind) && runs_claude_code(app) { + // 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())); @@ -2289,10 +2314,12 @@ fn on_permission(app: &mut SolveApp, key: u64, title: String, kind: Option<&str> } } -/// The running agent is Claude Code's ACP adapter. +/// 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; - agents::entries(app).iter().any(|entry| &entry.id == running && acp::is_claude_adapter(&entry.argv)) + 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) { @@ -2616,8 +2643,16 @@ pub fn poll(app: &mut SolveApp, ctx: &egui::Context) { b.answer_permission(key, None); } } - Some(Outcome::Permission { key, title, kind, options, reads }) => { - on_permission(app, key, title, kind.as_deref(), options, reads.as_deref()) + 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 => {} } diff --git a/crates/ui-egui/src/agent_chat/tests.rs b/crates/ui-egui/src/agent_chat/tests.rs index 23ed4c5b17b..3e095ecab62 100644 --- a/crates/ui-egui/src/agent_chat/tests.rs +++ b/crates/ui-egui/src/agent_chat/tests.rs @@ -923,14 +923,14 @@ fn the_agents_own_questions_are_answered_by_the_mode_or_asked() { PermissionOption { id: "no".into(), name: "Reject".into(), kind: "reject_once".into() }, ] }; - on_permission(&mut app, 1, "mcp__solidcraft-app__batch".into(), Some("other"), opts(), None); + on_permission(&mut app, 1, "mcp__solidcraft-app__batch".into(), Some("other"), opts(), None, None); assert!(matches!(app.agent_chat.items.last(), Some(Item::Notice { text, .. }) if text.contains("mcp__solidcraft-app__batch"))); - on_permission(&mut app, 2, "Run ls".into(), None, opts(), None); + on_permission(&mut app, 2, "Run ls".into(), None, opts(), None, None); assert!(matches!(app.agent_chat.items.last(), Some(Item::Permission { answer: None, .. }))); let n = app.agent_chat.items.len() - 1; answer_permission(&mut app, n, Some("always")); assert!(agents::always_allowed(&app.preferences, "claude", "Run ls")); - on_permission(&mut app, 3, "Run ls".into(), None, opts(), None); + on_permission(&mut app, 3, "Run ls".into(), None, opts(), None, None); assert!(matches!(app.agent_chat.items.last(), Some(Item::Notice { .. })), "remembered"); } @@ -982,45 +982,89 @@ fn claude_code_reads_only_what_was_sent_by_path() { let declined = |key: u64| answer(key).as_deref() == Some(&*format!("permission: {key} Some(\"no\")")); let photo = photos.join("a.jpg"); let secret = outside.join("secret.txt"); - on_permission(&mut app, 1, "Read photos/a.jpg".into(), Some("read"), opts(), Some(&photo)); + on_permission(&mut app, 1, "Read photos/a.jpg".into(), Some("read"), opts(), Some(&photo), None); assert!(declined(1), "nothing was sent by path yet: {:?}", script.calls()); assert!(matches!(app.agent_chat.items.last(), Some(Item::Notice { text, error: false }) if text.contains("Read photos/a.jpg"))); attach_path(&mut app, &photos.to_string_lossy()).unwrap(); send(&mut app, &ctx, "look at these".into()); - on_permission(&mut app, 2, "Read photos/a.jpg".into(), Some("read"), opts(), Some(&photo)); + on_permission(&mut app, 2, "Read photos/a.jpg".into(), Some("read"), opts(), Some(&photo), None); assert_eq!(answer(2).as_deref(), Some("permission: 2 Some(\"allow\")")); assert!( matches!(app.agent_chat.items.last(), Some(Item::Notice { text, error: false }) if text.contains("Read photos/a.jpg") && text.contains("attached")), "answered at once" ); - on_permission(&mut app, 3, "Find photos".into(), Some("search"), opts(), Some(&photos)); + on_permission(&mut app, 3, "Find photos".into(), Some("search"), opts(), Some(&photos), None); assert_eq!(answer(3).as_deref(), Some("permission: 3 Some(\"allow\")"), "the folder itself"); agents::remember(&mut app.preferences, "claude-test", "Read secret.txt"); - on_permission(&mut app, 4, "Read secret.txt".into(), Some("read"), opts(), Some(&secret)); + on_permission(&mut app, 4, "Read secret.txt".into(), Some("read"), opts(), Some(&secret), None); assert!(declined(4), "outside what was sent, though remembered and under Allow everything"); - on_permission(&mut app, 5, "Read secret.txt".into(), Some("read"), opts(), Some(&photos.join("../outside/secret.txt"))); + on_permission(&mut app, 5, "Read secret.txt".into(), Some("read"), opts(), Some(&photos.join("../outside/secret.txt")), None); assert!(declined(5), "stepping out of the folder"); - on_permission(&mut app, 6, "Find /".into(), Some("search"), opts(), None); + on_permission(&mut app, 6, "Find /".into(), Some("search"), opts(), None, None); assert!(declined(6), "a pattern that can't be checked"); #[cfg(unix)] { std::os::unix::fs::symlink(&secret, photos.join("link.txt")).unwrap(); - on_permission(&mut app, 7, "Read link.txt".into(), Some("read"), opts(), Some(&photos.join("link.txt"))); + on_permission(&mut app, 7, "Read link.txt".into(), Some("read"), opts(), Some(&photos.join("link.txt")), None); assert!(declined(7), "a link in the folder that leads out of it"); } assert!(!app.agent_chat.items.iter().any(|i| matches!(i, Item::Permission { .. })), "nothing waits for the user"); new_chat(&mut app); - on_permission(&mut app, 8, "Read photos/a.jpg".into(), Some("read"), opts(), Some(&photo)); + on_permission(&mut app, 8, "Read photos/a.jpg".into(), Some("read"), opts(), Some(&photo), None); assert!(declined(8), "a new chat starts with nothing sent"); app.agent_chat.running_id = "codex".into(); app.preferences.agent_permissions.insert("codex".into(), agents::Mode::Ask); app.agent_chat.items.clear(); - on_permission(&mut app, 9, "Read secret.txt".into(), Some("read"), opts(), Some(&secret)); + on_permission(&mut app, 9, "Read secret.txt".into(), Some("read"), opts(), Some(&secret), None); assert!(matches!(app.agent_chat.items.last(), Some(Item::Permission { answer: None, .. })), "another agent's read goes to the user"); let _ = std::fs::remove_dir_all(&d); } +/// Claude Code's adapter started by a command that doesn't name it (a wrapper script, `node +/// …/dist/index.js`) reads nothing unsent either, under Allow everything: a question the adapter +/// names as one of its read tools is declined, while the same question from an agent that names +/// no tool goes through the mode. A read that ran without asking stops the message (#16458 review). +#[test] +fn a_claude_adapter_started_another_way_reads_nothing_unsent() { + let d = attachable("wrapped"); + let outside = d.join("outside"); + std::fs::create_dir_all(&outside).unwrap(); + let secret = outside.join("secret.txt"); + std::fs::write(&secret, b"x").unwrap(); + let (mut app, script, ctx) = app_with_script(); + app.preferences.agents.push(agents::AgentConfig { + id: "wrapped".into(), + name: "Claude Code (wrapper)".into(), + command: "node /opt/claude/node_modules/@agentclientprotocol/claude-agent-acp/dist/index.js".into(), + ..Default::default() + }); + app.agent_chat.agent_id = Some("wrapped".into()); + app.agent_chat.running_id = "wrapped".into(); + app.preferences.agent_permissions.insert("wrapped".into(), agents::Mode::All); + assert!(!runs_claude_code(&app), "its command doesn't name the adapter"); + let opts = || { + vec![ + PermissionOption { id: "allow".into(), name: "Allow".into(), kind: "allow_once".into() }, + PermissionOption { id: "no".into(), name: "Reject".into(), kind: "reject_once".into() }, + ] + }; + let answer = |key: u64| script.calls().into_iter().rev().find(|c| c.starts_with(&format!("permission: {key} "))); + on_permission(&mut app, 1, format!("Read {}", secret.display()), Some("read"), opts(), Some(&secret), Some("Read")); + assert_eq!(answer(1).as_deref(), Some("permission: 1 Some(\"no\")"), "Read /outside under Allow everything"); + on_permission(&mut app, 2, "Find **".into(), Some("search"), opts(), None, Some("Glob")); + assert_eq!(answer(2).as_deref(), Some("permission: 2 Some(\"no\")"), "a listing it can't check"); + on_permission(&mut app, 3, format!("Read {}", secret.display()), Some("read"), opts(), Some(&secret), None); + assert_eq!(answer(3).as_deref(), Some("permission: 3 Some(\"allow\")"), "an agent naming no tool: its mode answers"); + + send(&mut app, &ctx, "look".into()); + script.report(Event::Unasked { tool: "Read".into() }); + poll(&mut app, &ctx); + assert!(script.calls().iter().any(|c| c == "cancel"), "the message stops: {:?}", script.calls()); + assert!(app.agent_chat.items.iter().any(|i| matches!(i, Item::Notice { text, error: true } if text.contains("Read")))); + let _ = std::fs::remove_dir_all(&d); +} + /// A title that only mentions SolidCraft is no tool of SolidCraft's: in every mode but Allow /// everything the user is asked, and the mode still answers when it says to. #[test] @@ -1038,17 +1082,17 @@ fn a_title_that_mentions_solidcraft_goes_through_the_users_mode() { for mode in [agents::Mode::Ask, agents::Mode::Edits] { app.preferences.agent_permissions.insert("codex".into(), mode); for (title, kind) in titles { - on_permission(&mut app, 1, title.into(), kind, opts(), None); + on_permission(&mut app, 1, title.into(), kind, opts(), None, None); assert!(matches!(app.agent_chat.items.last(), Some(Item::Permission { answer: None, .. })), "{mode:?}: {title}"); app.agent_chat.items.clear(); } // The chat's own tool stays a single question, the gate's. - on_permission(&mut app, 2, "mcp__solidcraft-app__batch".into(), Some("other"), opts(), None); + on_permission(&mut app, 2, "mcp__solidcraft-app__batch".into(), Some("other"), opts(), None, None); assert!(matches!(app.agent_chat.items.last(), Some(Item::Notice { .. })), "{mode:?}"); app.agent_chat.items.clear(); } app.preferences.agent_permissions.insert("codex".into(), agents::Mode::All); - on_permission(&mut app, 3, titles[0].0.into(), titles[0].1, opts(), None); + on_permission(&mut app, 3, titles[0].0.into(), titles[0].1, opts(), None, None); assert!(matches!(app.agent_chat.items.last(), Some(Item::Notice { .. })), "Allow everything answers it"); } @@ -1223,6 +1267,7 @@ fn a_late_sign_in_retry_or_permission_cannot_restart_a_departed_turn() { 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() }); diff --git a/docs/agent-chat.md b/docs/agent-chat.md index 03a171ad733..b8949eb967f 100644 --- a/docs/agent-chat.md +++ b/docs/agent-chat.md @@ -614,7 +614,10 @@ saves, opens or inserts. A sweep's or pattern's `path` (curve ids) and an occurr **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. + 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/design/in-app-agent-chat.md b/docs/design/in-app-agent-chat.md index 394bdf5991a..d06eed1d8f2 100644 --- a/docs/design/in-app-agent-chat.md +++ b/docs/design/in-app-agent-chat.md @@ -227,7 +227,8 @@ ACP lets the client offer a file system and a terminal; the chat offers neither, agent in an empty working folder of SolidCraft's own (`/agent-chat/work`), not the design's folder. The Claude Code adapter has shell, file and web tools of its own anyway: the session asks it to turn them off (`_meta.claudeCode.options.disallowedTools`) and not to offer -"bypass permissions". Its read tools (Read, Glob, Grep) are on in every session, behind a +"bypass permissions". Its 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 @@ -237,6 +238,14 @@ when the path, links followed, lies inside a file or folder sent by path in this `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 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