winx_code_agent/tools/
multi_file_edit.rs1use std::collections::HashSet;
17use std::sync::Arc;
18
19use tokio::sync::Mutex;
20use tracing::instrument;
21
22use crate::errors::{Result, WinxError};
23use crate::state::bash_state::BashState;
24use crate::tools::file_write_or_edit::{commit_edit, plan_edit};
25use crate::types::{normalize_thread_id, FileEditEntry, MultiFileEdit};
26
27const MAX_FILES_PER_BATCH: usize = 100;
32
33#[instrument(level = "info", skip(bash_state_arc, multi))]
34pub async fn handle_tool_call(
35 bash_state_arc: &Arc<Mutex<Option<BashState>>>,
36 multi: MultiFileEdit,
37) -> Result<String> {
38 let mut bash_state_guard = bash_state_arc.lock().await;
39
40 {
42 let bash_state = bash_state_guard.as_ref().ok_or(WinxError::BashStateNotInitialized)?;
43 let thread_id = normalize_thread_id(&multi.thread_id);
44 if thread_id != bash_state.current_thread_id {
45 return Err(WinxError::ThreadIdMismatch(thread_id));
46 }
47 }
48 if multi.files.len() < 2 {
49 return Err(WinxError::ArgumentParseError(
50 "MultiFileEdit needs at least 2 files; use FileWriteOrEdit for a single file."
51 .to_string(),
52 ));
53 }
54 if multi.files.len() > MAX_FILES_PER_BATCH {
55 return Err(WinxError::ArgumentParseError(format!(
56 "MultiFileEdit is limited to {MAX_FILES_PER_BATCH} files per batch (got {}); split the \
57 change into smaller batches.",
58 multi.files.len()
59 )));
60 }
61
62 let mut state = bash_state_guard.take().ok_or(WinxError::BashStateNotInitialized)?;
68 let files = multi.files;
69 let (state, result) = tokio::task::spawn_blocking(move || {
70 let r = apply_batch(&mut state, &files);
71 (state, r)
72 })
73 .await
74 .map_err(|e| WinxError::CommandExecutionError(format!("MultiFileEdit task failed: {e}")))?;
75 *bash_state_guard = Some(state);
76 result
77}
78
79fn apply_batch(bash_state: &mut BashState, files: &[FileEditEntry]) -> Result<String> {
83 let mut planned = Vec::with_capacity(files.len());
86 for (index, entry) in files.iter().enumerate() {
87 let edit = plan_edit(
88 bash_state,
89 &entry.file_path,
90 entry.percentage_to_change,
91 &entry.text_or_search_replace_blocks,
92 )
93 .map_err(|e| {
94 WinxError::ArgumentParseError(format!(
98 "MultiFileEdit aborted before writing anything - file {} ({}) failed validation: {e}",
99 index + 1,
100 entry.file_path
101 ))
102 })?;
103 planned.push(edit);
104 }
105
106 let mut seen = HashSet::with_capacity(planned.len());
111 for edit in &planned {
112 if !seen.insert(edit.target()) {
113 return Err(WinxError::ArgumentParseError(format!(
114 "MultiFileEdit targets '{}' more than once; edits to the same file don't compose - \
115 combine them into a single entry.",
116 edit.target()
117 )));
118 }
119 }
120
121 let total = planned.len();
125 let mut summaries = Vec::with_capacity(total);
126 for (committed, edit) in planned.into_iter().enumerate() {
127 let target = edit.target().to_string();
128 match commit_edit(bash_state, edit) {
129 Ok(summary) => summaries.push(format!("[{target}]\n{summary}")),
130 Err(e) => {
131 return Err(WinxError::CommandExecutionError(format!(
132 "MultiFileEdit: committed {committed} of {total} files, then failed writing \
133 {target}: {e}\nThe {committed} already-written file(s) were NOT rolled back. \
134 Re-read the affected files and retry the rest."
135 )));
136 }
137 }
138 }
139
140 Ok(format!("MultiFileEdit applied all {total} edits:\n\n{}", summaries.join("\n\n")))
141}