zerostack 1.5.0-rc5

Minimalistic coding agent written in Rust, optimized for memory footprint and performance
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
use std::io::Write;
use std::path::{Component, Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};

use crossterm::ExecutableCommand;
use crossterm::cursor::MoveTo;
use crossterm::style::{Color, ResetColor, SetForegroundColor};
use crossterm::terminal::Clear;

use super::super::utils::resolve_color;

pub struct FilePicker {
    pub active: bool,
    pub query: String,
    pub cursor: usize,
    pub matches: Vec<PathBuf>,
    pub selected: usize,
    file_cache: Arc<Mutex<Vec<PathBuf>>>,
    monochrome: bool,
    loading: bool,
    walk_done: Arc<AtomicBool>,
}

impl FilePicker {
    pub fn new() -> Self {
        FilePicker {
            active: false,
            query: String::new(),
            cursor: 0,
            matches: Vec::new(),
            selected: 0,
            file_cache: Arc::new(Mutex::new(Vec::new())),
            monochrome: false,
            loading: false,
            walk_done: Arc::new(AtomicBool::new(false)),
        }
    }

    pub fn set_monochrome(&mut self, monochrome: bool) {
        self.monochrome = monochrome;
    }

    fn color(&self, color: Color) -> Color {
        resolve_color(color, self.monochrome)
    }

    pub fn activate(&mut self) {
        self.active = true;
        self.query.clear();
        self.cursor = 0;
        self.matches.clear();
        self.selected = 0;

        if let Ok(handle) = tokio::runtime::Handle::try_current() {
            self.loading = true;
            self.walk_done.store(false, Ordering::Relaxed);
            let cache = self.file_cache.clone();
            let done = self.walk_done.clone();
            handle.spawn_blocking(move || {
                let files = walk_files(".");
                *cache.lock().unwrap_or_else(|e| e.into_inner()) = files;
                done.store(true, Ordering::Relaxed);
            });
        } else {
            self.load_files_sync();
        }
    }

    fn load_files_sync(&mut self) {
        let files = walk_files(".");
        *self.file_cache.lock().unwrap_or_else(|e| e.into_inner()) = files;
        self.filter();
    }

    pub fn deactivate(&mut self) {
        self.active = false;
    }

    pub fn try_finish_loading(&mut self) -> bool {
        if self.loading && self.walk_done.load(Ordering::Relaxed) {
            self.loading = false;
            self.filter();
            true
        } else {
            false
        }
    }

    pub fn char_input(&mut self, c: char) {
        let byte_pos = self
            .query
            .char_indices()
            .nth(self.cursor)
            .map(|(i, _)| i)
            .unwrap_or(self.query.len());
        self.query.insert(byte_pos, c);
        self.cursor += 1;
        if !self.loading {
            self.filter();
        }
    }

    pub fn backspace(&mut self) {
        if self.cursor > 0 && !self.query.is_empty() {
            self.cursor -= 1;
            let byte_pos = self
                .query
                .char_indices()
                .nth(self.cursor)
                .map(|(i, _)| i)
                .unwrap_or(self.query.len());
            self.query.remove(byte_pos);
            if !self.loading {
                self.filter();
            }
        }
    }

    fn filter(&mut self) {
        let cache = self.file_cache.lock().unwrap_or_else(|e| e.into_inner());
        if cache.is_empty() {
            self.matches.clear();
            return;
        }
        let query_lower = self.query.to_lowercase();
        self.matches = cache
            .iter()
            .filter(|p| {
                let lower = p.to_string_lossy().to_lowercase();
                lower.contains(&query_lower)
            })
            .take(50)
            .cloned()
            .collect();
        self.selected = 0;
    }

    pub fn select_next(&mut self) {
        if !self.matches.is_empty() {
            self.selected = (self.selected + 1) % self.matches.len();
        }
    }

    pub fn select_prev(&mut self) {
        if !self.matches.is_empty() {
            self.selected = if self.selected == 0 {
                self.matches.len() - 1
            } else {
                self.selected - 1
            };
        }
    }

    pub fn selected_path(&self) -> Option<&PathBuf> {
        self.matches.get(self.selected)
    }

