use crate::annotate::{Annotated, Annotation};
use brep_app::app::BrepApp;
use brep_app::automation::command::Envelope as AppEnvelope;
use brep_app::automation::AppOptions;
use brep_mcp_core::host::{HostConfig, HostHandle, HostInfo, HostRequest, Reply};
use egui_kittest::Harness;
use serde_json::Value;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
pub struct HeadlessConfig {
pub width: f32,
pub height: f32,
pub ppp: f32,
pub seed: bool,
pub store_dir: PathBuf,
pub max_steps: u32,
pub settle_limit: Duration,
pub scripts: Option<brep_mcp_core::cad::LocalScripts>,
}
struct EditorScripts(brep_mcp_core::cad::LocalScripts);
impl brep_app::javascript::ScriptHost for EditorScripts {
fn ready(&self) -> Result<bool, String> {
self.0.ready()
}
fn run(&self, source: &str) -> Result<String, String> {
self.0.run(source)
}
fn result(&self, id: &str) -> Result<Option<serde_json::Value>, String> {
self.0.result(id)
}
fn halt(&self, id: &str) -> Result<(), String> {
self.0.halt(id)
}
}
impl Default for HeadlessConfig {
fn default() -> Self {
Self {
width: 1400.0,
height: 960.0,
ppp: 1.0,
seed: true,
store_dir: std::env::temp_dir().join("brep-mcp-store"),
max_steps: 600,
settle_limit: Duration::from_secs(60),
scripts: None,
}
}
}
impl From<HostConfig> for HeadlessConfig {
fn from(c: HostConfig) -> Self {
Self { width: c.width, height: c.height, ppp: c.ppp, seed: c.seed, store_dir: c.store_dir, scripts: c.scripts, ..Self::default() }
}
}
static LAST_PANIC: Mutex<Option<String>> = Mutex::new(None);
fn install_panic_hook() {
static ONCE: std::sync::Once = std::sync::Once::new();
ONCE.call_once(|| {
let previous = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
let msg = info
.payload()
.downcast_ref::<String>()
.cloned()
.or_else(|| info.payload().downcast_ref::<&str>().map(|s| s.to_string()))
.unwrap_or_else(|| "panic".into());
let loc = info.location().map(|l| format!(" at {}:{}", l.file(), l.line())).unwrap_or_default();
*LAST_PANIC.lock().unwrap() = Some(format!("{msg}{loc}"));
previous(info);
}));
});
}
fn take_panic() -> Option<String> {
LAST_PANIC.lock().unwrap().take()
}
fn trace_on() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("BREP_FRAME_TRACE").is_some_and(|v| v == "1"))
}
pub fn spawn(cfg: impl Into<HeadlessConfig>) -> Result<HostHandle, String> {
let cfg: HeadlessConfig = cfg.into();
install_panic_hook();
brep_app::automation::registry::set_enabled(true);
brep_app::automation::registry::clear();
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<HostRequest>();
let (ready_tx, ready_rx) = std::sync::mpsc::channel::<Result<HostInfo, String>>();
let join = std::thread::Builder::new()
.name("brep-mcp-headless".into())
.spawn(move || {
let built = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| build(&cfg)));
let (mut harness, info) = match built {
Ok(Ok(v)) => v,
Ok(Err(e)) => {
let _ = ready_tx.send(Err(e));
return;
}
Err(_) => {
let _ = ready_tx.send(Err(format!("the app panicked while starting: {}", take_panic().unwrap_or_default())));
return;
}
};
let queue = harness.state().app().automation().clone();
let ppp = cfg.ppp;
if let Err(why) = settle(&mut harness, &queue, ppp, cfg.settle_limit) {
let _ = ready_tx.send(Err(format!("app was not settled before command 1 \u{2014} {why}")));
return;
}
let _ = ready_tx.send(Ok(info));
struct InFlight {
id: u64,
cmd: String,
rx: std::sync::mpsc::Receiver<brep_app::automation::command::Reply>,
reply: tokio::sync::oneshot::Sender<Reply>,
steps: u32,
started: Instant,
}
let mut inflight: Vec<InFlight> = Vec::new();
let mut stopping = false;
loop {
let req = if stopping {
None
} else if inflight.is_empty() {
match rx.blocking_recv() {
Some(req) => Some(req),
None => break,
}
} else {
match rx.try_recv() {
Ok(req) => Some(req),
Err(tokio::sync::mpsc::error::TryRecvError::Empty) => None,
Err(tokio::sync::mpsc::error::TryRecvError::Disconnected) => {
stopping = true;
None
}
}
};
match req {
Some(HostRequest::Stop) => stopping = true,
Some(HostRequest::Command { envelope, reply }) => {
let id = envelope.id;
let cmd = envelope.cmd.clone();
let rx_reply = queue.submit(AppEnvelope { id, cmd: envelope.cmd, args: envelope.args });
inflight.push(InFlight { id, cmd, rx: rx_reply, reply, steps: 0, started: Instant::now() });
}
Some(HostRequest::Annotate { spec, reply }) => {
let result = (|| {
let note = Annotation::parse(&spec)?;
let missing = crate::annotate::unknown_keys(¬e.highlight);
if !missing.is_empty() {
return Err(format!("annotate: {}", missing.join("; ")));
}
let highlighted = note.highlight.len();
harness.state_mut().note = note;
step(&mut harness, &queue, ppp)?;
Ok(serde_json::json!({
"frame": queue.frame(),
"highlighted": highlighted,
}))
})();
let _ = reply.send(result);
}
Some(HostRequest::Screenshot { region, reply }) => {
let result = (|| {
step(&mut harness, &queue, ppp)?;
let image = harness.render().map_err(|e| format!("headless render: {e}"))?;
let view = harness.state().app().view_rect();
let region: brep_app::automation::cmd_capture::Region =
serde_json::from_value(region).map_err(|e| format!("region: {e}"))?;
let color = egui::ColorImage {
size: [image.width() as usize, image.height() as usize],
source_size: egui::vec2(image.width() as f32, image.height() as f32),
pixels: image
.pixels()
.map(|p| egui::Color32::from_rgba_premultiplied(p.0[0], p.0[1], p.0[2], p.0[3]))
.collect(),
};
brep_app::automation::cmd_capture::encode_capture(&color, ppp, view, ®ion)
})();
let _ = reply.send(result);
}
None => {}
}
if stopping && inflight.is_empty() {
break;
}
let mut i = 0;
while i < inflight.len() {
let f = &inflight[i];
let done = if let Ok(r) = f.rx.try_recv() {
Some(r.into_host())
} else if queue.is_poisoned() {
Some(Reply::err(f.id, queue.frame(), "session poisoned"))
} else if f.steps >= cfg.max_steps && !queue.is_polling(f.id) {
Some(Reply::err(f.id, queue.frame(), format!("no reply after {} frames", cfg.max_steps)))
} else {
None
};
match done {
Some(result) => {
let f = inflight.swap_remove(i);
if trace_on() && f.started.elapsed() > Duration::from_millis(1000) {
eprintln!("[frame-trace] headless command {} took {} ms over {} frame(s)", f.cmd, f.started.elapsed().as_millis(), f.steps);
}
let _ = f.reply.send(result);
}
None => i += 1,
}
}
if inflight.is_empty() {
continue;
}
let stepped = Instant::now();
if let Err(why) = step(&mut harness, &queue, ppp) {
queue.poison(why.clone());
for f in inflight.drain(..) {
let _ = f.reply.send(Reply::err(f.id, queue.frame(), why.clone()));
}
continue;
}
if trace_on() && stepped.elapsed() > Duration::from_millis(250) {
eprintln!("[frame-trace] headless step {} ms", stepped.elapsed().as_millis());
}
for f in &mut inflight {
f.steps += 1;
}
if inflight.iter().all(|f| f.steps > 2) {
std::thread::sleep(Duration::from_millis(2));
}
}
})
.map_err(|e| format!("spawn host thread: {e}"))?;
match ready_rx.recv() {
Ok(Ok(info)) => Ok(HostHandle::new(tx, info, join)),
Ok(Err(e)) => Err(e),
Err(_) => Err("the host thread ended before the app was ready".into()),
}
}
type App = Harness<'static, Annotated>;
const SCRIPT_FONT: &str = "DejaVu Sans Mono";
const SCRIPT_FONT_FILE: &str = "DejaVuSansMono";
fn gpu_setup() -> Option<eframe::egui_wgpu::WgpuSetup> {
use eframe::egui_wgpu::{wgpu, WgpuSetup};
match std::env::var("BREP_MCP_ADAPTER").ok()?.to_ascii_lowercase().as_str() {
"gpu" => {}
"" | "cpu" => return None,
other => {
eprintln!("brep-mcp: BREP_MCP_ADAPTER={other} is not gpu or cpu; using the CPU adapter");
return None;
}
}
let mut setup = egui_kittest::wgpu::default_wgpu_setup();
if let WgpuSetup::CreateNew(create) = &mut setup {
create.native_adapter_selector = Some(Arc::new(|adapters, _surface| {
let rank = |a: &&wgpu::Adapter| match a.get_info().device_type {
wgpu::DeviceType::DiscreteGpu => 0,
wgpu::DeviceType::IntegratedGpu => 1,
wgpu::DeviceType::Other | wgpu::DeviceType::VirtualGpu => 2,
wgpu::DeviceType::Cpu => 3,
};
let mut ranked: Vec<&wgpu::Adapter> = adapters.iter().collect();
ranked.sort_by_key(rank);
let chosen = ranked.first().map(|a| (*a).clone()).ok_or_else(|| "No adapter found".to_owned())?;
if chosen.get_info().device_type == wgpu::DeviceType::Cpu {
eprintln!("brep-mcp: BREP_MCP_ADAPTER=gpu but no GPU adapter is available; using {}", chosen.get_info().name);
}
Ok(chosen)
}));
}
Some(setup)
}
fn build(cfg: &HeadlessConfig) -> Result<(App, HostInfo), String> {
std::fs::create_dir_all(&cfg.store_dir).map_err(|e| format!("store dir {}: {e}", cfg.store_dir.display()))?;
let store_dir = cfg.store_dir.clone();
let scripts = cfg.scripts.clone();
let seed = cfg.seed;
let adapter = Arc::new(Mutex::new(String::new()));
let adapter_out = adapter.clone();
let builder = Harness::builder()
.with_size(egui::vec2(cfg.width, cfg.height))
.with_pixels_per_point(cfg.ppp)
.with_step_dt(1.0 / 60.0);
let builder = match gpu_setup() {
Some(setup) => builder.wgpu_setup(setup),
None => builder.wgpu(),
};
let harness = builder
.build_eframe(move |cc| {
let font = brep_app::fonts::install_matching(&cc.egui_ctx, SCRIPT_FONT);
if !font.as_deref().is_some_and(|path| path.contains(SCRIPT_FONT_FILE)) {
eprintln!(
"brep-mcp: fontconfig has no {SCRIPT_FONT} (got {font:?}); \
script layouts will not match their recorded values"
);
}
let store = brep_app::store::native_store_at(store_dir.clone());
let mut app = BrepApp::new_with(cc, AppOptions { store: Some(store), seed })
.expect("BrepApp::new_with under kittest");
if let Some(scripts) = scripts.clone() {
app.set_script_host(Box::new(EditorScripts(scripts)));
}
*adapter_out.lock().unwrap() = app.diagnostics().adapter_line();
Annotated::new(app)
});
let info = HostInfo {
backend: "headless",
adapter: adapter.lock().unwrap().clone(),
platform: std::env::consts::OS,
width: cfg.width,
height: cfg.height,
ppp: cfg.ppp,
};
Ok((harness, info))
}
fn step(harness: &mut App, queue: &Arc<brep_app::automation::queue::AutomationQueue>, ppp: f32) -> Result<(), String> {
let frame = harness.ctx.cumulative_frame_nr();
let view = harness.state().app().view_rect();
let ctx = harness.ctx.clone();
queue.drain_input(harness.input_mut(), frame, ppp, view, &ctx);
let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| harness.step()));
match r {
Ok(()) => Ok(()),
Err(_) => Err(format!("the app panicked: {}", take_panic().unwrap_or_else(|| "(no message)".into()))),
}
}
#[derive(Debug, Clone)]
pub enum SettleError {
DeadlineExpired { limit: Duration, frames: u32, pending: Vec<&'static str> },
StepFailed(String),
}
impl std::fmt::Display for SettleError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
SettleError::DeadlineExpired { limit, frames, pending } => {
let plural = if *frames == 1 { "" } else { "s" };
write!(f, "the {} ms hang guard expired after {frames} frame{plural}; still pending: ", limit.as_millis())?;
if pending.is_empty() {
write!(f, "nothing, but the app had not been idle for two consecutive frames")
} else {
write!(f, "{}", pending.join(", "))
}
}
SettleError::StepFailed(why) => write!(f, "a frame failed: {why}"),
}
}
}
fn pending_work(harness: &App) -> Vec<&'static str> {
let e = harness.state().app().docs_engine();
[
("run", e.run_pending()),
("queries", e.queries_pending()),
("mesh_imports", e.mesh_imports_pending()),
("step_probes", e.step_probes_pending()),
("topology", e.topology_pending()),
("projection", e.sheet_lines_pending()),
]
.into_iter()
.filter_map(|(name, on)| on.then_some(name))
.collect()
}
fn settle(
harness: &mut App,
queue: &Arc<brep_app::automation::queue::AutomationQueue>,
ppp: f32,
limit: Duration,
) -> Result<(), SettleError> {
let start = Instant::now();
let mut idle_frames = 0u32;
let mut frames = 0u32;
loop {
step(harness, queue, ppp).map_err(SettleError::StepFailed)?;
frames += 1;
let pending = pending_work(harness);
if pending.is_empty() {
idle_frames += 1;
if idle_frames >= 2 {
return Ok(());
}
} else {
idle_frames = 0;
}
if start.elapsed() >= limit {
return Err(SettleError::DeadlineExpired { limit, frames, pending });
}
if !pending.is_empty() {
std::thread::sleep(Duration::from_millis(8));
}
}
}
#[allow(dead_code)]
fn _value(_: Value) {}