omniterm 0.2.5

Web-based tmux terminal manager — one browser tab to watch and drive your AI coding agents
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
//! Filesystem operations: path sanitization, directory listing, file I/O, search.
//!
//! ## Attribution
//!
//! This module's API shape and key algorithms were modeled after
//! [sigoden/dufs](https://github.com/sigoden/dufs) (MIT OR Apache-2.0).
//! Patterns adapted:
//!
//! - `PathType` / `FileEntry` field names and JSON shape (mirrors dufs's
//!   `PathType` / `PathItem`).
//! - mtime resolution with fallback to created time.
//! - Directory `size` = child entry count, capped by `MAX_SUBPATHS_COUNT`.
//! - Sort order: directories first, then by chosen key.
//! - Path normalization to forward slashes.
//!
//! No code is copied verbatim. Rust idioms, async I/O style, and the
//! public API surface were rewritten for OmniTerm's needs.

use anyhow::{Result, anyhow};
use serde::Serialize;
use std::path::{Path, PathBuf};
use std::time::SystemTime;
use tokio::fs;

const MAX_SUBPATHS_COUNT: u64 = 1000;

/// Sanitize a requested path against a base directory.
/// Prevents directory traversal attacks. The path must already exist.
pub fn sanitize_path(base: &Path, requested: &str) -> Result<PathBuf> {
    let joined = join_and_validate(base, requested)?;

    if !joined.exists() {
        return Err(anyhow!("path does not exist: {}", joined.display()));
    }

    let canonical = joined.canonicalize().map_err(|e| anyhow!("path resolution failed: {}", e))?;

    let canonical_base =
        base.canonicalize().map_err(|e| anyhow!("base path resolution failed: {}", e))?;

    if !canonical.starts_with(&canonical_base) {
        return Err(anyhow!("access denied: path escapes workspace root"));
    }

    Ok(canonical)
}

/// Sanitize a path for creation (write, mkdir, upload).
/// Does NOT require the path to exist — only validates the parent is within base.
pub fn sanitize_path_new(base: &Path, requested: &str) -> Result<PathBuf> {
    let joined = join_and_validate(base, requested)?;

    let canonical_base =
        base.canonicalize().map_err(|e| anyhow!("base path resolution failed: {}", e))?;

    // Walk up until we find an existing ancestor
    let mut check = joined.as_path();
    let mut tail = Vec::new();
    loop {
        if check.exists() {
            let canonical =
                check.canonicalize().map_err(|e| anyhow!("path resolution failed: {}", e))?;
            if !canonical.starts_with(&canonical_base) {
                return Err(anyhow!("access denied: path escapes workspace root"));
            }
            let mut result = canonical;
            for component in tail {
                result = result.join(component);
            }
            return Ok(result);
        }
        match check.file_name() {
            Some(name) => {
                tail.push(name.to_owned());
                check = check.parent().unwrap_or(check);
            }
            None => {
                let mut result = canonical_base;
                for component in tail.into_iter().rev() {
                    result = result.join(component);
                }
                return Ok(result);
            }
        }
    }
}

/// Shared helper: strip null bytes and join against base.
fn join_and_validate(base: &Path, requested: &str) -> Result<PathBuf> {
    if requested.as_bytes().contains(&0) {
        return Err(anyhow!("invalid path: contains null byte"));
    }

    let requested_path = Path::new(requested);
    // ponytail: absolute paths under base are used directly (canonicalize + starts_with still guards traversal)
    let joined = if requested_path.is_absolute() {
        requested_path.to_path_buf()
    } else {
        base.join(requested_path)
    };

    Ok(joined)
}

/// Path type of a filesystem entry.
#[derive(Debug, Serialize, PartialEq, Eq)]
pub enum PathType {
    #[serde(rename = "Dir")]
    Dir,
    #[serde(rename = "File")]
    File,
    #[serde(rename = "SymlinkDir")]
    SymlinkDir,
    #[serde(rename = "SymlinkFile")]
    SymlinkFile,
}