    #[cfg(test)]
    pub fn test_set_cache(&mut self, files: Vec<PathBuf>) {
        *self.file_cache.lock().unwrap_or_else(|e| e.into_inner()) = files;
        self.loading = false;
    }

    pub fn draw(&mut self) -> std::io::Result<()> {
        if !self.active {
            return Ok(());
        }

        self.try_finish_loading();

        let (cols, rows) = crossterm::terminal::size()?;
        let mut stdout = std::io::stdout();

        let max_items = (rows.saturating_sub(4)).min(10) as usize;

        if self.loading {
            let r = rows.saturating_sub(3);
            stdout.execute(MoveTo(0, r))?;
            write!(
                stdout,
                "{}",
                SetForegroundColor(self.color(Color::DarkGrey))
            )?;
            write!(stdout, "scanning files...")?;
            write!(stdout, "{}", ResetColor)?;
            stdout.flush()?;
            return Ok(());
        }

        if self.matches.is_empty() {
            let r = rows.saturating_sub(3);
            stdout.execute(MoveTo(0, r))?;
            write!(
                stdout,
                "{}",
                SetForegroundColor(self.color(Color::DarkGrey))
            )?;
            write!(stdout, "no matches")?;
            write!(stdout, "{}", ResetColor)?;
            stdout.flush()?;
            return Ok(());
        }

        let list_height = max_items.min(self.matches.len());
        let start_idx = self
            .selected
            .saturating_sub(list_height / 2)
            .min(self.matches.len().saturating_sub(list_height));
        let end_idx = (start_idx + list_height).min(self.matches.len());

        let top_row = rows.saturating_sub(3).saturating_sub(list_height as u16);

        for i in start_idx..end_idx {
            let render_row = top_row + (i - start_idx) as u16;
            stdout.execute(MoveTo(0, render_row))?;
            write!(
                stdout,
                "{}",
                Clear(crossterm::terminal::ClearType::CurrentLine)
            )?;

            let path = &self.matches[i];
            let mut display = path.to_string_lossy().to_string();
            if Path::new(&path).is_dir() {
                display.push('/');
            }
            let truncated: String = display
                .chars()
                .take(cols.saturating_sub(3) as usize)
                .collect();

            if i == self.selected {
                write!(stdout, "{}", SetForegroundColor(self.color(Color::Green)))?;
                write!(stdout, "â–¸ {}", truncated)?;
            } else {
                write!(
                    stdout,
                    "{}",
                    SetForegroundColor(self.color(Color::DarkGrey))
                )?;
                write!(stdout, "  {}", truncated)?;
            }
            write!(stdout, "{}", ResetColor)?;
        }
        stdout.flush()?;
        Ok(())
    }
}

