Skip to main content

mermaid_cli/app/
run.rs

1//! The ~30-line main loop.
2//!
3//! Single entry point that composes crossterm events with the engine:
4//!
5//! ```text
6//!   crossterm events ──┐
7//!                      ├── tokio::select! ── Msg ── Engine::step ──┐
8//!   effect results   ──┤                                            │
9//!                      │                            ▲               │
10//!   tick             ──┘                            └─ Msg back ◄───┘
11//! ```
12//!
13//! No parallel event loops, no observer callbacks, no polling. One select!,
14//! one `step` per message, effects dispatched into structured concurrency per
15//! turn.
16//!
17//! The reduce-and-route half lives in [`crate::engine`], shared with the
18//! headless drivers. What stays here is what is genuinely run-loop-owned: the
19//! terminal event stream (the `$EDITOR` round-trip has to drop and rebuild it
20//! around a suspend), the 16ms render tick, and `Cmd::ComposeInEditor`, which
21//! [`RunLoopSink`] peels out of the command flow for exactly that reason.
22
23use std::collections::VecDeque;
24use std::path::PathBuf;
25
26use anyhow::Result;
27use crossterm::event::EventStream;
28use futures::{FutureExt, StreamExt};
29use ratatui::layout::Rect;
30use tokio::time::{Duration, interval};
31
32use crate::app::event_source::{bridge_paste_chunks, coalesce_key_burst_seamed};
33use crate::app::lifecycle::RuntimeLifecycle;
34use crate::app::recorder::{RECORDING_FORMAT_VERSION, Recorder, SessionHeader};
35use crate::app::terminal::TerminalGuard;
36use crate::effect::EffectRunner;
37use crate::engine::{EffectSink, Engine, Observation, StepObserver};
38use crate::providers::ToolRegistry;
39use crate::render::{RenderCache, render};
40use mermaid_domain::Config;
41use mermaid_domain::ConversationHistory;
42use mermaid_domain::{Cmd, Msg, Paste, RuntimeSignal, State};
43
44/// Options for `run_interactive_with`. Added so new flags land without
45/// reshuffling positional args.
46///
47/// Not `Debug` because `Recorder` owns a `BufWriter<File>` which isn't
48/// Debug. The bigger picture is that nothing prints these — they're an
49/// argument bundle, not telemetry.
50#[derive(Default)]
51pub struct InteractiveOptions {
52    /// Optional recorder for `--record <file>` JSONL capture.
53    pub recorder: Option<Recorder>,
54    /// Optional conversation to seed the session with (e.g. from
55    /// `--continue` or `--sessions`). When `Some`, the seeded history
56    /// replaces `State::session.conversation` before the first frame.
57    pub seed_conversation: Option<ConversationHistory>,
58}
59
60/// The interactive loop's effect sink: everything reaches the runner except
61/// `Cmd::ComposeInEditor`, which is run-loop-owned — it suspends the terminal
62/// and drops the crossterm event stream, and only this loop holds either. At
63/// most one compose lands per reducer step by construction (a single Ctrl+O /
64/// `/editor` arm).
65struct RunLoopSink {
66    runner: EffectRunner,
67    compose: Option<String>,
68}
69
70impl EffectSink for RunLoopSink {
71    fn dispatch(&mut self, cmd: Cmd) {
72        if let Cmd::ComposeInEditor { text } = cmd {
73            self.compose = Some(text);
74        } else {
75            self.runner.dispatch(cmd);
76        }
77    }
78}
79
80/// `--record <file>`: one JSONL line per reducer input.
81///
82/// As an observer it writes *before* the reducer runs, so the log captures even
83/// no-op inputs, and it carries the exact `now` the message was reduced under —
84/// which is what lets `--replay` stamp each entry's `ts` back into `state.now`
85/// and recompute the identical states.
86struct RecorderTap(Option<Recorder>);
87
88impl StepObserver for RecorderTap {
89    fn observe(&mut self, obs: Observation<'_>) {
90        if let Some(r) = self.0.as_mut()
91            && let Err(err) = r.record_msg(obs.now, obs.msg)
92        {
93            tracing::warn!(error = %err, "recorder: failed to record message; --replay may be non-deterministic");
94        }
95    }
96}
97
98/// Interactive TUI main loop with explicit options. `recorder` (if
99/// provided) appends one JSONL line per reducer input to the file for
100/// debugging / replay.
101///
102/// # Errors
103///
104/// Setting up the terminal, opening the recorder when one is requested, and a
105/// failure in the main loop or in the shutdown that follows it. A model or
106/// tool that fails mid-session is not among them: those surface in the
107/// transcript and the loop continues, which is what makes a session survivable.
108#[expect(
109    clippy::too_many_lines,
110    reason = "the interactive main loop: boot wiring, the select! over terminal events, effect \
111     results, signals and ticks, and the ordered shutdown all share one scope because the \
112     terminal guard, event stream and engine must be created, suspended for $EDITOR, and dropped \
113     in a fixed order; moving any stage out would hand that order to call sites"
114)]
115pub async fn run_interactive_with(
116    mut config: Config,
117    cwd: PathBuf,
118    model_id: String,
119    mut opts: InteractiveOptions,
120) -> Result<()> {
121    // One startup clock read, shared by `State::new` and the recording
122    // header: replay seeds `State::new` with the recorded value and gets the
123    // same initial conversation id/title.
124    let startup_now = chrono::Local::now();
125    // Fold enabled plugins' MCP servers + agent types into the merged config
126    // BEFORE anything consumes it (State::new seeds server rows, the
127    // recording header captures the merged config — replay-faithful, and the
128    // provider factory + tool registry see the same view).
129    let plugin_assets = crate::app::plugin_assets::load();
130    let plugin_warnings = crate::app::plugin_assets::apply(&mut config, &plugin_assets);
131    let mut state = State::new(
132        config.clone(),
133        cwd.clone(),
134        model_id.clone(),
135        startup_now,
136        std::env::temp_dir(),
137    );
138    let seed = opts.seed_conversation.take();
139    if let Some(r) = opts.recorder.as_mut() {
140        // The header makes a recording self-contained: `--replay` rebuilds
141        // the initial State from it (config, model, cwd, seed) without
142        // reading this machine's live config. Written before the first Msg
143        // so even a crashed session leaves a parseable log.
144        r.record_header(&SessionHeader {
145            format: RECORDING_FORMAT_VERSION,
146            ts: startup_now,
147            model_id: model_id.clone(),
148            cwd: cwd.clone(),
149            config: config.clone(),
150            seed_conversation: seed.clone(),
151        })?;
152    }
153    if let Some(history) = seed {
154        // `--continue` / `--resume` seed — shared with `--replay` via
155        // `State::seed_conversation` so both build the same starting state.
156        state.seed_conversation(history);
157    }
158    state
159        .ui
160        .pending_msgs
161        .push_back(Msg::SessionProvenanceResolved(
162            crate::session::probe_session_provenance(&cwd),
163        ));
164    // NO_COLOR (https://no-color.org): present and non-empty disables all
165    // color. Read once here — the reducer never touches the environment; the
166    // render layer resolves `Theme::plain()` off this flag.
167    state.ui.no_color = std::env::var_os("NO_COLOR").is_some_and(|v| !v.is_empty());
168    // Skills load once at startup (authored artifacts, no watcher); the config
169    // watcher below keeps only instructions/memory fresh.
170    state.skills = crate::app::skills::load(&cwd);
171    // Plugin prompt commands: same restart-to-refresh policy as skills.
172    state.plugin_commands = plugin_assets.commands;
173    for warning in plugin_warnings {
174        state
175            .ui
176            .pending_msgs
177            .push_back(Msg::TransientStatus { text: warning });
178    }
179    let providers = std::sync::Arc::new(crate::providers::ProviderFactory::new(config.clone()));
180    let tools = ToolRegistry::build(&config, providers.clone());
181    if let Some(capabilities) = tools.web_capabilities()
182        && let Some(text) = web_capabilities_notice(&config, capabilities)
183    {
184        state
185            .ui
186            .pending_msgs
187            .push_back(Msg::TransientStatus { text });
188    }
189    let (runner, mut msg_rx) = EffectRunner::pair_from(cwd.clone(), providers, tools);
190    // Interactive TUI: enable inline approval prompts so `ask` mode (and Auto
191    // escalations) pause and prompt instead of erroring out, and inline
192    // `ask_user_question` prompts so the model can ask the user structured
193    // questions mid-run instead of proceeding without them.
194    let mut runner = runner
195        .with_interactive_approvals()
196        .with_interactive_questions();
197    // Keep instructions/memory fresh via the background config watcher (#45):
198    // it emits Msg::InstructionsChanged/MemoryChanged on change, so the reducer
199    // reads them as injected data and never does the refresh I/O inline.
200    runner.spawn_config_watcher(cwd.clone(), config.memory.clone());
201    let mut terminal = Some(TerminalGuard::setup()?);
202    let home_dir = directories::BaseDirs::new().map(|dirs| dirs.home_dir().to_path_buf());
203    let mut rstate = RenderCache::new(home_dir);
204    // `Option` because the $EDITOR compose round-trip must DROP the stream
205    // (its reader thread holds crossterm's internal reader mutex) before
206    // suspending, and build a fresh one after — same lifecycle dance as
207    // `terminal` above.
208    let mut events = Some(EventStream::new());
209    let mut lifecycle = RuntimeLifecycle::new();
210    let mut tick = interval(Duration::from_millis(16));
211
212    // Boot effects: MCP server init (if configured). Instructions/memory are
213    // loaded by the config watcher started above (#45), not here.
214    for cmd in bootstrap_cmds(&config, &state.session.conversation.id) {
215        runner.dispatch(cmd);
216    }
217    // A resumed session may carry an in-flight checklist; hand it to the
218    // TaskBroker (tool-side truth) so the first task tool call of the new
219    // process starts from the restored list instead of an empty one.
220    if !state.session.conversation.tasks.tasks.is_empty() {
221        runner.dispatch(mermaid_domain::Cmd::SyncTaskStore(
222            state.session.conversation.tasks.clone(),
223        ));
224    }
225
226    // Everything the reducer needs is in place: hand the state and the runner
227    // to the engine, which owns the reduce-and-route step from here. The
228    // `select!` below stays local — terminal events and the `$EDITOR`
229    // round-trip are genuinely run-loop-owned — but it now feeds one call.
230    let mut engine = Engine::new(
231        state,
232        RunLoopSink {
233            runner,
234            compose: None,
235        },
236    )
237    .with_observer(RecorderTap(opts.recorder));
238
239    // Which `select!` arm fired. Terminal events are handled *after* the
240    // select! returns so the paste-coalescing drain can borrow `events`
241    // again without tripping the borrow checker.
242    //
243    // `Msg` is the large variant, but this enum lives on the stack for one
244    // loop iteration and `Msg` is passed by value everywhere already —
245    // boxing it would add a per-event heap alloc on the hot input path.
246    #[expect(clippy::large_enum_variant)]
247    enum Sel {
248        Msg(Option<Msg>),
249        Term(Option<Result<crossterm::event::Event, std::io::Error>>),
250    }
251
252    // Msgs produced ahead of time — e.g. a non-paste event drained while
253    // coalescing a key burst. Processed before pulling the next event.
254    let mut pending_msgs: VecDeque<Msg> = VecDeque::new();
255
256    // Main loop. A fatal error inside the loop is captured here and returned
257    // AFTER the orderly-shutdown path below, so a draw failure can't skip MCP
258    // child cleanup / pending-save drains (the terminal is still restored by
259    // `TerminalGuard::Drop` regardless).
260    let mut exit_result: Result<()> = Ok(());
261    // Last-seen `full_redraw_seq`. When the reducer bumps it (shell command
262    // finished, Ctrl+L), `Terminal::clear()` resets ratatui's back buffer so
263    // the next draw repaints every cell — the only way to overwrite bytes
264    // some other process wrote directly to the tty (ghost cells).
265    let mut seen_redraw_seq = engine.state().ui.full_redraw_seq;
266    loop {
267        // Render the current state. ratatui's draw closure captures
268        // &State, so we don't thread &mut State through the renderer.
269        {
270            let term = terminal
271                .as_mut()
272                .expect("terminal guard is alive while the render loop runs")
273                .inner_mut();
274            if engine.state().ui.full_redraw_seq != seen_redraw_seq {
275                seen_redraw_seq = engine.state().ui.full_redraw_seq;
276                // NOT `Terminal::clear()`: it snapshots the cursor with an
277                // ESC[6n round-trip, and the reply never arrives — the
278                // `EventStream` reader thread is parked holding crossterm's
279                // internal reader mutex and swallows it — so the query dies
280                // fatally after crossterm's 2s deadline. `resize()` to the
281                // current size performs the same full clear + back-buffer
282                // reset for a Fullscreen viewport without querying the tty.
283                let repaint = term
284                    .size()
285                    .and_then(|size| term.resize(Rect::new(0, 0, size.width, size.height)));
286                if let Err(err) = repaint {
287                    exit_result = Err(err.into());
288                    break;
289                }
290            }
291            if let Err(err) = term.draw(|f| render(engine.state(), &mut rstate, f)) {
292                exit_result = Err(err.into());
293                break;
294            }
295        }
296
297        // Drain any msgs queued by a prior burst-coalesce before blocking
298        // on the next event.
299        let msg = if let Some(queued) = pending_msgs.pop_front() {
300            Some(queued)
301        } else {
302            let selected = tokio::select! {
303                // Fair (unbiased) polling. With `biased;`, the hot `msg_rx`
304                // arm would always win under sustained streaming and starve
305                // terminal input + OS signals (#112). Fair selection still
306                // drains streaming promptly — it's almost always ready — while
307                // guaranteeing the input/signal/tick arms get serviced too.
308                //
309                // Effect results (streaming chunks, tool output, …).
310                m = msg_rx.recv() => Sel::Msg(m),
311                // Crossterm events. Handled below, outside the select!, so
312                // coalescing can re-borrow `events`.
313                e = events.as_mut().expect("event stream is alive while the loop runs").next() => Sel::Term(e),
314                // OS lifecycle signals. A typed Ctrl+C in raw mode is handled
315                // by the crossterm branch above; this covers SIGINT/SIGTERM/
316                // SIGHUP delivered externally.
317                s = lifecycle.next_msg() => Sel::Msg(s),
318                // Tick — drives elapsed-time displays + self-dismissing status
319                // lines without busy-waiting.
320                _ = tick.tick() => Sel::Msg(Some(Msg::Tick)),
321            };
322
323            match selected {
324                Sel::Msg(m) => m,
325                Sel::Term(Some(Ok(evt))) => {
326                    if let crossterm::event::Event::Mouse(m) = &evt {
327                        use crossterm::event::{KeyModifiers, MouseButton, MouseEventKind as MEK};
328                        let ctrl = m.modifiers.contains(KeyModifiers::CONTROL);
329                        match m.kind {
330                            // F13: Ctrl+Click a chat image tile opens it via
331                            // the system viewer. The screen→image mapping
332                            // lives in ChatState (the render layer).
333                            MEK::Down(MouseButton::Left) if ctrl => rstate
334                                .chat
335                                .find_image_at_screen_pos(m.row)
336                                .map(|target| Msg::OpenImageAt {
337                                    message_index: target.message_index,
338                                    image_index: target.image_index,
339                                    image_number: target.image_number,
340                                }),
341                            // Plain (no-modifier) left drag selects chat text.
342                            // Handled render-side so wheel-scroll + Ctrl+Click
343                            // keep working; on release we copy the selection.
344                            MEK::Down(MouseButton::Left) => {
345                                rstate.chat.begin_selection(m.row, m.column);
346                                None
347                            },
348                            MEK::Drag(MouseButton::Left) => {
349                                rstate.chat.update_selection(m.row, m.column);
350                                None
351                            },
352                            MEK::Up(MouseButton::Left) => {
353                                // A drag only *selects* (the highlight persists);
354                                // copying is an explicit action (Ctrl+Shift+C).
355                                // Auto-copying on release would silently clobber
356                                // the user's clipboard.
357                                None
358                            },
359                            MEK::ScrollUp => Some(Msg::MouseScroll {
360                                delta: mermaid_model::constants::UI_MOUSE_SCROLL_LINES as i16,
361                            }),
362                            MEK::ScrollDown => Some(Msg::MouseScroll {
363                                delta: -(mermaid_model::constants::UI_MOUSE_SCROLL_LINES as i16),
364                            }),
365                            _ => None,
366                        }
367                    } else {
368                        // Non-mouse event. Ctrl+Shift+C copies the current chat
369                        // selection — the explicit copy step after a drag-select.
370                        // Because the app holds the mouse, the terminal has no
371                        // selection of its own and passes the shortcut through.
372                        // The SHIFT bit only arrives when the kitty keyboard
373                        // protocol was negotiated at setup (TerminalGuard); on
374                        // legacy terminals Ctrl+Shift+C is transmitted as the
375                        // identical byte 0x03 as Ctrl+C — physically
376                        // indistinguishable — so there it falls through to the
377                        // reducer's Ctrl+C handling (press-twice-to-exit keeps
378                        // a stray copy-chord harmless).
379                        if let crossterm::event::Event::Key(k) = &evt
380                            && k.kind == crossterm::event::KeyEventKind::Press
381                            && k.modifiers
382                                .contains(crossterm::event::KeyModifiers::CONTROL)
383                            && k.modifiers.contains(crossterm::event::KeyModifiers::SHIFT)
384                            && matches!(k.code, crossterm::event::KeyCode::Char(c) if c.eq_ignore_ascii_case(&'c'))
385                        {
386                            // Route the copy through the reducer (#18): the
387                            // selection lives in the render layer, but emitting a
388                            // Msg keeps the clipboard side effect recorded +
389                            // replayable instead of dispatched out-of-band.
390                            rstate
391                                .chat
392                                .selected_text()
393                                .filter(|t| !t.is_empty())
394                                .map(Msg::CopySelection)
395                        } else {
396                            // Coalesce a paste burst (crossterm 0.29 doesn't
397                            // deliver Event::Paste on the Windows console — a
398                            // paste arrives as a flood of Char/Enter key events).
399                            // The drain pulls every immediately-available event
400                            // so the whole block lands as one atomic Msg::Paste.
401                            let stream = events
402                                .as_mut()
403                                .expect("event stream is alive while the loop runs");
404                            let (mut primary, mut trailing, ends_with_cr) =
405                                coalesce_key_burst_seamed(evt, || {
406                                    stream.next().now_or_never().flatten().and_then(|r| r.ok())
407                                });
408                            // A paste-shaped burst that stopped on plain quiet
409                            // (no deliberate trailing event) may just be the
410                            // first chunk ConPTY delivered — bridge the gap so
411                            // a chunk boundary right after an Enter never
412                            // submits half a paste (#351). The fold state
413                            // crosses the seam with it, so a CRLF pair split
414                            // at the gap stays one newline.
415                            if trailing.is_empty()
416                                && let Some(Msg::Paste(Paste::Text(text))) = &mut primary
417                            {
418                                trailing = bridge_paste_chunks(text, ends_with_cr, stream).await;
419                            }
420                            for queued in trailing {
421                                pending_msgs.push_back(queued);
422                            }
423                            primary
424                        }
425                    }
426                },
427                Sel::Term(Some(Err(error))) => {
428                    tracing::warn!(error = %error, "terminal event stream failed");
429                    None
430                },
431                Sel::Term(None) => Some(Msg::RuntimeSignal(RuntimeSignal::Hangup)),
432            }
433        };
434
435        let Some(msg) = msg else { continue };
436
437        // Inject the wall clock as data (Cause 3): one stamp per tick, shared
438        // by the recorder observer and the reducer. The recorded `ts` IS the
439        // `state.now` this Msg was reduced under, so `--replay` folds the
440        // same log by stamping each entry's `ts` here and recomputes the
441        // exact same states.
442        let outcome = engine.step_at(chrono::Local::now(), msg);
443
444        // The sink peeled `ComposeInEditor` off on its way past; run it here,
445        // where the terminal and event stream it has to suspend actually live.
446        if let Some(draft) = engine.sink_mut().compose.take() {
447            match crate::app::editor::compose_in_editor(&mut terminal, &mut events, draft).await {
448                // Through pending_msgs, so the result flows through the
449                // recorder like any input — --replay never launches an editor.
450                Ok(msg) => pending_msgs.push_back(msg),
451                Err(err) => {
452                    exit_result = Err(err);
453                    break;
454                },
455            }
456        }
457
458        if outcome.should_exit {
459            break;
460        }
461    }
462
463    let (state, sink, RecorderTap(mut recorder)) = engine.into_parts();
464
465    // Seal the recording with a fingerprint of the final session, so a
466    // future `--replay` can verify its fold reproduces what this live
467    // session actually saw — not merely that the fold is self-consistent.
468    // (Wall-clock read is fine here: we're outside the reducer.)
469    if let Some(r) = recorder.as_mut()
470        && let Err(err) = r.record_trailer(chrono::Local::now(), &state.session)
471    {
472        tracing::warn!(error = %err, "recorder: failed to write replay trailer");
473    }
474
475    // Restore the user's terminal before async shutdown. Shutdown can
476    // wait on pending saves / cancelled scopes for a bounded period;
477    // keeping raw mode + mouse capture alive during that wait makes
478    // Ctrl+C feel ignored and can leak mouse escape sequences into
479    // the shell if the user keeps interacting.
480    drop(events);
481    if let Some(mut terminal) = terminal.take() {
482        terminal.restore_now();
483    }
484
485    // Orderly shutdown — wait for any pending saves / scope cleanup. Runs even
486    // when the loop broke on a draw error, so MCP children are reaped cleanly.
487    sink.runner.shutdown().await;
488    exit_result
489}
490
491/// Commands dispatched on startup before the first iteration of the
492/// loop. Fires MCP init (if configured) and materializes the session's
493/// scratch directory. Instructions/memory are loaded by the config
494/// watcher (#45), not here.
495fn bootstrap_cmds(config: &Config, session_id: &str) -> Vec<Cmd> {
496    // Instructions/memory load + stay fresh via the config watcher (#45),
497    // started in `run_interactive_with`.
498    let mut cmds = Vec::new();
499    if !config.mcp_servers.is_empty() {
500        cmds.push(Cmd::InitMcpServers(config.mcp_servers.clone()));
501    }
502    // Every session gets a scratch dir — `session_id` is captured AFTER any
503    // `--continue`/`--resume` seed, so a resumed session adopts the dir
504    // keyed by its restored conversation id.
505    cmds.push(Cmd::EnsureScratchpad {
506        session_id: session_id.to_string(),
507    });
508    cmds
509}
510
511/// One startup-visible summary built from the exact capability resolution used
512/// by the registry and subagents. This makes backend/trust routing explicit in
513/// the TUI without re-reading credentials or probing platform viability.
514///
515/// Returns `None` only for the boring case — every capability resolved AND
516/// every one of them terminates on this machine — so a healthy sovereign
517/// startup stays quiet. Silence therefore means "working and local"; anything
518/// else speaks. Availability alone is deliberately NOT the gate: a working
519/// cloud backend is exactly what a user needs told, so gating on viability
520/// would mute the disclosure precisely when traffic is leaving the machine.
521fn web_capabilities_notice(
522    config: &Config,
523    capabilities: &crate::providers::tool::web::WebCapabilities,
524) -> Option<String> {
525    use crate::providers::tool::web::Egress;
526
527    if config.safety.network == mermaid_domain::NetworkPolicy::Deny {
528        return Some(format!(
529            "Web egress disabled by safety.network = \"deny\" (selected fetch backend: {}; selected search backend: {}).",
530            capabilities.fetch.backend, capabilities.search.backend
531        ));
532    }
533
534    let all = [
535        ("fetch", &capabilities.fetch),
536        ("search", &capabilities.search),
537    ];
538    let degraded = all
539        .into_iter()
540        .filter(|(_, status)| !status.available)
541        .collect::<Vec<_>>();
542    let leaves_machine = all
543        .iter()
544        .any(|(_, status)| status.egress == Egress::OffMachine);
545    if degraded.is_empty() && !leaves_machine {
546        return None;
547    }
548
549    // Headline stays one line per capability: backend + availability, and the
550    // trust destination ONLY where it means something. An unavailable backend
551    // routes nowhere, so naming its destination there is noise that also
552    // strands the remediation text mid-sentence.
553    let headline = |name: &str, status: &crate::providers::tool::web::WebCapabilityStatus| {
554        if status.available {
555            format!(
556                "{name}: {} (available; {})",
557                status.backend, status.trust_destination
558            )
559        } else {
560            format!("{name}: {} (unavailable)", status.backend)
561        }
562    };
563
564    // Remediation prose is a paragraph, not a parenthetical — give each
565    // degraded capability its own line below the headline. The marker is a
566    // `-` bullet, not leading whitespace: the transcript renderer re-wraps
567    // system notices word by word (`wrap_text_with_indent`), so an indent is
568    // dropped and the detail lines would be indistinguishable from the
569    // wrapped headline. A glyph is a word, so it survives.
570    let mut notice = format!(
571        "Web capabilities - {}; {}.",
572        headline("fetch", &capabilities.fetch),
573        headline("search", &capabilities.search)
574    );
575    for (name, status) in degraded {
576        let reason = status
577            .reason
578            .as_deref()
579            .map(mermaid_model::utils::redact_secrets)
580            .unwrap_or_else(|| "backend initialization failed".to_string());
581        let reason = reason.split_whitespace().collect::<Vec<_>>().join(" ");
582        let reason = mermaid_model::utils::truncate_middle_bytes(&reason, 240)
583            .split_whitespace()
584            .collect::<Vec<_>>()
585            .join(" ");
586        notice.push_str(&format!("\n- {name}: {reason}"));
587    }
588    Some(notice)
589}
590
591#[cfg(test)]
592mod tests {
593    use super::*;
594
595    #[test]
596    fn bootstrap_always_ensures_the_session_scratchpad() {
597        // Instructions/memory load via the config watcher (#45), not
598        // bootstrap; with no MCP servers configured, only the scratchpad
599        // ensure remains — keyed by the caller's session id.
600        let cmds = bootstrap_cmds(&Config::default(), "sess-1");
601        assert_eq!(cmds.len(), 1);
602        assert!(
603            cmds.iter().any(
604                |c| matches!(c, Cmd::EnsureScratchpad { session_id } if session_id == "sess-1")
605            )
606        );
607    }
608
609    #[test]
610    fn bootstrap_skips_mcp_init_when_no_servers_configured() {
611        let cmds = bootstrap_cmds(&Config::default(), "sess-1");
612        assert!(!cmds.iter().any(|c| matches!(c, Cmd::InitMcpServers(_))));
613    }
614
615    #[test]
616    fn bootstrap_includes_mcp_init_when_servers_configured() {
617        let mut cfg = Config::default();
618        cfg.mcp_servers.insert(
619            "example".to_string(),
620            mermaid_domain::McpServerConfig {
621                command: "echo".to_string(),
622                args: vec![],
623                env: std::collections::HashMap::new(),
624                ..Default::default()
625            },
626        );
627        let cmds = bootstrap_cmds(&cfg, "sess-1");
628        assert!(cmds.iter().any(|c| matches!(c, Cmd::InitMcpServers(_))));
629    }
630
631    /// Statuses are built by hand rather than via `WebCapabilities::resolve`
632    /// so the notice's formatting is asserted independently of whichever
633    /// backends happen to be viable on the test host.
634    fn capabilities(
635        fetch: crate::providers::tool::web::WebCapabilityStatus,
636        search: crate::providers::tool::web::WebCapabilityStatus,
637    ) -> crate::providers::tool::web::WebCapabilities {
638        crate::providers::tool::web::WebCapabilities::from_statuses_for_test(fetch, search)
639    }
640
641    fn available(
642        backend: &'static str,
643        trust_destination: &'static str,
644        egress: crate::providers::tool::web::Egress,
645    ) -> crate::providers::tool::web::WebCapabilityStatus {
646        crate::providers::tool::web::WebCapabilityStatus {
647            available: true,
648            backend,
649            trust_destination,
650            egress,
651            reason: None,
652        }
653    }
654
655    fn unavailable(
656        backend: &'static str,
657        trust_destination: &'static str,
658        egress: crate::providers::tool::web::Egress,
659        reason: &str,
660    ) -> crate::providers::tool::web::WebCapabilityStatus {
661        crate::providers::tool::web::WebCapabilityStatus {
662            available: false,
663            backend,
664            trust_destination,
665            egress,
666            reason: Some(reason.to_string()),
667        }
668    }
669
670    /// The two sovereign defaults, spelled once: fetch straight off this
671    /// machine, search via the locally managed SearXNG process.
672    fn local_fetch() -> crate::providers::tool::web::WebCapabilityStatus {
673        available(
674            "native",
675            "direct from this machine",
676            crate::providers::tool::web::Egress::OnMachine,
677        )
678    }
679
680    fn local_search() -> crate::providers::tool::web::WebCapabilityStatus {
681        available(
682            "managed_searxng",
683            "local managed process",
684            crate::providers::tool::web::Egress::OnMachine,
685        )
686    }
687
688    #[test]
689    fn web_capability_notice_stays_silent_when_everything_resolved_and_local() {
690        let config = Config::default();
691        let capabilities = capabilities(local_fetch(), local_search());
692        assert_eq!(web_capabilities_notice(&config, &capabilities), None);
693    }
694
695    /// The regression this gate exists to prevent: a WORKING cloud backend is
696    /// the case a sovereignty-focused tool most needs to disclose, so
697    /// viability alone must never buy silence.
698    #[test]
699    fn web_capability_notice_discloses_working_cloud_egress() {
700        let config = Config::default();
701        let capabilities = capabilities(
702            local_fetch(),
703            available(
704                "ollama_cloud",
705                "Ollama Cloud",
706                crate::providers::tool::web::Egress::OffMachine,
707            ),
708        );
709        let notice =
710            web_capabilities_notice(&config, &capabilities).expect("cloud egress must disclose");
711        assert!(
712            notice.contains("search: ollama_cloud (available; Ollama Cloud)"),
713            "{notice}"
714        );
715        // Nothing is broken, so nothing earns a remediation line.
716        assert!(!notice.contains('\n'), "{notice}");
717    }
718
719    /// An operator-supplied SearXNG URL cannot be proven to be loopback, so it
720    /// discloses like any other off-machine destination.
721    #[test]
722    fn web_capability_notice_discloses_configured_searxng_endpoint() {
723        let config = Config::default();
724        let capabilities = capabilities(
725            local_fetch(),
726            available(
727                "searxng",
728                "configured SearXNG instance",
729                crate::providers::tool::web::Egress::OffMachine,
730            ),
731        );
732        let notice =
733            web_capabilities_notice(&config, &capabilities).expect("configured endpoint discloses");
734        assert!(notice.contains("configured SearXNG instance"), "{notice}");
735    }
736
737    #[test]
738    fn web_capability_notice_gives_every_degraded_capability_its_own_line() {
739        let config = Config::default();
740        let capabilities = capabilities(
741            unavailable(
742                "native",
743                "direct from this machine",
744                crate::providers::tool::web::Egress::OnMachine,
745                "TLS backend failed to initialize",
746            ),
747            unavailable(
748                "managed_searxng",
749                "local managed process",
750                crate::providers::tool::web::Egress::OnMachine,
751                "no sovereign SearXNG bundle is available for this platform",
752            ),
753        );
754        let notice = web_capabilities_notice(&config, &capabilities).expect("both degraded");
755        let lines = notice.lines().collect::<Vec<_>>();
756        assert_eq!(lines.len(), 3, "{notice}");
757        assert!(lines[1].starts_with("- fetch: TLS backend"), "{notice}");
758        assert!(lines[2].starts_with("- search: no sovereign"), "{notice}");
759    }
760
761    #[test]
762    fn web_capability_notice_discloses_shared_backend_and_trust_routing() {
763        let config = Config::default();
764        let capabilities = capabilities(
765            local_fetch(),
766            unavailable(
767                "managed_searxng",
768                "local managed process",
769                crate::providers::tool::web::Egress::OnMachine,
770                "no sovereign SearXNG bundle is available for this platform",
771            ),
772        );
773        let notice = web_capabilities_notice(&config, &capabilities).expect("degraded search");
774        // The healthy capability still discloses where its traffic goes.
775        assert!(notice.contains("fetch: native (available"), "{notice}");
776        assert!(notice.contains("direct from this machine"), "{notice}");
777        assert!(
778            notice.contains("search: managed_searxng (unavailable)"),
779            "{notice}"
780        );
781    }
782
783    #[test]
784    fn web_capability_notice_moves_remediation_off_the_headline() {
785        let config = Config::default();
786        let capabilities = capabilities(
787            local_fetch(),
788            unavailable(
789                "managed_searxng",
790                "local managed process",
791                crate::providers::tool::web::Egress::OnMachine,
792                "no sovereign SearXNG bundle is available for this platform (windows/x86_64).\n  Configure `[web] search_backend = \"ollama\"`.",
793            ),
794        );
795        let notice = web_capabilities_notice(&config, &capabilities).expect("degraded search");
796        let (headline, detail) = notice.split_once('\n').expect("detail line");
797        // The unavailable backend routes nowhere, so its trust destination is
798        // not named — and the paragraph never lands mid-parenthetical.
799        assert!(!headline.contains("local managed process"), "{headline}");
800        assert!(!headline.contains("SearXNG bundle"), "{headline}");
801        assert_eq!(
802            detail,
803            "- search: no sovereign SearXNG bundle is available for this platform (windows/x86_64). Configure `[web] search_backend = \"ollama\"`."
804        );
805    }
806
807    #[test]
808    fn web_capability_notice_honors_global_network_denial() {
809        let mut config = Config::default();
810        config.safety.network = mermaid_domain::NetworkPolicy::Deny;
811        // Denial reports regardless of viability or locality — both backends
812        // resolve here, and both stay on this machine.
813        let capabilities = capabilities(local_fetch(), local_search());
814        let notice = web_capabilities_notice(&config, &capabilities).expect("denial always shows");
815        assert!(notice.contains("Web egress disabled"), "{notice}");
816        assert!(notice.contains("fetch backend: native"), "{notice}");
817        assert!(
818            notice.contains("search backend: managed_searxng"),
819            "{notice}"
820        );
821    }
822}