Skip to main content

brep_app/panels/
info.rs

1//! The **Info** window — the licences, and what this build is running on.
2//!
3//! The toolbar's ℹ button opens it. Two things live here because a user asking
4//! either question is in the same place: "what am I allowed to do with this"
5//! and "what is it running on".
6//!
7//! * **Licences.** The project licence and the maintained third-party notices,
8//!   compiled into the binary from the very files the help site renders
9//!   (`LICENSE.md`, `THIRD-PARTY-NOTICES.md`) — so a build that is not served
10//!   beside its `web/help/` still carries them. The GENERATED crate inventory
11//!   (every shipped dependency, grouped by licence expression) is built from
12//!   `cargo metadata` at docs time and cannot be compiled in, so the window
13//!   links to its help page instead.
14//! * **Diagnostics.** [`crate::diagnostics::Diagnostics`], rendered row for row.
15//!   The window OWNS no diagnostic of its own: it is handed the app's one
16//!   instance, the same one the problem report embeds, so what a user reads
17//!   here and what a triager reads in their report cannot differ.
18//! * **Connect an agent (MCP).** A button that starts the embedded MCP server
19//!   at runtime — what `brep-app --mcp` does at launch — and, once it runs,
20//!   the very text the console prints for pointing an agent at this window,
21//!   selectable and with a Copy button. It is here, beside the diagnostics,
22//!   because the URL and the session root are facts about THIS session, like
23//!   the renderer: not a setting that persists. The window owns none of the
24//!   state: it is handed a [`McpView`] snapshot each frame (the shell reads
25//!   `crate::mcp::status()`), and a click is handed back to the shell, which
26//!   owns the automation queue the server attaches to.
27//!
28//! Not to be confused with [`crate::panels::info_windows`], the pinned
29//! per-ENTITY inspectors opened from the context bar. This window is about the
30//! application; those are about a face, an edge or a solid.
31
32use crate::automation::hit_keys::HitKeyDoc;
33use crate::diagnostics::Diagnostics;
34use eframe::egui;
35use std::collections::HashMap;
36
37/// The project licence, as authored. `BREP_docs` renders this same file as the
38/// help site's first Licences page.
39///
40/// This is the crate's OWN copy, not the repository root's. An `include_str!`
41/// that climbs out of the package compiles in a checkout and fails in the
42/// tarball `cargo publish` verifies, which is exactly where nobody looks —
43/// `build.rs` holds the two copies identical so the distinction stays
44/// bookkeeping rather than a second source of truth.
45const PROJECT_LICENCE: &str = include_str!("../../LICENSE.md");
46
47/// The maintained third-party notices, as authored — the embedded fonts and the
48/// material whose licence requires its notice to travel with it. The crate's own
49/// copy, for the reason given above.
50const THIRD_PARTY_NOTICES: &str = include_str!("../../THIRD-PARTY-NOTICES.md");
51
52/// The generated crate inventory on the help site: every crate the application
53/// ships, grouped under its declared licence expression. Generated from `cargo
54/// metadata` by `BREP_docs` (see its `licences` module), so it exists only
55/// beside the served page — hence a link rather than an include.
56const INVENTORY_URL: &str = "help/licences/third-party-crates.html";
57
58/// The label on the start button — the one a user looks for in the window.
59pub const START_MCP_LABEL: &str = "Start MCP server";
60
61/// What this build says when it has no server to start: main.rs's own words
62/// for `--mcp` on such a build, so the button and the flag agree.
63pub const NO_MCP_TEXT: &str = "this build has no MCP server (built without the `mcp` feature)";
64
65/// What the "Connect an agent" section shows this frame. A SNAPSHOT: the
66/// shell builds it from `crate::mcp::status()` (or [`McpView::Unavailable`]
67/// when the build has no server) so this module compiles the same with and
68/// without the `mcp` feature and on the web.
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub enum McpView {
71    /// No server in this build (built without `mcp`, or the browser build).
72    Unavailable,
73    /// Not running; `error` is the console's line from the last failure.
74    Stopped { error: Option<String> },
75    /// Serving: `instructions` is EXACTLY `crate::mcp::agent_instructions` for
76    /// the live `url`; `note` says a fallback port was used, when one was.
77    Running { url: String, instructions: String, note: Option<String> },
78}
79
80/// The Info window's state. Its whole model is `open`: everything it draws is
81/// either a compiled-in constant or read live from the app's [`Diagnostics`]
82/// and the [`McpView`] it is handed.
83#[derive(Default)]
84pub struct InfoPanel {
85    /// Whether the window is showing — the toolbar ℹ toggle's flag, also set by
86    /// the `info_window` command.
87    pub open: bool,
88    /// Per-frame widget screen rects for the headed verifier, like every other
89    /// panel.
90    hits: HashMap<String, egui::Rect>,
91    /// Set by a click on **Start MCP server**; the shell takes it after the
92    /// frame ([`Self::take_mcp_start`]) because the shell, not this window,
93    /// owns the queue the server attaches to.
94    mcp_start: bool,
95    #[cfg(all(feature = "mcp", not(target_arch = "wasm32")))]
96    mcp_preferences: Option<McpPreferences>,
97}
98
99/// Where the next launch keeps its MCP state (the persistence dropdown).
100#[cfg(all(feature = "mcp", not(target_arch = "wasm32")))]
101#[derive(Debug, Clone, Copy, PartialEq, Eq)]
102enum McpPersistence {
103    Named,
104    Directory,
105    Ephemeral,
106}
107
108#[cfg(all(feature = "mcp", not(target_arch = "wasm32")))]
109impl McpPersistence {
110    /// `(value, hit id, label)` for [`crate::form::enum_dropdown`].
111    const CHOICES: [(Self, &'static str, &'static str); 3] = [
112        (Self::Named, "named", "Named instance"),
113        (Self::Directory, "directory", "Explicit directory"),
114        (Self::Ephemeral, "ephemeral", "Ephemeral"),
115    ];
116}
117
118#[cfg(all(feature = "mcp", not(target_arch = "wasm32")))]
119struct McpPreferences {
120    mode: McpPersistence,
121    instance: String,
122    path: String,
123    message: Option<Result<String, String>>,
124}
125
126#[cfg(all(feature = "mcp", not(target_arch = "wasm32")))]
127impl McpPreferences {
128    fn load() -> Self {
129        let loaded = crate::mcp::state_settings_path().and_then(|path| brep_mcp_core::launch_state::Settings::load(&path));
130        let error = loaded.as_ref().err().cloned();
131        let policy = loaded.ok().and_then(|s| s.desktop).unwrap_or_default();
132        Self {
133            mode: if policy.ephemeral { McpPersistence::Ephemeral } else if policy.state_dir.is_some() { McpPersistence::Directory } else { McpPersistence::Named },
134            instance: policy.instance.unwrap_or_else(|| "desktop".into()),
135            path: policy.state_dir.map(|p| p.to_string_lossy().into_owned()).unwrap_or_default(),
136            message: error.map(Err),
137        }
138    }
139}
140
141impl InfoPanel {
142    pub fn new() -> Self {
143        Self::default()
144    }
145
146    /// Whether **Start MCP server** was clicked since the last call. The shell
147    /// answers it with `crate::mcp::start_from_window`.
148    pub fn take_mcp_start(&mut self) -> bool {
149        std::mem::take(&mut self.mcp_start)
150    }
151
152    /// Draw the floating window (if open) at ctx level, after the panels, so it
153    /// floats over the shell. Idempotent while closed.
154    pub fn show(&mut self, ctx: &egui::Context, diagnostics: &Diagnostics, mcp: &McpView) {
155        if !self.open {
156            return;
157        }
158        // `egui::Window::open` needs its own `&mut bool`; borrow a copy so the
159        // draw closure can still take `&mut self`, then fold the close back in
160        // (the Part Properties window's rule).
161        let mut open = true;
162        egui::Window::new("Info")
163            .open(&mut open)
164            .movable(true)
165            .resizable(true)
166            // A bounded default plus the filling ScrollArea in `body`: without a
167            // filling child egui hugs the window to its content and the user
168            // cannot drag it larger.
169            .default_size([560.0, 520.0])
170            // Clear of the Settings (x 720) and Part Properties (x 660)
171            // rest positions, so opening all three does not stack them.
172            .default_pos(super::below_chrome(ctx, 120.0, 0.0))
173            .show(ctx, |ui| self.body(ui, diagnostics, mcp));
174        self.open = open;
175
176        if crate::automation::registry::enabled() {
177            crate::automation::registry::publish(
178                "__brepInfoHit",
179                "info window widget rects (copy, inventory, licence:*, mcp:*)",
180                &self.hits_json(),
181            );
182        }
183    }
184
185    fn body(&mut self, ui: &mut egui::Ui, diagnostics: &Diagnostics, mcp: &McpView) {
186        self.hits.clear();
187        egui::ScrollArea::vertical()
188            .auto_shrink([false; 2])
189            .show(ui, |ui| {
190                self.diagnostics_section(ui, diagnostics);
191                ui.add_space(12.0);
192                ui.separator();
193                ui.add_space(6.0);
194                self.mcp_section(ui, mcp);
195                ui.add_space(12.0);
196                ui.separator();
197                ui.add_space(6.0);
198                self.licences_section(ui);
199            });
200    }
201
202    /// The button that starts the MCP server in this window, and — once it
203    /// runs — the console's own agent instructions to copy into Claude Code
204    /// or Codex. The button is the whole control: disabled with the reason
205    /// when there is nothing to start (no server in this build, or it already
206    /// runs — started here or by `--mcp`, the section cannot tell and need
207    /// not), enabled otherwise. A failure's line sits under it in the words
208    /// the console used, so a window launched from a desktop icon, with no
209    /// terminal to read, still says what went wrong.
210    fn mcp_section(&mut self, ui: &mut egui::Ui, mcp: &McpView) {
211        ui.heading("Connect an agent (MCP)");
212        ui.label(
213            egui::RichText::new(
214                "Start the MCP server inside this window — what launching with --mcp does — so \
215                 Claude Code or Codex can drive the documents you see here.",
216            )
217            .weak()
218            .small(),
219        );
220        ui.add_space(4.0);
221        let (enabled, label) = match mcp {
222            McpView::Unavailable => (false, START_MCP_LABEL),
223            McpView::Stopped { .. } => (true, START_MCP_LABEL),
224            McpView::Running { .. } => (false, "MCP server running"),
225        };
226        let start = ui.add_enabled(enabled, egui::Button::new(label));
227        self.hit("mcp:start", &start);
228        if start.clicked() {
229            self.mcp_start = true;
230        }
231        match mcp {
232            McpView::Unavailable => {
233                ui.label(egui::RichText::new(NO_MCP_TEXT).weak());
234            }
235            McpView::Stopped { error: None } => {}
236            McpView::Stopped { error: Some(error) } => {
237                ui.label(egui::RichText::new(error).color(ui.visuals().error_fg_color));
238            }
239            McpView::Running { url, instructions, note } => {
240                ui.label(format!("Listening on {url}"));
241                if let Some(note) = note {
242                    ui.label(egui::RichText::new(note).color(ui.visuals().warn_fg_color));
243                }
244                ui.add_space(4.0);
245                ui.label(
246                    egui::RichText::new("Paste this into your agent (the same text the terminal prints):")
247                        .weak()
248                        .small(),
249                );
250                // A read-only text edit: selectable with the pointer, wrapped
251                // to the window, and painted as ONE galley so a test reading
252                // the frame sees the whole text, not a line of it.
253                ui.add(
254                    egui::TextEdit::multiline(&mut instructions.as_str())
255                        .font(egui::TextStyle::Monospace)
256                        .desired_width(f32::INFINITY)
257                        .desired_rows(instructions.lines().count()),
258                );
259                let copy = ui.button("Copy agent instructions");
260                self.hit("mcp:copy", &copy);
261                if copy.clicked() {
262                    ui.ctx().copy_text(instructions.clone());
263                }
264            }
265        }
266        #[cfg(all(feature = "mcp", not(target_arch = "wasm32")))]
267        if !matches!(mcp, McpView::Unavailable) { self.mcp_persistence(ui); }
268    }
269
270    #[cfg(all(feature = "mcp", not(target_arch = "wasm32")))]
271    fn mcp_persistence(&mut self, ui: &mut egui::Ui) {
272        ui.separator();
273        ui.label("MCP state persistence");
274        match crate::mcp::state_configuration() {
275            Some(Ok(state)) => {
276                if let Some(path) = &state.state_dir {
277                    ui.label(format!("This launch: persistent ({:?})", state.source));
278                    if let Some(name) = &state.instance { ui.label(format!("Instance: {name}")); }
279                    ui.label(format!("Journal: {}", path.display()));
280                } else { ui.label(format!("This launch: ephemeral ({:?})", state.source)); }
281            }
282            Some(Err(error)) => { ui.colored_label(ui.visuals().error_fg_color, error); }
283            None => { ui.label("Launch configuration has not been initialized."); }
284        }
285        ui.label("Machine-local preference for the next launch. Command-line and environment overrides take precedence. Restart required after saving.");
286        if let Ok(path) = crate::mcp::state_settings_path() { ui.label(format!("Settings: {}", path.display())); }
287        let preferences = self.mcp_preferences.get_or_insert_with(McpPreferences::load);
288        crate::form::enum_dropdown(ui, "mcp:persistence", &McpPersistence::CHOICES, &mut preferences.mode, None, Some(&mut self.hits));
289        match preferences.mode {
290            McpPersistence::Named => {
291                ui.label("Instance name");
292                let response = ui.text_edit_singleline(&mut preferences.instance);
293                self.hits.insert("mcp:instance".into(), response.rect);
294            }
295            McpPersistence::Directory => {
296                ui.label("Journal directory");
297                let response = ui.text_edit_singleline(&mut preferences.path);
298                self.hits.insert("mcp:state-dir".into(), response.rect);
299            }
300            McpPersistence::Ephemeral => {}
301        }
302        let save = ui.button("Save MCP preference for next launch");
303        self.hits.insert("mcp:save-preference".into(), save.rect);
304        if save.clicked() {
305            let policy = brep_mcp_core::launch_state::Policy {
306                instance: (preferences.mode == McpPersistence::Named).then(|| preferences.instance.clone()),
307                state_dir: (preferences.mode == McpPersistence::Directory).then(|| preferences.path.clone().into()),
308                ephemeral: preferences.mode == McpPersistence::Ephemeral,
309            };
310            preferences.message = Some(crate::mcp::save_desktop_policy(policy).map(|()| "Saved. Restart the application to apply; launch overrides still take precedence.".into()));
311        }
312        if let Some(message) = &preferences.message {
313            match message {
314                Ok(message) => { ui.label(message); }
315                Err(error) => { ui.colored_label(ui.visuals().error_fg_color, error); }
316            }
317        }
318    }
319
320    /// The diagnostics grid, then the one button that puts the very same text a
321    /// problem report would carry on the clipboard — for a user reporting
322    /// somewhere other than the in-app form.
323    fn diagnostics_section(&mut self, ui: &mut egui::Ui, diagnostics: &Diagnostics) {
324        ui.heading("Diagnostics");
325        ui.label(
326            egui::RichText::new("Sent with every problem report from the Submit Bug button.")
327                .weak()
328                .small(),
329        );
330        ui.add_space(4.0);
331        egui::Grid::new("brep-info-diagnostics")
332            .num_columns(2)
333            .spacing([12.0, 4.0])
334            .striped(true)
335            .show(ui, |ui| {
336                for (label, value) in diagnostics.rows() {
337                    ui.label(egui::RichText::new(label).strong());
338                    ui.label(egui::RichText::new(value).monospace());
339                    ui.end_row();
340                }
341            });
342        ui.add_space(6.0);
343        let copy = ui.button("Copy diagnostics");
344        self.hit("copy", &copy);
345        if copy.clicked() {
346            ui.ctx().copy_text(diagnostics.report_text());
347        }
348    }
349
350    /// The licences: the project's own, the maintained notices, and a link to
351    /// the generated crate inventory. Each authored file is behind a collapsing
352    /// header — several thousand words of licence text opened by default would
353    /// bury the diagnostics above it.
354    fn licences_section(&mut self, ui: &mut egui::Ui) {
355        ui.heading("Licences");
356        ui.add_space(4.0);
357        let project = egui::CollapsingHeader::new("Project licence (LICENSE.md)")
358            .id_salt("brep-info-licence-project")
359            .show(ui, |ui| licence_text(ui, PROJECT_LICENCE));
360        self.hit("licence:project", &project.header_response);
361        let notices = egui::CollapsingHeader::new("Third-party notices (THIRD-PARTY-NOTICES.md)")
362            .id_salt("brep-info-licence-notices")
363            .show(ui, |ui| licence_text(ui, THIRD_PARTY_NOTICES));
364        self.hit("licence:notices", &notices.header_response);
365        ui.add_space(6.0);
366        ui.label(
367            egui::RichText::new(
368                "Every crate this application ships, grouped by its licence, is generated \
369                 into the help site from the dependency graph itself:",
370            )
371            .weak()
372            .small(),
373        );
374        let inventory = ui.button("Open the third-party crate inventory");
375        self.hit("inventory", &inventory);
376        if inventory.clicked() {
377            ui.ctx().open_url(egui::OpenUrl::new_tab(INVENTORY_URL));
378        }
379    }
380
381    /// Record a widget's screen rect for the headed verifier.
382    fn hit(&mut self, key: &str, resp: &egui::Response) {
383        self.hits.insert(key.to_string(), resp.rect);
384    }
385
386    /// The published widget hit-rects (egui points) for the headed verifier.
387    pub fn hits_json(&self) -> String {
388        let map: serde_json::Map<String, serde_json::Value> = self
389            .hits
390            .iter()
391            .map(|(k, r)| {
392                (
393                    k.clone(),
394                    serde_json::json!([r.center().x, r.center().y, r.width(), r.height()]),
395                )
396            })
397            .collect();
398        serde_json::Value::Object(map).to_string()
399    }
400}
401
402/// One authored licence file, verbatim. Markdown as typed — the app has no
403/// markdown renderer, and a licence is one of the few texts where showing
404/// exactly the bytes that ship is the right answer anyway. Selectable, so a
405/// reader can copy a clause out.
406fn licence_text(ui: &mut egui::Ui, text: &str) {
407    ui.add(egui::Label::new(egui::RichText::new(text).monospace().small()).wrap());
408}
409
410/// The hit keys this panel publishes (see `automation::hit_keys`).
411/// Every `command` here is `None`, and honestly so: the registered command is
412/// the one that DOES what a click does, and no command copies to a clipboard,
413/// opens this particular help page or expands a header. The window itself is
414/// reachable without a pointer (`info_window`), and the diagnostics it shows are
415/// readable without one (`diagnostics`) — naming either against a button that
416/// does something else would put a promise in the generated widget docs that
417/// `tools/call` cannot keep.
418pub static HIT_KEYS: &[HitKeyDoc] = &[
419    HitKeyDoc { panel: "info", prefix: "copy", meaning: "copy the diagnostics block to the clipboard (the same rows `diagnostics` returns)", command: None },
420    HitKeyDoc { panel: "info", prefix: "inventory", meaning: "open the generated third-party crate inventory on the help site", command: None },
421    HitKeyDoc { panel: "info", prefix: "licence:", meaning: "expand a licence text (licence:project, licence:notices)", command: None },
422    // No command either: a server started from the agent's own tool call
423    // would be the server that call came in on, and the copy goes to a
424    // clipboard. The instructions are the console's, so a host has them.
425    HitKeyDoc { panel: "info", prefix: "mcp:", meaning: "the Connect an agent section: mcp:start starts the embedded MCP server (disabled while it runs or in a build without one), mcp:copy copies the agent instructions; mcp:persistence is the next-launch state dropdown (mcp:persistence#named/#directory/#ephemeral while open), mcp:instance and mcp:state-dir edit the location, mcp:save-preference saves machine-local settings", command: None },
426];
427