1#![allow(clippy::unwrap_used)]
2use anyhow::Result;
3use rand::RngExt;
4use serde::{Deserialize, Serialize};
5use std::collections::{HashMap, VecDeque};
6use std::path::{Path, PathBuf};
7use std::sync::Arc;
8use tokio::sync::Mutex;
9use tracing::info;
10
11use crate::state::persistence::{
12 load_bash_state as load_state_file, save_bash_state as save_state_file, BashStateSnapshot,
13};
14use crate::state::pty::PtyShell;
15use crate::types::{
16 AllowedCommands, AllowedGlobs, BashCommandMode, BashMode, FileEditMode, Modes, WriteIfEmptyMode,
17};
18
19#[derive(Debug, Clone, Serialize, Deserialize)]
20pub struct FileWhitelistData {
21 pub file_hash: String,
22 pub line_ranges_read: Vec<(usize, usize)>,
23 pub total_lines: usize,
24}
25
26fn clamped_sorted(ranges: &[(usize, usize)], total_lines: usize) -> Vec<(usize, usize)> {
29 let mut v: Vec<(usize, usize)> = ranges
30 .iter()
31 .map(|&(s, e)| (s.max(1), e.min(total_lines)))
32 .filter(|&(s, e)| s <= e)
33 .collect();
34 v.sort_unstable();
35 v
36}
37
38fn covered_line_count(ranges: &[(usize, usize)], total_lines: usize) -> usize {
41 let mut covered = 0usize;
42 let mut last_end = 0usize; for (s, e) in clamped_sorted(ranges, total_lines) {
44 let s = s.max(last_end + 1);
45 if s <= e {
46 covered += e - s + 1;
47 last_end = e;
48 }
49 }
50 covered
51}
52
53impl FileWhitelistData {
54 pub fn new(
55 file_hash: String,
56 line_ranges_read: Vec<(usize, usize)>,
57 total_lines: usize,
58 ) -> Self {
59 let mut data = Self { file_hash, line_ranges_read: Vec::new(), total_lines };
60 data.merge_ranges(line_ranges_read);
61 data
62 }
63
64 pub fn is_read_enough(&self) -> bool {
65 self.get_percentage_read() >= 99.0
66 }
67
68 #[allow(clippy::cast_precision_loss)]
69 pub fn get_percentage_read(&self) -> f64 {
70 if self.total_lines == 0 {
71 return 100.0;
72 }
73 let covered = covered_line_count(&self.line_ranges_read, self.total_lines);
77 (covered as f64 / self.total_lines as f64) * 100.0
78 }
79
80 pub fn get_unread_ranges(&self) -> Vec<(usize, usize)> {
81 if self.total_lines == 0 {
82 return vec![];
83 }
84 let sorted = clamped_sorted(&self.line_ranges_read, self.total_lines);
85 let mut unread = vec![];
86 let mut next = 1usize; for (s, e) in sorted {
88 if s > next {
89 unread.push((next, s - 1));
90 }
91 next = next.max(e.saturating_add(1));
92 }
93 if next <= self.total_lines {
94 unread.push((next, self.total_lines));
95 }
96 unread
97 }
98
99 pub fn add_range(&mut self, start: usize, end: usize) {
104 self.merge_ranges(std::iter::once((start, end)));
105 }
106
107 pub fn merge_ranges(&mut self, new: impl IntoIterator<Item = (usize, usize)>) {
110 self.line_ranges_read.extend(new);
111 self.line_ranges_read.retain(|(s, e)| s <= e);
112 self.line_ranges_read.sort_unstable();
113 let mut merged: Vec<(usize, usize)> = Vec::with_capacity(self.line_ranges_read.len());
114 for (s, e) in self.line_ranges_read.drain(..) {
115 match merged.last_mut() {
116 Some(last) if s <= last.1.saturating_add(1) => last.1 = last.1.max(e),
117 _ => merged.push((s, e)),
118 }
119 }
120 self.line_ranges_read = merged;
121 }
122
123 pub fn needs_more_reading(&self) -> bool {
124 !self.is_read_enough()
125 }
126}
127
128const EDIT_CHECKPOINT_CAP: usize = 10;
131
132const EDIT_CHECKPOINT_MAX_CONTENT_BYTES: usize = 1_000_000;
137
138#[derive(Debug, Clone)]
142pub struct EditCheckpoint {
143 pub file_path_str: String,
145 pub path: PathBuf,
146 pub prior_content: String,
148 pub prior_whitelist: Option<FileWhitelistData>,
151}
152
153#[derive(Debug, Clone)]
154pub struct BashState {
155 pub cwd: PathBuf,
156 pub workspace_root: PathBuf,
157 pub current_thread_id: String,
158 pub mode: Modes,
159 pub bash_command_mode: BashCommandMode,
160 pub file_edit_mode: FileEditMode,
161 pub write_if_empty_mode: WriteIfEmptyMode,
162 pub whitelist_for_overwrite: HashMap<String, FileWhitelistData>,
163 pub pty_shell: Arc<Mutex<Option<PtyShell>>>,
164 pub foreground_command_gate: Arc<Mutex<()>>,
167 pub initialized: bool,
168 pub edit_checkpoints: VecDeque<EditCheckpoint>,
172}
173
174impl Default for BashState {
175 fn default() -> Self {
176 Self::new()
177 }
178}
179
180impl BashState {
181 pub fn new() -> Self {
182 let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("/tmp"));
183 Self {
184 cwd: cwd.clone(),
185 workspace_root: cwd,
186 current_thread_id: generate_thread_id(),
187 mode: Modes::Wcgw,
188 bash_command_mode: BashCommandMode {
189 bash_mode: BashMode::NormalMode,
190 allowed_commands: AllowedCommands::All("all".to_string()),
191 },
192 file_edit_mode: FileEditMode { allowed_globs: AllowedGlobs::All("all".to_string()) },
193 write_if_empty_mode: WriteIfEmptyMode {
194 allowed_globs: AllowedGlobs::All("all".to_string()),
195 },
196 whitelist_for_overwrite: HashMap::new(),
197 pty_shell: Arc::new(Mutex::new(None)),
198 foreground_command_gate: Arc::new(Mutex::new(())),
199 initialized: false,
200 edit_checkpoints: VecDeque::new(),
201 }
202 }
203
204 pub fn push_edit_checkpoint(&mut self, checkpoint: EditCheckpoint) {
207 if checkpoint.prior_content.len() > EDIT_CHECKPOINT_MAX_CONTENT_BYTES {
208 info!(
209 file = %checkpoint.file_path_str,
210 "UndoEdit: not checkpointing a file over 1 MB (too large to hold in memory)"
211 );
212 return;
213 }
214 self.edit_checkpoints.push_back(checkpoint);
215 while self.edit_checkpoints.len() > EDIT_CHECKPOINT_CAP {
216 self.edit_checkpoints.pop_front();
217 }
218 }
219
220 pub fn pop_edit_checkpoint_for(&mut self, file_path_str: &str) -> Option<EditCheckpoint> {
224 let index =
225 self.edit_checkpoints.iter().rposition(|cp| cp.file_path_str == file_path_str)?;
226 self.edit_checkpoints.remove(index)
227 }
228
229 pub async fn init_pty_shell(&mut self) -> Result<()> {
230 let cwd = self.cwd.clone();
231 let restricted = self.bash_command_mode.bash_mode == BashMode::RestrictedMode;
232 let shell = tokio::task::spawn_blocking(move || PtyShell::new(&cwd, restricted))
236 .await
237 .map_err(|e| {
238 crate::errors::WinxError::ShellInitializationError(format!("PTY init task failed: {e}"))
239 })??;
240 *self.pty_shell.lock().await = Some(shell);
241 Ok(())
242 }
243
244 pub fn update_cwd(&mut self, path: &Path) -> Result<()> {
245 self.cwd = path.to_path_buf();
246 Ok(())
247 }
248
249 pub fn update_workspace_root(&mut self, path: &Path) -> Result<()> {
250 self.workspace_root = path.to_path_buf();
251 Ok(())
252 }
253
254 pub fn is_command_allowed(&self, command: &str) -> bool {
255 if self.mode == Modes::Architect {
256 crate::utils::bash_parser::is_architect_command_allowed(command)
257 } else {
258 self.bash_command_mode.allowed_commands.is_allowed(command)
259 }
260 }
261
262 pub fn is_file_edit_allowed(&self, path: &str) -> bool {
263 self.file_edit_mode.allowed_globs.is_allowed(path)
264 }
265
266 pub fn is_file_write_allowed(&self, path: &str) -> bool {
267 self.write_if_empty_mode.allowed_globs.is_allowed(path)
268 }
269 pub fn save_state_to_disk(&self) -> Result<()> {
270 let snapshot = self.snapshot();
271 save_state_file(&self.current_thread_id, &snapshot)?;
272 Ok(())
273 }
274
275 pub fn snapshot(&self) -> BashStateSnapshot {
276 BashStateSnapshot::from_state(
277 &self.cwd.to_string_lossy(),
278 &self.workspace_root.to_string_lossy(),
279 &self.mode,
280 &self.bash_command_mode,
281 &self.file_edit_mode,
282 &self.write_if_empty_mode,
283 &self.whitelist_for_overwrite,
284 &self.current_thread_id,
285 )
286 }
287
288 pub fn apply_snapshot(&mut self, snapshot: &BashStateSnapshot) {
289 let (cwd, root, mode, bmode, emode, wmode, whitelist, tid) = snapshot.to_state_components();
290
291 self.cwd = PathBuf::from(cwd);
292 self.workspace_root = PathBuf::from(root);
293 self.mode = mode;
294 self.bash_command_mode = bmode;
295 self.file_edit_mode = emode;
296 self.write_if_empty_mode = wmode;
297 self.whitelist_for_overwrite = whitelist;
298 self.current_thread_id = tid;
299 self.initialized = true;
300 }
301
302 pub fn load_state_from_disk(&mut self, thread_id: &str) -> Result<bool> {
303 if let Some(snapshot) = load_state_file(thread_id)? {
304 self.apply_snapshot(&snapshot);
305 Ok(true)
306 } else {
307 Ok(false)
308 }
309 }
310
311 pub fn new_with_thread_id(thread_id: Option<&str>) -> Self {
312 let mut state = Self::new();
313
314 if let Some(tid) = thread_id {
315 if !tid.is_empty() {
316 if let Ok(true) = state.load_state_from_disk(tid) {
317 info!("Loaded state for thread_id '{}'", tid);
318 } else {
319 state.current_thread_id = tid.to_string();
320 }
321 }
322 }
323
324 state
325 }
326}
327
328pub fn generate_thread_id() -> String {
329 let mut rng = rand::rng();
330 format!("tid_{:x}", rng.random::<u64>())
331}
332
333#[cfg(test)]
334mod whitelist_range_tests {
335 use super::FileWhitelistData;
336
337 fn wl(ranges: &[(usize, usize)], total: usize) -> FileWhitelistData {
338 FileWhitelistData::new("h".to_string(), ranges.to_vec(), total)
339 }
340
341 #[test]
342 fn merge_collapses_overlap_and_adjacency() {
343 let w = wl(&[(4, 5), (1, 3), (8, 12), (7, 9)], 20);
345 assert_eq!(w.line_ranges_read, vec![(1, 5), (7, 12)]);
346 }
347
348 #[test]
349 fn re_reading_does_not_grow_unbounded() {
350 let mut w = wl(&[(1, 10)], 100);
351 for _ in 0..1000 {
352 w.merge_ranges(std::iter::once((1, 10)));
353 w.merge_ranges(std::iter::once((5, 15)));
354 }
355 assert_eq!(w.line_ranges_read, vec![(1, 15)]);
357 }
358
359 #[test]
360 fn percentage_counts_distinct_lines_with_overlap() {
361 let w = wl(&[(1, 5), (3, 8)], 10);
363 assert!((w.get_percentage_read() - 80.0).abs() < 1e-9);
364 assert!(wl(&[(1, 10)], 10).is_read_enough());
365 }
366
367 #[test]
368 fn unread_ranges_are_the_gaps() {
369 let w = wl(&[(2, 4), (7, 8)], 10);
371 assert_eq!(w.get_unread_ranges(), vec![(1, 1), (5, 6), (9, 10)]);
372 }
373
374 #[test]
375 fn out_of_range_entries_are_clamped() {
376 let w = wl(&[(0, 999)], 10);
378 assert!((w.get_percentage_read() - 100.0).abs() < 1e-9);
379 assert!(w.get_unread_ranges().is_empty());
380 }
381}