From 76a217cc7cc1da5f0a29cdfb0b9c8c9586ca717c Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 2 Dec 2026 10:25:21 -0600 Subject: [PATCH 1/3] feat(assistant): connect an agent from the pane, and keep the conversation in view Using an agent you already have over MCP was set up at the bottom of the assistant's settings, and open settings filled the pane, even while an action waited for approval. - "Connect my agent", under the model's name, opens a view with the switch that lets agents in, the commands to copy, who is connected, the last call, and a connection test that reaches the app through rustgis-cli. - The relay keeps the name each attached client gives in its initialize. - An empty conversation offers the view once when an agent is installed here. Nothing is turned on for the user. - Open settings leave the conversation a share of the pane. An approval card's details scroll in what the pane has, so its buttons and the message box stay in view; where settings and the whole card don't fit, a note says an action waits, with Review it and Decline. - ui.pane.assistant {"connect": true} opens the view (desktop only). Part of #3568. --- crates/assistant/src/relay.rs | 50 ++- crates/ui-egui/src/assistant.rs | 10 + crates/ui-egui/src/assistantpane.rs | 208 +++++++++++- crates/ui-egui/src/connectui.rs | 497 +++++++++++++++++++++++++--- crates/ui-egui/src/layout_reach.rs | 20 ++ crates/ui-egui/src/lib.rs | 33 +- crates/ui-egui/tests/smoke.rs | 10 +- docs/mcp.md | 25 +- docs/user-guide/assistant.md | 15 + 9 files changed, 779 insertions(+), 89 deletions(-) diff --git a/crates/assistant/src/relay.rs b/crates/assistant/src/relay.rs index 14f04cc38c..66a9ac4b11 100644 --- a/crates/assistant/src/relay.rs +++ b/crates/assistant/src/relay.rs @@ -16,7 +16,7 @@ //! token is checked, and every read and write wait are bounded. A command whose reply does not //! come in time is cancelled before the app can run it. Stopping the relay, or dropping its last //! owner, closes the listener and every client and removes the token file. -use std::collections::{HashMap, VecDeque}; +use std::collections::{BTreeMap, HashMap, VecDeque}; use std::io::{Read, Write}; use std::net::{Shutdown, SocketAddr, TcpListener, TcpStream}; use std::path::PathBuf; @@ -159,6 +159,8 @@ struct Shared { preauth: AtomicUsize, /// Authenticated connections. attached: AtomicUsize, + /// What the attached clients call themselves (MCP's `clientInfo.name`), by connection id. + clients: Mutex>, /// How long a request waits for the app before it is cancelled, unless its client asked for /// another time. reply_wait: Duration, @@ -589,6 +591,7 @@ impl Relay { next_id: AtomicU64::new(0), preauth: AtomicUsize::new(0), attached: AtomicUsize::new(0), + clients: Mutex::new(BTreeMap::new()), reply_wait, busy_after, last_poll: Mutex::new(Instant::now()), @@ -633,6 +636,13 @@ impl Relay { self.owner.shared.attached.load(SeqCst) } + /// The names the attached clients gave in their `initialize`, oldest connection first. One + /// that hasn't sent it isn't listed. A client's own word, for the user to read, never to + /// decide anything by. + pub fn client_names(&self) -> Vec { + lock(&self.owner.shared.clients).values().cloned().collect() + } + /// Writes a request and how it went to the audit log, if there is one. fn audit(&self, line: &str, reply: Option<&str>, took: Duration) { // Out of the lock first, so changing the folder never waits on the disk. @@ -1183,6 +1193,20 @@ fn asks_for_skills(line: &str) -> bool { } } +/// The most characters of a client's name kept. +const MAX_CLIENT_NAME: usize = 60; + +/// What an `initialize` message calls its client: one line, without control characters, cut to +/// [`MAX_CLIENT_NAME`]. +fn client_name(msg: &Value) -> Option { + if msg.get("method").and_then(Value::as_str) != Some("initialize") { + return None; + } + let name = msg.pointer("/params/clientInfo/name").and_then(Value::as_str)?; + let name: String = name.chars().filter(|c| !c.is_control()).take(MAX_CLIENT_NAME).collect(); + Some(name.trim().to_string()).filter(|n| !n.is_empty()) +} + /// Accepts connections until the relay is stopped, then closes the listener. fn accept_loop(listener: TcpListener, shared: Arc) { while !shared.stopped.load(SeqCst) { @@ -1212,6 +1236,7 @@ impl Drop for Slot { fn drop(&mut self) { lock(&self.shared.streams).remove(&self.id); lock(&self.shared.granted).remove(&self.id); + lock(&self.shared.clients).remove(&self.id); if self.preauth { self.shared.preauth.fetch_sub(1, SeqCst); } @@ -1376,6 +1401,9 @@ fn connection(stream: TcpStream, slot: &mut Slot) { if shared.access(&token, asked).is_none() { return; } + if let Some(name) = msg.as_ref().and_then(client_name) { + lock(&shared.clients).insert(slot.id, name); + } let expects = expects_reply(&line); let id = msg.as_ref().map_or(Value::Null, request_id); let state = Arc::new(AtomicU8::new(PENDING)); @@ -2680,6 +2708,26 @@ mod tests { relay.stop(); } + /// An attached client is named by its `initialize`, in one clipped line, until it leaves. + #[test] + fn relay_names_its_clients_while_they_stay() { + let relay = Relay::start(0).unwrap(); + let mut client = TcpStream::connect(("127.0.0.1", relay.port())).unwrap(); + attach(&mut client, &relay, false); + wait_until("the attach", || relay.attached_clients() == 1); + assert!(relay.client_names().is_empty(), "no name before initialize"); + let name = format!("claude-code\n\u{7}{}", "x".repeat(200)); + let hello = json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"clientInfo": {"name": name}}}); + writeln!(client, "{hello}").unwrap(); + // The app answers it, and the connection reads on. + settle(&relay, &mut Session::new(Project::default())); + assert_eq!(relay.client_names(), vec![format!("claude-code{}", "x".repeat(49))]); + drop(client); + wait_until("the disconnect", || relay.attached_clients() == 0); + assert!(relay.client_names().is_empty()); + relay.stop(); + } + /// Stopping closes the listener and every client, removes the token, and drops the /// attached count; a temporary clone that drops first does not stop the relay. #[test] diff --git a/crates/ui-egui/src/assistant.rs b/crates/ui-egui/src/assistant.rs index 17f896b02f..3bcb74db3f 100644 --- a/crates/ui-egui/src/assistant.rs +++ b/crates/ui-egui/src/assistant.rs @@ -438,6 +438,12 @@ pub(crate) fn toggle_settings(app: &mut RustGisApp) { #[cfg(not(target_arch = "wasm32"))] { app.assistant.settings_pending = None; + // Asked for from the connect view: the settings show, whether or not they were open + // under it. + if std::mem::take(&mut app.connect.view) { + app.assistant.settings = true; + return; + } } app.assistant.settings = !app.assistant.settings; } @@ -1435,6 +1441,10 @@ fn to_box(state: &mut AssistantState, text: &str) { /// be sent ([`AssistantState::sending_when_ready`]) isn't sent into the new one: it stays in the /// box. pub fn new_conversation(app: &mut RustGisApp) { + #[cfg(not(target_arch = "wasm32"))] + { + app.connect.view = false; + } if let Some(a) = app.assistant.agent.as_mut() { a.clear(); } diff --git a/crates/ui-egui/src/assistantpane.rs b/crates/ui-egui/src/assistantpane.rs index 644543fa28..62bac97e75 100644 --- a/crates/ui-egui/src/assistantpane.rs +++ b/crates/ui-egui/src/assistantpane.rs @@ -25,6 +25,8 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { assistant::open(app, ui.ctx()); let ctx = ui.ctx().clone(); let busy = app.assistant.busy(); + #[cfg(not(target_arch = "wasm32"))] + let short = ui.available_height() < SHORT_PANE; // The model and settings, at the top. egui::Frame::NONE.inner_margin(egui::Margin::symmetric(10, 6)).show(ui, |ui| { ui.horizontal(|ui| { @@ -66,7 +68,25 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { }); }); }); + // Using an agent the user already has (desktop), outside the settings. While an action + // waits for approval, a short pane or open settings take its row. + #[cfg(not(target_arch = "wasm32"))] + if assistant::pending(app).is_none() || !(short || app.assistant.settings) { + crate::connectui::entry(app, ui, t); + } }); + // Its view takes the pane. The message box stays only while the assistant here works or + // waits: an approval is never out of sight. + #[cfg(not(target_arch = "wasm32"))] + if app.connect.view { + if busy || app.assistant.sending_when_ready() { + composer_panel(app, ui, t, busy, &ctx); + } + egui::ScrollArea::vertical().id_salt("assistant_connect_scroll").auto_shrink([false, false]).show(ui, |ui| { + egui::Frame::NONE.inner_margin(egui::Margin::symmetric(12, 8)).show(ui, |ui| crate::connectui::view(app, ui, t)); + }); + return; + } // The composer first, so tall settings scroll above it instead of running under it. composer_panel(app, ui, t, busy, &ctx); // Closed settings look for the agents again when they next open. @@ -75,20 +95,26 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { app.assistant.agents_found = None; } if app.assistant.settings { + // The conversation keeps room for a few lines below, where it scrolls; in a short pane, + // less, so the settings keep most of it. An action waiting for approval is already + // below, so then they take the rest. + let room = ui.available_height(); + let conversation = if assistant::pending(app).is_some() { 0.0 } else { CONVERSATION_ROOM.min(room * 0.3) }; egui::ScrollArea::vertical() .id_salt("assistant_settings_scroll") .auto_shrink([false, true]) .min_scrolled_height(0.0) - // The conversation keeps room for a few lines below, where it scrolls; in a short pane, - // less, so the settings keep most of it. - .max_height((ui.available_height() - 8.0 - CONVERSATION_ROOM.min(ui.available_height() * 0.3)).max(0.0)) + .max_height((room - 8.0 - conversation).max(0.0)) .show(ui, |ui| { egui::Frame::NONE.inner_margin(egui::Margin::symmetric(12, 4)).show(ui, |ui| settings(app, ui, t)); }); ui.separator(); } // The conversation in between. - egui::ScrollArea::vertical().auto_shrink([false, false]).stick_to_bottom(true).min_scrolled_height(0.0).show(ui, |ui| { + // An empty conversation reads from its top; one with messages follows its newest. + let empty = app.assistant.messages().is_empty(); + let area = egui::ScrollArea::vertical().id_salt(("assistant_transcript", empty)).stick_to_bottom(!empty); + area.auto_shrink([false, false]).min_scrolled_height(0.0).show(ui, |ui| { egui::Frame::NONE.inner_margin(egui::Margin::symmetric(12, 8)).show(ui, |ui| { // Text in a row (a list item, a quote, the user's message) wraps too, instead of widening the pane. ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Wrap); @@ -97,13 +123,27 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { }); } +/// A pane under this height is short. +#[cfg(not(target_arch = "wasm32"))] +const SHORT_PANE: f32 = 400.0; + +/// What the rows of an approval card and the message box under it take besides the card's +/// details; the least and the most those details get; and what they keep, where the pane has it, +/// when settings are open above (an SQL query shows without scrolling). +const CARD_AND_BOX: f32 = 220.0; +const CARD_DETAILS_LEAST: f32 = 48.0; +const CARD_DETAILS_MOST: f32 = 280.0; +const CARD_DETAILS_KEPT: f32 = 140.0; + /// The height the conversation keeps under open settings, at most: never over 30% of the pane. const CONVERSATION_ROOM: f32 = 96.0; fn composer_panel(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, busy: bool, ctx: &egui::Context) { + // What the pane has under its heading, before the panel takes its part. + let room = ui.available_height(); egui::Panel::bottom("assistant_composer") .frame(egui::Frame::NONE.fill(t.pane).inner_margin(egui::Margin::symmetric(10, 8))) - .show(ui, |ui| composer(app, ui, t, busy, ctx)); + .show(ui, |ui| composer(app, ui, t, busy, ctx, room)); } /// Edits provider settings and invalidates pending key reads as soon as a key changes. @@ -145,9 +185,6 @@ fn settings(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { local_agents_setting(app, ui, t); #[cfg(not(target_arch = "wasm32"))] skills_setting(app, ui, t); - // Agents on this computer working on this map through the MCP relay (desktop). - #[cfg(not(target_arch = "wasm32"))] - crate::connectui::section(app, ui, t); assistant::apply_settings(app, cfg, before, ui.ctx()); } @@ -731,25 +768,77 @@ fn account_row(_app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, _cfg: &mut Config const INPUT_HEIGHT: f32 = 44.0; const INPUT_GROWS: f32 = 160.0; -fn composer(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, busy: bool, ctx: &egui::Context) { +/// Whether something is open over the conversation: the settings, or the connect view. +fn covered(app: &RustGisApp) -> bool { + #[cfg(not(target_arch = "wasm32"))] + if app.connect.view { + return true; + } + app.assistant.settings +} + +/// In a pane too short for a whole approval card and what is open over the conversation: that an +/// action waits, a way back to it, and Decline. It is never allowed unseen. +fn waiting_note(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, asked: &rustgis_assistant::Asking, ctx: &egui::Context) { + egui::Frame::NONE.fill(t.amber.gamma_multiply(0.15)).corner_radius(6).inner_margin(8).stroke(egui::Stroke::new(1.0, t.amber)).show( + ui, + |ui| { + ui.label(RichText::new(tl!("An action is waiting for your approval.")).font(semibold(12.5))); + ui.push_id(("assistant_waiting_buttons", asked), |ui| { + ui.horizontal(|ui| { + if crate::widgets::primary_button(ui, tl!("Review it"), true, vec2(70.0, 26.0)).clicked() { + if app.assistant.settings { + assistant::toggle_settings(app); + } + #[cfg(not(target_arch = "wasm32"))] + { + app.connect.view = false; + } + } + if ui.button(tl!("Decline")).clicked() { + app.assistant.always = false; + assistant::decide(app, asked, false, false, ctx); + } + }); + }); + }, + ); +} + +fn composer(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, busy: bool, ctx: &egui::Context, room: f32) { // Agent threads on this computer, working or waiting for a follow-up. #[cfg(not(target_arch = "wasm32"))] crate::agentthreads::list(app, ui, t); - // An action waiting for approval comes first. - if let Some(approval) = assistant::pending(app) { + // The card's details scroll in what the pane has, so its buttons and the message box stay + // in it. + let free = room - CARD_AND_BOX; + let covered = covered(app); + let waiting = assistant::pending(app); + if let Some(approval) = waiting.as_ref().filter(|_| covered && free < CARD_DETAILS_KEPT - CARD_DETAILS_LEAST) { + waiting_note(app, ui, t, &approval.asked, ctx); + ui.add_space(6.0); + } else if let Some(approval) = waiting { + // An action waiting for approval comes first. let Approval { what, why, can_always, asked, .. } = &approval; // The tick is this approval's: another's, answered or not, isn't carried over to it. if app.assistant.always_for.as_ref() != Some(asked) { app.assistant.always = false; app.assistant.always_for = Some(asked.clone()); } + // With something open above, they keep no more than they need to be read. + let details = if covered { free.min(CARD_DETAILS_KEPT) } else { free }; + let details = details.clamp(CARD_DETAILS_LEAST, CARD_DETAILS_MOST); egui::Frame::NONE.fill(t.amber.gamma_multiply(0.15)).corner_radius(6).inner_margin(8).stroke(egui::Stroke::new(1.0, t.amber)).show( ui, |ui| { ui.label(RichText::new(tl!("Allow this action?")).font(semibold(12.5))); - egui::ScrollArea::vertical().max_height(280.0).id_salt(("assistant_approval", what, why)).show(ui, |ui| { - approval_details(ui, app, &approval); - }); + egui::ScrollArea::vertical() + .max_height(details) + .min_scrolled_height(details) + .id_salt(("assistant_approval", what, why)) + .show(ui, |ui| { + approval_details(ui, app, &approval); + }); // Plugin commands, scripts and replacing the project are asked about every time. if *can_always { ui.checkbox(&mut app.assistant.always, tl!("Don't ask again for exactly this action")); @@ -937,6 +1026,9 @@ fn transcript(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, ctx: &egui::Context return; } if app.assistant.messages().is_empty() { + // First, so a short pane shows it. + #[cfg(not(target_arch = "wasm32"))] + crate::connectui::offer(app, ui, t); ui.label(RichText::new(tl!("Ask a question about your data, or describe what to do with the map. The assistant runs RustGIS commands for you. Changes to the project can be undone; files it writes can't.")).color(t.text_dim)); ui.add_space(8.0); let mut chosen = None; @@ -1685,7 +1777,8 @@ pub(crate) mod tests { return; } let ctx = ui.ctx().clone(); - composer(app, ui, &Tokens::light(), true, &ctx); + let room = ui.available_height(); + composer(app, ui, &Tokens::light(), true, &ctx, room); }, app, ); @@ -1980,7 +2073,8 @@ pub(crate) mod tests { |ui, app: &mut RustGisApp| { let ctx = ui.ctx().clone(); let busy = app.assistant.agent.as_ref().is_some_and(Agent::busy); - composer(app, ui, &Tokens::light(), busy, &ctx); + let room = ui.available_height(); + composer(app, ui, &Tokens::light(), busy, &ctx, room); }, app, ); @@ -2228,7 +2322,8 @@ pub(crate) mod tests { return; } let ctx = ui.ctx().clone(); - composer(app, ui, &Tokens::light(), true, &ctx); + let room = ui.available_height(); + composer(app, ui, &Tokens::light(), true, &ctx, room); }, app, ); @@ -2746,6 +2841,85 @@ pub(crate) mod tests { assert!(app.assistant.inflight.is_none()); } + /// The window at `size` with the assistant open, its settings too, and an SQL query waiting + /// for approval when `waiting`. + fn settings_open(size: egui::Vec2, waiting: bool) -> egui_kittest::Harness<'static, RustGisApp> { + let mut app = RustGisApp::with_sample(); + #[cfg(not(target_arch = "wasm32"))] + { + app.connect.detected = Some(Vec::new()); + } + let mut config = Config::from_env("custom"); + config.base_url = "https://provider.invalid/v1".into(); + config.model = "synthetic".into(); + let mut agent = Agent::new(config, &app.session); + if waiting { + assert!(matches!(agent.ask("Review only", &app.session), Step::Send(_))); + let args = serde_json::json!({"command": "layer.addSql", "params": {"sql": "SELECT name FROM Cities"}}); + let body = serde_json::json!({"choices":[{"message":{"role":"assistant","content":null,"tool_calls":[{ + "id":"c","type":"function","function":{"name":"run_command","arguments":args.to_string()} + }]},"finish_reason":"tool_calls"}]}) + .to_string() + .into_bytes(); + let step = agent.receive(agent.generation(), Ok(HttpResponse { status: 200, body, headers: vec![] }), &mut app.session); + assert_eq!(step, Step::Confirm); + } else { + agent.transcript = vec![Entry::Assistant("The newest reply.".into())]; + } + app.assistant.agent = Some(agent); + app.assistant.loaded = true; + app.run("ui.pane.assistant", serde_json::Value::Null).unwrap(); + app.assistant.settings = true; + let mut h = egui_kittest::Harness::builder().with_size(size).build_ui_state( + |ui, app: &mut RustGisApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + h.run_steps(8); + h + } + + /// Whether the control named `label` lies whole in the window, over the status bar. + fn in_window(h: &egui_kittest::Harness<'_, RustGisApp>, label: &str) -> bool { + use egui_kittest::kittest::Queryable; + let rect = h.get_by_label(label).rect(); + rect.min.y >= 0.0 && rect.max.y <= h.ctx.content_rect().max.y - 26.0 + } + + /// Open settings leave the conversation, an action waiting for approval and the message box + /// in view, down to the smallest window. + #[test] + fn open_settings_leave_the_conversation_and_the_approval_in_view() { + use egui_kittest::kittest::Queryable; + let input_in_window = |h: &egui_kittest::Harness<'_, RustGisApp>| { + h.get_by_role(egui::accesskit::Role::MultilineTextInput).rect().max.y <= h.ctx.content_rect().max.y - 26.0 + }; + // With nothing waiting, the newest reply shows under the settings. + let h = settings_open(vec2(1280.0, 720.0), false); + h.get_by_label("Provider"); + assert!(in_window(&h, "The newest reply.") && input_in_window(&h)); + let reply = h.get_by_label("The newest reply.").rect(); + assert!(reply.min.y > h.get_by_label("Provider").rect().max.y); + + // A laptop's window has room for the whole card under the settings. + let h = settings_open(vec2(1280.0, 720.0), true); + h.get_by_label("Provider"); + assert!(in_window(&h, "Allow") && in_window(&h, "Decline") && input_in_window(&h)); + + // The smallest window says an action waits, and shows it on request. + let mut h = settings_open(vec2(900.0, 560.0), true); + h.get_by_label("Provider"); + assert!(h.query_by_label("Allow").is_none(), "never allowed unseen"); + assert!(in_window(&h, "Review it") && in_window(&h, "Decline") && input_in_window(&h)); + h.get_by_label("Review it").click(); + h.run_steps(8); + assert!(!h.state().assistant.settings); + assert!(in_window(&h, "Allow") && in_window(&h, "Decline") && input_in_window(&h)); + } + /// The right pane's width with `entries` in the conversation and `model` as the model's name. fn pane_width(entries: Vec, model: &str) -> f32 { let h = chat(entries, model); diff --git a/crates/ui-egui/src/connectui.rs b/crates/ui-egui/src/connectui.rs index 7c0fadc723..b58ef1eaf5 100644 --- a/crates/ui-egui/src/connectui.rs +++ b/crates/ui-egui/src/connectui.rs @@ -1,18 +1,39 @@ -//! "Let your Agents Control RustGIS" (desktop), in the AI Assistant settings. Ticking it turns -//! on the MCP relay ([`rustgis_assistant::relay`]): AI agents on this computer that connect -//! (Claude Code, Codex, Cursor…) work on the map open here, with file and network access, no -//! `--yes` needed. While it's on, the section shows what an agent needs to connect, and nothing -//! else. The choice is remembered: the relay starts with the app. +//! "Connect my agent" (desktop), a view of the AI Assistant pane for using an agent the user +//! already has. Ticking "Let your Agents Control RustGIS" turns on the MCP relay +//! ([`rustgis_assistant::relay`]): AI agents on this computer that connect (Claude Code, Codex, +//! Cursor…) work on the map open here, with file and network access, no `--yes` needed. While the +//! relay runs, the view shows who is connected, tests the connection and gives what an agent needs +//! to connect. The choice is remembered: the relay starts with the app. An empty conversation +//! offers the view once when an agent is installed here; nothing is turned on for the user. + +use std::time::Duration; use egui::RichText; -use serde_json::json; +use serde_json::{Value, json}; -use crate::RustGisApp; -use crate::theme::Tokens; +use crate::assistant::{pref, save_pref}; +use crate::theme::{Tokens, semibold}; +use crate::{RustGisApp, Slot}; /// The preference that remembers the choice. pub const PREF: &str = "agents_control"; +/// The preference that remembers that the offer to connect an agent was answered. +const OFFER_PREF: &str = "agents_offer"; + +/// The connection test's message: MCP's ping, which every connection may send and which changes +/// nothing. +const PING: &str = r#"{"jsonrpc":"2.0","id":1,"method":"ping"}"#; + +/// How long a connection test waits for `rustgis-cli` to answer and end. +const TEST_WAIT: Duration = Duration::from_secs(15); + +/// A connection test: the port of the relay it asks, and how it went once it has. +struct Test { + port: u16, + outcome: Slot>, +} + #[derive(Default)] pub struct ConnectState { /// The choice, once read from the preferences. @@ -26,6 +47,14 @@ pub struct ConnectState { bridge_dir: Option, /// Full access: ticked for this session only, never remembered, so each launch asks afresh. full: bool, + /// The assistant pane shows the view. + pub(crate) view: bool, + /// The connection test under way or last made. + test: Option, + /// The agents installed here, by name, looked for once, for the offer. + pub(crate) detected: Option>, + /// The offer was answered (kept in the preferences too, where there are any). + offer_answered: bool, } /// Whether the user lets agents control RustGIS. @@ -198,24 +227,124 @@ fn copyable(ui: &mut egui::Ui, text: &str) { }); } -/// The section in the assistant settings: the switch in a header that folds away the access -/// switch and the connection details (folded until agents are turned on). -pub fn section(app: &mut RustGisApp, ui: &mut egui::Ui, t: &Tokens) { +/// Shows the view in the assistant pane (opening the pane is the caller's). +pub(crate) fn open_view(app: &mut RustGisApp) { + app.connect.view = true; +} + +/// The pane's way into the view, under the model's name, with whether agents can connect or are. +pub(crate) fn entry(app: &mut RustGisApp, ui: &mut egui::Ui, t: &Tokens) { + ui.horizontal(|ui| { + let hint = tl!("Use Claude Code, Codex or another agent you already have on this map"); + let button = egui::Button::new(RichText::new(tl!("Connect my agent")).small()).selected(app.connect.view); + if ui.add(button).on_hover_text(hint).clicked() { + app.connect.view = !app.connect.view; + } + let said = match &app.relay { + Some(relay) => match relay.attached_clients() { + 0 => Some(tl!("MCP relay on").to_string()), + n => Some(crate::i18n::fmt("{n} connected", &[("n", &n.to_string())])), + }, + None => app.file_bridge.is_some().then(|| tl!("File bridge only").to_string()), + }; + if let Some(said) = said { + ui.add(egui::Label::new(RichText::new(said).small().color(t.text_dim)).truncate()); + } + }); +} + +/// The agents installed on this computer, by name: those the assistant could start, and those +/// whose ACP adapter would need Node.js (connecting over MCP needs neither). +fn installed_agents() -> Vec<&'static str> { + let (ready, need_node) = rustgis_assistant::acp::installed(); + rustgis_assistant::acp::AGENTS + .iter() + .filter(|a| ready.iter().any(|(r, _)| r.id == a.id) || need_node.iter().any(|n| n.id == a.id)) + .map(|a| a.label) + .collect() +} + +/// Records that the offer was answered, so it isn't made again. +fn answer_offer(app: &mut RustGisApp) { + app.connect.offer_answered = true; + save_pref(app, OFFER_PREF, "answered"); +} + +/// In an empty conversation: when an agent is installed here, offers to connect it alongside the +/// built-in assistant, until that is answered. Never once agents can already connect. +pub(crate) fn offer(app: &mut RustGisApp, ui: &mut egui::Ui, t: &Tokens) { + if app.connect.offer_answered || enabled(app) || app.relay.is_some() || pref(app, OFFER_PREF).is_some() { + return; + } + let names = app.connect.detected.get_or_insert_with(installed_agents).join(", "); + if names.is_empty() { + return; + } + egui::Frame::group(ui.style()).show(ui, |ui| { + let said = crate::i18n::fmt( + "Found on this computer: {names}. You can connect one to work on this map with its own sign-in, alongside the assistant here.", + &[("names", &names)], + ); + ui.label(RichText::new(said).small().color(t.text)); + ui.horizontal_wrapped(|ui| { + if ui.button(tl!("Show how to connect")).clicked() { + answer_offer(app); + open_view(app); + } + if ui.button(tl!("Not now")).clicked() { + answer_offer(app); + } + }); + }); + ui.add_space(8.0); +} + +/// The view: what connecting an agent means, the switch that lets agents in, and while they can +/// connect, who is connected, the connection test and what to give an agent. +pub(crate) fn view(app: &mut RustGisApp, ui: &mut egui::Ui, t: &Tokens) { + if ui.button(tl!("Back to the conversation")).clicked() { + app.connect.view = false; + } + ui.add_space(4.0); + ui.label(RichText::new(tl!("Connect my agent")).font(semibold(14.0))); + ui.label( + RichText::new(tl!( + "Keep using Claude Code, Codex, Cursor or another agent in its own terminal or app, with its own sign-in. It works on the map open here with RustGIS's tools." + )) + .small(), + ); + ui.label( + RichText::new(tl!( + "The agent's own shell, files and web access follow that agent's permissions. RustGIS controls only what it does through RustGIS." + )) + .small() + .color(t.text_dim), + ); + ui.add_space(4.0); + switch(app, ui, t); + if let Some(e) = &app.connect.error { + ui.label(RichText::new(e).small().color(t.red)); + } + // Also while the relay runs by the MCP Relay command alone. + if app.relay.is_none() && app.file_bridge.is_none() { + return; + } + status(app, ui, t); + instructions(app, ui); +} + +/// "Let your Agents Control RustGIS", and under it full access while ticked. +fn switch(app: &mut RustGisApp, ui: &mut egui::Ui, t: &Tokens) { let mut on = enabled(app); let hint = tl!( "Agents on this computer that connect (Claude Code, Codex, Cursor and others) work on the map open here, with RustGIS's tools: they can open and save files and use the web. So can a script any program of yours writes to the file bridge shown below. Scripts and plugin management stay off. The choice is remembered across launches." ); - let id = ui.make_persistent_id("connect_agents_section"); - let mut changed = false; - let mut header = egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, false) - .show_header(ui, |ui| changed = ui.checkbox(&mut on, tl!("Let your Agents Control RustGIS")).on_hover_text(hint).changed()); - if changed { + if ui.checkbox(&mut on, tl!("Let your Agents Control RustGIS")).on_hover_text(hint).changed() { app.connect.on = Some(on); app.connect.error = None; - if let Some(save) = &app.services.save_pref { - save(PREF, if on { "on" } else { "off" }); - } + save_pref(app, PREF, if on { "on" } else { "off" }); if on { + answer_offer(app); // The relay not started (the port is taken, say): with the file bridge agents stay // on; without, the box and the remembered choice go back off. let bridge = start_bridge(app); @@ -234,23 +363,18 @@ pub fn section(app: &mut RustGisApp, ui: &mut egui::Ui, t: &Tokens) { relay.set_allow_access(on); relay.set_full_access(full_access(app)); } - // Turned on: show what to give the agents. - header.set_open(on); } - header.body(|ui| { - if on { - details(app, ui); - } else { - ui.label(RichText::new(hint).small().color(t.text_dim)); + if !on { + ui.label(RichText::new(hint).small().color(t.text_dim)); + if app.relay.is_some() { + ui.label( + RichText::new(tl!("The MCP Relay command is running: agents have only the access their --yes asks for.")) + .small() + .color(t.amber), + ); } - }); - if let Some(e) = &app.connect.error { - ui.label(RichText::new(e).small().color(t.red)); + return; } -} - -/// The open section's body: full access and how agents connect. -fn details(app: &mut RustGisApp, ui: &mut egui::Ui) { let mut full = full_access(app); let hint = tl!( "Agents may also run scripts, tasks and models, and install, remove and run plugins: anything you could do yourself. Turn it on only for an agent you trust with your computer. It lasts until RustGIS closes or agents are turned off." @@ -268,37 +392,179 @@ fn details(app: &mut RustGisApp, ui: &mut egui::Ui) { ui.label( RichText::new(tl!("Connected agents can now run scripts, tasks, models and plugins, and install plugins, without asking you.")) .small() - .color(Tokens::get(ui.ctx()).red), + .color(t.red), ); } ui.label(RichText::new(tl!("This is for agents you connect. It doesn't change what the assistant in this pane asks about.")).small()); - // Agents that can't use MCP: a script written to a file. - if let Some(bridge) = &app.file_bridge { - let (command, result) = (bridge.command_path().display().to_string(), bridge.result_path().display().to_string()); - ui.label(RichText::new(tl!("Agents without MCP can write a script (one command per line) to:")).small()); - copyable(ui, &command); - ui.label(RichText::new(tl!("RustGIS runs it and writes the outcome to:")).small()); - copyable(ui, &result); +} + +/// Who is connected, what an agent did last, and the connection test. +fn status(app: &mut RustGisApp, ui: &mut egui::Ui, t: &Tokens) { + let Some(relay) = app.relay.clone() else { return }; + ui.separator(); + ui.label(RichText::new(tl!("Connection")).font(semibold(12.5))); + // A test of a relay since stopped or moved says nothing about this one. + if app.connect.test.as_ref().is_some_and(|test| test.port != relay.port()) { + app.connect.test = None; } - let Some(port) = app.relay.as_ref().map(|r| r.port()) else { return }; - // What an agent needs: RustGIS's MCP server, attached to this app. - let cli = cli(); + let outcome = app.connect.test.as_ref().map(|test| test.outcome.lock().ok().and_then(|o| o.clone())); + let testing = matches!(outcome, Some(None)); + let names = relay.client_names(); + // The test's own connection isn't an agent's. + let n = relay.attached_clients().saturating_sub(usize::from(testing)).max(names.len()); + let count = n.to_string(); + let said = if n == 0 { + tl!("No agent is connected.").to_string() + } else if names.is_empty() { + crate::i18n::fmt("Connected agents: {n}", &[("n", &count)]) + } else { + crate::i18n::fmt("Connected agents: {n} ({names})", &[("n", &count), ("names", &names.join(", "))]) + }; + ui.label(RichText::new(said).small().color(if n > 0 { t.green } else { t.text })); + if let Some(last) = relay.last_action() { + let said = if last.ok { "Last agent call: {call} ({secs} s ago)" } else { "Last agent call failed: {call} ({secs} s ago)" }; + let text = crate::i18n::fmt(said, &[("call", &last.detail), ("secs", &last.at.elapsed().as_secs().to_string())]); + ui.label(RichText::new(text).small().color(if last.ok { t.text_dim } else { t.red })); + // The age counts while it is shown. + ui.ctx().request_repaint_after(Duration::from_secs(1)); + } else if n == 0 { + ui.label( + RichText::new(tl!( + "An agent connects when it starts, once RustGIS is added to it. One that uses HTTP doesn't stay connected: only its calls show here." + )) + .small() + .color(t.text_dim), + ); + } + ui.horizontal_wrapped(|ui| { + let hint = tl!("Starts rustgis-cli as your agent would and asks this app for an answer. It doesn't check the agent's own setup."); + if ui.add_enabled(!testing, egui::Button::new(tl!("Test connection"))).on_hover_text(hint).clicked() { + start_test(app, relay.port(), ui.ctx()); + } + if testing { + ui.spinner(); + } + }); + match outcome.flatten() { + Some(Ok(())) => { + ui.label(RichText::new(tl!("Test passed: rustgis-cli reached this app.")).small().color(t.green)); + } + Some(Err(e)) => { + let text = crate::i18n::fmt("Test failed: {error}", &[("error", &e)]); + ui.label(RichText::new(text).small().color(t.red)); + } + None => {} + } +} + +/// Tests the relay on `port` off the frame, as an agent would reach it: through `rustgis-cli`. +fn start_test(app: &mut RustGisApp, port: u16, ctx: &egui::Context) { + let outcome: Slot> = Default::default(); + let (slot, ctx) = (outcome.clone(), ctx.clone()); + let (program, args) = (cli(), attach_args(port)); + let spawned = std::thread::Builder::new().name("rustgis-connect-test".into()).spawn(move || { + let went = ping(&program, &args, TEST_WAIT); + if let Ok(mut slot) = slot.lock() { + *slot = Some(went); + } + ctx.request_repaint(); + }); + if let Err(e) = spawned + && let Ok(mut slot) = outcome.lock() + { + *slot = Some(Err(e.to_string())); + } + app.connect.test = Some(Test { port, outcome }); +} + +/// Runs `program` with `args` (an MCP server on its standard input and output), sends it +/// [`PING`] and says whether the answer came back before it ended, within `wait`. +fn ping(program: &str, args: &[String], wait: Duration) -> Result<(), String> { + use std::io::Write; + use std::process::Stdio; + let mut command = std::process::Command::new(program); + command.args(args).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()); + // No console window flashing up on Windows. + #[cfg(windows)] + std::os::windows::process::CommandExt::creation_flags(&mut command, 0x0800_0000); + let mut child = command.spawn().map_err(|e| format!("{program}: {e}"))?; + // Closing its input after the message ends it once it has answered. A program that ended + // already says why on its error output, so a write that fails is not the report. + if let Some(mut input) = child.stdin.take() { + let _ = writeln!(input, "{PING}"); + } + let end = web_time::Instant::now() + wait; + while child.try_wait().map_err(|e| format!("{program}: {e}"))?.is_none() { + if web_time::Instant::now() >= end { + let _ = child.kill(); + let _ = child.wait(); + return Err(crate::i18n::fmt("no answer after {secs} seconds", &[("secs", &wait.as_secs().to_string())])); + } + std::thread::sleep(Duration::from_millis(20)); + } + let output = child.wait_with_output().map_err(|e| format!("{program}: {e}"))?; + let reply: Value = + String::from_utf8_lossy(&output.stdout).lines().next().and_then(|l| serde_json::from_str(l).ok()).unwrap_or(Value::Null); + if reply.get("id") == Some(&json!(1)) && reply.get("result").is_some() { + return Ok(()); + } + // The app's error reply, else the last thing the program said. + let errors = String::from_utf8_lossy(&output.stderr); + let why = reply + .pointer("/error/message") + .and_then(Value::as_str) + .or_else(|| errors.lines().rev().find(|l| !l.trim().is_empty())) + .map_or_else(|| output.status.to_string(), |why| rustgis_assistant::tools::clip(why.trim(), 300)); + Err(why) +} + +/// The arguments of `rustgis-cli` that attach an agent to the relay on `port`. +fn attach_args(port: u16) -> Vec { let mut args = vec!["mcp".to_string(), "--attach".to_string()]; if port != rustgis_assistant::relay::DEFAULT_PORT { args.push(port.to_string()); } + args +} + +/// The lines that add RustGIS to Claude Code and to Codex, with `cli` and its `args`. +fn register_commands(cli: &str, args: &[String]) -> [String; 2] { + let quoted = shell_arg(cli); + ["claude", "codex"].map(|agent| format!("{agent} mcp add rustgis-app -- {quoted} {}", args.join(" "))) +} + +/// What an agent needs to connect: the file bridge's files, the MCP server's configuration and +/// the lines that register it. +fn instructions(app: &RustGisApp, ui: &mut egui::Ui) { + ui.separator(); + // Agents that can't use MCP: a script written to a file. + let bridge = |ui: &mut egui::Ui| { + if let Some(bridge) = &app.file_bridge { + let (command, result) = (bridge.command_path().display().to_string(), bridge.result_path().display().to_string()); + ui.label(RichText::new(tl!("Agents without MCP can write a script (one command per line) to:")).small()); + copyable(ui, &command); + ui.label(RichText::new(tl!("RustGIS runs it and writes the outcome to:")).small()); + copyable(ui, &result); + } + }; + let Some(port) = app.relay.as_ref().map(|r| r.port()) else { + bridge(ui); + return; + }; + // What an agent needs: RustGIS's MCP server, attached to this app. + let cli = cli(); + let args = attach_args(port); let config = serde_json::to_string_pretty(&json!({"mcpServers": {"rustgis-app": {"command": cli, "args": args}}})).unwrap_or_default(); - ui.label(RichText::new(tl!("Add this MCP server to your agent:")).small()); - copyable(ui, &config); let hint = if cfg!(windows) { tl!("Or run in PowerShell, for Claude Code or Codex:") } else { tl!("Or run in a POSIX shell, for Claude Code or Codex:") }; + ui.label(RichText::new(tl!("Add this MCP server to your agent:")).small()); + copyable(ui, &config); ui.label(RichText::new(hint).small()); - let quoted = shell_arg(&cli); - for agent in ["claude", "codex"] { - copyable(ui, &format!("{agent} mcp add rustgis-app -- {quoted} {}", args.join(" "))); + for command in register_commands(&cli, &args) { + copyable(ui, &command); } // Clients that speak MCP over HTTP: registered with the stable token, kept off the screen. if let Some(http) = app.relay.as_ref().and_then(|r| r.http_port()) { @@ -306,12 +572,14 @@ fn details(app: &mut RustGisApp, ui: &mut egui::Ui) { ui.label(RichText::new(text).small()); // PowerShell runs a quoted program only through its call operator. let call = if cfg!(windows) { "& " } else { "" }; + let quoted = shell_arg(&cli); let mut register = format!("{call}{quoted} mcp-register --client claude"); if http != rustgis_assistant::relay::HTTP_PORT { register.push_str(&format!(" --port {http}")); } copyable(ui, ®ister); } + bridge(ui); } #[cfg(test)] @@ -437,6 +705,137 @@ mod tests { assert_eq!(*saved.lock().unwrap(), "off"); } + /// The whole window, tall enough to lay out the view to its end. + fn window(mut app: RustGisApp) -> egui_kittest::Harness<'static, RustGisApp> { + app.assistant.agent = Some(rustgis_assistant::Agent::new(rustgis_assistant::Config::from_env("custom"), &app.session)); + app.assistant.loaded = true; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1400.0, 2000.0)).build_ui_state( + |ui, app: &mut RustGisApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + h.run_steps(3); + h + } + + /// The pane's "Connect my agent" shows without opening the settings, opens the view, and the + /// lines the view copies are the ones that register RustGIS with its relay. + #[test] + fn the_pane_leads_to_the_commands_to_copy() { + use egui_kittest::kittest::Queryable; + let mut app = RustGisApp::with_sample(); + app.connect.detected = Some(Vec::new()); + app.run("ui.pane.assistant", serde_json::Value::Null).unwrap(); + let mut h = window(app); + assert!(!h.state().assistant.settings); + h.get_by_label("Connect my agent").click(); + h.run_steps(3); + assert!(h.query_by_label("Let your Agents Control RustGIS").is_some()); + assert!(h.query_by_label("Test connection").is_none(), "nothing to test while nothing listens"); + assert!(h.state().relay.is_none(), "opening the view turns nothing on"); + h.state_mut().run("ui.mcpRelay", json!({"port": 0})).unwrap(); + h.run_steps(3); + h.get_by_label("No agent is connected."); + let port = h.state().relay.as_ref().unwrap().port(); + let expected = register_commands(&cli(), &attach_args(port)); + assert!(expected[0].starts_with("claude mcp add rustgis-app -- "), "{expected:?}"); + assert!(expected[0].ends_with(&format!(" mcp --attach {port}")), "{expected:?}"); + // The Copy buttons, top down: the configuration, Claude Code's line, Codex's. + for (button, line) in [(1, &expected[0]), (2, &expected[1])] { + h.get_all_by_label("Copy").nth(button).unwrap().click(); + h.step(); + let copied = h.output().platform_output.commands.iter().any(|c| matches!(c, egui::OutputCommand::CopyText(t) if t == line)); + assert!(copied, "button {button} didn't copy {line}"); + } + h.get_by_label("Back to the conversation").click(); + h.run_steps(3); + assert!(!h.state().connect.view); + assert!(h.query_by_label("Let your Agents Control RustGIS").is_none()); + } + + /// The command that opens the view refuses a message to send with it. + #[test] + fn the_view_opens_by_command_without_a_message() { + let mut app = RustGisApp::with_sample(); + assert!(app.run("ui.pane.assistant", json!({"connect": true, "ask": "hello"})).is_err()); + assert!(!app.connect.view && app.assistant.asked.is_empty()); + app.run("ui.pane.assistant", json!({"connect": true})).unwrap(); + app.run("ui.pane.assistant", json!({"connect": true})).unwrap(); + assert!(app.connect.view && app.ui.right == Some(crate::RightPane::Assistant), "opened, not toggled"); + app.run("ui.pane.assistant", json!({"ask": "Zoom to Tokyo"})).unwrap(); + assert!(!app.connect.view, "a message is sent where the conversation shows"); + } + + /// The offer to connect an installed agent is made until it is answered, and stays answered; + /// it is never made with none installed or agents already on, and never turns anything on. + #[test] + fn an_installed_agent_is_offered_until_answered() { + use egui_kittest::kittest::Queryable; + use std::collections::HashMap; + use std::sync::{Arc, Mutex}; + let prefs: Arc>> = Arc::default(); + let app_with = |found: Vec<&'static str>| { + let mut app = RustGisApp::with_sample(); + let read = prefs.clone(); + app.services.load_pref = Some(Box::new(move |k: &str| read.lock().unwrap().get(k).cloned())); + let write = prefs.clone(); + app.services.save_pref = Some(Box::new(move |k: &str, v: &str| { + write.lock().unwrap().insert(k.into(), v.into()); + })); + app.connect.detected = Some(found); + app.run("ui.pane.assistant", serde_json::Value::Null).unwrap(); + window(app) + }; + const OFFER: &str = "Found on this computer: Claude Code, Codex."; + assert!(app_with(Vec::new()).query_by_label("Not now").is_none(), "no agent, no offer"); + let h = app_with(vec!["Claude Code", "Codex"]); + h.get_by_label_contains(OFFER); + // Unanswered, it is made again. + let mut h = app_with(vec!["Claude Code", "Codex"]); + h.get_by_label("Not now").click(); + h.run_steps(3); + assert!(h.query_by_label_contains(OFFER).is_none()); + assert!(h.state().relay.is_none() && !enabled(h.state())); + assert!(!prefs.lock().unwrap().contains_key(PREF)); + assert!(app_with(vec!["Claude Code", "Codex"]).query_by_label_contains(OFFER).is_none(), "remembered"); + // Accepting shows the view, with agents still off, and answers it too. + prefs.lock().unwrap().clear(); + let mut h = app_with(vec!["Claude Code", "Codex"]); + h.get_by_label("Show how to connect").click(); + h.run_steps(3); + assert!(h.state().connect.view && !enabled(h.state()) && h.state().relay.is_none()); + assert!(app_with(vec!["Claude Code", "Codex"]).query_by_label_contains(OFFER).is_none()); + // Agents already on. + prefs.lock().unwrap().clear(); + let mut h = app_with(Vec::new()); + h.state_mut().connect.on = Some(true); + h.state_mut().connect.detected = Some(vec!["Claude Code", "Codex"]); + h.run_steps(3); + assert!(h.query_by_label_contains(OFFER).is_none()); + } + + /// The connection test passes only on the app's answer to its ping, and says why otherwise. + #[cfg(unix)] + #[test] + fn the_connection_test_reports_the_answer_or_why_there_is_none() { + let run = |script: &str, wait: Duration| ping("/bin/sh", &["-c".to_string(), script.to_string()], wait); + let long = Duration::from_secs(30); + // The stand-in answers only when it reads the ping itself. + let answers = format!(r#"read line; [ "$line" = '{PING}' ] && echo '{{"jsonrpc":"2.0","id":1,"result":{{}}}}'"#); + assert_eq!(run(&answers, long), Ok(())); + let refused = r#"echo '{"jsonrpc":"2.0","id":1,"error":{"code":-32001,"message":"the app is busy"}}'"#; + assert_eq!(run(refused, long), Err("the app is busy".to_string())); + let nothing = run("echo ready >&2; echo 'nothing is listening' >&2; exit 1", long); + assert_eq!(nothing, Err("nothing is listening".to_string())); + let hung = run("exec sleep 30", Duration::from_millis(200)).unwrap_err(); + assert!(hung.starts_with("no answer after"), "{hung}"); + let missing = ping("/nonexistent/rustgis-cli", &[], long).unwrap_err(); + assert!(missing.starts_with("/nonexistent/rustgis-cli: "), "{missing}"); + } + #[test] fn copyable_program_paths_are_literal_shell_arguments() { #[cfg(not(windows))] diff --git a/crates/ui-egui/src/layout_reach.rs b/crates/ui-egui/src/layout_reach.rs index 0b260490e0..ff6c3df829 100644 --- a/crates/ui-egui/src/layout_reach.rs +++ b/crates/ui-egui/src/layout_reach.rs @@ -446,6 +446,18 @@ fn surfaces() -> Vec { vec![("ui.pane.script", Value::Null)], Box::new(|a| a.ui.right == Some(RightPane::Script)), )); + // The assistant pane's "Connect my agent". + all.push(( + "assistant connect".into(), + vec![("ui.pane.assistant", json!({"connect": true}))], + Box::new(|a| a.ui.right == Some(RightPane::Assistant) && a.connect.view), + )); + // The welcome's offer to connect an agent found on this computer. + all.push(( + "assistant offer".into(), + vec![("ui.pane.assistant", Value::Null)], + Box::new(|a| a.ui.right == Some(RightPane::Assistant) && a.connect.detected.as_ref().is_some_and(|d| !d.is_empty())), + )); all.push(("left catalog".into(), vec![("ui.pane.catalog", Value::Null)], Box::new(|a| a.ui.left == Some(LeftPane::Catalog)))); all.push(("left sources".into(), vec![("ui.pane.sources", Value::Null)], Box::new(|a| a.ui.left == Some(LeftPane::Sources)))); all.push(("view table".into(), vec![table.clone()], Box::new(|a| a.session.table_layer.is_some()))); @@ -577,6 +589,14 @@ fn app(surface: &str) -> RustGisApp { if surface == "pane Script, long script" { app.workflow.script = (0..80).map(|i| format!("map.zoomIn {{\"step\": {i}}}\n")).collect(); } + let found = if surface == "assistant offer" { vec!["Claude Code", "Codex"] } else { Vec::new() }; + app.connect.detected = Some(found); + // A provider that is set up, so no settings open over the welcome and its offer. + if surface == "assistant offer" { + let config = rustgis_assistant::Config { model: "m".into(), ..rustgis_assistant::Config::from_env("custom") }; + app.assistant.agent = Some(rustgis_assistant::Agent::new(config, &app.session)); + app.assistant.loaded = true; + } app.ui.left = Some(LeftPane::Contents); app.ui.language = "en".into(); app diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index f9f581bc56..774f016f8a 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -5759,14 +5759,33 @@ impl RustGisApp { "ui.pane.presentation" => toggle_right(&mut self.ui, RightPane::Presentation), "ui.pane.notebook" => toggle_right(&mut self.ui, RightPane::Notebook), // `{"ask": text}` opens the pane and sends the text. - "ui.pane.assistant" => match p.get("ask").and_then(Value::as_str).map(str::trim).filter(|t| !t.is_empty()) { - Some(text) => { - // Sent on the next frame, as a suggestion is. - self.assistant.ask(text)?; - self.ui.open_right(RightPane::Assistant); + "ui.pane.assistant" => { + let ask = p.get("ask").and_then(Value::as_str).map(str::trim).filter(|t| !t.is_empty()); + let connect = p.get("connect").and_then(Value::as_bool).unwrap_or(false); + match ask { + Some(_) if connect => return Err(tl!("ui.pane.assistant takes ask or connect, not both").to_string()), + Some(text) => { + // Sent on the next frame, as a suggestion is, where the conversation shows. + self.assistant.ask(text)?; + #[cfg(not(target_arch = "wasm32"))] + { + self.connect.view = false; + } + self.ui.open_right(RightPane::Assistant); + } + // "Connect my agent", the pane's view for an agent the user already has. + None if connect => { + #[cfg(target_arch = "wasm32")] + return Err(tl!("Connecting your own agent needs the desktop app: a web page can't be reached by it.").to_string()); + #[cfg(not(target_arch = "wasm32"))] + { + connectui::open_view(self); + self.ui.open_right(RightPane::Assistant); + } + } + None => toggle_right(&mut self.ui, RightPane::Assistant), } - None => toggle_right(&mut self.ui, RightPane::Assistant), - }, + } "ui.pane.shares" => toggle_right(&mut self.ui, RightPane::Shares), // Share As: to a file (recorded under Status › Jobs), or a download in the browser. "ui.share" => { diff --git a/crates/ui-egui/tests/smoke.rs b/crates/ui-egui/tests/smoke.rs index 8237766b5c..1297c4829c 100644 --- a/crates/ui-egui/tests/smoke.rs +++ b/crates/ui-egui/tests/smoke.rs @@ -4794,7 +4794,7 @@ fn dialogs_can_be_moved() { assert!((after.left_top() - (before.left_top() + (to - from))).length() < 2.0, "{before:?} → {after:?}"); } -/// "Let your Agents Control RustGIS", in the AI Assistant settings: ticking it starts the relay, +/// "Let your Agents Control RustGIS", in the assistant's "Connect my agent" view: ticking it starts the relay, /// lets attached agents use files and the network, shows what an agent needs to connect and is /// remembered; unticking it stops the relay. #[cfg(not(target_arch = "wasm32"))] @@ -4809,9 +4809,8 @@ fn letting_agents_control_rustgis_starts_the_relay_and_shows_how_to_connect() { s.push((k.to_string(), v.to_string())); } })); - app.run("ui.pane.assistant", json!({})).expect("opens the assistant"); - // The connection instructions expand below the checkbox: keep the settings above the - // bottom composer so both pointer clicks reach the checkbox. + app.run("ui.pane.assistant", json!({"connect": true})).expect("opens the assistant"); + // A tall window, so the instructions below the checkbox are all laid out. let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1400.0, 2000.0)).with_max_steps(64).build_ui_state( |ui, app: &mut RustGisApp| { let ctx = ui.ctx().clone(); @@ -4820,10 +4819,7 @@ fn letting_agents_control_rustgis_starts_the_relay_and_shows_how_to_connect() { }, app, ); - // The first frame loads the assistant's settings and closes the form when they're complete (a - // key in the environment): open it after that. h.step(); - h.state_mut().assistant.settings = true; h.step(); assert!(h.state().relay.is_none(), "off until the user turns it on"); assert!(h.query_by_label("Add this MCP server to your agent:").is_none(), "nothing to connect to while it's off"); diff --git a/docs/mcp.md b/docs/mcp.md index 8d387ebf92..0394d7e8a9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -75,13 +75,22 @@ Then ask, for example: ## Managing the open desktop app By default each agent gets its own project in memory. To drive the project that is open in the -desktop app instead, open **Analyze › AI Assistant**, click the **Assistant settings** (gear) -icon in the pane's header, and tick **Let your Agents Control RustGIS** below **Skills**. -These are the AI Assistant's settings, separate from the main **Settings** ribbon tab, and are -there while the [AI Assistant extension](user-guide/assistant.md#turning-the-assistant-off) is on -(the MCP Relay command runs either way). Ticking it +desktop app instead, open **Analyze › AI Assistant**, click **Connect my agent** under the +model's name, and tick **Let your Agents Control RustGIS**. The view is part of the AI Assistant +pane, so it's there while the +[AI Assistant extension](user-guide/assistant.md#turning-the-assistant-off) is on +(the MCP Relay command runs either way). Ticking the box starts the relay and shows what an agent needs to connect: the MCP server configuration, and the -`claude mcp add` / `codex mcp add` commands. While it's ticked, attached agents may also read and +`claude mcp add` / `codex mcp add` commands. You need no model or API key set up in RustGIS for +this. The agent's own shell, files and web access follow that agent's permissions; RustGIS +controls only what it does through RustGIS. + +The view also shows who is connected (the name each agent gives itself) and the last call an agent +made. **Test connection** starts `rustgis-cli mcp --attach` as an agent would and asks the open +app for an answer. A test that passes shows RustGIS's side works; it can't check that your agent +was given the configuration. + +While it's ticked, attached agents may also read and write files and use the network, without `--yes`. RustGIS remembers the choice and starts the relay with the app. The **MCP Relay** command (Help menu, or Command Search with Ctrl+K) starts the relay too, without that: attached agents then have the access their `--yes` asks for. @@ -189,7 +198,7 @@ name in the undo history, and the token lasts across launches where the relay's `rustgis-cli mcp-register --client claude` registers it with Claude Code (`claude mcp add --transport http rustgis-live http://127.0.0.1:8768/mcp --header "Authorization: Bearer …"`), and -the settings section shows that command. Without `--client` it prints the configuration for any +the **Connect my agent** view shows that command. Without `--client` it prints the configuration for any HTTP client. `--name` and `--port` change the registration's name and port. Either way the token leaves its file: `claude mcp add` takes it as an argument (other users of the computer can see a running program's arguments for the moment it runs), and the printed configuration shows it, so @@ -212,7 +221,7 @@ couldn't start: agents then stay on, and the status bar says only the file bridg 1. Write a script to `bridge-command.txt` in the relay's private folder (`$XDG_RUNTIME_DIR/rustgis` on Linux, a `rustgis-mcp-` folder in the temporary folder - elsewhere). The settings section shows the full path. The script is in the `script.run` format: + elsewhere). The **Connect my agent** view shows the full path. The script is in the `script.run` format: one `command-id {json}` per line, `#` for comments. 2. Once the file has stopped changing for half a second, RustGIS runs it on the open project. (To be sure a half-written script never runs, write it to another file in the folder and rename it to diff --git a/docs/user-guide/assistant.md b/docs/user-guide/assistant.md index f04c1dd650..e953261faa 100644 --- a/docs/user-guide/assistant.md +++ b/docs/user-guide/assistant.md @@ -47,6 +47,21 @@ controls. From the command line, `rustgis-cli ask` sends one request (see [Command Line](../cli.md#asking-the-ai-assistant)). +## Connect my agent + +If you already use Claude Code, Codex, Cursor or another agent that speaks MCP, you can keep +using it in its own terminal or app, with its own sign-in, and have it work on the map you have +open. On the desktop, click **Connect my agent** under the model's name in the pane. The view +there has the switch that lets agents in (off until you tick it), the commands to copy, a +connection test, and who is connected. See +[Managing the open desktop app](../mcp.md#managing-the-open-desktop-app). + +When one of these agents is installed on your computer, an empty conversation offers to show you +how to connect it. Nothing is turned on for you, and **Not now** keeps the offer from coming back. + +The entry isn't in the web app or the phone's touch interface: a web page can't be reached by an +agent on your computer, and the agents don't run on a phone. + ## On a phone In the [touch interface](field-work.md#the-touch-interface) nothing of the assistant shows until From 1aad2eccaef31698d8a00521ead795802b92fd16 Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 2 Dec 2026 14:53:17 -0600 Subject: [PATCH 2/3] fix(assistant): keep the pending query visible and test the current relay --- crates/ui-egui/src/approvalcard.rs | 18 +++++++++--------- crates/ui-egui/src/assistantpane.rs | 23 +++++++++++++++-------- crates/ui-egui/src/connectui.rs | 12 ++++++------ 3 files changed, 30 insertions(+), 23 deletions(-) diff --git a/crates/ui-egui/src/approvalcard.rs b/crates/ui-egui/src/approvalcard.rs index 45c44d87b9..5048743265 100644 --- a/crates/ui-egui/src/approvalcard.rs +++ b/crates/ui-egui/src/approvalcard.rs @@ -41,6 +41,15 @@ pub(crate) fn show(ui: &mut Ui, registry: &Registry, review: &Review) { count => crate::i18n::fmt("{actions} · {count} project edits", &[("actions", &actions), ("count", &count.to_string())]), }; ui.add(egui::Label::new(RichText::new(title).strong()).wrap()); + // What a query does is its text, so it isn't left under Details. + for (_, query) in &queries { + ui.add(egui::Label::new(RichText::new(query).monospace().small()).wrap().selectable(true)); + } + // Secrets are left out of what is shown (a CREATE SECRET's options, a key): said, so the + // text isn't taken for the whole query. + if review.sql_hidden { + ui.label(RichText::new(tl!("Secret values are hidden here, but the request runs with them.")).small().italics()); + } // These are starting defaults, not an exhaustive target list for a composite request. if let Some((active, selected)) = &review.defaults { ui.add( @@ -52,15 +61,6 @@ pub(crate) fn show(ui: &mut Ui, registry: &Registry, review: &Review) { ); } ui.add(egui::Label::new(RichText::new(reason(review)).small()).wrap()); - // What a query does is its text, so it isn't left under Details. - for (_, query) in &queries { - ui.add(egui::Label::new(RichText::new(query).monospace().small()).wrap().selectable(true)); - } - // Secrets are left out of what is shown (a CREATE SECRET's options, a key): said, so the - // text isn't taken for the whole query. - if review.sql_hidden { - ui.label(RichText::new(tl!("Secret values are hidden here, but the request runs with them.")).small().italics()); - } for detail in &review.details { let name = operation(registry, &detail.operation); if !detail.targets.is_empty() { diff --git a/crates/ui-egui/src/assistantpane.rs b/crates/ui-egui/src/assistantpane.rs index 62bac97e75..cadacd84d2 100644 --- a/crates/ui-egui/src/assistantpane.rs +++ b/crates/ui-egui/src/assistantpane.rs @@ -127,11 +127,11 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { #[cfg(not(target_arch = "wasm32"))] const SHORT_PANE: f32 = 400.0; -/// What the rows of an approval card and the message box under it take besides the card's -/// details; the least and the most those details get; and what they keep, where the pane has it, -/// when settings are open above (an SQL query shows without scrolling). +/// Below this height, show the compact approval note while another view is open above it. +const COMPACT_APPROVAL_ROOM: f32 = 312.0; +/// The space reserved for the card's controls and the message box before sizing the details. const CARD_AND_BOX: f32 = 220.0; -const CARD_DETAILS_LEAST: f32 = 48.0; +const CARD_DETAILS_LEAST: f32 = 56.0; const CARD_DETAILS_MOST: f32 = 280.0; const CARD_DETAILS_KEPT: f32 = 140.0; @@ -787,13 +787,13 @@ fn waiting_note(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, asked: &rustgis_a ui.push_id(("assistant_waiting_buttons", asked), |ui| { ui.horizontal(|ui| { if crate::widgets::primary_button(ui, tl!("Review it"), true, vec2(70.0, 26.0)).clicked() { - if app.assistant.settings { - assistant::toggle_settings(app); - } #[cfg(not(target_arch = "wasm32"))] { app.connect.view = false; } + if app.assistant.settings { + assistant::toggle_settings(app); + } } if ui.button(tl!("Decline")).clicked() { app.assistant.always = false; @@ -814,7 +814,7 @@ fn composer(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, busy: bool, ctx: &egu let free = room - CARD_AND_BOX; let covered = covered(app); let waiting = assistant::pending(app); - if let Some(approval) = waiting.as_ref().filter(|_| covered && free < CARD_DETAILS_KEPT - CARD_DETAILS_LEAST) { + if let Some(approval) = waiting.as_ref().filter(|_| covered && room < COMPACT_APPROVAL_ROOM) { waiting_note(app, ui, t, &approval.asked, ctx); ui.add_space(6.0); } else if let Some(approval) = waiting { @@ -2918,6 +2918,13 @@ pub(crate) mod tests { h.run_steps(8); assert!(!h.state().assistant.settings); assert!(in_window(&h, "Allow") && in_window(&h, "Decline") && input_in_window(&h)); + assert!( + h.output().shapes.iter().any(|shape| { + matches!(&shape.shape, egui::Shape::Text(text) + if text.galley.text() == "SELECT name FROM Cities" && shape.clip_rect.contains_rect(text.visual_bounding_rect())) + }), + "the query fits in the visible part of the approval card" + ); } /// The right pane's width with `entries` in the conversation and `model` as the model's name. diff --git a/crates/ui-egui/src/connectui.rs b/crates/ui-egui/src/connectui.rs index b58ef1eaf5..655b4193a4 100644 --- a/crates/ui-egui/src/connectui.rs +++ b/crates/ui-egui/src/connectui.rs @@ -187,6 +187,7 @@ pub(crate) fn stopped(app: &mut RustGisApp) { // Agents turned on again start without full access. app.connect.full = false; app.connect.error = None; + app.connect.test = None; if let Some(bridge) = app.file_bridge.take() { bridge.stop(); } @@ -520,11 +521,7 @@ fn ping(program: &str, args: &[String], wait: Duration) -> Result<(), String> { /// The arguments of `rustgis-cli` that attach an agent to the relay on `port`. fn attach_args(port: u16) -> Vec { - let mut args = vec!["mcp".to_string(), "--attach".to_string()]; - if port != rustgis_assistant::relay::DEFAULT_PORT { - args.push(port.to_string()); - } - args + vec!["mcp".to_string(), "--attach".to_string(), port.to_string()] } /// The lines that add RustGIS to Claude Code and to Codex, with `cli` and its `args`. @@ -697,10 +694,13 @@ mod tests { let bridge_dir = tempfile::tempdir().unwrap(); app.connect.bridge_dir = Some(bridge_dir.path().to_path_buf()); resume_on(&mut app, 0); - assert!(app.relay.is_some()); + let port = app.relay.as_ref().unwrap().port(); assert!(enabled(&app)); + let outcome = Arc::new(Mutex::new(Some(Ok(())))); + app.connect.test = Some(Test { port, outcome }); app.run("ui.mcpRelay", json!({"stop":true})).unwrap(); assert!(app.relay.is_none()); + assert!(app.connect.test.is_none(), "the result can't outlive its relay"); assert!(!enabled(&app)); assert_eq!(*saved.lock().unwrap(), "off"); } From 1cf0ad00e82e7377a145b1c56aea90e7f052047a Mon Sep 17 00:00:00 2001 From: mavrick Date: Wed, 2 Dec 2026 16:21:07 -0600 Subject: [PATCH 3/3] fix(assistant): keep approvals reachable and tighten connection setup --- crates/assistant/src/relay.rs | 16 +++- crates/ui-egui/src/agentthreads.rs | 17 ++-- crates/ui-egui/src/assistantpane.rs | 106 +++++++++++++++++----- crates/ui-egui/src/connectui.rs | 135 ++++++++++++++++++++-------- crates/ui-egui/src/lib.rs | 6 +- docs/mcp.md | 6 +- 6 files changed, 217 insertions(+), 69 deletions(-) diff --git a/crates/assistant/src/relay.rs b/crates/assistant/src/relay.rs index 66a9ac4b11..63008c9360 100644 --- a/crates/assistant/src/relay.rs +++ b/crates/assistant/src/relay.rs @@ -1196,14 +1196,24 @@ fn asks_for_skills(line: &str) -> bool { /// The most characters of a client's name kept. const MAX_CLIENT_NAME: usize = 60; -/// What an `initialize` message calls its client: one line, without control characters, cut to +/// What an `initialize` message calls its client: one line, without control or invisible formatting characters, cut to /// [`MAX_CLIENT_NAME`]. fn client_name(msg: &Value) -> Option { if msg.get("method").and_then(Value::as_str) != Some("initialize") { return None; } let name = msg.pointer("/params/clientInfo/name").and_then(Value::as_str)?; - let name: String = name.chars().filter(|c| !c.is_control()).take(MAX_CLIENT_NAME).collect(); + let name: String = name + .chars() + .filter(|c| { + !c.is_control() + && !matches!( + c, + '\u{AD}' | '\u{061C}' | '\u{200B}'..='\u{200F}' | '\u{2028}'..='\u{202E}' | '\u{2060}'..='\u{2069}' | '\u{FEFF}' + ) + }) + .take(MAX_CLIENT_NAME) + .collect(); Some(name.trim().to_string()).filter(|n| !n.is_empty()) } @@ -2716,7 +2726,7 @@ mod tests { attach(&mut client, &relay, false); wait_until("the attach", || relay.attached_clients() == 1); assert!(relay.client_names().is_empty(), "no name before initialize"); - let name = format!("claude-code\n\u{7}{}", "x".repeat(200)); + let name = format!("claude-code\n\u{7}\u{061C}\u{200B}\u{200D}\u{2028}\u{202E}\u{2066}\u{2069}\u{FEFF}{}", "x".repeat(200)); let hello = json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"clientInfo": {"name": name}}}); writeln!(client, "{hello}").unwrap(); // The app answers it, and the connection reads on. diff --git a/crates/ui-egui/src/agentthreads.rs b/crates/ui-egui/src/agentthreads.rs index ad2d0f709d..8a96128830 100644 --- a/crates/ui-egui/src/agentthreads.rs +++ b/crates/ui-egui/src/agentthreads.rs @@ -6,7 +6,7 @@ //! //! Threads end with a new conversation, when the user closes them, or after half an hour idle. -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::time::Duration; use egui::{Align, Layout, RichText, Ui, vec2}; @@ -101,10 +101,17 @@ impl Drop for Threads { } } -/// `rustgis-cli` beside the app. -fn cli() -> Option { - let name = if cfg!(windows) { "rustgis-cli.exe" } else { "rustgis-cli" }; - std::env::current_exe().ok().map(|p| p.with_file_name(name)).filter(|p| p.is_file()) +pub(crate) const CLI_NAME: &str = if cfg!(windows) { "rustgis-cli.exe" } else { "rustgis-cli" }; + +/// The CLI shipped beside the app. +pub(crate) fn cli_beside(app_exe: &Path) -> Option { + let cli = app_exe.with_file_name(CLI_NAME); + cli.is_file().then_some(cli) +} + +/// The CLI shipped beside the running app. +pub(crate) fn cli() -> Option { + std::env::current_exe().ok().as_deref().and_then(cli_beside) } /// Starts the tasks the assistant handed out, passes on what threads did, asked and reported, diff --git a/crates/ui-egui/src/assistantpane.rs b/crates/ui-egui/src/assistantpane.rs index cadacd84d2..e70985d594 100644 --- a/crates/ui-egui/src/assistantpane.rs +++ b/crates/ui-egui/src/assistantpane.rs @@ -131,6 +131,8 @@ const SHORT_PANE: f32 = 400.0; const COMPACT_APPROVAL_ROOM: f32 = 312.0; /// The space reserved for the card's controls and the message box before sizing the details. const CARD_AND_BOX: f32 = 220.0; +/// The card's frame, title, checkbox and answer buttons, without the scrolling details. +const CARD_CONTROLS_ROOM: f32 = 100.0; const CARD_DETAILS_LEAST: f32 = 56.0; const CARD_DETAILS_MOST: f32 = 280.0; const CARD_DETAILS_KEPT: f32 = 140.0; @@ -141,9 +143,21 @@ const CONVERSATION_ROOM: f32 = 96.0; fn composer_panel(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, busy: bool, ctx: &egui::Context) { // What the pane has under its heading, before the panel takes its part. let room = ui.available_height(); - egui::Panel::bottom("assistant_composer") - .frame(egui::Frame::NONE.fill(t.pane).inner_margin(egui::Margin::symmetric(10, 8))) - .show(ui, |ui| composer(app, ui, t, busy, ctx, room)); + let frame = egui::Frame::NONE.fill(t.pane).inner_margin(egui::Margin::symmetric(10, 8)); + egui::Panel::bottom("assistant_composer").frame(frame).show(ui, |ui| { + if let Some(asked) = app.assistant.agent.as_ref().and_then(|agent| agent.asking()) { + // If even the smallest card and composer can't both fit, start at the card and let + // the user scroll to the message box. A new approval starts at the top again. + let height = (room - frame.total_margin().sum().y).max(0.0); + egui::ScrollArea::vertical() + .id_salt(("assistant_composer_scroll", asked, covered(app))) + .max_height(height) + .min_scrolled_height(height) + .show(ui, |ui| composer(app, ui, t, busy, ctx, room)); + } else { + composer(app, ui, t, busy, ctx, room); + } + }); } /// Edits provider settings and invalidates pending key reads as soon as a key changes. @@ -806,14 +820,21 @@ fn waiting_note(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, asked: &rustgis_a } fn composer(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, busy: bool, ctx: &egui::Context, room: f32) { - // Agent threads on this computer, working or waiting for a follow-up. + let waiting = assistant::pending(app); + let approving = waiting.is_some(); + // A long list of agent threads must leave room for the pending approval. #[cfg(not(target_arch = "wasm32"))] - crate::agentthreads::list(app, ui, t); - // The card's details scroll in what the pane has, so its buttons and the message box stay - // in it. - let free = room - CARD_AND_BOX; + if approving && app.assistant.threads.count() > 0 { + egui::ScrollArea::vertical() + .id_salt("assistant_thread_list") + .max_height(ui.available_height() * 0.25) + .min_scrolled_height(0.0) + .show(ui, |ui| crate::agentthreads::list(app, ui, t)); + } else { + crate::agentthreads::list(app, ui, t); + } + let most = (ui.ctx().content_rect().height() * 0.5).max(INPUT_HEIGHT); let covered = covered(app); - let waiting = assistant::pending(app); if let Some(approval) = waiting.as_ref().filter(|_| covered && room < COMPACT_APPROVAL_ROOM) { waiting_note(app, ui, t, &approval.asked, ctx); ui.add_space(6.0); @@ -825,9 +846,26 @@ fn composer(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, busy: bool, ctx: &egu app.assistant.always = false; app.assistant.always_for = Some(asked.clone()); } - // With something open above, they keep no more than they need to be read. - let details = if covered { free.min(CARD_DETAILS_KEPT) } else { free }; - let details = details.clamp(CARD_DETAILS_LEAST, CARD_DETAILS_MOST); + // Budget the details after the thread rows and the resized message box. In a tight + // pane, the details may shrink further so the answer buttons still fit. + let room = ui.available_height(); + let input_extra = app.assistant.input_height.clamp(INPUT_HEIGHT, most) - INPUT_HEIGHT; + let free = room - CARD_AND_BOX - input_extra; + let limit = if covered { CARD_DETAILS_KEPT } else { CARD_DETAILS_MOST }; + // In the tightest panes the optional checkbox scrolls with the details, leaving + // the title and answer buttons in view. + let tight = room < CARD_AND_BOX; + let controls_room = if tight { CARD_CONTROLS_ROOM - 28.0 } else { CARD_CONTROLS_ROOM }; + let details = free.clamp(CARD_DETAILS_LEAST, limit).min((room - controls_room).max(24.0)); + let remember = |ui: &mut Ui, always: &mut bool| { + if *can_always { + ui.checkbox(always, tl!("Don't ask again for exactly this action")); + } + }; + // Plugin commands, scripts and replacing the project are asked about every time. + if !can_always { + app.assistant.always = false; + } egui::Frame::NONE.fill(t.amber.gamma_multiply(0.15)).corner_radius(6).inner_margin(8).stroke(egui::Stroke::new(1.0, t.amber)).show( ui, |ui| { @@ -838,12 +876,12 @@ fn composer(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, busy: bool, ctx: &egu .id_salt(("assistant_approval", what, why)) .show(ui, |ui| { approval_details(ui, app, &approval); + if tight { + remember(ui, &mut app.assistant.always); + } }); - // Plugin commands, scripts and replacing the project are asked about every time. - if *can_always { - ui.checkbox(&mut app.assistant.always, tl!("Don't ask again for exactly this action")); - } else { - app.assistant.always = false; + if !tight { + remember(ui, &mut app.assistant.always); } // The buttons are this approval's own: a click begun on another's isn't one on them. ui.push_id(("assistant_approval_buttons", asked), |ui| { @@ -889,7 +927,6 @@ fn composer(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, busy: bool, ctx: &egu } crate::assistantpictures::chips(app, ui, t); // A grip above the box: dragging it up makes the box taller, up to half the window. - let most = (ui.ctx().content_rect().height() * 0.5).max(INPUT_HEIGHT); let (grip, drag) = ui.allocate_exact_size(vec2(ui.available_width(), 8.0), egui::Sense::drag()); let drag = drag.on_hover_cursor(egui::CursorIcon::ResizeVertical).on_hover_text(tl!("Drag to resize the message box")); if drag.dragged() { @@ -898,14 +935,20 @@ fn composer(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, busy: bool, ctx: &egu let color = if drag.hovered() || drag.dragged() { t.text } else { t.text_dim.gamma_multiply(0.6) }; ui.painter().line_segment([grip.center() - vec2(14.0, 0.0), grip.center() + vec2(14.0, 0.0)], egui::Stroke::new(2.0, color)); let height = app.assistant.input_height.clamp(INPUT_HEIGHT, most); + let mut limit = height.max(INPUT_GROWS).min(most); + if approving { + // Keep the composer footer visible and retain the preferred height for after approval. + const FOOTER_ROOM: f32 = 36.0; + limit = limit.min((ui.available_height() - FOOTER_ROOM).max(INPUT_HEIGHT)); + } // The box grows with what is typed, past the height set, then scrolls. - egui::ScrollArea::vertical().id_salt("assistant_input_scroll").max_height(height.max(INPUT_GROWS).min(most)).show(ui, |ui| { + egui::ScrollArea::vertical().id_salt("assistant_input_scroll").min_scrolled_height(INPUT_HEIGHT).max_height(limit).show(ui, |ui| { ui.add( egui::TextEdit::multiline(&mut app.assistant.input) .id(id) .desired_rows(2) .desired_width(f32::INFINITY) - .min_size(vec2(0.0, height)) + .min_size(vec2(0.0, height.min(limit))) .font(regular(13.0)) .hint_text(tl!("Ask about the map, or tell it what to do…")), ); @@ -2927,6 +2970,29 @@ pub(crate) mod tests { ); } + #[test] + fn a_short_pane_keeps_the_approval_buttons_in_view() { + use egui_kittest::kittest::Queryable; + for (window_height, input_height, has_footer_room) in [(400.0, INPUT_HEIGHT, false), (400.0, 200.0, false), (560.0, 280.0, true)] { + let mut h = settings_open(vec2(900.0, window_height), true); + h.state_mut().assistant.settings = false; + h.state_mut().assistant.input_height = input_height; + h.run_steps(8); + + let pane = right_pane(&h); + for label in ["Allow", "Decline"] { + let rect = h.get_by_label(label).rect(); + assert!(pane.contains_rect(rect), "{label} {rect:?} is outside {pane:?}"); + } + if has_footer_room { + assert!(pane.contains_rect(h.get_by_label("Stop").rect())); + } + h.get_by_label("Decline").click(); + h.run_steps(3); + assert!(assistant::pending(h.state()).is_none(), "Decline can be clicked inside the pane"); + } + } + /// The right pane's width with `entries` in the conversation and `model` as the model's name. fn pane_width(entries: Vec, model: &str) -> f32 { let h = chat(entries, model); diff --git a/crates/ui-egui/src/connectui.rs b/crates/ui-egui/src/connectui.rs index 655b4193a4..ea73808d63 100644 --- a/crates/ui-egui/src/connectui.rs +++ b/crates/ui-egui/src/connectui.rs @@ -6,11 +6,13 @@ //! to connect. The choice is remembered: the relay starts with the app. An empty conversation //! offers the view once when an agent is installed here; nothing is turned on for the user. +use std::path::Path; use std::time::Duration; use egui::RichText; use serde_json::{Value, json}; +use crate::agentthreads::{self, CLI_NAME}; use crate::assistant::{pref, save_pref}; use crate::theme::{Tokens, semibold}; use crate::{RustGisApp, Slot}; @@ -53,8 +55,8 @@ pub struct ConnectState { test: Option, /// The agents installed here, by name, looked for once, for the offer. pub(crate) detected: Option>, - /// The offer was answered (kept in the preferences too, where there are any). - offer_answered: bool, + /// The answer to the offer, read from preferences on first use. + offer_answered: Option, } /// Whether the user lets agents control RustGIS. @@ -207,19 +209,14 @@ fn shell_arg(text: &str) -> String { /// `rustgis-cli` beside the app, or its name (for a PATH lookup) when it isn't there. fn cli() -> String { - let name = if cfg!(windows) { "rustgis-cli.exe" } else { "rustgis-cli" }; - std::env::current_exe() - .ok() - .map(|p| p.with_file_name(name)) - .filter(|p| p.is_file()) - .map_or(name.to_string(), |p| p.display().to_string()) + agentthreads::cli().map_or_else(|| CLI_NAME.to_string(), |p| p.display().to_string()) } /// A line to copy: shown in monospace, with a Copy button. -fn copyable(ui: &mut egui::Ui, text: &str) { +fn copyable(ui: &mut egui::Ui, text: &str, name: &str) { // The button first, at the right, so long text wraps in the room left instead of pushing it out. ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| { - if ui.small_button(tl!("Copy")).clicked() { + if ui.small_button(tl!("Copy")).accessible_name(name).clicked() { ui.ctx().copy_text(text.to_string()); } ui.with_layout(egui::Layout::left_to_right(egui::Align::Min), |ui| { @@ -267,20 +264,26 @@ fn installed_agents() -> Vec<&'static str> { /// Records that the offer was answered, so it isn't made again. fn answer_offer(app: &mut RustGisApp) { - app.connect.offer_answered = true; + app.connect.offer_answered = Some(true); save_pref(app, OFFER_PREF, "answered"); } /// In an empty conversation: when an agent is installed here, offers to connect it alongside the /// built-in assistant, until that is answered. Never once agents can already connect. pub(crate) fn offer(app: &mut RustGisApp, ui: &mut egui::Ui, t: &Tokens) { - if app.connect.offer_answered || enabled(app) || app.relay.is_some() || pref(app, OFFER_PREF).is_some() { + if enabled(app) || app.relay.is_some() { return; } - let names = app.connect.detected.get_or_insert_with(installed_agents).join(", "); + let answered = app.connect.offer_answered.unwrap_or_else(|| pref(app, OFFER_PREF).is_some()); + app.connect.offer_answered = Some(answered); + if answered { + return; + } + let names = app.connect.detected.get_or_insert_with(installed_agents); if names.is_empty() { return; } + let names = names.join(", "); egui::Frame::group(ui.style()).show(ui, |ui| { let said = crate::i18n::fmt( "Found on this computer: {names}. You can connect one to work on this map with its own sign-in, alongside the assistant here.", @@ -462,9 +465,8 @@ fn status(app: &mut RustGisApp, ui: &mut egui::Ui, t: &Tokens) { fn start_test(app: &mut RustGisApp, port: u16, ctx: &egui::Context) { let outcome: Slot> = Default::default(); let (slot, ctx) = (outcome.clone(), ctx.clone()); - let (program, args) = (cli(), attach_args(port)); let spawned = std::thread::Builder::new().name("rustgis-connect-test".into()).spawn(move || { - let went = ping(&program, &args, TEST_WAIT); + let went = ping_relay(std::env::current_exe().ok().as_deref(), port); if let Ok(mut slot) = slot.lock() { *slot = Some(went); } @@ -480,7 +482,7 @@ fn start_test(app: &mut RustGisApp, port: u16, ctx: &egui::Context) { /// Runs `program` with `args` (an MCP server on its standard input and output), sends it /// [`PING`] and says whether the answer came back before it ended, within `wait`. -fn ping(program: &str, args: &[String], wait: Duration) -> Result<(), String> { +fn ping(program: &Path, args: &[String], wait: Duration) -> Result<(), String> { use std::io::Write; use std::process::Stdio; let mut command = std::process::Command::new(program); @@ -488,14 +490,15 @@ fn ping(program: &str, args: &[String], wait: Duration) -> Result<(), String> { // No console window flashing up on Windows. #[cfg(windows)] std::os::windows::process::CommandExt::creation_flags(&mut command, 0x0800_0000); - let mut child = command.spawn().map_err(|e| format!("{program}: {e}"))?; + let failed = |e| format!("{}: {e}", program.display()); + let mut child = command.spawn().map_err(failed)?; // Closing its input after the message ends it once it has answered. A program that ended // already says why on its error output, so a write that fails is not the report. if let Some(mut input) = child.stdin.take() { let _ = writeln!(input, "{PING}"); } let end = web_time::Instant::now() + wait; - while child.try_wait().map_err(|e| format!("{program}: {e}"))?.is_none() { + while child.try_wait().map_err(failed)?.is_none() { if web_time::Instant::now() >= end { let _ = child.kill(); let _ = child.wait(); @@ -503,7 +506,7 @@ fn ping(program: &str, args: &[String], wait: Duration) -> Result<(), String> { } std::thread::sleep(Duration::from_millis(20)); } - let output = child.wait_with_output().map_err(|e| format!("{program}: {e}"))?; + let output = child.wait_with_output().map_err(failed)?; let reply: Value = String::from_utf8_lossy(&output.stdout).lines().next().and_then(|l| serde_json::from_str(l).ok()).unwrap_or(Value::Null); if reply.get("id") == Some(&json!(1)) && reply.get("result").is_some() { @@ -520,8 +523,23 @@ fn ping(program: &str, args: &[String], wait: Duration) -> Result<(), String> { } /// The arguments of `rustgis-cli` that attach an agent to the relay on `port`. -fn attach_args(port: u16) -> Vec { - vec!["mcp".to_string(), "--attach".to_string(), port.to_string()] +fn attach_args(port: Option) -> Vec { + let mut args = vec!["mcp".to_string(), "--attach".to_string()]; + if let Some(port) = port { + args.push(port.to_string()); + } + args +} + +/// The connection test always uses the CLI beside the app and the current relay's exact port. +fn ping_relay(app_exe: Option<&Path>, port: u16) -> Result<(), String> { + let program = app_exe.and_then(agentthreads::cli_beside).ok_or_else(|| tl!("rustgis-cli isn't beside RustGIS").to_string())?; + ping(&program, &attach_args(Some(port)), TEST_WAIT) +} + +/// A copied configuration follows the CLI's default when the relay uses the standard port. +fn copied_attach_args(port: u16) -> Vec { + attach_args((port != rustgis_assistant::relay::DEFAULT_PORT).then_some(port)) } /// The lines that add RustGIS to Claude Code and to Codex, with `cli` and its `args`. @@ -539,9 +557,9 @@ fn instructions(app: &RustGisApp, ui: &mut egui::Ui) { if let Some(bridge) = &app.file_bridge { let (command, result) = (bridge.command_path().display().to_string(), bridge.result_path().display().to_string()); ui.label(RichText::new(tl!("Agents without MCP can write a script (one command per line) to:")).small()); - copyable(ui, &command); + copyable(ui, &command, tl!("Copy script path")); ui.label(RichText::new(tl!("RustGIS runs it and writes the outcome to:")).small()); - copyable(ui, &result); + copyable(ui, &result, tl!("Copy result path")); } }; let Some(port) = app.relay.as_ref().map(|r| r.port()) else { @@ -550,7 +568,7 @@ fn instructions(app: &RustGisApp, ui: &mut egui::Ui) { }; // What an agent needs: RustGIS's MCP server, attached to this app. let cli = cli(); - let args = attach_args(port); + let args = copied_attach_args(port); let config = serde_json::to_string_pretty(&json!({"mcpServers": {"rustgis-app": {"command": cli, "args": args}}})).unwrap_or_default(); let hint = if cfg!(windows) { tl!("Or run in PowerShell, for Claude Code or Codex:") @@ -558,11 +576,11 @@ fn instructions(app: &RustGisApp, ui: &mut egui::Ui) { tl!("Or run in a POSIX shell, for Claude Code or Codex:") }; ui.label(RichText::new(tl!("Add this MCP server to your agent:")).small()); - copyable(ui, &config); + copyable(ui, &config, tl!("Copy MCP configuration")); ui.label(RichText::new(hint).small()); - for command in register_commands(&cli, &args) { - copyable(ui, &command); - } + let [claude, codex] = register_commands(&cli, &args); + copyable(ui, &claude, tl!("Copy Claude Code command")); + copyable(ui, &codex, tl!("Copy Codex command")); // Clients that speak MCP over HTTP: registered with the stable token, kept off the screen. if let Some(http) = app.relay.as_ref().and_then(|r| r.http_port()) { let text = crate::i18n::fmt("Or, for agents that use MCP over HTTP (port {port}):", &[("port", &http.to_string())]); @@ -574,7 +592,7 @@ fn instructions(app: &RustGisApp, ui: &mut egui::Ui) { if http != rustgis_assistant::relay::HTTP_PORT { register.push_str(&format!(" --port {http}")); } - copyable(ui, ®ister); + copyable(ui, ®ister, tl!("Copy HTTP registration command")); } bridge(ui); } @@ -740,12 +758,11 @@ mod tests { h.run_steps(3); h.get_by_label("No agent is connected."); let port = h.state().relay.as_ref().unwrap().port(); - let expected = register_commands(&cli(), &attach_args(port)); + let expected = register_commands(&cli(), &copied_attach_args(port)); assert!(expected[0].starts_with("claude mcp add rustgis-app -- "), "{expected:?}"); assert!(expected[0].ends_with(&format!(" mcp --attach {port}")), "{expected:?}"); - // The Copy buttons, top down: the configuration, Claude Code's line, Codex's. - for (button, line) in [(1, &expected[0]), (2, &expected[1])] { - h.get_all_by_label("Copy").nth(button).unwrap().click(); + for (button, line) in [("Copy Claude Code command", &expected[0]), ("Copy Codex command", &expected[1])] { + h.get_by_label(button).click(); h.step(); let copied = h.output().platform_output.commands.iter().any(|c| matches!(c, egui::OutputCommand::CopyText(t) if t == line)); assert!(copied, "button {button} didn't copy {line}"); @@ -762,6 +779,11 @@ mod tests { let mut app = RustGisApp::with_sample(); assert!(app.run("ui.pane.assistant", json!({"connect": true, "ask": "hello"})).is_err()); assert!(!app.connect.view && app.assistant.asked.is_empty()); + for bad in [json!("yes"), json!(null), json!(1), json!({}), json!([])] { + let error = app.run("ui.pane.assistant", json!({"connect": bad})).unwrap_err(); + assert_eq!(error, "ui.pane.assistant's connect is true or false"); + assert!(app.ui.right.is_none() && !app.connect.view); + } app.run("ui.pane.assistant", json!({"connect": true})).unwrap(); app.run("ui.pane.assistant", json!({"connect": true})).unwrap(); assert!(app.connect.view && app.ui.right == Some(crate::RightPane::Assistant), "opened, not toggled"); @@ -777,10 +799,17 @@ mod tests { use std::collections::HashMap; use std::sync::{Arc, Mutex}; let prefs: Arc>> = Arc::default(); + let reads = Arc::new(std::sync::atomic::AtomicUsize::new(0)); let app_with = |found: Vec<&'static str>| { let mut app = RustGisApp::with_sample(); let read = prefs.clone(); - app.services.load_pref = Some(Box::new(move |k: &str| read.lock().unwrap().get(k).cloned())); + let reads = reads.clone(); + app.services.load_pref = Some(Box::new(move |k: &str| { + if k == OFFER_PREF { + reads.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + read.lock().unwrap().get(k).cloned() + })); let write = prefs.clone(); app.services.save_pref = Some(Box::new(move |k: &str, v: &str| { write.lock().unwrap().insert(k.into(), v.into()); @@ -791,8 +820,11 @@ mod tests { }; const OFFER: &str = "Found on this computer: Claude Code, Codex."; assert!(app_with(Vec::new()).query_by_label("Not now").is_none(), "no agent, no offer"); - let h = app_with(vec!["Claude Code", "Codex"]); + let before = reads.load(std::sync::atomic::Ordering::Relaxed); + let mut h = app_with(vec!["Claude Code", "Codex"]); + h.run_steps(3); h.get_by_label_contains(OFFER); + assert_eq!(reads.load(std::sync::atomic::Ordering::Relaxed), before + 1); // Unanswered, it is made again. let mut h = app_with(vec!["Claude Code", "Codex"]); h.get_by_label("Not now").click(); @@ -821,7 +853,7 @@ mod tests { #[cfg(unix)] #[test] fn the_connection_test_reports_the_answer_or_why_there_is_none() { - let run = |script: &str, wait: Duration| ping("/bin/sh", &["-c".to_string(), script.to_string()], wait); + let run = |script: &str, wait: Duration| ping(Path::new("/bin/sh"), &["-c".to_string(), script.to_string()], wait); let long = Duration::from_secs(30); // The stand-in answers only when it reads the ping itself. let answers = format!(r#"read line; [ "$line" = '{PING}' ] && echo '{{"jsonrpc":"2.0","id":1,"result":{{}}}}'"#); @@ -832,10 +864,39 @@ mod tests { assert_eq!(nothing, Err("nothing is listening".to_string())); let hung = run("exec sleep 30", Duration::from_millis(200)).unwrap_err(); assert!(hung.starts_with("no answer after"), "{hung}"); - let missing = ping("/nonexistent/rustgis-cli", &[], long).unwrap_err(); + let missing = ping(Path::new("/nonexistent/rustgis-cli"), &[], long).unwrap_err(); assert!(missing.starts_with("/nonexistent/rustgis-cli: "), "{missing}"); } + #[test] + fn copied_attach_omits_the_default_port() { + let default_port = rustgis_assistant::relay::DEFAULT_PORT; + assert_eq!(copied_attach_args(default_port), ["mcp", "--attach"]); + assert_eq!(copied_attach_args(9000), ["mcp", "--attach", "9000"]); + } + + #[cfg(unix)] + #[test] + fn the_connection_test_only_uses_the_cli_beside_the_app() { + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + let app_exe = dir.path().join("rustgis"); + let port = rustgis_assistant::relay::DEFAULT_PORT; + assert_eq!(ping_relay(Some(&app_exe), port), Err("rustgis-cli isn't beside RustGIS".to_string())); + + // The sibling replies only to a ping aimed at the exact port, even for the default. + let cli = dir.path().join(CLI_NAME); + let script = format!( + r#"#!/bin/sh +read line +[ "$*" = 'mcp --attach {port}' ] && [ "$line" = '{PING}' ] && echo '{{"jsonrpc":"2.0","id":1,"result":{{}}}}' +"# + ); + std::fs::write(&cli, script).unwrap(); + std::fs::set_permissions(&cli, std::fs::Permissions::from_mode(0o700)).unwrap(); + assert_eq!(ping_relay(Some(&app_exe), port), Ok(())); + } + #[test] fn copyable_program_paths_are_literal_shell_arguments() { #[cfg(not(windows))] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 774f016f8a..1cdcc10ff6 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -5761,7 +5761,11 @@ impl RustGisApp { // `{"ask": text}` opens the pane and sends the text. "ui.pane.assistant" => { let ask = p.get("ask").and_then(Value::as_str).map(str::trim).filter(|t| !t.is_empty()); - let connect = p.get("connect").and_then(Value::as_bool).unwrap_or(false); + let connect = match p.get("connect") { + None | Some(Value::Bool(false)) => false, + Some(Value::Bool(true)) => true, + Some(_) => return Err(tl!("ui.pane.assistant's connect is true or false").to_string()), + }; match ask { Some(_) if connect => return Err(tl!("ui.pane.assistant takes ask or connect, not both").to_string()), Some(text) => { diff --git a/docs/mcp.md b/docs/mcp.md index 0394d7e8a9..fe044c89ef 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -86,9 +86,9 @@ this. The agent's own shell, files and web access follow that agent's permission controls only what it does through RustGIS. The view also shows who is connected (the name each agent gives itself) and the last call an agent -made. **Test connection** starts `rustgis-cli mcp --attach` as an agent would and asks the open -app for an answer. A test that passes shows RustGIS's side works; it can't check that your agent -was given the configuration. +made. **Test connection** runs the `rustgis-cli` installed beside RustGIS and pings the open +app on its active relay port. A passed test confirms that RustGIS answers through the CLI. +Give the copied configuration to your agent to connect it. While it's ticked, attached agents may also read and write files and use the network, without `--yes`. RustGIS remembers the choice and starts the