1use crate::annotate::{Annotated, Annotation};
6use brep_app::app::BrepApp;
7use brep_app::automation::command::Envelope as AppEnvelope;
8use brep_app::automation::AppOptions;
9use brep_mcp_core::host::{HostConfig, HostHandle, HostInfo, HostRequest, Reply};
10use egui_kittest::Harness;
11use serde_json::Value;
12use std::path::PathBuf;
13use std::sync::{Arc, Mutex};
14use std::time::{Duration, Instant};
15
16pub struct HeadlessConfig {
17 pub width: f32,
18 pub height: f32,
19 pub ppp: f32,
20 pub seed: bool,
21 pub store_dir: PathBuf,
23 pub max_steps: u32,
25 pub settle_limit: Duration,
31 pub scripts: Option<brep_mcp_core::cad::LocalScripts>,
33}
34
35struct EditorScripts(brep_mcp_core::cad::LocalScripts);
38
39impl brep_app::javascript::ScriptHost for EditorScripts {
40 fn ready(&self) -> Result<bool, String> {
41 self.0.ready()
42 }
43 fn run(&self, source: &str) -> Result<String, String> {
44 self.0.run(source)
45 }
46 fn result(&self, id: &str) -> Result<Option<serde_json::Value>, String> {
47 self.0.result(id)
48 }
49 fn halt(&self, id: &str) -> Result<(), String> {
50 self.0.halt(id)
51 }
52}
53
54impl Default for HeadlessConfig {
55 fn default() -> Self {
56 Self {
57 width: 1400.0,
58 height: 960.0,
59 ppp: 1.0,
60 seed: true,
61 store_dir: std::env::temp_dir().join("brep-mcp-store"),
62 max_steps: 600,
63 settle_limit: Duration::from_secs(60),
64 scripts: None,
65 }
66 }
67}
68
69impl From<HostConfig> for HeadlessConfig {
70 fn from(c: HostConfig) -> Self {
71 Self { width: c.width, height: c.height, ppp: c.ppp, seed: c.seed, store_dir: c.store_dir, scripts: c.scripts, ..Self::default() }
72 }
73}
74
75static LAST_PANIC: Mutex<Option<String>> = Mutex::new(None);
77
78fn install_panic_hook() {
79 static ONCE: std::sync::Once = std::sync::Once::new();
80 ONCE.call_once(|| {
81 let previous = std::panic::take_hook();
82 std::panic::set_hook(Box::new(move |info| {
83 let msg = info
84 .payload()
85 .downcast_ref::<String>()
86 .cloned()
87 .or_else(|| info.payload().downcast_ref::<&str>().map(|s| s.to_string()))
88 .unwrap_or_else(|| "panic".into());
89 let loc = info.location().map(|l| format!(" at {}:{}", l.file(), l.line())).unwrap_or_default();
90 *LAST_PANIC.lock().unwrap() = Some(format!("{msg}{loc}"));
91 previous(info);
92 }));
93 });
94}
95
96fn take_panic() -> Option<String> {
97 LAST_PANIC.lock().unwrap().take()
98}
99
100fn trace_on() -> bool {
104 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
105 *ON.get_or_init(|| std::env::var_os("BREP_FRAME_TRACE").is_some_and(|v| v == "1"))
106}
107
108pub fn spawn(cfg: impl Into<HeadlessConfig>) -> Result<HostHandle, String> {
109 let cfg: HeadlessConfig = cfg.into();
110 install_panic_hook();
111 brep_app::automation::registry::set_enabled(true);
113 brep_app::automation::registry::clear();
118 let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<HostRequest>();
119 let (ready_tx, ready_rx) = std::sync::mpsc::channel::<Result<HostInfo, String>>();
120 let join = std::thread::Builder::new()
121 .name("brep-mcp-headless".into())
122 .spawn(move || {
123 let built = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| build(&cfg)));
124 let (mut harness, info) = match built {
125 Ok(Ok(v)) => v,
126 Ok(Err(e)) => {
127 let _ = ready_tx.send(Err(e));
128 return;
129 }
130 Err(_) => {
131 let _ = ready_tx.send(Err(format!("the app panicked while starting: {}", take_panic().unwrap_or_default())));
132 return;
133 }
134 };
135 let queue = harness.state().app().automation().clone();
136 let ppp = cfg.ppp;
137 if let Err(why) = settle(&mut harness, &queue, ppp, cfg.settle_limit) {
145 let _ = ready_tx.send(Err(format!("app was not settled before command 1 \u{2014} {why}")));
146 return;
147 }
148 let _ = ready_tx.send(Ok(info));
149
150 struct InFlight {
157 id: u64,
158 cmd: String,
159 rx: std::sync::mpsc::Receiver<brep_app::automation::command::Reply>,
160 reply: tokio::sync::oneshot::Sender<Reply>,
161 steps: u32,
162 started: Instant,
163 }
164 let mut inflight: Vec<InFlight> = Vec::new();
165 let mut stopping = false;
166 loop {
167 let req = if stopping {
168 None
169 } else if inflight.is_empty() {
170 match rx.blocking_recv() {
171 Some(req) => Some(req),
172 None => break,
173 }
174 } else {
175 match rx.try_recv() {
176 Ok(req) => Some(req),
177 Err(tokio::sync::mpsc::error::TryRecvError::Empty) => None,
178 Err(tokio::sync::mpsc::error::TryRecvError::Disconnected) => {
179 stopping = true;
180 None
181 }
182 }
183 };
184 match req {
185 Some(HostRequest::Stop) => stopping = true,
186 Some(HostRequest::Command { envelope, reply }) => {
187 let id = envelope.id;
188 let cmd = envelope.cmd.clone();
189 let rx_reply = queue.submit_for(AppEnvelope { id, cmd: envelope.cmd, args: envelope.args }, None, envelope.client);
190 inflight.push(InFlight { id, cmd, rx: rx_reply, reply, steps: 0, started: Instant::now() });
191 }
192 Some(HostRequest::Annotate { spec, reply }) => {
199 let result = (|| {
200 let note = Annotation::parse(&spec)?;
201 let missing = crate::annotate::unknown_keys(¬e.highlight);
202 if !missing.is_empty() {
203 return Err(format!("annotate: {}", missing.join("; ")));
204 }
205 let highlighted = note.highlight.len();
206 harness.state_mut().note = note;
207 step(&mut harness, &queue, ppp)?;
208 Ok(serde_json::json!({
209 "frame": queue.frame(),
210 "highlighted": highlighted,
211 }))
212 })();
213 let _ = reply.send(result);
214 }
215 Some(HostRequest::Screenshot { region, reply }) => {
216 let result = (|| {
217 step(&mut harness, &queue, ppp)?;
218 let image = harness.render().map_err(|e| format!("headless render: {e}"))?;
219 let view = harness.state().app().view_rect();
220 let region: brep_app::automation::cmd_capture::Region =
221 serde_json::from_value(region).map_err(|e| format!("region: {e}"))?;
222 let color = egui::ColorImage {
223 size: [image.width() as usize, image.height() as usize],
224 source_size: egui::vec2(image.width() as f32, image.height() as f32),
225 pixels: image
226 .pixels()
227 .map(|p| egui::Color32::from_rgba_premultiplied(p.0[0], p.0[1], p.0[2], p.0[3]))
228 .collect(),
229 };
230 brep_app::automation::cmd_capture::encode_capture(&color, ppp, view, ®ion)
231 })();
232 let _ = reply.send(result);
233 }
234 None => {}
235 }
236 if stopping && inflight.is_empty() {
237 break;
238 }
239 let mut i = 0;
241 while i < inflight.len() {
242 let f = &inflight[i];
243 let done = if let Ok(r) = f.rx.try_recv() {
244 Some(r.into_host())
245 } else if queue.is_poisoned() {
246 Some(Reply::err(f.id, queue.frame(), "session poisoned"))
247 } else if f.steps >= cfg.max_steps && !queue.is_polling(f.id) {
248 Some(Reply::err(f.id, queue.frame(), format!("no reply after {} frames", cfg.max_steps)))
252 } else {
253 None
254 };
255 match done {
256 Some(result) => {
257 let f = inflight.swap_remove(i);
258 if trace_on() && f.started.elapsed() > Duration::from_millis(1000) {
259 eprintln!("[frame-trace] headless command {} took {} ms over {} frame(s)", f.cmd, f.started.elapsed().as_millis(), f.steps);
260 }
261 let _ = f.reply.send(result);
262 }
263 None => i += 1,
264 }
265 }
266 if inflight.is_empty() {
267 continue;
268 }
269 let stepped = Instant::now();
270 if let Err(why) = step(&mut harness, &queue, ppp) {
271 queue.poison(why.clone());
272 for f in inflight.drain(..) {
273 let _ = f.reply.send(Reply::err(f.id, queue.frame(), why.clone()));
274 }
275 continue;
276 }
277 if trace_on() && stepped.elapsed() > Duration::from_millis(250) {
278 eprintln!("[frame-trace] headless step {} ms", stepped.elapsed().as_millis());
279 }
280 for f in &mut inflight {
281 f.steps += 1;
282 }
283 if inflight.iter().all(|f| f.steps > 2) {
284 std::thread::sleep(Duration::from_millis(2));
285 }
286 }
287 })
288 .map_err(|e| format!("spawn host thread: {e}"))?;
289 let failed = match ready_rx.recv() {
294 Ok(Ok(info)) => return Ok(HostHandle::new(tx, info, join)),
295 Ok(Err(e)) => e,
296 Err(_) => "the host thread ended before the app was ready".to_string(),
297 };
298 let _ = join.join();
299 Err(failed)
300}
301
302type App = Harness<'static, Annotated>;
307
308const SCRIPT_FONT: &str = "DejaVu Sans Mono";
313const SCRIPT_FONT_FILE: &str = "DejaVuSansMono";
314
315fn gpu_setup() -> Option<eframe::egui_wgpu::WgpuSetup> {
323 use eframe::egui_wgpu::{wgpu, WgpuSetup};
324 match std::env::var("BREP_MCP_ADAPTER").ok()?.to_ascii_lowercase().as_str() {
325 "gpu" => {}
326 "" | "cpu" => return None,
327 other => {
328 eprintln!("brep-mcp: BREP_MCP_ADAPTER={other} is not gpu or cpu; using the CPU adapter");
329 return None;
330 }
331 }
332 let mut setup = egui_kittest::wgpu::default_wgpu_setup();
333 if let WgpuSetup::CreateNew(create) = &mut setup {
334 create.native_adapter_selector = Some(Arc::new(|adapters, _surface| {
335 let rank = |a: &&wgpu::Adapter| match a.get_info().device_type {
336 wgpu::DeviceType::DiscreteGpu => 0,
337 wgpu::DeviceType::IntegratedGpu => 1,
338 wgpu::DeviceType::Other | wgpu::DeviceType::VirtualGpu => 2,
339 wgpu::DeviceType::Cpu => 3,
340 };
341 let mut ranked: Vec<&wgpu::Adapter> = adapters.iter().collect();
342 ranked.sort_by_key(rank);
343 let chosen = ranked.first().map(|a| (*a).clone()).ok_or_else(|| "No adapter found".to_owned())?;
344 if chosen.get_info().device_type == wgpu::DeviceType::Cpu {
345 eprintln!("brep-mcp: BREP_MCP_ADAPTER=gpu but no GPU adapter is available; using {}", chosen.get_info().name);
346 }
347 Ok(chosen)
348 }));
349 }
350 Some(setup)
351}
352
353fn build(cfg: &HeadlessConfig) -> Result<(App, HostInfo), String> {
354 std::fs::create_dir_all(&cfg.store_dir).map_err(|e| format!("store dir {}: {e}", cfg.store_dir.display()))?;
355 let store_dir = cfg.store_dir.clone();
356 let scripts = cfg.scripts.clone();
357 let seed = cfg.seed;
358 let adapter = Arc::new(Mutex::new(String::new()));
359 let adapter_out = adapter.clone();
360 let builder = Harness::builder()
361 .with_size(egui::vec2(cfg.width, cfg.height))
362 .with_pixels_per_point(cfg.ppp)
363 .with_step_dt(1.0 / 60.0);
364 let builder = match gpu_setup() {
365 Some(setup) => builder.wgpu_setup(setup),
366 None => builder.wgpu(),
367 };
368 let harness = builder
369 .build_eframe(move |cc| {
370 let font = brep_app::fonts::install_matching(&cc.egui_ctx, SCRIPT_FONT);
374 if !font.as_deref().is_some_and(|path| path.contains(SCRIPT_FONT_FILE)) {
375 eprintln!(
376 "brep-mcp: fontconfig has no {SCRIPT_FONT} (got {font:?}); \
377 script layouts will not match their recorded values"
378 );
379 }
380 let store = brep_app::store::native_store_at(store_dir.clone());
381 let mut app = BrepApp::new_with(cc, AppOptions { store: Some(store), seed })
382 .expect("BrepApp::new_with under kittest");
383 if let Some(scripts) = scripts.clone() {
384 app.set_script_host(Box::new(EditorScripts(scripts)));
385 }
386 *adapter_out.lock().unwrap() = app.diagnostics().adapter_line();
390 Annotated::new(app)
391 });
392 let info = HostInfo {
393 backend: "headless",
394 adapter: adapter.lock().unwrap().clone(),
395 platform: std::env::consts::OS,
396 width: cfg.width,
397 height: cfg.height,
398 ppp: cfg.ppp,
399 };
400 Ok((harness, info))
401}
402
403fn step(harness: &mut App, queue: &Arc<brep_app::automation::queue::AutomationQueue>, ppp: f32) -> Result<(), String> {
405 let frame = harness.ctx.cumulative_frame_nr();
406 let view = harness.state().app().view_rect();
407 let ctx = harness.ctx.clone();
408 queue.drain_input(harness.input_mut(), frame, ppp, view, &ctx);
409 brep_app::select_mods::rewrite_raw(&ctx, harness.input_mut());
412 let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| harness.step()));
413 match r {
414 Ok(()) => Ok(()),
415 Err(_) => Err(format!("the app panicked: {}", take_panic().unwrap_or_else(|| "(no message)".into()))),
416 }
417}
418
419#[derive(Debug, Clone)]
426pub enum SettleError {
427 DeadlineExpired { limit: Duration, frames: u32, pending: Vec<&'static str> },
432 StepFailed(String),
434}
435
436impl std::fmt::Display for SettleError {
437 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
438 match self {
439 SettleError::DeadlineExpired { limit, frames, pending } => {
440 let plural = if *frames == 1 { "" } else { "s" };
441 write!(f, "the {} ms hang guard expired after {frames} frame{plural}; still pending: ", limit.as_millis())?;
442 if pending.is_empty() {
443 write!(f, "nothing, but the app had not been idle for two consecutive frames")
444 } else {
445 write!(f, "{}", pending.join(", "))
446 }
447 }
448 SettleError::StepFailed(why) => write!(f, "a frame failed: {why}"),
449 }
450 }
451}
452
453fn pending_work(harness: &App) -> Vec<&'static str> {
461 let e = harness.state().app().docs_engine();
462 [
463 ("run", e.run_pending()),
464 ("queries", e.queries_pending()),
465 ("mesh_imports", e.mesh_imports_pending()),
466 ("step_probes", e.step_probes_pending()),
467 ("topology", e.topology_pending()),
468 ("projection", e.sheet_lines_pending()),
469 ]
470 .into_iter()
471 .filter_map(|(name, on)| on.then_some(name))
472 .collect()
473}
474
475fn settle(
481 harness: &mut App,
482 queue: &Arc<brep_app::automation::queue::AutomationQueue>,
483 ppp: f32,
484 limit: Duration,
485) -> Result<(), SettleError> {
486 let start = Instant::now();
487 let mut idle_frames = 0u32;
488 let mut frames = 0u32;
489 loop {
490 step(harness, queue, ppp).map_err(SettleError::StepFailed)?;
494 frames += 1;
495 let pending = pending_work(harness);
496 if pending.is_empty() {
497 idle_frames += 1;
498 if idle_frames >= 2 {
499 return Ok(());
500 }
501 } else {
502 idle_frames = 0;
503 }
504 if start.elapsed() >= limit {
505 return Err(SettleError::DeadlineExpired { limit, frames, pending });
506 }
507 if !pending.is_empty() {
508 std::thread::sleep(Duration::from_millis(8));
509 }
510 }
511}
512
513#[allow(dead_code)]
514fn _value(_: Value) {}