Skip to main content

brep_mcp/
headless.rs

1//! The headless host: the whole `BrepApp` inside `egui_kittest::Harness` on a
2//! wgpu device, stepped on demand on a dedicated thread (measured in §12). No
3//! window, no display. Answers the `brep_mcp_core` host protocol; the app's
4//! own envelope and reply types are converted at the boundary.
5use 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    /// The session's private store directory.
22    pub store_dir: PathBuf,
23    /// Frames to step while waiting for one command's reply before giving up.
24    pub max_steps: u32,
25    /// HANG GUARD on the seed history landing before the first command
26    /// (`settle`). Generous on purpose and with NO performance meaning:
27    /// nothing about the app is asserted by how long the seed takes, only that
28    /// it finishes at all. Sixty seconds to match the other liveness guards in
29    /// the UI-side suites.
30    pub settle_limit: Duration,
31    /// The server's code mode: the app's JavaScript editor runs on it.
32    pub scripts: Option<brep_mcp_core::cad::LocalScripts>,
33}
34
35/// The editor's runner in a headless session: the serving `brep-mcp`'s own
36/// code mode, as an agent's `run` reaches it.
37struct 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
75/// The last panic message, captured by the hook the host installs.
76static 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
100/// Spawn the host thread; returns once the app is built and its seed history
101/// has settled, or with the build error.
102/// `BREP_FRAME_TRACE=1`: report slow host steps and commands on stderr.
103fn 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    // Publishers are off in a plain native run; a host is what turns them on.
112    brep_app::automation::registry::set_enabled(true);
113    // ...and the registry is process-global while the app is not: the previous
114    // script's session published into this same map and nothing has emptied it.
115    // A reader would otherwise answer THIS session from the LAST one's frame
116    // for any key this app has not published yet.
117    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            // Let the seed history land before the first command. A settle
138            // that does not reach the idle contract is a FAILED START, not a
139            // slow one. Sending `Ok(info)` regardless — which is what this did
140            // until 2026-09-21 — handed the script an app with work still in
141            // flight, and the script then failed further down, on whichever
142            // expectation happened to touch the state that had not landed: a
143            // hang reported as a wrong answer somewhere else.
144            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            // Commands are served CONCURRENTLY, as the desktop host serves
151            // them (a task per command): each is submitted to the app queue
152            // on arrival and answered on the frame its reply comes, so a
153            // command the queue is polling for seconds (`Outcome::Poll`)
154            // never holds a `frame_info` behind it. Frames step while any
155            // command is in flight; the thread blocks only when none is.
156            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                    // The DOCS ANNOTATION overlay (`crate::annotate`): set the
193                    // caption and the ring, then draw one frame so the next
194                    // capture — and anything that reads the session — sees it.
195                    // The keys are checked HERE, against what the app is
196                    // publishing right now, so a renamed control fails the
197                    // walkthrough by name instead of dropping its highlight.
198                    Some(HostRequest::Annotate { spec, reply }) => {
199                        let result = (|| {
200                            let note = Annotation::parse(&spec)?;
201                            let missing = crate::annotate::unknown_keys(&note.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, &region)
231                        })();
232                        let _ = reply.send(result);
233                    }
234                    None => {}
235                }
236                if stopping && inflight.is_empty() {
237                    break;
238                }
239                // Answer what has replied (or failed) before stepping again.
240                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                        // A command the queue is POLLING has started work that
249                        // lands on later frames: it keeps its frames, bounded
250                        // by its own deadline.
251                        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    // A start that failed has no handle to stop it by: its thread is on its
290    // way out, releasing the app and its graphics device, and is joined here
291    // so that it has finished before the caller goes on (and never runs
292    // beside the process's own exit).
293    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
302/// The harness's state is [`Annotated`] — `BrepApp` plus the docs-annotation
303/// overlay painted over it — so the app is reached through `state().app()`.
304/// See `crate::annotate` for why the overlay lives inside an `update` rather
305/// than in the image compositor.
306type App = Harness<'static, Annotated>;
307
308/// The text face every headless session draws with — the face the scripts'
309/// pinned layouts were recorded in. A family name, resolved through fontconfig
310/// (the repo ships no font file); [`SCRIPT_FONT_FILE`] is how its file is
311/// recognised when fontconfig substitutes another.
312const SCRIPT_FONT: &str = "DejaVu Sans Mono";
313const SCRIPT_FONT_FILE: &str = "DejaVuSansMono";
314
315/// `BREP_MCP_ADAPTER=gpu`: render on a hardware GPU, for MEASUREMENT runs only
316/// (playback timings on a machine that has one). kittest's own setup ranks a
317/// CPU rasteriser first, so screenshots come out the same on every machine, and
318/// the gated test-mcp keeps it: its baselines were recorded that way. This
319/// ranks discrete over integrated over any other GPU and falls back to the CPU
320/// adapter with a notice. The adapter used is in `__brepDiagnostics`, which a
321/// timing record quotes.
322fn 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            // One named face, never whatever the machine answers for
371            // `monospace`: the scripts' recorded chrome/camera values were
372            // recorded with it and must hold on every host.
373            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            // The app's OWN diagnostics, not a second reading of the same
387            // adapter: `HostInfo.adapter`, the `diagnostics` command and the
388            // Info window must all name the same device (brep_app::diagnostics).
389            *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
403/// One frame: drain input into the harness's RawInput, step, check for a panic.
404fn 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    // As the app's `raw_input_hook` does after its input: on (emulated)
410    // macOS a Ctrl+click is the secondary click.
411    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/// Why a `settle` never reached the idle contract.
420///
421/// It exists because the two ways of not settling used to be spelled the same
422/// as settling: the function returned `()`, the deadline simply ended the loop
423/// and a failed frame simply returned. A caller could not tell a settled app
424/// from an app that had run out of time, so it proceeded with the second one.
425#[derive(Debug, Clone)]
426pub enum SettleError {
427    /// The hang guard expired. `pending` names the work still in flight, which
428    /// is the whole diagnostic: "still pending: mesh_imports" says which part
429    /// of the app is stuck, and an EMPTY list says the app had gone idle but
430    /// not for the two consecutive frames the contract asks for.
431    DeadlineExpired { limit: Duration, frames: u32, pending: Vec<&'static str> },
432    /// A frame failed (the app panicked); the message is `step`'s.
433    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
453/// What the app still has in flight, named.
454///
455/// The SAME six the app's own idle contract reads
456/// (`brep_app::automation::cmd_frame::frame_info` — `pending` and the
457/// `idle` computed from it, which is what every waiting tool polls). Settling
458/// on fewer than the app calls idle is the same defect in a smaller costume:
459/// the host would declare the app ready while `frame` still called it busy.
460fn 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
475/// Step until the app is idle two frames running, or say why it is not.
476///
477/// `limit` is a HANG GUARD with no performance meaning: it is not a claim about
478/// how long a seed run may take, only a refusal to step forever. Blowing it is
479/// reported, never absorbed.
480fn 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        // One frame ALWAYS runs before the deadline is consulted, so the
491        // pending list in the error was read from a stepped app rather than
492        // from whatever it happened to hold before the first frame.
493        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) {}