Skip to main content

agent_hub_runtime/core/
file_preview.rs

1use std::{fs, path::PathBuf, sync::Mutex};
2
3use tempfile::TempDir;
4
5use super::{error::AppError, path_guard::ensure_safe_skill_relative_path};
6
7/// Own preview copies for the application session, including after the reader closes.
8/// Dropping the state removes the temporary directories; original files are never touched.
9#[derive(Default)]
10pub struct FilePreviews {
11    session: Mutex<PreviewSession>,
12}
13
14#[derive(Default)]
15struct PreviewSession {
16    directories: Vec<TempDir>,
17    closed: bool,
18}
19
20impl FilePreviews {
21    /// Remove session copies during orderly quit or restart, before process exit.
22    pub fn clear(&self) -> Result<(), AppError> {
23        let mut session = self
24            .session
25            .lock()
26            .map_err(|_| AppError::internal("Preview state is unavailable"))?;
27        // A pending writer must not publish another copy after quit cleanup.
28        session.closed = true;
29        session.directories.clear();
30        Ok(())
31    }
32
33    /// Materialize the exact text shown in the reader without installing or running it.
34    pub fn prepare(&self, path: &str, content: &str) -> Result<PathBuf, AppError> {
35        ensure_safe_skill_relative_path(path)?;
36        if path.contains(['\\', ':']) || content.len() > 4 * 1024 * 1024 {
37            return Err(AppError::invalid_input(
38                "Invalid preview path or text exceeds 4 MiB",
39            ));
40        }
41        let directory = tempfile::Builder::new()
42            .prefix("agent-hub-preview-")
43            .tempdir()
44            .map_err(AppError::io)?;
45        let file = directory.path().join(path);
46        if let Some(parent) = file.parent() {
47            fs::create_dir_all(parent).map_err(AppError::io)?;
48        }
49        fs::write(&file, content).map_err(AppError::io)?;
50        let mut session = self
51            .session
52            .lock()
53            .map_err(|_| AppError::internal("Preview state is unavailable"))?;
54        if session.closed {
55            return Err(AppError::cancelled("Preview session has ended"));
56        }
57        session.directories.push(directory);
58        Ok(file)
59    }
60}
61
62#[cfg(test)]
63mod tests;