use std::ffi::OsString;
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{mpsc, Arc, Mutex, MutexGuard};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};
use blyte_agent::sandbox::surface_token_path_for_id;
use blyte_agent::tools::PeerTools;
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, read_record_in, surfaces_dir, write_record_in, SurfaceRecord,
};
use blyte_cli::surface_registry::{
entry_path, read_entries, write_entry, RegistryEntry, SurfaceState,
};
use blyte_cli::surface_version::{BinaryFingerprint, SurfaceRuntimeInfo, CURRENT_VERSION};
use blyte_cli::surfaces_cmd::{run_surfaces, surfaces_payload};
use blyte_cli::tell::SurfacePeerTools;
static ENV_MUTEX: Mutex<()> = Mutex::new(());
struct EnvGuard {
_lock: MutexGuard<'static, ()>,
prev_xdg: Option<OsString>,
prev_blyte_state: Option<OsString>,
}
impl EnvGuard {
fn set_state_root(state_root: &Path) -> Self {
let lock = ENV_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
let prev_xdg = std::env::var_os("XDG_STATE_HOME");
let prev_blyte_state = std::env::var_os("BLYTE_STATE_DIR");
std::env::set_var("XDG_STATE_HOME", state_root);
std::env::set_var("BLYTE_STATE_DIR", state_root.join("blyte"));
Self {
_lock: lock,
prev_xdg,
prev_blyte_state,
}
}
}
impl Drop for EnvGuard {
fn drop(&mut self) {
match &self.prev_xdg {
Some(v) => std::env::set_var("XDG_STATE_HOME", v),
None => std::env::remove_var("XDG_STATE_HOME"),
}
match &self.prev_blyte_state {
Some(v) => std::env::set_var("BLYTE_STATE_DIR", v),
None => std::env::remove_var("BLYTE_STATE_DIR"),
}
}
}
struct NoopRunner;
impl PromptRunner for NoopRunner {
fn run(
&mut self,
_prompt: &str,
_model: &str,
_emit: &(dyn Fn(EntryBody) + Sync),
) -> Result<(), String> {
Ok(())
}
}
struct MockHealthServer {
port: u16,
stop: Arc<AtomicBool>,
handle: Option<JoinHandle<()>>,
}
impl MockHealthServer {
fn start(surface_id: &str) -> Self {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
listener.set_nonblocking(true).unwrap();
let stop = Arc::new(AtomicBool::new(false));
let stop_flag = Arc::clone(&stop);
let id = surface_id.to_string();
let handle = std::thread::spawn(move || {
while !stop_flag.load(Ordering::Relaxed) {
match listener.accept() {
Ok((mut stream, _)) => {
let _ = stream.set_read_timeout(Some(Duration::from_millis(500)));
let mut buf = [0u8; 1024];
let _ = stream.read(&mut buf);
let body = format!(r#"{{"surface_id":"{id}"}}"#);
let resp = format!(
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
body.len(),
body
);
let _ = stream.write_all(resp.as_bytes());
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
std::thread::sleep(Duration::from_millis(10));
}
Err(_) => break,
}
}
});
Self {
port,
stop,
handle: Some(handle),
}
}
}
impl Drop for MockHealthServer {
fn drop(&mut self) {
self.stop.store(true, Ordering::Relaxed);
let _ = TcpStream::connect(("127.0.0.1", self.port));
if let Some(handle) = self.handle.take() {
let _ = handle.join();
}
}
}
fn make_entry(
id: &str,
name: &str,
root: PathBuf,
port: u16,
started_at: u64,
runtime: SurfaceRuntimeInfo,
) -> RegistryEntry {
RegistryEntry {
id: id.to_string(),
name: name.to_string(),
root,
branch: Some("main".to_string()),
pid: std::process::id(),
port,
started_at,
doing: "idle".to_string(),
state: SurfaceState::Idle,
runtime,
}
}
fn make_surface(root: PathBuf, runtime: SurfaceRuntimeInfo) -> Surface {
let session = Session::start(Box::new(NoopRunner), "m1".to_string());
let mcp = Arc::new(blyte_cli::mcp::McpManager::empty_in(&root));
Surface {
surface_id: "s00000000000000aa".to_string(),
surface_name: "alpha".to_string(),
root,
repo: "alpha".to_string(),
session,
session_id: "sess-version-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_get_request(path: &str, token: &str) -> Request {
Request {
method: "GET".to_string(),
path: path.to_string(),
query: Vec::new(),
headers: vec![(TOKEN_HEADER.to_string(), token.to_string())],
body: Vec::new(),
}
}
fn write_token(id: &str, token: &str) {
let token_path = surface_token_path_for_id(id).unwrap();
std::fs::create_dir_all(token_path.parent().unwrap()).unwrap();
std::fs::write(&token_path, format!("{token}\n")).unwrap();
}
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"]);
}
#[test]
fn binary_fingerprint_detects_unchanged_modified_replaced_and_missing_binary() {
let tmp = tempfile::tempdir().unwrap();
let bin = tmp.path().join("blyte-bin");
std::fs::write(&bin, b"version-1-bytes").unwrap();
let fp = BinaryFingerprint::from_path(&bin).unwrap();
assert_eq!(fp.path, bin);
assert_eq!(fp.size, b"version-1-bytes".len() as u64);
assert!(!fp.is_stale().unwrap());
std::fs::write(&bin, b"version-2-longer-bytes").unwrap();
assert!(fp.is_stale().unwrap());
let fp2 = BinaryFingerprint::from_path(&bin).unwrap();
assert!(!fp2.is_stale().unwrap());
let replacement = tmp.path().join("blyte-bin.new");
std::fs::write(&replacement, b"version-3-replaced-bin").unwrap();
std::fs::rename(&replacement, &bin).unwrap();
assert!(fp2.is_stale().unwrap());
std::fs::remove_file(&bin).unwrap();
let err = fp2.is_stale().unwrap_err();
assert!(
err.contains(&bin.display().to_string()),
"error should name the missing binary: {err}"
);
}
#[test]
fn surface_runtime_info_generates_distinct_boot_ids_and_validates() {
let a = SurfaceRuntimeInfo::current().unwrap();
let b = SurfaceRuntimeInfo::current().unwrap();
assert_eq!(a.version, CURRENT_VERSION);
assert_eq!(b.version, CURRENT_VERSION);
assert!(!a.boot_id.is_empty());
assert!(!b.boot_id.is_empty());
assert_ne!(a.boot_id, b.boot_id);
assert!(!a.is_stale().unwrap());
assert!(!b.is_stale().unwrap());
let tmp = tempfile::tempdir().unwrap();
let bin = tmp.path().join("blyte");
std::fs::write(&bin, b"bin").unwrap();
assert!(SurfaceRuntimeInfo::from_binary("", &bin, "boot-1").is_err());
assert!(SurfaceRuntimeInfo::from_binary("0.83.0", &bin, " ").is_err());
assert!(SurfaceRuntimeInfo::from_binary("0.83.0", &tmp.path().join("missing"), "b1").is_err());
}
#[test]
fn surface_record_omits_runtime_and_registry_entry_requires_it() {
let tmp = tempfile::tempdir().unwrap();
let fake_bin = tmp.path().join("blyte");
std::fs::write(&fake_bin, b"fake-blyte-binary").unwrap();
let runtime =
SurfaceRuntimeInfo::from_binary("0.83.0 (abc1234)", &fake_bin, "boot-rt-1").unwrap();
let sdir = tmp.path().join("s00000000000000a1");
let record = SurfaceRecord {
id: "s00000000000000a1".to_string(),
name: "alpha".to_string(),
pid: std::process::id(),
port: 4321,
session_id: "sess-1".to_string(),
started_at: 1_700_000_000,
};
write_record_in(&sdir, &record).unwrap();
let raw_record: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(sdir.join("surface.json")).unwrap()).unwrap();
assert!(raw_record.get("version").is_none());
assert!(raw_record.get("boot_id").is_none());
assert!(raw_record.get("binary_fingerprint").is_none());
let loaded_record = read_record_in(&sdir, &record.id).unwrap();
assert_eq!(loaded_record, record);
let legacy_dir = tmp.path().join("s00000000000000a2");
std::fs::create_dir_all(&legacy_dir).unwrap();
std::fs::write(
legacy_dir.join("surface.json"),
r#"{"id":"s00000000000000a2","name":"legacy","pid":123,"port":0,"session_id":"s","started_at":1}"#,
)
.unwrap();
let legacy_record = read_record_in(&legacy_dir, "s00000000000000a2").unwrap();
assert_eq!(legacy_record.name, "legacy");
assert_eq!(legacy_record.pid, 123);
assert_eq!(legacy_record.session_id, "s");
assert_eq!(legacy_record.started_at, 1);
let newer_dir = tmp.path().join("s00000000000000a3");
std::fs::create_dir_all(&newer_dir).unwrap();
std::fs::write(
newer_dir.join("surface.json"),
r#"{"id":"s00000000000000a3","name":"newer","pid":7,"port":0,"session_id":"s3","started_at":2,"version":"0.85.0 (055df959)","binary_fingerprint":{"path":"/x/blyte","size":1,"modified_secs":1,"modified_nanos":0},"boot_id":"b"}"#,
)
.unwrap();
let newer_record = read_record_in(&newer_dir, "s00000000000000a3").unwrap();
assert_eq!(newer_record.name, "newer");
assert_eq!(newer_record.pid, 7);
let reg_dir = tmp.path().join("registry");
let entry = make_entry(
"s00000000000000a1",
"alpha",
tmp.path().join("repo"),
4321,
1_700_000_000,
runtime.clone(),
);
write_entry(®_dir, &entry).unwrap();
let raw_entry: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(entry_path(®_dir, &entry.id)).unwrap())
.unwrap();
assert_eq!(raw_entry["version"], "0.83.0 (abc1234)");
assert_eq!(raw_entry["boot_id"], "boot-rt-1");
assert_eq!(
raw_entry["binary_fingerprint"]["path"],
fake_bin.to_string_lossy().as_ref()
);
let legacy_reg_path = entry_path(®_dir, "s00000000000000a2");
std::fs::write(
&legacy_reg_path,
r#"{"id":"s00000000000000a2","name":"legacy","root":"/tmp/r","branch":"main","pid":1,"port":0,"started_at":1,"doing":"idle","state":"idle"}"#,
)
.unwrap();
let listing = read_entries(®_dir).unwrap();
assert_eq!(listing.entries, vec![entry]);
assert_eq!(listing.unreadable.len(), 1);
assert_eq!(listing.unreadable[0].path, legacy_reg_path);
assert!(
listing.unreadable[0].reason.contains("missing field"),
"unexpected unreadable reason: {}",
listing.unreadable[0].reason
);
assert!(
legacy_reg_path.exists(),
"unreadable registry entry must not be deleted"
);
}
#[test]
fn surfaces_cli_peer_tool_and_switcher_payload_report_version_and_staleness() {
let tmp = tempfile::tempdir().unwrap();
let _env_guard = EnvGuard::set_state_root(tmp.path());
let state_dir = tmp.path().join("blyte");
let reg_dir = state_dir.join("surfaces");
let repo_a = tmp.path().join("repo-current");
let repo_b = tmp.path().join("repo-stale");
let repo_c = tmp.path().join("repo-missing-bin");
std::fs::create_dir_all(&repo_a).unwrap();
std::fs::create_dir_all(&repo_b).unwrap();
std::fs::create_dir_all(&repo_c).unwrap();
let bin_current = tmp.path().join("blyte-current");
let bin_stale = tmp.path().join("blyte-stale");
let bin_missing = tmp.path().join("blyte-missing");
std::fs::write(&bin_current, b"current-binary").unwrap();
std::fs::write(&bin_stale, b"old-binary").unwrap();
std::fs::write(&bin_missing, b"vanishing-binary").unwrap();
let rt_current =
SurfaceRuntimeInfo::from_binary("0.83.0 (aaaaaaa)", &bin_current, "boot-cur").unwrap();
let rt_stale =
SurfaceRuntimeInfo::from_binary("0.82.0 (bbbbbbb)", &bin_stale, "boot-old").unwrap();
let rt_missing =
SurfaceRuntimeInfo::from_binary("0.81.0 (ccccccc)", &bin_missing, "boot-gone").unwrap();
std::fs::write(&bin_stale, b"rebuilt-newer-binary-bytes").unwrap();
std::fs::remove_file(&bin_missing).unwrap();
let srv_a = MockHealthServer::start("s00000000000000b1");
let srv_b = MockHealthServer::start("s00000000000000b2");
let srv_c = MockHealthServer::start("s00000000000000b3");
let entry_a = make_entry(
"s00000000000000b1",
"current-surf",
repo_a,
srv_a.port,
100,
rt_current,
);
let entry_b = make_entry(
"s00000000000000b2",
"stale-surf",
repo_b,
srv_b.port,
200,
rt_stale,
);
let entry_c = make_entry(
"s00000000000000b3",
"missing-bin-surf",
repo_c,
srv_c.port,
300,
rt_missing,
);
write_entry(®_dir, &entry_a).unwrap();
write_entry(®_dir, &entry_b).unwrap();
write_entry(®_dir, &entry_c).unwrap();
write_token(&entry_a.id, "tok-a");
write_token(&entry_b.id, "tok-b");
write_token(&entry_c.id, "tok-c");
let mut out = Vec::new();
let mut err = Vec::new();
let code = run_surfaces(®_dir, false, &mut out, &mut err);
assert_eq!(code, 0);
assert!(
err.is_empty(),
"unexpected stderr: {:?}",
String::from_utf8_lossy(&err)
);
let table = String::from_utf8(out).unwrap();
let lines: Vec<&str> = table.lines().collect();
assert_eq!(lines.len(), 4, "{table}");
assert!(lines[0].contains("VERSION"), "{table}");
assert!(lines[1].contains("0.83.0 (aaaaaaa)"), "{table}");
assert!(!lines[1].contains("(stale)"), "{table}");
assert!(lines[2].contains("0.82.0 (bbbbbbb) (stale)"), "{table}");
assert!(
lines[3].contains("0.81.0 (ccccccc) (stale unknown:"),
"{table}"
);
let mut json_out = Vec::new();
let mut json_err = Vec::new();
let json_code = run_surfaces(®_dir, true, &mut json_out, &mut json_err);
assert_eq!(json_code, 0);
assert!(json_err.is_empty());
let parsed: Vec<serde_json::Value> = serde_json::from_slice(&json_out).unwrap();
assert_eq!(parsed.len(), 3);
assert_eq!(parsed[0]["version"], "0.83.0 (aaaaaaa)");
assert_eq!(parsed[0]["boot_id"], "boot-cur");
assert_eq!(parsed[0]["stale"], false);
assert!(parsed[0].get("stale_error").is_none());
assert_eq!(parsed[1]["version"], "0.82.0 (bbbbbbb)");
assert_eq!(parsed[1]["boot_id"], "boot-old");
assert_eq!(parsed[1]["stale"], true);
assert!(parsed[1].get("stale_error").is_none());
assert_eq!(parsed[2]["version"], "0.81.0 (ccccccc)");
assert_eq!(parsed[2]["boot_id"], "boot-gone");
assert!(parsed[2]["stale"].is_null());
assert!(
parsed[2]["stale_error"]
.as_str()
.unwrap()
.contains(&bin_missing.display().to_string()),
"{:?}",
parsed[2]
);
let peer_tools = SurfacePeerTools {
registry_dir: reg_dir.clone(),
surface_id: entry_a.id.clone(),
surface_name: entry_a.name.clone(),
repository: "repo-current".to_string(),
};
let tool_out = peer_tools.surfaces().unwrap();
let tool_lines: Vec<&str> = tool_out.lines().collect();
assert_eq!(tool_lines.len(), 4, "{tool_out}");
assert!(tool_lines[0].contains("VERSION"), "{tool_out}");
assert!(
tool_lines[1].contains("current-surf (this surface)"),
"{tool_out}"
);
assert!(tool_lines[1].contains("0.83.0 (aaaaaaa)"), "{tool_out}");
assert!(!tool_lines[1].contains("(stale)"), "{tool_out}");
assert!(
tool_lines[2].contains("0.82.0 (bbbbbbb) (stale)"),
"{tool_out}"
);
assert!(
tool_lines[3].contains("0.81.0 (ccccccc) (stale unknown:"),
"{tool_out}"
);
let payload = surfaces_payload(®_dir, &state_dir, &entry_a.id, &[]).unwrap();
let surfaces = payload["surfaces"].as_array().unwrap();
assert_eq!(surfaces.len(), 3);
let by_name = |name: &str| {
surfaces
.iter()
.find(|s| s["name"].as_str() == Some(name))
.unwrap()
};
let cur = by_name("current-surf");
assert_eq!(cur["version"], "0.83.0 (aaaaaaa)");
assert_eq!(cur["boot_id"], "boot-cur");
assert_eq!(cur["stale"], false);
assert!(cur["stale_error"].is_null());
let stale = by_name("stale-surf");
assert_eq!(stale["version"], "0.82.0 (bbbbbbb)");
assert_eq!(stale["boot_id"], "boot-old");
assert_eq!(stale["stale"], true);
assert!(stale["stale_error"].is_null());
let missing = by_name("missing-bin-surf");
assert_eq!(missing["version"], "0.81.0 (ccccccc)");
assert_eq!(missing["boot_id"], "boot-gone");
assert!(missing["stale"].is_null());
assert!(
missing["stale_error"]
.as_str()
.unwrap()
.contains(&bin_missing.display().to_string()),
"{missing:?}"
);
}
#[test]
fn session_http_api_exposes_version_boot_id_and_stale_status() {
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-exe");
std::fs::write(&fake_bin, b"initial-binary").unwrap();
let runtime =
SurfaceRuntimeInfo::from_binary("0.83.0 (deadbee)", &fake_bin, "boot-http-1").unwrap();
let surface = make_surface(repo, runtime);
let req = make_get_request("/api/session", &surface.token);
let resp = route(&surface, &req, 1_700_000_010);
assert_eq!(resp.status, 200);
let body: serde_json::Value = serde_json::from_slice(&resp.body).unwrap();
assert_eq!(body["version"], "0.83.0 (deadbee)");
assert_eq!(body["boot_id"], "boot-http-1");
assert_eq!(body["stale"], false);
std::fs::write(&fake_bin, b"updated-binary-content").unwrap();
let resp_stale = route(&surface, &req, 1_700_000_020);
assert_eq!(resp_stale.status, 200);
let body_stale: serde_json::Value = serde_json::from_slice(&resp_stale.body).unwrap();
assert_eq!(body_stale["version"], "0.83.0 (deadbee)");
assert_eq!(body_stale["boot_id"], "boot-http-1");
assert_eq!(body_stale["stale"], true);
std::fs::remove_file(&fake_bin).unwrap();
let resp_err = route(&surface, &req, 1_700_000_030);
assert_eq!(resp_err.status, 500);
let body_err: serde_json::Value = serde_json::from_slice(&resp_err.body).unwrap();
assert!(
body_err["error"]
.as_str()
.unwrap()
.contains(&fake_bin.display().to_string()),
"expected missing binary path in 500 error, got: {body_err:?}"
);
}
#[cfg(unix)]
#[test]
fn real_surface_startup_records_version_fingerprint_and_boot_id_everywhere() {
struct ChildGuard(Option<std::process::Child>);
impl Drop for ChildGuard {
fn drop(&mut self) {
if let Some(mut child) = self.0.take() {
let _ = child.kill();
let _ = child.wait();
}
}
}
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("demo-repo");
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 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();
let records = list_records_in(&surfaces_dir(&repo)).unwrap().records;
assert_eq!(records.len(), 1);
let rec = &records[0].record;
let reg = read_entries(&state_dir.join("surfaces")).unwrap();
assert!(reg.unreadable.is_empty(), "{:?}", reg.unreadable);
assert_eq!(reg.entries.len(), 1);
let entry = ®.entries[0];
assert_eq!(entry.id, rec.id);
assert_eq!(entry.runtime.version, CURRENT_VERSION);
assert!(!entry.runtime.boot_id.is_empty());
assert!(!entry.runtime.is_stale().unwrap());
let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap();
stream
.set_read_timeout(Some(Duration::from_secs(5)))
.unwrap();
let req = format!(
"GET /api/session HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n{TOKEN_HEADER}: {token}\r\nConnection: close\r\n\r\n"
);
stream.write_all(req.as_bytes()).unwrap();
let mut raw = String::new();
stream.read_to_string(&mut raw).unwrap();
let (_, resp_body) = raw.split_once("\r\n\r\n").unwrap();
let session_json: serde_json::Value = serde_json::from_str(resp_body).unwrap();
assert_eq!(session_json["version"], entry.runtime.version);
assert_eq!(session_json["boot_id"], entry.runtime.boot_id);
assert_eq!(session_json["stale"], false);
let pid = guard.0.as_ref().unwrap().id().to_string();
let _ = Command::new("kill").args(["-TERM", &pid]).status();
if let Some(mut c) = guard.0.take() {
let _ = c.wait();
}
drop(rx);
let _ = stdout_handle.join();
let _ = stderr_handle.join();
}