/// A file or directory entry returned by [`list_dir`].
#[derive(Debug, Serialize)]
pub struct FileEntry {
    pub path_type: PathType,
    pub name: String,
    pub mtime: u64,
    pub size: u64,
    /// 相对搜索根的路径(仅 [`search_files`] 填充;目录列表为 None 不序列化)。
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rel_path: Option<String>,
}

impl FileEntry {
    pub fn is_dir(&self) -> bool {
        self.path_type == PathType::Dir || self.path_type == PathType::SymlinkDir
    }
}

/// Convert `SystemTime` to unix milliseconds.
fn to_timestamp(time: &SystemTime) -> u64 {
    time.duration_since(SystemTime::UNIX_EPOCH).unwrap_or_default().as_millis() as u64
}

/// Normalize a path for API responses / frontend display.
///
/// On Windows, `canonicalize()` returns verbatim paths (`\\?\G:\...`) and
/// psmux reports backslash paths (`G:\...`); the frontend splits paths on
/// `/`. Strip the verbatim prefix and use forward slashes so Windows paths
/// come out as `G:/...`. Unix paths pass through unchanged.
pub fn display_path(path: &Path) -> String {
    display_path_str(&path.to_string_lossy())
}

/// String variant of [`display_path`] for paths already held as strings
/// (e.g. pane CWD from the multiplexer).
pub fn display_path_str(path: &str) -> String {
    if !cfg!(windows) {
        return path.to_string();
    }
    let s = path.replace('\\', "/");
    if let Some(rest) = s.strip_prefix("//?/UNC/") {
        format!("//{rest}")
    } else if let Some(rest) = s.strip_prefix("//?/") {
        rest.to_string()
    } else {
        s
    }
}

/// Sort key for directory listing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SortKey {
    Name,
    Mtime,
    Size,
}

/// List directory contents.
pub async fn list_dir(
    base: &Path,
    rel_path: &str,
    sort: SortKey,
    desc: bool,
) -> Result<Vec<FileEntry>> {
    let dir = sanitize_path(base, rel_path)?;

    let mut entries = Vec::new();
    let mut read_dir = fs::read_dir(&dir).await?;

    while let Some(entry) = read_dir.next_entry().await? {
        let name = entry.file_name().to_string_lossy().to_string();

        // 单条目 metadata 失败(如 Windows 用户目录下 ACL 拒绝访问的遗留
        // junction「Application Data」等)只跳过该条目,不让整个列表失败
        let Ok(meta) = fs::metadata(entry.path()).await else {
            continue;
        };
        let Ok(meta2) = fs::symlink_metadata(entry.path()).await else {
            continue;
        };
        let is_symlink = meta2.is_symlink();
        let is_dir = meta.is_dir();

        let path_type = match (is_symlink, is_dir) {
            (true, true) => PathType::SymlinkDir,
            (false, true) => PathType::Dir,
            (true, false) => PathType::SymlinkFile,
            (false, false) => PathType::File,
        };

        // mtime: prefer modified, fallback to created
        let mtime = meta
            .modified()
            .ok()
            .or_else(|| meta.created().ok())
            .map(|t| to_timestamp(&t))
            .unwrap_or(0);

        // For directories, count entries (capped by MAX_SUBPATHS_COUNT)
        let size = if is_dir {
            let mut count: u64 = 0;
            if let Ok(mut sub) = fs::read_dir(entry.path()).await {
                while let Ok(Some(_sub_entry)) = sub.next_entry().await {
                    count += 1;
                    if count >= MAX_SUBPATHS_COUNT {
                        break;
                    }
                }
            }
            count
        } else {
            meta.len()
        };

        entries.push(FileEntry { path_type, name, mtime, size, rel_path: None });
    }

    // Sort: directories first, then by chosen key
    entries.sort_by(|a, b| {
        let dir_cmp = b.is_dir().cmp(&a.is_dir());
        if dir_cmp != std::cmp::Ordering::Equal {
            return dir_cmp;
        }
        let key_cmp = match sort {
            SortKey::Name => a.name.to_lowercase().cmp(&b.name.to_lowercase()),
            SortKey::Mtime => a.mtime.cmp(&b.mtime),
            SortKey::Size => a.size.cmp(&b.size),
        };
        if desc { key_cmp.reverse() } else { key_cmp }
    });

    Ok(entries)
}

