The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
//! Run the local App workflows through the installed CLI with no external executables on PATH.
use anyhow::{Context, Result};
use axum::{
Json, Router,
extract::{WebSocketUpgrade, ws::Message},
http::HeaderMap,
routing::{get, post},
};
use nix::{
sys::signal::{Signal, kill},
unistd::Pid,
};
use serde_json::{Value, json};
use std::{fs, net::SocketAddr, path::Path, process::Stdio, time::Duration};
use tokio::{
io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader},
net::{TcpListener, TcpStream},
process::{Child, Command},
time::timeout,
};
async fn platform(routes: Router) -> Result<String> {
let listener = TcpListener::bind("127.0.0.1:0").await?;
let url = format!("http://{}/api", listener.local_addr()?);
let app = Router::new().nest("/api/v1/org/apps/shop/envs/qa", routes);
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
Ok(url)
}
fn cli(dir: &Path, url: &str) -> Command {
let mut command = Command::new(assert_cmd::cargo::cargo_bin!("boxlite"));
command
.current_dir(dir)
.env_clear()
.env("HOME", dir)
.env("PATH", "")
.env("BOXLITE_API_KEY", "fixture-org-key")
.args([
"--url",
url,
"--path-prefix",
"org",
"app",
"--app",
"shop",
"--env",
"qa",
"--json",
])
.kill_on_drop(true);
command
}
async fn first_event(child: &mut Child) -> Result<Value> {
let mut lines = BufReader::new(child.stdout.take().context("expected stdout")?).lines();
let line = timeout(Duration::from_secs(10), lines.next_line())
.await??
.context("CLI exited before reporting its listening address")?;
Ok(serde_json::from_str(&line)?)
}
async fn stop(child: &mut Child, port: SocketAddr) -> Result<()> {
kill(
Pid::from_raw(child.id().context("CLI already exited")? as i32),
Signal::SIGTERM,
)?;
assert!(
timeout(Duration::from_secs(10), child.wait())
.await??
.success()
);
assert!(
TcpStream::connect(port).await.is_err(),
"CLI kept listening after exit"
);
Ok(())
}
#[tokio::test]
async fn app_local_dev_serves_static_files_without_node() -> Result<()> {
let url = platform(Router::new().route(
"/dev-env",
get(|| async { Json(json!({"env":{"COLOR":"blue"},"database":null})) }),
))
.await?;
let dir = tempfile::tempdir()?;
let addr = TcpListener::bind("127.0.0.1:0").await?.local_addr()?;
fs::create_dir(dir.path().join("public"))?;
fs::write(dir.path().join("public/index.html"), "<h1>Shop</h1>")?;
fs::write(
dir.path().join("boxlite.toml"),
format!(
r#"[app]
name = "shop"
[runtime]
image = "base"
[[service]]
name = "web"
static = "public"
port = {}
"#,
addr.port()
),
)?;
let mut dev = cli(dir.path(), &url)
.args(["dev", "--as", "[email protected]"])
.stdout(Stdio::piped())
.spawn()?;
let ready = first_event(&mut dev).await?;
assert_eq!(ready["source"], "web");
assert!(ready["line"].as_str().unwrap().contains(&addr.to_string()));
let response = reqwest::get(format!("http://{addr}/")).await?;
assert_eq!(response.status(), 200);
assert_eq!(response.text().await?, "<h1>Shop</h1>");
let env = fs::read_to_string(dir.path().join(".env.local"))?;
assert!(env.contains("COLOR=blue") && env.contains("[email protected]"));
stop(&mut dev, addr).await
}
#[tokio::test]
async fn app_local_psql_uses_the_api_and_tunnels_without_node_or_psql() -> Result<()> {
let routes = Router::new()
.route(
"/db",
get(|| async { Json(json!({"status":"ready","database":"records"})) }),
)
.route(
"/db/sql",
post(|Json(body): Json<Value>| async move {
assert_eq!(
body,
json!({"query":"SELECT 1","write":false,"explain":true})
);
Json(json!({"columns":["QUERY PLAN"],"rows":[["Result"]],"row_count":1}))
}),
)
.route(
"/db/connect",
get(|headers: HeaderMap, ws: WebSocketUpgrade| async move {
assert_eq!(headers["authorization"], "Bearer fixture-org-key");
assert!(headers.contains_key("x-boxlite-proxy-session"));
ws.on_upgrade(|mut socket| async move {
let Some(Ok(Message::Binary(bytes))) = socket.recv().await else {
panic!("expected PostgreSQL SSLRequest")
};
assert_eq!(bytes.as_ref(), &[0, 0, 0, 8, 4, 210, 22, 47]);
socket
.send(Message::Binary(b"N".to_vec().into()))
.await
.unwrap();
})
}),
);
let url = platform(routes).await?;
let dir = tempfile::tempdir()?;
let mut query = cli(dir.path(), &url)
.args(["psql", "--query", "-", "--explain"])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()?;
query.stdin.take().unwrap().write_all(b"SELECT 1").await?;
let query = timeout(Duration::from_secs(10), query.wait_with_output()).await??;
assert!(query.status.success());
let result: Value = serde_json::from_slice(&query.stdout)?;
assert_eq!(result["rows"], json!([["Result"]]));
let mut proxy = cli(dir.path(), &url)
.args(["psql", "--proxy", "--port", "0"])
.stdout(Stdio::piped())
.spawn()?;
let ready = first_event(&mut proxy).await?;
assert_eq!(ready["role"], "reader");
assert_eq!(ready["host"], "127.0.0.1");
let addr = SocketAddr::from(([127, 0, 0, 1], ready["port"].as_u64().unwrap() as u16));
assert_eq!(
ready["database_url"],
format!("postgresql://boxlite@{addr}/records?sslmode=disable")
);
let mut client = TcpStream::connect(addr).await?;
client.write_all(&[0, 0, 0, 8, 4, 210, 22, 47]).await?;
assert_eq!(
timeout(Duration::from_secs(10), client.read_u8()).await??,
b'N'
);
stop(&mut proxy, addr).await
}