Skip to main content

winx_code_agent/state/
bash_state.rs

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
26/// Clamp ranges to `1..=total_lines`, drop inverted/empty ones, and sort. Shared
27/// by the coverage queries so both tolerate overlapping/out-of-bounds ranges.
28fn 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
38/// Count distinct lines covered by (possibly overlapping) `ranges`, clamped to
39/// `1..=total_lines`, via a single sort+sweep — O(k log k) in the range count.
40fn covered_line_count(ranges: &[(usize, usize)], total_lines: usize) -> usize {
41    let mut covered = 0usize;
42    let mut last_end = 0usize; // highest line already counted (0 = none)
43    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        // Sort+sweep over the ranges (O(k log k) in the range count) instead of
74        // building an O(total_lines) HashSet on every call. Robust to overlapping
75        // or out-of-range entries from older un-merged snapshots.
76        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; // next line not yet known-read
87        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    /// Record `[start, end]` as read, merging it into the existing intervals so
100    /// `line_ranges_read` stays a bounded set of disjoint ranges. Without the
101    /// merge, re-reading a file appended duplicate ranges forever (unbounded
102    /// memory per session).
103    pub fn add_range(&mut self, start: usize, end: usize) {
104        self.merge_ranges(std::iter::once((start, end)));
105    }
106
107    /// Merge `new` ranges into `line_ranges_read`, keeping it sorted and disjoint
108    /// (adjacent inclusive ranges like `(1,3)` and `(4,5)` collapse to `(1,5)`).
109    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
128/// How many edit checkpoints to keep per session for `UndoEdit`. In-memory only
129/// (not persisted), oldest dropped past the cap, bounding memory on long sessions.
130const EDIT_CHECKPOINT_CAP: usize = 10;
131
132/// Largest prior-content a checkpoint will hold. Files (up to the 50 MB edit
133/// ceiling) above this aren't checkpointed, so a session editing huge assets
134/// can't pile up to ~CAP * 50 MB of undo snapshots in memory; those edits just
135/// aren't undoable.
136const EDIT_CHECKPOINT_MAX_CONTENT_BYTES: usize = 1_000_000;
137
138/// Maximum number of files whose read coverage is retained in one session.
139/// Evicting an old entry is fail-closed: a later edit simply has to read that
140/// file again, while long-lived HTTP/plugin sessions keep bounded memory and
141/// persisted state.
142const MAX_WHITELIST_FILES: usize = 1_024;
143
144/// A single file's pre-edit state, captured by `FileWriteOrEdit`/`MultiFileEdit`
145/// after a successful write so `UndoEdit` can restore it. Only existing files get
146/// one (a brand-new file's creation is not undoable - there is no prior content).
147#[derive(Debug, Clone)]
148pub struct EditCheckpoint {
149    /// Resolved, workspace-confined path string (matches `whitelist_for_overwrite` keys).
150    pub file_path_str: String,
151    pub path: PathBuf,
152    /// File content before the edit, to be written back on undo.
153    pub prior_content: String,
154    /// The whitelist entry before the edit, restored on undo so the hash gate of a
155    /// later edit matches the reverted content. `None` if there was none.
156    pub prior_whitelist: Option<FileWhitelistData>,
157}
158
159#[derive(Debug, Clone)]
160pub struct BashState {
161    pub cwd: PathBuf,
162    pub workspace_root: PathBuf,
163    pub current_thread_id: String,
164    pub mode: Modes,
165    pub bash_command_mode: BashCommandMode,
166    pub file_edit_mode: FileEditMode,
167    pub write_if_empty_mode: WriteIfEmptyMode,
168    pub whitelist_for_overwrite: HashMap<String, FileWhitelistData>,
169    /// Least-recently-used order for `whitelist_for_overwrite`, oldest first.
170    /// Snapshots intentionally persist only the guarded data; restored entries
171    /// receive a deterministic order when loaded.
172    whitelist_recency: VecDeque<String>,
173    pub pty_shell: Arc<Mutex<Option<PtyShell>>>,
174    /// Serializes foreground command startup across cloned request-local states.
175    /// Status/input actions remain concurrent so callers can drive a running TUI.
176    pub foreground_command_gate: Arc<Mutex<()>>,
177    pub initialized: bool,
178    /// In-memory ring of recent edit checkpoints for `UndoEdit` (newest at the
179    /// back). Deliberately not part of `BashStateSnapshot`: undo is for immediate
180    /// mid-session recovery, not across restarts.
181    pub edit_checkpoints: VecDeque<EditCheckpoint>,
182}
183
184impl Default for BashState {
185    fn default() -> Self {
186        Self::new()
187    }
188}
189
190impl BashState {
191    pub fn new() -> Self {
192        let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("/tmp"));
193        Self {
194            cwd: cwd.clone(),
195            workspace_root: cwd,
196            current_thread_id: generate_thread_id(),
197            mode: Modes::Wcgw,
198            bash_command_mode: BashCommandMode {
199                bash_mode: BashMode::NormalMode,
200                allowed_commands: AllowedCommands::All("all".to_string()),
201            },
202            file_edit_mode: FileEditMode { allowed_globs: AllowedGlobs::All("all".to_string()) },
203            write_if_empty_mode: WriteIfEmptyMode {
204                allowed_globs: AllowedGlobs::All("all".to_string()),
205            },
206            whitelist_for_overwrite: HashMap::new(),
207            whitelist_recency: VecDeque::new(),
208            pty_shell: Arc::new(Mutex::new(None)),
209            foreground_command_gate: Arc::new(Mutex::new(())),
210            initialized: false,
211            edit_checkpoints: VecDeque::new(),
212        }
213    }
214
215    /// Record a pre-edit checkpoint for `UndoEdit`, dropping the oldest past the
216    /// cap. Large files are skipped (not undoable) to bound memory.
217    pub fn push_edit_checkpoint(&mut self, checkpoint: EditCheckpoint) {
218        if checkpoint.prior_content.len() > EDIT_CHECKPOINT_MAX_CONTENT_BYTES {
219            info!(
220                file = %checkpoint.file_path_str,
221                "UndoEdit: not checkpointing a file over 1 MB (too large to hold in memory)"
222            );
223            return;
224        }
225        self.edit_checkpoints.push_back(checkpoint);
226        while self.edit_checkpoints.len() > EDIT_CHECKPOINT_CAP {
227            self.edit_checkpoints.pop_front();
228        }
229    }
230
231    /// Remove and return the most recent checkpoint for `file_path_str` (per-file
232    /// LIFO, so repeated undos on one file walk its edits back while leaving other
233    /// files' checkpoints in place). `None` if that file has no checkpoint.
234    pub fn pop_edit_checkpoint_for(&mut self, file_path_str: &str) -> Option<EditCheckpoint> {
235        let index =
236            self.edit_checkpoints.iter().rposition(|cp| cp.file_path_str == file_path_str)?;
237        self.edit_checkpoints.remove(index)
238    }
239
240    /// Merge visible read coverage for `path` and make it the newest guarded
241    /// entry. Coverage from a different file version is discarded instead of
242    /// being combined with the new hash, which could otherwise make disjoint
243    /// reads across two versions look like one complete read.
244    pub fn record_read_coverage(
245        &mut self,
246        path: &str,
247        ranges: impl IntoIterator<Item = (usize, usize)>,
248        file_hash: String,
249        total_lines: usize,
250    ) {
251        let ranges = ranges.into_iter().collect::<Vec<_>>();
252        match self.whitelist_for_overwrite.get_mut(path) {
253            Some(existing)
254                if existing.file_hash == file_hash && existing.total_lines == total_lines =>
255            {
256                existing.merge_ranges(ranges);
257            }
258            Some(existing) => {
259                *existing = FileWhitelistData::new(file_hash, ranges, total_lines);
260            }
261            None => {
262                self.whitelist_for_overwrite.insert(
263                    path.to_string(),
264                    FileWhitelistData::new(file_hash, ranges, total_lines),
265                );
266            }
267        }
268        self.touch_whitelist(path);
269        self.enforce_whitelist_cap();
270    }
271
272    /// Replace a whitelist entry after a successful edit or undo.
273    pub fn set_whitelist_entry(&mut self, path: &str, entry: FileWhitelistData) {
274        self.whitelist_for_overwrite.insert(path.to_string(), entry);
275        self.touch_whitelist(path);
276        self.enforce_whitelist_cap();
277    }
278
279    /// Remove a whitelist entry and its LRU metadata.
280    pub fn remove_whitelist_entry(&mut self, path: &str) -> Option<FileWhitelistData> {
281        self.whitelist_recency.retain(|candidate| candidate != path);
282        self.whitelist_for_overwrite.remove(path)
283    }
284
285    fn touch_whitelist(&mut self, path: &str) {
286        self.whitelist_recency.retain(|candidate| candidate != path);
287        self.whitelist_recency.push_back(path.to_string());
288    }
289
290    fn rebuild_whitelist_recency(&mut self) {
291        let mut paths = self.whitelist_for_overwrite.keys().cloned().collect::<Vec<_>>();
292        paths.sort_unstable();
293        self.whitelist_recency = paths.into();
294        self.enforce_whitelist_cap();
295    }
296
297    fn enforce_whitelist_cap(&mut self) {
298        self.whitelist_recency.retain(|path| self.whitelist_for_overwrite.contains_key(path));
299        while self.whitelist_for_overwrite.len() > MAX_WHITELIST_FILES {
300            let victim = self.whitelist_recency.pop_front().or_else(|| {
301                // The map remains public for compatibility, so tolerate callers
302                // that inserted directly without updating the LRU metadata.
303                self.whitelist_for_overwrite.keys().min().cloned()
304            });
305            let Some(victim) = victim else { break };
306            self.whitelist_for_overwrite.remove(&victim);
307        }
308    }
309
310    pub async fn init_pty_shell(&mut self) -> Result<()> {
311        let cwd = self.cwd.clone();
312        let workspace_root = self.workspace_root.clone();
313        let temporary_artifact_dir =
314            crate::utils::agent_temp::session_info(&workspace_root, &self.current_thread_id)
315                .directory;
316        let restricted = self.bash_command_mode.bash_mode == BashMode::RestrictedMode;
317        // PtyShell::new forks+execs a shell and does a ~300ms blocking prompt init
318        // (thread::sleep + drain_output busy-wait). Run it on the blocking pool so
319        // it never pins a tokio worker thread.
320        let shell = tokio::task::spawn_blocking(move || {
321            PtyShell::new_with_agent_paths(
322                &cwd,
323                restricted,
324                Some(&workspace_root),
325                Some(&temporary_artifact_dir),
326            )
327        })
328        .await
329        .map_err(|e| {
330            crate::errors::WinxError::ShellInitializationError(format!("PTY init task failed: {e}"))
331        })??;
332        *self.pty_shell.lock().await = Some(shell);
333        Ok(())
334    }
335
336    pub fn update_cwd(&mut self, path: &Path) -> Result<()> {
337        self.cwd = path.to_path_buf();
338        Ok(())
339    }
340
341    pub fn update_workspace_root(&mut self, path: &Path) -> Result<()> {
342        self.workspace_root = path.to_path_buf();
343        Ok(())
344    }
345
346    pub fn is_command_allowed(&self, command: &str) -> bool {
347        if self.mode == Modes::Architect {
348            crate::utils::bash_parser::is_architect_command_allowed(command)
349        } else {
350            self.bash_command_mode.allowed_commands.is_allowed(command)
351        }
352    }
353
354    pub fn is_file_edit_allowed(&self, path: &str) -> bool {
355        self.file_edit_mode.allowed_globs.is_allowed(path)
356    }
357
358    pub fn is_file_write_allowed(&self, path: &str) -> bool {
359        self.write_if_empty_mode.allowed_globs.is_allowed(path)
360    }
361    pub fn save_state_to_disk(&self) -> Result<()> {
362        let snapshot = self.snapshot();
363        save_state_file(&self.current_thread_id, &snapshot)?;
364        Ok(())
365    }
366
367    pub fn snapshot(&self) -> BashStateSnapshot {
368        BashStateSnapshot::from_state(
369            &self.cwd.to_string_lossy(),
370            &self.workspace_root.to_string_lossy(),
371            &self.mode,
372            &self.bash_command_mode,
373            &self.file_edit_mode,
374            &self.write_if_empty_mode,
375            &self.whitelist_for_overwrite,
376            &self.current_thread_id,
377        )
378    }
379
380    pub fn apply_snapshot(&mut self, snapshot: &BashStateSnapshot) {
381        let (cwd, root, mode, bmode, emode, wmode, whitelist, tid) = snapshot.to_state_components();
382
383        self.cwd = PathBuf::from(cwd);
384        self.workspace_root = PathBuf::from(root);
385        self.mode = mode;
386        self.bash_command_mode = bmode;
387        self.file_edit_mode = emode;
388        self.write_if_empty_mode = wmode;
389        self.whitelist_for_overwrite = whitelist;
390        self.rebuild_whitelist_recency();
391        self.current_thread_id = tid;
392        self.initialized = true;
393    }
394
395    pub fn load_state_from_disk(&mut self, thread_id: &str) -> Result<bool> {
396        if let Some(snapshot) = load_state_file(thread_id)? {
397            self.apply_snapshot(&snapshot);
398            Ok(true)
399        } else {
400            Ok(false)
401        }
402    }
403
404    pub fn new_with_thread_id(thread_id: Option<&str>) -> Self {
405        let mut state = Self::new();
406
407        if let Some(tid) = thread_id {
408            if !tid.is_empty() {
409                if let Ok(true) = state.load_state_from_disk(tid) {
410                    info!("Loaded state for thread_id '{}'", tid);
411                } else {
412                    state.current_thread_id = tid.to_string();
413                }
414            }
415        }
416
417        state
418    }
419}
420
421pub fn generate_thread_id() -> String {
422    let mut rng = rand::rng();
423    format!("tid_{:x}", rng.random::<u64>())
424}
425
426#[cfg(test)]
427mod whitelist_range_tests {
428    use super::{BashState, FileWhitelistData, MAX_WHITELIST_FILES};
429
430    fn wl(ranges: &[(usize, usize)], total: usize) -> FileWhitelistData {
431        FileWhitelistData::new("h".to_string(), ranges.to_vec(), total)
432    }
433
434    #[test]
435    fn merge_collapses_overlap_and_adjacency() {
436        // (1,3)+(4,5) are adjacent (inclusive) -> (1,5); (7,9)+(8,12) overlap -> (7,12).
437        let w = wl(&[(4, 5), (1, 3), (8, 12), (7, 9)], 20);
438        assert_eq!(w.line_ranges_read, vec![(1, 5), (7, 12)]);
439    }
440
441    #[test]
442    fn re_reading_does_not_grow_unbounded() {
443        let mut w = wl(&[(1, 10)], 100);
444        for _ in 0..1000 {
445            w.merge_ranges(std::iter::once((1, 10)));
446            w.merge_ranges(std::iter::once((5, 15)));
447        }
448        // 1000 re-reads collapse to a single interval, not 2000 entries.
449        assert_eq!(w.line_ranges_read, vec![(1, 15)]);
450    }
451
452    #[test]
453    fn percentage_counts_distinct_lines_with_overlap() {
454        // lines 1..=5 and 3..=8 cover 1..=8 = 8 of 10 = 80%.
455        let w = wl(&[(1, 5), (3, 8)], 10);
456        assert!((w.get_percentage_read() - 80.0).abs() < 1e-9);
457        assert!(wl(&[(1, 10)], 10).is_read_enough());
458    }
459
460    #[test]
461    fn unread_ranges_are_the_gaps() {
462        // read 2..=4 and 7..=8 of 10 -> unread 1, 5..=6, 9..=10.
463        let w = wl(&[(2, 4), (7, 8)], 10);
464        assert_eq!(w.get_unread_ranges(), vec![(1, 1), (5, 6), (9, 10)]);
465    }
466
467    #[test]
468    fn out_of_range_entries_are_clamped() {
469        // A (0, 999) range on a 10-line file counts as full coverage, not a panic.
470        let w = wl(&[(0, 999)], 10);
471        assert!((w.get_percentage_read() - 100.0).abs() < 1e-9);
472        assert!(w.get_unread_ranges().is_empty());
473    }
474
475    #[test]
476    fn coverage_from_different_file_versions_is_not_combined() {
477        let mut state = BashState::new();
478        state.record_read_coverage("/workspace/file.rs", [(1, 50)], "old-hash".to_string(), 100);
479        state.record_read_coverage("/workspace/file.rs", [(51, 100)], "new-hash".to_string(), 100);
480
481        let coverage = &state.whitelist_for_overwrite["/workspace/file.rs"];
482        assert_eq!(coverage.file_hash, "new-hash");
483        assert_eq!(coverage.line_ranges_read, vec![(51, 100)]);
484        assert_eq!(coverage.get_unread_ranges(), vec![(1, 50)]);
485    }
486
487    #[test]
488    fn whitelist_is_lru_bounded_and_recent_entries_survive() {
489        let mut state = BashState::new();
490        for index in 0..MAX_WHITELIST_FILES {
491            let path = format!("/workspace/file-{index:04}.rs");
492            state.record_read_coverage(&path, [(1, 1)], format!("hash-{index}"), 1);
493        }
494
495        // Refresh the oldest entry, then force one eviction. The next-oldest
496        // entry must be discarded while the refreshed one stays guarded.
497        state.record_read_coverage("/workspace/file-0000.rs", [(1, 1)], "hash-0".to_string(), 1);
498        state.record_read_coverage("/workspace/newest.rs", [(1, 1)], "newest-hash".to_string(), 1);
499
500        assert_eq!(state.whitelist_for_overwrite.len(), MAX_WHITELIST_FILES);
501        assert!(state.whitelist_for_overwrite.contains_key("/workspace/file-0000.rs"));
502        assert!(!state.whitelist_for_overwrite.contains_key("/workspace/file-0001.rs"));
503        assert!(state.whitelist_for_overwrite.contains_key("/workspace/newest.rs"));
504    }
505}