/// Read file content as UTF-8 string.
pub async fn read_file(base: &Path, rel_path: &str) -> Result<String> {
    let path = sanitize_path(base, rel_path)?;
    let content = fs::read_to_string(&path).await?;
    Ok(content)
}

/// Write content to a file. Creates the file if it doesn't exist.
pub async fn write_file(base: &Path, rel_path: &str, content: &[u8]) -> Result<()> {
    let path = sanitize_path_new(base, rel_path)?;

    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).await?;
    }

    fs::write(&path, content).await?;
    Ok(())
}

/// Create a directory (and parents).
pub async fn create_dir(base: &Path, rel_path: &str) -> Result<()> {
    let path = sanitize_path_new(base, rel_path)?;
    fs::create_dir_all(&path).await?;
    Ok(())
}

/// Delete a file or directory.
pub async fn delete_path(base: &Path, rel_path: &str) -> Result<()> {
    let path = sanitize_path(base, rel_path)?;
    let metadata = fs::metadata(&path).await?;

    if metadata.is_dir() {
        fs::remove_dir_all(&path).await?;
    } else {
        fs::remove_file(&path).await?;
    }

    Ok(())
}

/// Rename/move a file or directory to a new path.
/// `new_rel_path` is the full new relative path, not just a name.
pub async fn move_path(base: &Path, old_rel: &str, new_rel: &str) -> Result<()> {
    let old = sanitize_path(base, old_rel)?;
    let new = sanitize_path_new(base, new_rel)?;

    if let Some(parent) = new.parent() {
        fs::create_dir_all(parent).await?;
    }

    fs::rename(&old, &new).await?;
    Ok(())
}

/// Copy files/directories to a destination directory.
pub async fn copy_paths(base: &Path, paths: &[String], dest: &str) -> Result<()> {
    let dest_dir = sanitize_path_new(base, dest)?;

    fs::create_dir_all(&dest_dir).await?;

    for p in paths {
        let src = sanitize_path(base, p)?;
        let file_name = src.file_name().ok_or_else(|| anyhow!("invalid path"))?;
        let target = dest_dir.join(file_name);

        let metadata = fs::metadata(&src).await?;
        if metadata.is_dir() {
            copy_dir_recursive(&src, &target).await?;
        } else {
            fs::copy(&src, &target).await?;
        }
    }

    Ok(())
}

/// Recursively copy a directory.
async fn copy_dir_recursive(src: &Path, dest: &Path) -> Result<()> {
    fs::create_dir_all(dest).await?;
    let mut read_dir = fs::read_dir(src).await?;

    while let Some(entry) = read_dir.next_entry().await? {
        let src_path = entry.path();
        let dest_path = dest.join(entry.file_name());

        if src_path.is_dir() {
            Box::pin(copy_dir_recursive(&src_path, &dest_path)).await?;
        } else {
            fs::copy(&src_path, &dest_path).await?;
        }
    }

    Ok(())
}

/// Search for files matching a query string.
pub async fn search_files(base: &Path, rel_path: &str, query: &str) -> Result<Vec<FileEntry>> {
    // Absolute paths (from session mode) use the path directly; relative paths join against base.
    let dir = if Path::new(rel_path).is_absolute() {
        PathBuf::from(rel_path)
    } else if rel_path.is_empty() || rel_path == "." {
        base.to_path_buf()
    } else {
        sanitize_path(base, rel_path)?
    };
    let query_lower = query.to_lowercase();
    let mut results = Vec::new();

    search_recursive(&dir, &query_lower, "", &mut results, 100, 8).await?;

    Ok(results)
}

