use std::io::{BufRead, BufReader, Read, Write};
use std::net::TcpStream;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::atomic::AtomicBool;
use std::sync::{mpsc, Arc, Mutex};
use std::time::{Duration, Instant};
use blyte_cli::http::Request;
use blyte_cli::serve::{generate_token, route, OpenCodes, Surface, TOKEN_HEADER};
use blyte_cli::session::{EntryBody, PromptRunner, Session};
use blyte_cli::surface_dir::{list_records_in, surfaces_dir};
use blyte_cli::surface_registry::read_entries;
use blyte_cli::surface_version::SurfaceRuntimeInfo;
struct NoopRunner;
impl PromptRunner for NoopRunner {
fn run(
&mut self,
_prompt: &str,
_model: &str,
_emit: &(dyn Fn(EntryBody) + Sync),
) -> Result<(), String> {
Ok(())
}
}
struct BlockingRunner {
started: mpsc::Sender<()>,
release: Arc<Mutex<Option<mpsc::Receiver<()>>>>,
}
impl PromptRunner for BlockingRunner {
fn run(
&mut self,
_prompt: &str,
_model: &str,
_emit: &(dyn Fn(EntryBody) + Sync),
) -> Result<(), String> {
let _ = self.started.send(());
if let Some(rx) = self.release.lock().unwrap().take() {
let _ = rx.recv_timeout(Duration::from_secs(10));
}
Ok(())
}
}
fn make_executable_file(path: &Path, bytes: &[u8]) {
std::fs::write(path, bytes).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
}
}
fn make_surface_with_runner(
root: PathBuf,
runtime: SurfaceRuntimeInfo,
runner: Box<dyn PromptRunner>,
) -> Surface {
let session = Session::start(runner, "m1".to_string());
let mcp = Arc::new(blyte_cli::mcp::McpManager::empty_in(&root));
Surface {
surface_id: "s00000000000000c1".to_string(),
surface_name: "reload-test".to_string(),
root,
repo: "reload-test".to_string(),
session,
session_id: "sess-reload-test".to_string(),
started_at: 1_700_000_000,
runtime,
days: 14,
token: generate_token().unwrap(),
message_credential: generate_token().unwrap(),
open_codes: OpenCodes::new(),
requests: Arc::new(blyte_cli::requests::RequestsState::new()),
publisher: Arc::new(blyte_cli::requests::RealPublisher),
mcp,
reconcile_lock: Mutex::new(()),
reconcile_requested: AtomicBool::new(false),
}
}
fn make_request(method: &str, path: &str, token: Option<&str>) -> Request {
let headers = match token {
Some(t) => vec![(TOKEN_HEADER.to_string(), t.to_string())],
None => Vec::new(),
};
Request {
method: method.to_string(),
path: path.to_string(),
query: Vec::new(),
headers,
body: Vec::new(),
}
}
#[test]
fn reload_endpoint_rejects_unauthenticated_and_non_post() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
std::fs::create_dir_all(&repo).unwrap();
let fake_bin = tmp.path().join("blyte-bin");
make_executable_file(&fake_bin, b"#!/bin/sh\n");
let runtime = SurfaceRuntimeInfo::from_binary("0.83.0", &fake_bin, "boot-auth-1").unwrap();
let surface = make_surface_with_runner(repo, runtime, Box::new(NoopRunner));
let unauth = route(&surface, &make_request("POST", "/api/reload", None), 100);
assert_eq!(unauth.status, 403);
let wrong = route(
&surface,
&make_request("POST", "/api/reload", Some("wrong-token")),
100,
);
assert_eq!(wrong.status, 403);
let wrong_method = route(
&surface,
&make_request("GET", "/api/reload", Some(&surface.token)),
100,
);
assert_eq!(wrong_method.status, 405);
}
#[test]
fn reload_endpoint_refuses_active_turn_with_409_conflict() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
std::fs::create_dir_all(&repo).unwrap();
let fake_bin = tmp.path().join("blyte-bin");
make_executable_file(&fake_bin, b"#!/bin/sh\n");
let (started_tx, started_rx) = mpsc::channel();
let (release_tx, release_rx) = mpsc::channel();
let runner = BlockingRunner {
started: started_tx,
release: Arc::new(Mutex::new(Some(release_rx))),
};
let runtime = SurfaceRuntimeInfo::from_binary("0.83.0", &fake_bin, "boot-turn-1").unwrap();
let surface = make_surface_with_runner(repo, runtime, Box::new(runner));
let _ = surface.session.submit("do work", Vec::new()).unwrap();
started_rx
.recv_timeout(Duration::from_secs(5))
.expect("blocking turn did not start");
let conflict = route(
&surface,
&make_request("POST", "/api/reload", Some(&surface.token)),
100,
);
assert_eq!(conflict.status, 409);
let body: serde_json::Value = serde_json::from_slice(&conflict.body).unwrap();
let err_msg = body["error"].as_str().unwrap().to_lowercase();
assert!(
err_msg.contains("turn") && err_msg.contains("progress"),
"expected active turn conflict error, got: {body:?}"
);
let _ = release_tx.send(());
let deadline = Instant::now() + Duration::from_secs(5);
while Instant::now() < deadline {
if !surface.session.info().busy {
break;
}
std::thread::sleep(Duration::from_millis(20));
}
assert!(!surface.session.info().busy);
let ok = route(
&surface,
&make_request("POST", "/api/reload", Some(&surface.token)),
101,
);
assert_eq!(ok.status, 200);
let ok_body: serde_json::Value = serde_json::from_slice(&ok.body).unwrap();
assert_eq!(ok_body["reloading"], true);
}
#[test]
fn reload_endpoint_verifies_target_executable_before_accepting_reload() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
std::fs::create_dir_all(&repo).unwrap();
let fake_bin = tmp.path().join("blyte-bin");
std::fs::write(&fake_bin, b"not-executable").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&fake_bin, std::fs::Permissions::from_mode(0o644)).unwrap();
}
let runtime = SurfaceRuntimeInfo::from_binary("0.83.0", &fake_bin, "boot-exec-1").unwrap();
let surface = make_surface_with_runner(repo, runtime, Box::new(NoopRunner));
#[cfg(unix)]
{
let non_exec = route(
&surface,
&make_request("POST", "/api/reload", Some(&surface.token)),
100,
);
assert_eq!(non_exec.status, 500);
let body: serde_json::Value = serde_json::from_slice(&non_exec.body).unwrap();
assert!(
body["error"].as_str().unwrap().contains("not executable"),
"expected not executable error, got: {body:?}"
);
}
std::fs::remove_file(&fake_bin).unwrap();
let missing = route(
&surface,
&make_request("POST", "/api/reload", Some(&surface.token)),
101,
);
assert_eq!(missing.status, 500);
let missing_body: serde_json::Value = serde_json::from_slice(&missing.body).unwrap();
assert!(
missing_body["error"]
.as_str()
.unwrap()
.contains(&fake_bin.display().to_string()),
"expected missing path in error, got: {missing_body:?}"
);
}
#[cfg(unix)]
mod unix_e2e {
use super::*;
struct ChildGuard(Option<std::process::Child>);
impl Drop for ChildGuard {
fn drop(&mut self) {
if let Some(mut child) = self.0.take() {
let pid = child.id().to_string();
let _ = Command::new("kill").args(["-TERM", &pid]).status();
let deadline = Instant::now() + Duration::from_secs(3);
while Instant::now() < deadline {
if let Ok(Some(_)) = child.try_wait() {
return;
}
std::thread::sleep(Duration::from_millis(25));
}
let _ = child.kill();
let _ = child.wait();
}
}
}
struct RunningSurface {
guard: ChildGuard,
port: u16,
token: String,
_rx: mpsc::Receiver<String>,
_stdout_handle: std::thread::JoinHandle<()>,
_stderr_handle: std::thread::JoinHandle<String>,
}
fn init_repo_with_commit(repo: &Path) {
std::fs::create_dir_all(repo).unwrap();
let run = |args: &[&str]| {
let out = Command::new("git")
.args(args)
.current_dir(repo)
.output()
.unwrap();
assert!(
out.status.success(),
"git {:?} failed: {}",
args,
String::from_utf8_lossy(&out.stderr)
);
};
run(&["init", "-b", "main"]);
run(&["config", "user.name", "Test"]);
run(&["config", "user.email", "test@example.com"]);
std::fs::write(repo.join("README.md"), "hello\n").unwrap();
run(&["add", "README.md"]);
run(&["commit", "-m", "initial"]);
}
fn spawn_surface(repo: &Path, home: &Path, state_dir: &Path) -> RunningSurface {
let bin_path = PathBuf::from(env!("CARGO_BIN_EXE_blyte"));
let mut child = Command::new(&bin_path)
.args(["--foreground", "--no-open", "--port", "0"])
.current_dir(repo)
.env("HOME", home)
.env("XDG_CONFIG_HOME", home.join(".config"))
.env("BLYTE_STATE_DIR", state_dir)
.env("BLYTE_ENV_FILE", "")
.env("BLYTE_NO_UPDATE_CHECK", "1")
.env("BLYTE_USAGE_LOG", "off")
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
let stdout = child.stdout.take().unwrap();
let mut stderr = child.stderr.take().unwrap();
let mut guard = ChildGuard(Some(child));
let stderr_handle = std::thread::spawn(move || {
let mut buf = String::new();
let _ = stderr.read_to_string(&mut buf);
buf
});
let (tx, rx) = mpsc::channel::<String>();
let stdout_handle = std::thread::spawn(move || {
for line in BufReader::new(stdout).lines().map_while(Result::ok) {
if tx.send(line).is_err() {
break;
}
}
});
let deadline = Instant::now() + Duration::from_secs(15);
let mut url: Option<String> = None;
let mut seen = Vec::new();
while Instant::now() < deadline {
let remaining = deadline.saturating_duration_since(Instant::now());
match rx.recv_timeout(remaining.min(Duration::from_millis(100))) {
Ok(line) => {
if let Some((_, rest)) = line.split_once(" at http://127.0.0.1:") {
url = Some(format!("http://127.0.0.1:{rest}"));
break;
}
seen.push(line);
}
Err(mpsc::RecvTimeoutError::Timeout) => {}
Err(mpsc::RecvTimeoutError::Disconnected) => break,
}
}
let url = match url {
Some(u) => u,
None => {
if let Some(mut c) = guard.0.take() {
let _ = c.kill();
let _ = c.wait();
}
let err_text = stderr_handle.join().unwrap_or_default();
drop(rx);
let _ = stdout_handle.join();
panic!(
"surface did not print url\nstdout:\n{}\nstderr:\n{err_text}",
seen.join("\n")
);
}
};
let (base, token) = url.split_once("/#token=").unwrap();
let port: u16 = base
.strip_prefix("http://127.0.0.1:")
.unwrap()
.parse()
.unwrap();
RunningSurface {
guard,
port,
token: token.to_string(),
_rx: rx,
_stdout_handle: stdout_handle,
_stderr_handle: stderr_handle,
}
}
fn http_json(
method: &str,
port: u16,
path: &str,
token: &str,
) -> Result<(u16, serde_json::Value), String> {
let mut stream =
TcpStream::connect(("127.0.0.1", port)).map_err(|e| format!("connect: {e}"))?;
let _ = stream.set_read_timeout(Some(Duration::from_secs(5)));
let _ = stream.set_write_timeout(Some(Duration::from_secs(5)));
let body = if method == "POST" { "{}" } else { "" };
let req = format!(
"{method} {path} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n{TOKEN_HEADER}: {token}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
);
stream
.write_all(req.as_bytes())
.map_err(|e| format!("write: {e}"))?;
let mut raw = String::new();
stream
.read_to_string(&mut raw)
.map_err(|e| format!("read: {e}"))?;
let (head, resp_body) = raw
.split_once("\r\n\r\n")
.ok_or_else(|| format!("malformed response: {raw}"))?;
let status = head
.lines()
.next()
.and_then(|l| l.split_whitespace().nth(1))
.and_then(|s| s.parse::<u16>().ok())
.ok_or_else(|| format!("bad status line: {head}"))?;
let json =
serde_json::from_str(resp_body).map_err(|e| format!("bad json ({e}): {resp_body}"))?;
Ok((status, json))
}
fn wait_for_new_boot_id(
port: u16,
token: &str,
old_boot_id: &str,
timeout: Duration,
) -> serde_json::Value {
let deadline = Instant::now() + timeout;
let mut last = String::new();
while Instant::now() < deadline {
match http_json("GET", port, "/api/session", token) {
Ok((200, val)) => {
if let Some(bid) = val["boot_id"].as_str() {
if !bid.is_empty() && bid != old_boot_id {
return val;
}
}
last = format!("same boot_id: {val}");
}
Ok((status, val)) => last = format!("HTTP {status}: {val}"),
Err(e) => last = e,
}
std::thread::sleep(Duration::from_millis(100));
}
panic!("surface on port {port} did not return with a new boot_id (last: {last})");
}
#[test]
fn end_to_end_post_api_reload_reexecs_same_port_token_surface_and_new_boot_id() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("reload-e2e");
let home = tmp.path().join("home");
let state_dir = tmp.path().join("state");
std::fs::create_dir_all(&home).unwrap();
init_repo_with_commit(&repo);
let running = spawn_surface(&repo, &home, &state_dir);
let (status1, sess1) = http_json("GET", running.port, "/api/session", &running.token)
.expect("initial GET /api/session failed");
assert_eq!(status1, 200);
let boot1 = sess1["boot_id"].as_str().unwrap().to_string();
let surface_name1 = sess1["surface_name"].as_str().unwrap().to_string();
let recs1 = list_records_in(&surfaces_dir(&repo)).unwrap().records;
assert_eq!(recs1.len(), 1);
let surface_id1 = recs1[0].record.id.clone();
let pid1 = recs1[0].record.pid;
let (reload_status, reload_body) =
http_json("POST", running.port, "/api/reload", &running.token)
.expect("POST /api/reload failed");
assert_eq!(reload_status, 200);
assert_eq!(reload_body["reloading"], true);
let sess2 = wait_for_new_boot_id(
running.port,
&running.token,
&boot1,
Duration::from_secs(15),
);
let boot2 = sess2["boot_id"].as_str().unwrap().to_string();
assert_ne!(boot2, boot1);
assert_eq!(sess2["surface_name"].as_str().unwrap(), surface_name1);
let (health_status, health) =
http_json("GET", running.port, "/api/health", &running.token).unwrap();
assert_eq!(health_status, 200);
assert_eq!(health["surface_id"].as_str().unwrap(), surface_id1);
let recs2 = list_records_in(&surfaces_dir(&repo)).unwrap().records;
assert_eq!(recs2.len(), 1);
assert_eq!(recs2[0].record.id, surface_id1);
assert_eq!(recs2[0].record.pid, pid1);
let reg = read_entries(&state_dir.join("surfaces")).unwrap();
assert!(reg.unreadable.is_empty(), "{:?}", reg.unreadable);
assert_eq!(reg.entries.len(), 1);
assert_eq!(reg.entries[0].id, surface_id1);
assert_eq!(reg.entries[0].port, running.port);
assert_eq!(reg.entries[0].runtime.boot_id, boot2);
drop(running.guard);
}
#[test]
fn blyte_reload_cli_named_all_and_unknown_error() {
let tmp = tempfile::tempdir().unwrap();
let repo_one = tmp.path().join("repo-one");
let repo_two = tmp.path().join("repo-two");
let home = tmp.path().join("home");
let state_dir = tmp.path().join("state");
std::fs::create_dir_all(&home).unwrap();
init_repo_with_commit(&repo_one);
init_repo_with_commit(&repo_two);
let surf_one = spawn_surface(&repo_one, &home, &state_dir);
let surf_two = spawn_surface(&repo_two, &home, &state_dir);
let (_, s1_initial) =
http_json("GET", surf_one.port, "/api/session", &surf_one.token).unwrap();
let (_, s2_initial) =
http_json("GET", surf_two.port, "/api/session", &surf_two.token).unwrap();
let boot1_a = s1_initial["boot_id"].as_str().unwrap().to_string();
let boot2_a = s2_initial["boot_id"].as_str().unwrap().to_string();
let bin_path = PathBuf::from(env!("CARGO_BIN_EXE_blyte"));
let run_cli = |args: &[&str], cwd: &Path| {
Command::new(&bin_path)
.args(args)
.current_dir(cwd)
.env("HOME", &home)
.env("XDG_CONFIG_HOME", home.join(".config"))
.env("BLYTE_STATE_DIR", &state_dir)
.env("BLYTE_ENV_FILE", "")
.env("BLYTE_NO_UPDATE_CHECK", "1")
.env("BLYTE_USAGE_LOG", "off")
.output()
.unwrap()
};
let unknown = run_cli(&["reload", "does-not-exist"], &repo_one);
assert!(!unknown.status.success());
let unknown_err = String::from_utf8_lossy(&unknown.stderr);
assert!(
unknown_err.contains("does-not-exist"),
"expected unknown surface name in stderr, got: {unknown_err}"
);
let named = run_cli(&["reload", "repo-one"], &repo_two);
assert!(
named.status.success(),
"blyte reload repo-one failed: stdout={} stderr={}",
String::from_utf8_lossy(&named.stdout),
String::from_utf8_lossy(&named.stderr)
);
let named_out = String::from_utf8_lossy(&named.stdout);
assert!(named_out.contains("repo-one"), "{named_out}");
let s1_after_named = wait_for_new_boot_id(
surf_one.port,
&surf_one.token,
&boot1_a,
Duration::from_secs(15),
);
let boot1_b = s1_after_named["boot_id"].as_str().unwrap().to_string();
assert_ne!(boot1_b, boot1_a);
let (_, s2_still_same) =
http_json("GET", surf_two.port, "/api/session", &surf_two.token).unwrap();
assert_eq!(s2_still_same["boot_id"].as_str().unwrap(), boot2_a);
let cwd_default = run_cli(&["reload"], &repo_two);
assert!(
cwd_default.status.success(),
"blyte reload (default cwd) failed: stdout={} stderr={}",
String::from_utf8_lossy(&cwd_default.stdout),
String::from_utf8_lossy(&cwd_default.stderr)
);
let s2_after_cwd = wait_for_new_boot_id(
surf_two.port,
&surf_two.token,
&boot2_a,
Duration::from_secs(15),
);
let boot2_b = s2_after_cwd["boot_id"].as_str().unwrap().to_string();
assert_ne!(boot2_b, boot2_a);
let all = run_cli(&["reload", "--all"], &repo_one);
assert!(
all.status.success(),
"blyte reload --all failed: stdout={} stderr={}",
String::from_utf8_lossy(&all.stdout),
String::from_utf8_lossy(&all.stderr)
);
let all_out = String::from_utf8_lossy(&all.stdout);
assert!(all_out.contains("repo-one"), "{all_out}");
assert!(all_out.contains("repo-two"), "{all_out}");
let s1_after_all = wait_for_new_boot_id(
surf_one.port,
&surf_one.token,
&boot1_b,
Duration::from_secs(15),
);
let s2_after_all = wait_for_new_boot_id(
surf_two.port,
&surf_two.token,
&boot2_b,
Duration::from_secs(15),
);
assert_ne!(s1_after_all["boot_id"].as_str().unwrap(), boot1_b);
assert_ne!(s2_after_all["boot_id"].as_str().unwrap(), boot2_b);
drop(surf_one.guard);
drop(surf_two.guard);
}
}