fn walk_files(root: &str) -> Vec<PathBuf> {
    let mut files = Vec::new();
    let walker = ignore::WalkBuilder::new(root)
        .hidden(false)
        .git_ignore(true)
        .max_depth(Some(8))
        .sort_by_file_name(|a, b| a.cmp(b))
        .build();

    for entry in walker.flatten() {
        let path = entry.path();
        if !path.is_file() && !path.is_dir() {
            continue;
        }
        if path
            .components()
            .any(|c| matches!(c, Component::Normal(n) if n.to_string_lossy().starts_with('.')))
        {
            continue;
        }
        let rel = path
            .strip_prefix(root)
            .unwrap_or(path)
            .to_string_lossy()
            .to_string();
        let rel = rel.trim_start_matches('/').to_string();
        files.push(PathBuf::from(rel));
        if files.len() >= 200 {
            break;
        }
    }
    files
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::path::Path;
    use std::sync::atomic::{AtomicUsize, Ordering};

    static TEMP_COUNTER: AtomicUsize = AtomicUsize::new(0);

    fn with_temp_dir<F>(f: F)
    where
        F: FnOnce(&Path),
    {
        let n = TEMP_COUNTER.fetch_add(1, Ordering::SeqCst);
        let dir = std::env::temp_dir().join(format!("zerostack_test_{}_{}", std::process::id(), n));
        fs::create_dir_all(&dir).unwrap();
        let canonical = dir.canonicalize().unwrap();
        f(&canonical);
        let _ = fs::remove_dir_all(&canonical);
    }

    #[test]
    fn test_walk_files_includes_directories() {
        with_temp_dir(|root| {
            fs::create_dir(root.join("subdir")).unwrap();
            fs::write(root.join("file.txt"), b"hello").unwrap();

            let files = walk_files(&root.to_string_lossy());
            let names: Vec<&str> = files.iter().map(|p| p.to_str().unwrap()).collect();

            assert!(
                names.contains(&"file.txt"),
                "walk_files should include files"
            );
            assert!(
                names.contains(&"subdir"),
                "walk_files should include directories, got: {:?}",
                names
            );
        });
    }

    #[test]
    fn test_walk_files_includes_nested_dirs() {
        with_temp_dir(|root| {
            fs::create_dir_all(root.join("a").join("b")).unwrap();
            fs::write(root.join("a").join("b").join("deep.txt"), b"deep").unwrap();

            let files = walk_files(&root.to_string_lossy());
            let names: Vec<&str> = files.iter().map(|p| p.to_str().unwrap()).collect();

            assert!(names.contains(&"a"));
            assert!(names.contains(&"a/b"));
            assert!(names.contains(&"a/b/deep.txt"));
        });
    }

    #[test]
    fn test_walk_files_skips_dotfiles() {
        with_temp_dir(|root| {
            fs::write(root.join(".hidden"), b"secret").unwrap();
            fs::write(root.join("visible.txt"), b"hello").unwrap();

            let files = walk_files(&root.to_string_lossy());
            let names: Vec<&str> = files.iter().map(|p| p.to_str().unwrap()).collect();

            assert!(!names.contains(&".hidden"));
            assert!(names.contains(&"visible.txt"));
        });
    }

    #[test]
    fn test_walk_files_skips_files_in_dot_dirs() {
        with_temp_dir(|root| {
            fs::create_dir_all(root.join(".secret").join("nested")).unwrap();
            fs::write(
                root.join(".secret").join("nested").join("file.txt"),
                b"hidden",
            )
            .unwrap();
            fs::write(root.join(".secret").join("secret_file.txt"), b"hidden").unwrap();
            fs::write(root.join("public.txt"), b"visible").unwrap();

            let files = walk_files(&root.to_string_lossy());
            let names: Vec<&str> = files.iter().map(|p| p.to_str().unwrap()).collect();

            assert!(!names.contains(&".secret"));
            assert!(!names.contains(&".secret/nested"));
            assert!(!names.contains(&".secret/nested/file.txt"));
            assert!(!names.contains(&".secret/secret_file.txt"));
            assert!(names.contains(&"public.txt"));
        });
    }

    #[test]
    fn test_walk_files_root_is_sorted_and_stripped() {
        with_temp_dir(|root| {
            fs::write(root.join("z.txt"), b"z").unwrap();
            fs::write(root.join("c.txt"), b"c").unwrap();
            fs::write(root.join("a.txt"), b"a").unwrap();

            let files = walk_files(&root.to_string_lossy());
            let names: Vec<&str> = files.iter().map(|p| p.to_str().unwrap()).collect();

            let root_idx = names.iter().position(|n| n.is_empty());
            assert!(
                root_idx.is_some(),
                "root entry (empty string) should be present"
            );

            let file_indices: Vec<usize> = names
                .iter()
                .enumerate()
                .filter(|(_, n)| n.ends_with(".txt"))
                .map(|(i, _)| i)
                .collect();
            assert!(
                file_indices.windows(2).all(|w| w[0] < w[1]),
                "files should be sorted"
            );
        });
    }

    #[test]
    fn test_walk_files_empty_directory() {
        with_temp_dir(|root| {
            let files = walk_files(&root.to_string_lossy());
            let names: Vec<&str> = files.iter().map(|p| p.to_str().unwrap()).collect();

            assert_eq!(names.len(), 1, "only root entry expected in empty dir");
            assert!(names.contains(&""), "root entry should be present");
        });
    }
}