const SKIP_DIRS: &[&str] = &[
    "node_modules",
    ".git",
    "target",
    "__pycache__",
    ".venv",
    "venv",
    ".next",
    ".nuxt",
    "dist",
    "build",
    ".cache",
    "vendor",
];

/// Recursive search with result and depth limits.
/// `prefix` 是当前目录相对搜索根的路径(根为空串),用于填充 [`FileEntry::rel_path`]。
fn search_recursive<'a>(
    dir: &'a Path,
    query: &'a str,
    prefix: &'a str,
    results: &'a mut Vec<FileEntry>,
    max_results: usize,
    max_depth: usize,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send + 'a>> {
    Box::pin(async move {
        if results.len() >= max_results || max_depth == 0 {
            return Ok(());
        }

        let mut read_dir = match fs::read_dir(dir).await {
            Ok(rd) => rd,
            Err(_) => return Ok(()), // skip unreadable directories
        };

        while let Some(entry) = read_dir.next_entry().await? {
            if results.len() >= max_results {
                break;
            }

            let name = entry.file_name().to_string_lossy().to_string();

            // Skip hidden dirs and common heavy directories
            if name.starts_with('.') || SKIP_DIRS.contains(&name.as_str()) {
                continue;
            }

            let rel = if prefix.is_empty() { name.clone() } else { format!("{prefix}/{name}") };

            let meta = match fs::metadata(entry.path()).await {
                Ok(m) => m,
                Err(_) => continue, // skip inaccessible entries
            };
            let meta2 = fs::symlink_metadata(entry.path()).await;
            let is_symlink = meta2.map(|m| m.is_symlink()).unwrap_or(false);
            let is_dir = meta.is_dir();

            if name.to_lowercase().contains(query) {
                let path_type = match (is_symlink, is_dir) {
                    (true, true) => PathType::SymlinkDir,
                    (false, true) => PathType::Dir,
                    (true, false) => PathType::SymlinkFile,
                    (false, false) => PathType::File,
                };
                let mtime = meta
                    .modified()
                    .ok()
                    .or_else(|| meta.created().ok())
                    .map(|t| to_timestamp(&t))
                    .unwrap_or(0);

                results.push(FileEntry {
                    path_type,
                    name,
                    mtime,
                    size: if is_dir { 0 } else { meta.len() },
                    rel_path: Some(rel.clone()),
                });
            }

            if is_dir && !is_symlink {
                search_recursive(&entry.path(), query, &rel, results, max_results, max_depth - 1)
                    .await?;
            }
        }

        Ok(())
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;

    #[test]
    fn test_sanitize_valid() {
        let base = Path::new("/tmp/omniterm_test");
        // sanitize_path 是“读路径”变体:被校验路径必须实际存在(sanitize_path_new 才用于创建)
        fs::create_dir_all(base.join("foo/bar")).unwrap();
        assert!(sanitize_path(base, "foo/bar").is_ok());
    }

    #[test]
    fn test_sanitize_traversal() {
        let base = Path::new("/tmp/omniterm_test");
        fs::create_dir_all(base).unwrap();
        assert!(sanitize_path(base, "../../../etc/passwd").is_err());
    }

    #[test]
    fn test_sanitize_null_byte() {
        let base = Path::new("/tmp/omniterm_test");
        assert!(sanitize_path(base, "foo\0bar").is_err());
    }

    #[cfg(windows)]
    #[test]
    fn test_display_path_windows() {
        assert_eq!(display_path_str(r"\\?\G:\Codes\ot"), "G:/Codes/ot");
        assert_eq!(display_path_str(r"G:\Codes\ot"), "G:/Codes/ot");
        assert_eq!(display_path_str(r"\\?\UNC\server\share\x"), "//server/share/x");
        assert_eq!(display_path_str("G:/already/normal"), "G:/already/normal");
    }

    #[cfg(unix)]
    #[test]
    fn test_display_path_unix_passthrough() {
        assert_eq!(display_path_str("/home/user/proj"), "/home/user/proj");
    }
}