Skip to main content

agent_hub_runtime/core/preview/
development.rs

1//! Vite project previews run in owned terminal panes; ordinary HTML stays static.
2use anyhow::{bail, Context, Result};
3use portable_pty::CommandBuilder;
4use serde::{Deserialize, Serialize};
5use std::{
6    net::TcpListener,
7    path::{Path, PathBuf},
8    time::{Duration, Instant},
9};
10
11#[derive(Clone, Deserialize, Serialize)]
12pub struct DevelopmentLaunch {
13    pub relative_path: String,
14    pub port: u16,
15}
16#[derive(Serialize)]
17pub struct DevelopmentPlan {
18    pub directory: String,
19    pub url: String,
20    pub running: bool,
21    pub launch: DevelopmentLaunch,
22}
23
24fn package_directory(root: &Path, relative: &str) -> Result<Option<PathBuf>> {
25    let path = crate::core::project_file_actions::existing_path(root, relative)?;
26    if !path.is_file()
27        || !path
28            .extension()
29            .and_then(|s| s.to_str())
30            .is_some_and(|s| s.eq_ignore_ascii_case("html") || s.eq_ignore_ascii_case("htm"))
31    {
32        return Ok(None);
33    }
34    let mut directory = path.parent();
35    while let Some(current) = directory.filter(|path| path.starts_with(root)) {
36        let package = current.join("package.json");
37        if package.exists() {
38            let text = crate::core::project_worktrees::read_file(
39                root,
40                &package.strip_prefix(root)?.to_string_lossy(),
41            )?;
42            let value: serde_json::Value = serde_json::from_str(&text)?;
43            // Only explicit Vite dev scripts accept the controlled host/port arguments below.
44            return Ok(value["scripts"]["dev"]
45                .as_str()
46                .filter(|script| script.split_whitespace().next() == Some("vite"))
47                .map(|_| current.to_path_buf()));
48        }
49        directory = current.parent();
50    }
51    Ok(None)
52}
53
54fn client() -> Result<reqwest::blocking::Client> {
55    Ok(reqwest::blocking::Client::builder()
56        .no_proxy()
57        .timeout(Duration::from_millis(500))
58        .redirect(reqwest::redirect::Policy::none())
59        .build()?)
60}
61fn ready(client: &reqwest::blocking::Client, port: u16) -> bool {
62    client
63        .get(format!("http://127.0.0.1:{port}/@vite/client"))
64        .send()
65        .is_ok_and(|response| response.status().is_success())
66}
67
68/// Match the process working directory before inspecting its listening ports.
69fn running_port(directory: &Path) -> Result<Option<u16>> {
70    use sysinfo::{ProcessRefreshKind, System, UpdateKind};
71    let mut system = System::new();
72    system.refresh_processes_specifics(
73        ProcessRefreshKind::new()
74            .with_cmd(UpdateKind::Always)
75            .with_cwd(UpdateKind::Always),
76    );
77    let client = client()?;
78    for process in system.processes().values().filter(|process| {
79        process.cwd().and_then(|p| p.canonicalize().ok()).as_deref() == Some(directory)
80            && process
81                .cmd()
82                .iter()
83                .any(|arg| arg.replace('\\', "/").contains("vite"))
84    }) {
85        #[cfg(unix)]
86        let ports = {
87            let output = std::process::Command::new("lsof")
88                .args([
89                    "-a",
90                    "-p",
91                    &process.pid().to_string(),
92                    "-iTCP",
93                    "-sTCP:LISTEN",
94                    "-Fn",
95                ])
96                .output()
97                .context("Cannot inspect development server ports (lsof required)")?;
98            String::from_utf8_lossy(&output.stdout)
99                .lines()
100                .filter_map(|line| {
101                    line.strip_prefix('n')?
102                        .rsplit(':')
103                        .next()?
104                        .parse::<u16>()
105                        .ok()
106                })
107                .collect::<Vec<_>>()
108        };
109        #[cfg(windows)]
110        let ports = {
111            let output = std::process::Command::new("netstat")
112                .args(["-ano", "-p", "tcp"])
113                .output()?;
114            String::from_utf8_lossy(&output.stdout)
115                .lines()
116                .filter_map(|line| {
117                    let fields: Vec<_> = line.split_whitespace().collect();
118                    if fields.len() != 5
119                        || fields[4] != process.pid().to_string()
120                        || fields[3] != "LISTENING"
121                    {
122                        return None;
123                    }
124                    fields[1].rsplit(':').next()?.parse::<u16>().ok()
125                })
126                .collect::<Vec<_>>()
127        };
128        for port in ports {
129            if ready(&client, port) {
130                return Ok(Some(port));
131            }
132        }
133    }
134    Ok(None)
135}
136
137pub fn plan(root: &Path, relative: &str) -> Result<Option<DevelopmentPlan>> {
138    let root = root.canonicalize()?;
139    let Some(directory) = package_directory(&root, relative)? else {
140        return Ok(None);
141    };
142    let running = running_port(&directory)?;
143    let port = match running {
144        Some(port) => port,
145        None => TcpListener::bind(("127.0.0.1", 0))?.local_addr()?.port(),
146    };
147    let path = crate::core::project_file_actions::existing_path(&root, relative)?;
148    let suffix = path
149        .strip_prefix(&directory)?
150        .to_string_lossy()
151        .replace('\\', "/");
152    Ok(Some(DevelopmentPlan {
153        directory: directory.to_string_lossy().into_owned(),
154        url: format!(
155            "http://127.0.0.1:{port}/{}",
156            super::documents::resource_path(&suffix)
157        ),
158        running: running.is_some(),
159        launch: DevelopmentLaunch {
160            relative_path: relative.into(),
161            port,
162        },
163    }))
164}
165
166pub fn command(root: &Path, launch: &DevelopmentLaunch) -> Result<(PathBuf, CommandBuilder)> {
167    if launch.port < 1024 {
168        bail!("Invalid development server port");
169    }
170    let directory = package_directory(root, &launch.relative_path)?
171        .context("No supported Vite development script found")?;
172    let manager = if directory.join("pnpm-lock.yaml").is_file() {
173        "pnpm"
174    } else if directory.join("yarn.lock").is_file() {
175        "yarn"
176    } else if directory.join("bun.lock").is_file() || directory.join("bun.lockb").is_file() {
177        "bun"
178    } else {
179        "npm"
180    };
181    #[cfg(windows)]
182    let mut command = {
183        if manager == "bun" {
184            CommandBuilder::new("bun")
185        } else {
186            let mut command = CommandBuilder::new("cmd.exe");
187            command.args(["/d", "/c", &format!("{manager}.cmd")]);
188            command
189        }
190    };
191    #[cfg(not(windows))]
192    let mut command = CommandBuilder::new(manager);
193    command.args(["run", "dev"]);
194    if manager == "npm" {
195        command.arg("--");
196    }
197    command.args([
198        "--host",
199        "127.0.0.1",
200        "--port",
201        &launch.port.to_string(),
202        "--strictPort",
203    ]);
204    command.env("TERM", "xterm-256color");
205    Ok((directory, command))
206}
207
208pub fn wait(port: u16) -> Result<()> {
209    if port < 1024 {
210        bail!("Invalid development server port");
211    }
212    let client = client()?;
213    let deadline = Instant::now() + Duration::from_secs(30);
214    while Instant::now() < deadline {
215        if ready(&client, port) {
216            return Ok(());
217        }
218        std::thread::sleep(Duration::from_millis(200));
219    }
220    bail!("Development server did not become ready within 30 seconds; check its terminal output")
221}
222
223#[cfg(test)]
224mod tests;