diff --git a/apps/rustgis/src/main.rs b/apps/rustgis/src/main.rs index 872cfaca4d..5cc15356d5 100644 --- a/apps/rustgis/src/main.rs +++ b/apps/rustgis/src/main.rs @@ -477,11 +477,13 @@ impl eframe::App for App { #[cfg(target_os = "macos")] impl App { - /// The menu bar: built once the app runs, again for a new language or shortcut; its items + /// The menu bar: built once the app runs, again for a new language, shortcut or extension + /// choice; its items /// greyed out as their commands are; the commands chosen from it run, unless a dialog (Save /// changes?) has the keys, as the keymap's do. fn menus(&mut self, ctx: &egui::Context) { - // The shortcuts shown can only change with the language or the keymap. + // The items and shortcuts shown can only change with the language, the keymap or the + // extensions that are on. let seen = (self.0.chosen_lang(), self.0.shortcuts_fingerprint()); if self.2.seen != Some(seen) { self.2.seen = Some(seen); diff --git a/apps/rustgis/src/menu.rs b/apps/rustgis/src/menu.rs index 05fc7395fd..a6c033a922 100644 --- a/apps/rustgis/src/menu.rs +++ b/apps/rustgis/src/menu.rs @@ -199,11 +199,18 @@ fn shortcut(app: &RustGisApp, action: Action, fixed: Option<(Key, bool)>) -> Opt app.shortcuts_of(command).into_iter().find(|k| k.modifiers.command && !matches!(k.logical_key, Key::Z | Key::Y)) } -/// The app's own items, in order, with their shortcuts now. +/// Whether an item's command belongs to an extension that is off: the menus leave it out. +fn hidden(app: &RustGisApp, action: Action) -> bool { + matches!(action, Command(id, _) if app.command_hidden(id)) +} + +/// The app's own items shown now, in order, with their shortcuts. fn own_items(app: &RustGisApp) -> impl Iterator)> + '_ { MENUS.iter().enumerate().flat_map(move |(m, (_, rows))| { rows.iter().enumerate().filter_map(move |(r, row)| match *row { - Item(label, action, fixed) => Some((format!("rustgis.{m}.{r}"), label, action, shortcut(app, action, fixed))), + Item(label, action, fixed) if !hidden(app, action) => { + Some((format!("rustgis.{m}.{r}"), label, action, shortcut(app, action, fixed))) + } _ => None, }) }) @@ -353,6 +360,7 @@ impl MenuBar { let sub = Submenu::new(label(lang, title), true); for row in *rows { match *row { + Item(_, action, _) if hidden(app, action) => {} Item(..) => { let (id, text, action, shortcut) = own.next().ok_or("the menu's items are out of step")?; let enabled = enabled_now(app, action, false); @@ -544,6 +552,19 @@ mod tests { assert_eq!(command_of(Command("ui.tab", r#"{"tab":"Settings"}"#)).map(|c| c.1["tab"].clone()), Some(Value::from("Settings"))); } + /// The AI Assistant's item leaves the menus while its extension is off, and the bar is built + /// again for it. + #[test] + fn the_items_of_an_extension_that_is_off_are_left_out() { + let mut app = RustGisApp::new(Session::new(Project::default())); + let offered = |app: &RustGisApp| own_items(app).any(|(_, label, ..)| label == "AI Assistant"); + assert!(offered(&app)); + let before = signature(&app); + assert!(app.run("extension.disable", serde_json::json!({"id": "assistant"})).is_ok()); + assert!(!offered(&app)); + assert_ne!(signature(&app), before); + } + const UNDO: Action = Keys { command: "edit.undo", fallback: (Key::Z, false) }; const REDO: Action = Keys { command: "edit.redo", fallback: (Key::Z, true) }; diff --git a/crates/assistant/src/agent.rs b/crates/assistant/src/agent.rs index 26e67b4b2d..91bb464feb 100644 --- a/crates/assistant/src/agent.rs +++ b/crates/assistant/src/agent.rs @@ -158,7 +158,19 @@ pub struct Agent { /// Delegations for the app to start ([`Agent::take_delegations`]). delegations: Vec, /// Threads' reports waiting for the assistant to be free ([`Agent::deliver`]). - reports: Vec<(String, String, String, bool)>, + reports: Vec, +} + +/// A thread's report waiting for the model, and the line the transcript shows for it, each cut +/// from the report as written so that what a cut says counts what the thread wrote. +struct Report { + thread: String, + label: String, + /// For the model: at most [`tools::MAX_RESULT`] characters. + text: String, + /// For the transcript: shorter, and saying when the thread failed. + note: String, + error: bool, } /// An agent thread on this computer: an ACP session that works in the background and takes @@ -262,7 +274,9 @@ impl Agent { let Some(t) = self.threads.iter_mut().find(|t| t.id == thread) else { return }; t.working = false; let label = t.agent.label.to_string(); - self.reports.push((thread.to_string(), label, tools::clip(&report, tools::MAX_RESULT), error)); + let failed = if error { " failed" } else { "" }; + let note = format!("{thread} ({label}){failed}: {}", tools::clip(&report, 600)); + self.reports.push(Report { thread: thread.to_string(), label, text: tools::clip(&report, tools::MAX_RESULT), note, error }); } /// A thread ended (stopped, closed, or its process exited): it takes no more follow-ups. @@ -280,8 +294,8 @@ impl Agent { let mut message = String::from( "(Not from the user: agent threads working in the background have reported. Tell the user briefly what came of it.)", ); - for (id, label, report, error) in std::mem::take(&mut a.reports) { - a.transcript.push(Entry::Note(Note::text(format!("{id} ({label}): {}", tools::clip(&report, 600))))); + for Report { thread: id, label, text: report, note, error } in std::mem::take(&mut a.reports) { + a.transcript.push(Entry::Note(Note::text(note))); let quoted = report.replace('&', "&").replace('<', "<").replace('>', ">"); let quoted = tools::bounded_json(&serde_json::json!({"report":quoted}), a.config.tool_output_token_limit); message.push_str(&format!( @@ -917,6 +931,7 @@ impl Agent { let State::Calls(q, _) = &mut self.state else { return }; let Some(call) = q.pop_front() else { return }; let permit = self.pending_policy.take().filter(|_| allow).map(Pending::allow); + let was_on = s.extensions().is_on(rustgis_engine::extensions::ASSISTANT.id); let (content, error, images) = if allow { match self.run_tool(s, &call, tokens, permit) { Ok((c, images)) => (c, false, images), @@ -927,6 +942,13 @@ impl Agent { }; let shown = if allow { content.clone() } else { "Declined".to_string() }; self.record(call, content, shown, error, images); + // A call that turned the AI Assistant off ends its reply: the calls after it aren't run. + if was_on && !s.extensions().is_on(rustgis_engine::extensions::ASSISTANT.id) { + let why = "Not run: an earlier call turned the AI Assistant off."; + while matches!(&self.state, State::Calls(q, _) if !q.is_empty()) { + self.record_front(why.to_string(), why.to_string(), true); + } + } } /// Takes the first waiting call off the queue with its result (and what the transcript shows). @@ -1152,6 +1174,18 @@ impl Agent { self.halt(Entry::Note(Note::new("Stopped.")), "Stopped by the user.", "Stopped by the user."); } + /// Ends everything that would go on by itself, keeping the conversation: the run stops, and + /// the agent threads are forgotten. Reports waiting for the model stay in the transcript and + /// aren't sent to it. + pub fn suspend(&mut self) { + self.stop(); + self.threads.clear(); + self.delegations.clear(); + for report in std::mem::take(&mut self.reports) { + self.transcript.push(Entry::Note(Note::text(report.note))); + } + } + /// Runs one step of the conversation. A bug in RustGIS that panics while reading a reply or /// running its calls ends the turn with an error in the transcript instead of taking the app /// down with it (the commands it runs are guarded the same way by `Session::run`). As there, diff --git a/crates/assistant/src/tests.rs b/crates/assistant/src/tests.rs index 9b52bf1060..d5839e6cef 100644 --- a/crates/assistant/src/tests.rs +++ b/crates/assistant/src/tests.rs @@ -1095,6 +1095,30 @@ fn always_allow_is_per_command_and_never_for_reserved_actions() { } } +/// A call that turns the AI Assistant off, approved, ends its reply: a call after it that needs +/// no approval isn't run, and says why. +#[test] +fn calls_after_one_turning_the_assistant_off_are_not_run() { + let mut s = sample(); + let mut a = Agent::new(cfg("openai"), &s); + let Step::Send(_) = a.ask("x", &s) else { panic!("expected a request") }; + let before = s.map().center_lonlat(); + let run = |command: &str, params: Value| json!({"command": command, "params": params}).to_string(); + let reply = json!({"choices": [{"message": {"role": "assistant", "content": null, "tool_calls": [ + {"id": "c0", "type": "function", "function": {"name": "run_command", "arguments": run("extension.disable", json!({"id": "assistant"}))}}, + {"id": "c1", "type": "function", "function": {"name": "run_command", "arguments": run("map.goToXY", json!({"lon": 2.35, "lat": 48.85, "scale": 5000000}))}} + ]}, "finish_reason": "tool_calls"}]}); + assert_eq!(a.receive(a.generation(), ok(reply), &mut s), Step::Confirm); + assert!(a.pending(&s).is_some_and(|p| p.0.starts_with("extension.disable"))); + // Nothing left to ask about or run: the results go back. + assert!(matches!(a.decide(true, false, &mut s), Step::Send(_))); + assert!(!s.extensions().is_on("assistant")); + let after = s.map().center_lonlat(); + assert!((after.x - before.x).abs() < 1e-9 && (after.y - before.y).abs() < 1e-9, "the map moved to {after:?}"); + let not_run = |e: &Entry| matches!(e, Entry::Tool { result, error: true, .. } if result.contains("turned the AI Assistant off")); + assert_eq!(a.transcript.iter().filter(|e| not_run(e)).count(), 1, "{:?}", a.transcript); +} + #[test] fn stopping_a_request_drops_its_message() { let s = sample(); @@ -3895,6 +3919,26 @@ fn the_assistant_hands_tasks_to_agent_threads_in_the_background() { assert_eq!(a.threads()[0].id, "claude-code-2", "thread ids aren't reused"); a.clear(); assert!(a.threads().is_empty() && a.take_delegations().is_empty()); + // Suspended (the app turned the assistant off): a report waiting stays in the transcript and + // is never sent. + assert!(matches!(a.ask("once more", &s), Step::Send(_))); + let call = calls("delegate", json!({"task": "w", "agent": "claude-code"})); + assert!(matches!(a.receive(a.generation(), ok(call), &mut s), Step::Send(_))); + let thread = a.threads()[0].id.clone(); + // A long report from a thread that failed: the transcript says it failed, and its cut counts + // what the thread wrote. + let long = "x".repeat(tools::MAX_RESULT + 100); + a.thread_report(&thread, long, true); + a.suspend(); + assert!(!a.busy() && a.threads().is_empty() && a.take_delegations().is_empty()); + assert!(a.deliver(&s).is_none(), "not sent to the model"); + let said = format!("{thread} (Claude Code) failed: "); + let cut = format!("(cut: {} characters in all)", tools::MAX_RESULT + 100); + assert!( + a.transcript.iter().any(|e| matches!(e, Entry::Note(n) if n.to_string().starts_with(&said) && n.to_string().ends_with(&cut))), + "{:?}", + a.transcript.last() + ); // The command line offers no agents: such a delegation is refused. let mut c = Agent::new(cfg("openai"), &s); let mut replies = VecDeque::from(vec![ok(calls("delegate", json!({"task": "z", "agent": "codex"}))), ok(say("Couldn't."))]); diff --git a/crates/engine/src/extensions.rs b/crates/engine/src/extensions.rs index df669539a8..e3abc0d844 100644 --- a/crates/engine/src/extensions.rs +++ b/crates/engine/src/extensions.rs @@ -25,12 +25,15 @@ pub struct Extension { pub name: &'static str, /// One sentence on what it adds. pub description: &'static str, - /// The caption of its own ribbon tab (`extension:`), or `None` for a group on the Plugins - /// tab. + /// The caption of its own ribbon tab (`extension:`), or `None` for one without a tab: + /// its buttons are at `place`, or in a group on the Plugins tab. pub tab: Option<&'static str>, + /// Where its buttons are, for one that adds them to RustGIS's own tabs (`Tab › Group`). + pub place: Option<&'static str>, /// Whether the desktop and web apps start with it on until the user says otherwise. pub default_on: bool, - /// The command ids it owns. + /// The command ids it owns: the engine's, and the front end's `ui.*` ones, which the front + /// end refuses while it is off. pub commands: &'static [&'static str], } @@ -42,6 +45,7 @@ pub const IMAGERY: Extension = Extension { name: "Imagery", description: "Ortho and reality mapping, georeferencing, image analysis and classification, deep learning, mensuration and hosted imagery, on a tab of its own.", tab: Some("Imagery"), + place: None, default_on: false, commands: &[ "imagery.workspace", @@ -67,8 +71,21 @@ pub const IMAGERY: Extension = Extension { ], }; +/// The AI Assistant: the chat pane, its buttons and the local agents it starts. The MCP server +/// (`rustgis-cli mcp` and the desktop app's MCP Relay), for agents the user runs, and +/// `rustgis-cli ask` are no part of it. +pub const ASSISTANT: Extension = Extension { + id: "assistant", + name: "AI Assistant", + description: "A chat pane that answers questions about your data and acts on the map, using the AI model you choose.", + tab: None, + place: Some("Analyze › AI"), + default_on: true, + commands: &["ui.pane.assistant"], +}; + /// Every extension, in the order the Extensions window lists them. -pub const ALL: &[Extension] = &[IMAGERY]; +pub const ALL: &[Extension] = &[IMAGERY, ASSISTANT]; /// The most entries the setting keeps (a hand-edited or hostile one can't grow without bound). const MAX_ENTRIES: usize = 256; @@ -222,7 +239,8 @@ mod tests { for e in ALL { assert!(e.id.chars().all(|c| c.is_ascii_lowercase() || c == '-'), "{}", e.id); for c in e.commands { - assert!(registry.iter().any(|s| s.id == *c), "{} owns {c}, which isn't a command", e.id); + // `ui.*` commands are the front end's, which checks them against its own. + assert!(c.starts_with("ui.") || registry.iter().any(|s| s.id == *c), "{} owns {c}, which isn't a command", e.id); assert_eq!(owner(c).map(|o| o.id), Some(e.id), "{c} is owned twice"); } } @@ -240,6 +258,23 @@ mod tests { assert!(chosen.is_on("imagery")); } + #[test] + fn the_assistant_is_on_until_the_user_turns_it_off() { + const { assert!(ASSISTANT.default_on) }; + let (apps, _) = State::from_setting(None); + assert!(apps.is_on("assistant")); + assert_eq!(apps.blocks("ui.pane.assistant"), None); + let (mut off, said) = State::from_setting(Some(r#"{"assistant": false}"#)); + assert_eq!(said, None); + let why = off.blocks("ui.pane.assistant").unwrap_or_default(); + assert!(why.contains("AI Assistant extension, which is off"), "{why}"); + // The relay is for agents the user runs: no extension owns it. + assert_eq!(off.blocks("ui.mcpRelay"), None); + assert!(off.set("assistant", true).is_ok()); + assert_eq!(off.blocks("ui.pane.assistant"), None); + assert!(off.to_setting().is_some_and(|t| t.contains("\"assistant\":true"))); + } + /// Clip, resample, mosaic, project and rasterize serve any raster (#2823): no extension owns them. #[test] fn general_raster_commands_are_in_no_extension() { diff --git a/crates/ui-egui/src/agentthreads.rs b/crates/ui-egui/src/agentthreads.rs index d49e660bec..ad2d0f709d 100644 --- a/crates/ui-egui/src/agentthreads.rs +++ b/crates/ui-egui/src/agentthreads.rs @@ -63,6 +63,11 @@ pub struct Threads { } impl Threads { + /// How many threads there are, working or waiting for a follow-up. + pub(crate) fn count(&self) -> usize { + self.runs.len() + } + /// Publish the shared approval setting synchronously to every live ACP session. pub(crate) fn set_auto(&self, auto: bool) { for t in &self.runs { diff --git a/crates/ui-egui/src/assistant.rs b/crates/ui-egui/src/assistant.rs index abb6a81b8f..13864c37ff 100644 --- a/crates/ui-egui/src/assistant.rs +++ b/crates/ui-egui/src/assistant.rs @@ -38,6 +38,8 @@ pub struct AssistantState { /// The message waiting is the input box's own draft (sent from the box, which keeps it until /// it goes): nothing to put back if it isn't sent. pub(crate) queued_from_box: bool, + /// Pictures that landed while the extension was off, to be said once. + pub(crate) late_pictures: usize, /// The request out: its generation and where its response lands. pub(crate) inflight: Option<(u64, Reply)>, /// The pieces of the request out's reply, as they stream in (desktop). @@ -631,6 +633,11 @@ fn end_threads(app: &mut RustGisApp) { /// Carries out what the agent asked for. pub(crate) fn follow(app: &mut RustGisApp, step: Step, ctx: &egui::Context) { app.map.invalidate(); + // A command it ran, approved, may have turned its own extension off: nothing more is sent, + // and the next frame stops the run. + if !app.session.extensions().is_on(rustgis_engine::extensions::ASSISTANT.id) { + return; + } if let Step::Retry(after) = step { let generation = app.assistant.agent.as_ref().map_or(0, Agent::generation); app.assistant.retry = Some((generation, web_time::Instant::now() + after)); @@ -662,13 +669,77 @@ fn with_agent(app: &mut RustGisApp, f: impl FnOnce(&mut Agent, &mut rustgis_engi Some(step) } +/// The AI Assistant extension was turned off: everything it would still do on its own stops +/// (the run, a message waiting to be sent, the agent threads, a sign-in under way), and the +/// conversation is kept for when it's on again. A chat request already sent may still reach its +/// provider; its reply is dropped. A model list under way is kept and applied when it's on again; +/// a sign-in is cancelled. Says what happened, when there was anything to say. +pub(crate) fn turned_off(app: &mut RustGisApp) { + let busy = app.assistant.busy(); + #[cfg(not(target_arch = "wasm32"))] + let threads = app.assistant.threads.count(); + #[cfg(target_arch = "wasm32")] + let threads = 0; + // Dropping a sign-in stops its callback server, so it can't finish while off. + #[cfg(not(target_arch = "wasm32"))] + let signing_in = app.assistant.login.take().is_some(); + #[cfg(target_arch = "wasm32")] + let signing_in = false; + // A message not sent yet goes back to the message box. + unqueue(&mut app.assistant); + if let Some(agent) = app.assistant.agent.as_mut() { + agent.suspend(); + } + drop_request(&mut app.assistant); + app.assistant.always = false; + end_threads(app); + let chat = app.assistant.agent.as_ref().is_some_and(|a| !a.transcript.is_empty()) + || !app.assistant.input.trim().is_empty() + || app.assistant.pictures.any(); + let mut said = Vec::new(); + if busy { + said.push(tl!("The AI Assistant's running request was stopped; what it had already done stays.").to_string()); + } + if threads > 0 { + said.push(crate::i18n::fmt("Agent threads stopped: {n}.", &[("n", &threads.to_string())])); + } + if signing_in { + said.push(tl!("The ChatGPT sign-in under way was cancelled.").to_string()); + } + if chat { + said.push(tl!("The AI Assistant's conversation is kept until RustGIS closes: turn the extension on again to see it.").to_string()); + } + // Still running: for agents the user runs, which the extension doesn't cover. + #[cfg(not(target_arch = "wasm32"))] + if app.relay.is_some() || app.file_bridge.is_some() { + said.push( + tl!("Agents on this computer can still control RustGIS: that isn't part of the extension. Click its status in the status bar to stop it.") + .to_string(), + ); + } + if !said.is_empty() { + app.session.notify(said.join(" "), false); + } +} + /// Per-frame: responses that arrived, a message queued by a command, and settings to save. pub(crate) fn poll(app: &mut RustGisApp, ctx: &egui::Context) { + // While the extension is off nothing is sent or run: what is already on its way (a model + // list, a picture being read) waits for it to be on again. Keys and settings are still kept. + let on = app.session.extensions().is_on(rustgis_engine::extensions::ASSISTANT.id); + let late = std::mem::take(&mut app.assistant.late_pictures); + if late > 0 { + let said = crate::i18n::fmt("The AI Assistant is off. Pictures not attached: {n}.", &[("n", &late.to_string())]); + app.session.notify(said, false); + } #[cfg(not(target_arch = "wasm32"))] poll_keys(app, ctx); #[cfg(not(target_arch = "wasm32"))] - poll_sign_in(app, ctx); - if app.assistant.catalog_pending + if on { + poll_sign_in(app, ctx); + } + if on + && app.assistant.catalog_pending && let Some(cfg) = app.assistant.agent.as_ref().map(|a| a.config.clone()) { list_models(app, &cfg, ctx); @@ -680,6 +751,9 @@ pub(crate) fn poll(app: &mut RustGisApp, ctx: &egui::Context) { save_config(app, &cfg, ctx); } } + if !on { + return; + } // Pictures read off the frame are taken in here, not only by the desktop composer, so a // message waiting for one goes even while no composer is drawn. if crate::assistantpictures::take_read(app) { diff --git a/crates/ui-egui/src/assistantpane.rs b/crates/ui-egui/src/assistantpane.rs index 74bf210c1a..3a1179774e 100644 --- a/crates/ui-egui/src/assistantpane.rs +++ b/crates/ui-egui/src/assistantpane.rs @@ -1376,6 +1376,72 @@ pub(crate) mod tests { app } + /// Turned off as its extension with a run under way, through the app's own frame: the run + /// stops, the conversation and the message waiting are kept and said, and nothing is sent + /// until it is on again. + #[test] + fn turning_the_extension_off_stops_a_run_keeps_the_conversation_and_sends_nothing() { + let mut app = RustGisApp::with_sample(); + let sent = std::sync::Arc::new(std::sync::Mutex::new(0)); + let count = sent.clone(); + app.services.http = Some(Box::new(move |_, _| *count.lock().unwrap() += 1)); + let mut config = Config::from_env("custom"); + config.base_url = "https://example.test/v1".into(); + config.model = "test".into(); + let mut agent = Agent::new(config, &app.session); + let request = agent.ask("Zoom to Tokyo", &app.session); + assert!(agent.busy()); + app.assistant.inflight = Some((agent.generation(), crate::Slot::default())); + app.assistant.agent = Some(agent); + app.assistant.loaded = true; + let ctx = egui::Context::default(); + let frame = |app: &mut RustGisApp| { + let mut output = ctx.run_ui(egui::RawInput::default(), |ui| app.logic(ui.ctx())); + output.textures_delta.clear(); + }; + frame(&mut app); + let said = |app: &RustGisApp| -> Vec { + app.session.notices.iter().filter(|n| n.text.contains("AI Assistant")).map(|n| n.text.clone()).collect() + }; + assert_eq!(said(&app), Vec::::new()); + // A message asked for and not sent yet. + app.run("ui.pane.assistant", serde_json::json!({"ask": "Label the cities"})).unwrap(); + + app.run("extension.disable", serde_json::json!({"id": "assistant"})).unwrap(); + // A step that follows the command turning it off (an approved one of its own) isn't sent. + crate::assistant::follow(&mut app, request, &ctx); + // A model list due waits too. + app.assistant.catalog_pending = true; + frame(&mut app); + frame(&mut app); + let agent = app.assistant.agent.as_ref().unwrap(); + assert!(!agent.busy()); + let kept = agent.transcript.len(); + assert!(kept > 0); + assert!(app.assistant.inflight.is_none() && app.assistant.queued.is_none()); + assert_eq!(app.assistant.input, "Label the cities"); + assert!(app.ui.right_open.is_empty()); + let notices = said(&app); + assert_eq!(notices.len(), 1, "{notices:?}"); + assert!(notices[0].contains("running request was stopped") && notices[0].contains("conversation is kept"), "{notices:?}"); + assert_eq!(*sent.lock().unwrap(), 0); + // Pictures picked before, landing now, are counted in one notice rather than attached; a + // cancelled pick isn't one. + for name in ["map.png", "sketch.png", ""] { + app.open_picked(&format!("{}{name}", crate::ASSISTANT_PICK), &[0]).unwrap(); + } + frame(&mut app); + let late: Vec = said(&app).into_iter().filter(|n| n.contains("Pictures not attached")).collect(); + assert_eq!(late.len(), 1, "{late:?}"); + assert!(late[0].ends_with("not attached: 2."), "{late:?}"); + assert!(!app.assistant.pictures.any() && !app.assistant.pictures.reading()); + + app.run("extension.enable", serde_json::json!({"id": "assistant"})).unwrap(); + frame(&mut app); + assert_eq!(app.assistant.agent.as_ref().unwrap().transcript.len(), kept); + assert_eq!(*sent.lock().unwrap(), 1); + } + /// Clicking Stop drops the old UI backoff deadline and streamed chunks before another run. #[test] fn stop_button_clears_retry_deadline_and_chunks() { diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 56dd706e6e..19f41e1d0c 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -218,7 +218,9 @@ fn header_branding(ui: &mut Ui, app: &mut RustGisApp, right: f32, tokens: &Token /// Fits as many toolbar items as the header has room for. At the narrowest width, search joins the overflow. fn quick_access(ui: &mut Ui, app: &mut RustGisApp, right: f32, separate_search: bool) { - let pinned = app.ui.quick_access.clone(); + // A pinned command of an extension that is off stays pinned, and isn't shown (#1752). + let mut pinned = app.ui.quick_access.clone(); + pinned.retain(|id| !crate::extensionsui::hidden(app, id)); let mut items = vec![ ("project.new", "new", "New project"), ("ui.open", "open", "Open project"), @@ -1501,6 +1503,10 @@ pub fn command_search(app: &mut RustGisApp, ctx: &egui::Context) { if !command_available(id, cfg!(target_arch = "wasm32")) { continue; } + // A pane of an extension that is off isn't offered (#1752). + if crate::extensionsui::hidden(app, id) { + continue; + } // Only a shell with a touch interface (a phone's) has one to go back to. if id == "ui.touchInterface" && app.touch.is_none() { continue; @@ -1730,6 +1736,7 @@ pub fn about(app: &mut RustGisApp, ctx: &egui::Context) { .keymap .grouped() .into_iter() + .filter(|(command, ..)| !crate::extensionsui::hidden(app, command)) .map(|(command, params, keys)| { let keys: Vec = keys.into_iter().map(|c| c.shown(ctx)).collect(); (keys.join(" / "), crate::keymap::label(app, command, params)) diff --git a/crates/ui-egui/src/extensionsui.rs b/crates/ui-egui/src/extensionsui.rs index cbd56055a3..1eff5c528e 100644 --- a/crates/ui-egui/src/extensionsui.rs +++ b/crates/ui-egui/src/extensionsui.rs @@ -1,13 +1,13 @@ //! The Extensions window (Plugins › Extensions, #1752): every extension with a switch to turn it //! on or off, and where to find it when it's on. What the user chose is the `extensions` //! setting: read at start, written whenever it changes (by the window, command search, a script -//! or the command line in the app alike). +//! or the command line in the app alike). The panes of an extension that is off are closed. use egui::{Align2, vec2}; use serde_json::json; -use crate::RustGisApp; use crate::theme::Tokens; +use crate::{RightPane, RustGisApp}; use rustgis_engine::extensions; /// The setting the choices are kept in. @@ -31,13 +31,33 @@ pub fn load(app: &mut RustGisApp) { app.extensions.saved = Some(app.session.extensions().clone()); } -/// Writes the choices when they changed since they were last written. +/// Whether command `id` belongs to an extension that is off: no button, menu item or search +/// row offers it. +pub(crate) fn hidden(app: &RustGisApp, id: &str) -> bool { + app.session.extensions().blocks(id).is_some() +} + +/// Closes the panes of extensions that are off: one open as it was turned off, or brought back +/// by a saved pane set. +pub(crate) fn close_panes(app: &mut RustGisApp) { + if !app.session.extensions().is_on(extensions::ASSISTANT.id) { + app.ui.close_right(RightPane::Assistant); + } +} + +/// Each frame: follows an extension turned off (its panes close and its work stops), and writes +/// the choices when they changed since they were last written. pub fn persist(app: &mut RustGisApp) { + close_panes(app); + let assistant = extensions::ASSISTANT.id; let now = app.session.extensions(); if app.extensions.saved.as_ref() == Some(now) { return; } let now = now.clone(); + if !now.is_on(assistant) && app.extensions.saved.as_ref().is_some_and(|was| was.is_on(assistant)) { + crate::assistant::turned_off(app); + } // A setting that couldn't be read is never written over (said when it was read). if let (Some(save), Some(text)) = (&app.services.save_pref, now.to_setting()) { save(SETTING, &text); @@ -50,10 +70,12 @@ fn set(app: &mut RustGisApp, id: &str, on: bool) { match app.run("extension.enable", json!({"id": id, "enabled": on})) { Ok(_) => { let name = extensions::get(id).map_or(id, |e| e.name); - let text = if on { - crate::i18n::fmt("{name} is on.", &[("name", tl_raw!(name))]) - } else { - crate::i18n::fmt("{name} is off: its tab and commands are hidden.", &[("name", tl_raw!(name))]) + let tab = extensions::get(id).is_some_and(|e| e.tab.is_some()); + let name = [("name", tl_raw!(name))]; + let text = match (on, tab) { + (true, _) => crate::i18n::fmt("{name} is on.", &name), + (false, true) => crate::i18n::fmt("{name} is off: its tab and commands are hidden.", &name), + (false, false) => crate::i18n::fmt("{name} is off: its buttons and commands are hidden.", &name), }; app.extensions.message = Some((true, text)); } @@ -80,7 +102,7 @@ pub fn show(app: &mut RustGisApp, ctx: &egui::Context) { .show(ctx, |ui| { ui.label( egui::RichText::new(tl!( - "Extensions are optional parts of RustGIS: nothing to download. Turn one off to hide its tab and commands." + "Extensions are optional parts of RustGIS: nothing to download. Turn one off to hide its buttons and commands." )) .size(12.0) .color(t.text_dim), @@ -125,12 +147,16 @@ fn row(app: &mut RustGisApp, ui: &mut egui::Ui, t: &Tokens, e: &extensions::Exte } }); ui.label(egui::RichText::new(tl_raw!(e.description)).size(12.0)); - let place = match e.tab { - Some(caption) => crate::i18n::fmt("On its own tab, {tab}.", &[("tab", tl_raw!(caption))]), - None => tl!("On the Plugins tab.").to_string(), + let place = match (e.tab, e.place) { + (Some(caption), _) => crate::i18n::fmt("On its own tab, {tab}.", &[("tab", tl_raw!(caption))]), + (None, Some(place)) => crate::i18n::fmt("In {place}.", &[("place", &crate::i18n::location(place))]), + (None, None) => tl!("On the Plugins tab.").to_string(), + }; + // An extension of one command is its pane's switch: no count to give. + let said = match e.commands.len() { + 1 => place, + n => crate::i18n::fmt("{place} {count} commands.", &[("place", &place), ("count", &n.to_string())]), }; - let count = e.commands.len().to_string(); - let said = crate::i18n::fmt("{place} {count} commands.", &[("place", &place), ("count", &count)]); ui.label(egui::RichText::new(said).size(11.5).color(t.text_dim)); if on != was { set(app, e.id, on); @@ -235,6 +261,58 @@ mod tests { assert!(prefs.lock().unwrap().iter().any(|(k, v)| k == SETTING && v.contains("\"imagery\":true"))); } + /// What was said of the AI Assistant, refusals (errors) apart. + fn assistant_notices(app: &RustGisApp) -> Vec { + app.session.notices.iter().filter(|n| !n.error && n.text.contains("AI Assistant")).map(|n| n.text.clone()).collect() + } + + #[test] + fn turning_the_assistant_off_closes_its_pane_refuses_it_and_is_saved() { + let prefs = Arc::new(Mutex::new(Vec::new())); + let mut app = app_with_prefs(&prefs); + load(&mut app); + let offered = |app: &RustGisApp| crate::shortcutui::can_customize(app, "ui.pane.assistant"); + // On until the user says otherwise. + assert!(offered(&app)); + app.run("ui.pane.assistant", json!(null)).unwrap(); + app.run("ui.paneSet", json!({"save": "with chat"})).unwrap(); + + set(&mut app, "assistant", false); + persist(&mut app); + assert!(app.extensions.message.as_ref().is_some_and(|(ok, said)| *ok && said.contains("its buttons and commands are hidden"))); + assert!(!app.ui.right_open.contains(&RightPane::Assistant)); + assert!(!offered(&app)); + for params in [json!(null), json!({"ask": "hello"}), json!({"close": true})] { + let why = app.run("ui.pane.assistant", params).unwrap_err(); + assert!(why.contains("AI Assistant extension, which is off"), "{why}"); + } + assert_eq!(app.assistant.queued, None); + // A saved pane set doesn't bring the pane back. + app.run("ui.paneSet", json!({"load": "with chat"})).unwrap(); + close_panes(&mut app); + assert!(!app.ui.right_open.contains(&RightPane::Assistant)); + // No conversation: nothing to say beyond the window's own line. + assert_eq!(assistant_notices(&app), Vec::::new()); + + // A shell's menus and shortcut cache are built again. + let off = app.shortcuts_fingerprint(); + app.run("extension.enable", json!({"id": "assistant"})).unwrap(); + assert_ne!(app.shortcuts_fingerprint(), off); + app.run("extension.disable", json!({"id": "assistant"})).unwrap(); + persist(&mut app); + + let saved = prefs.lock().unwrap().iter().rev().find(|(k, _)| k == SETTING).map(|(_, v)| v.clone()).unwrap(); + assert!(saved.contains("\"assistant\":false"), "{saved}"); + let mut again = app_with_prefs(&prefs); + load(&mut again); + assert!(again.run("ui.pane.assistant", json!(null)).is_err()); + again.run("extension.enable", json!({"id": "assistant"})).unwrap(); + persist(&mut again); + assert!(offered(&again)); + again.run("ui.pane.assistant", json!(null)).unwrap(); + assert_eq!(again.ui.right, Some(RightPane::Assistant)); + } + #[test] fn show_me_opens_an_extensions_tab_for_its_commands() { let mut app = RustGisApp::with_sample(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 6f2e680bd0..d4cd2bf854 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1712,10 +1712,17 @@ impl RustGisApp { widgets::enabled(self, command) } + /// Whether `command` belongs to an extension that is off, so that a menu offering it leaves + /// it out. + pub fn command_hidden(&self, command: &str) -> bool { + extensionsui::hidden(self, command) + } + /// A fingerprint of the keymap's key combinations and what they run: cheap to take every /// frame (no allocation), it changes when a shortcut is added, removed or rebound (to - /// another key or another command), or Command Search opens or closes, so a caller can - /// rebuild [`RustGisApp::command_keys`] only then. + /// another key or another command), Command Search opens or closes, or an extension is + /// turned on or off, so a caller can rebuild [`RustGisApp::command_keys`], or a menu, only + /// then. pub fn shortcuts_fingerprint(&self) -> u64 { use std::hash::{Hash, Hasher}; let mut h = std::collections::hash_map::DefaultHasher::new(); @@ -1741,6 +1748,9 @@ impl RustGisApp { self.ui.keymap.bindings.len().hash(&mut h); // Command Search takes the number keys while it is open. self.ui.command_search.is_some().hash(&mut h); + for e in rustgis_engine::extensions::ALL { + self.session.extensions().is_on(e.id).hash(&mut h); + } h.finish() } @@ -2527,7 +2537,11 @@ impl RustGisApp { if let Some(name) = name.strip_prefix(ASSISTANT_PICK) { // An answer with no name is a cancelled picker. if !name.is_empty() { - assistantpictures::received(self, name, bytes.to_vec()); + if extensionsui::hidden(self, "ui.pane.assistant") { + self.assistant.late_pictures += 1; + } else { + assistantpictures::received(self, name, bytes.to_vec()); + } } return Ok(Value::Null); } @@ -3987,6 +4001,10 @@ impl RustGisApp { /// Runs a `ui.*` command: panes, dialogs and the app's own settings. fn run_ui(&mut self, id: &str, p: &Value) -> Result { + // A pane of an extension that is off says so, as its other commands do (#1752). + if let Some(why) = self.session.extensions().blocks(id) { + return Err(why); + } // A pane's command toggles it; `{"close": true}` closes it, in view or not (a tab's ✕), // whatever else the command is given (SQL to run, a question to ask). if p.get("close").and_then(Value::as_bool) == Some(true) && panes::close_pane_of(self, id) { @@ -7086,6 +7104,9 @@ impl RustGisApp { if ctx.current_pass_index() == 0 { self.frame_start = Some(web_time::Instant::now()); } + // An extension turned off while the last frame was drawn stops its work first: the AI + // Assistant's agent threads lose their relay access before the relay runs anything. + extensionsui::persist(self); // The MCP relay: what attached agents sent runs here, on this session, before the frame // draws (Session lives on this thread; the listener only queues messages). #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index 4bd3b2b3b2..bafa32dca8 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -33,6 +33,8 @@ const MIN_MAP_WIDTH: f32 = 320.0; const RIGHT_PANE_MAX: f32 = 640.0; pub fn show(app: &mut RustGisApp, ui: &mut Ui) { + // Before one is drawn, and so loads or asks its provider anything. + crate::extensionsui::close_panes(app); let t = Tokens::get(ui.ctx()); let frame = egui::Frame::NONE.fill(t.pane).inner_margin(egui::Margin::ZERO); app.ui.pane_rects = [None; 2]; diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index b83d307032..38573f6752 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -1864,19 +1864,22 @@ fn analysis_groups(app: &mut RustGisApp, ui: &mut Ui) { }); }); }); - group(ui, "AI", |ui| { - big( - ui, - app, - "assistant", - "AI\nAssistant", - "Ask about your data, or tell the assistant what to do with the map.", - "ui.pane.assistant", - Value::Null, - app.ui.right == Some(RightPane::Assistant), - false, - ); - }); + // The AI Assistant extension's (#1752). + if !crate::extensionsui::hidden(app, "ui.pane.assistant") { + group(ui, "AI", |ui| { + big( + ui, + app, + "assistant", + "AI\nAssistant", + "Ask about your data, or tell the assistant what to do with the map.", + "ui.pane.assistant", + Value::Null, + app.ui.right == Some(RightPane::Assistant), + false, + ); + }); + } group(ui, "Portal", |ui| { for (kind, icon, label, desc) in [ ("feature", "buffer", "Feature\nAnalysis", "Tools that analyse features."), @@ -2467,16 +2470,18 @@ fn view_tab(app: &mut RustGisApp, ui: &mut Ui) { ); }); col(ui, |ui| { - small( - ui, - app, - "assistant", - "AI Assistant", - "Show or hide the AI Assistant.", - "ui.pane.assistant", - Value::Null, - app.ui.right == Some(RightPane::Assistant), - ); + if !crate::extensionsui::hidden(app, "ui.pane.assistant") { + small( + ui, + app, + "assistant", + "AI Assistant", + "Show or hide the AI Assistant.", + "ui.pane.assistant", + Value::Null, + app.ui.right == Some(RightPane::Assistant), + ); + } small( ui, app, diff --git a/crates/ui-egui/src/shortcutui.rs b/crates/ui-egui/src/shortcutui.rs index d42c955de9..c798a5c4a6 100644 --- a/crates/ui-egui/src/shortcutui.rs +++ b/crates/ui-egui/src/shortcutui.rs @@ -108,7 +108,7 @@ fn rows(app: &RustGisApp, web: bool) -> Vec<(String, Value, String)> { rows.push((command.to_string(), params.clone(), keymap::label(app, command, params))); } } - rows.retain(|(id, _, _)| crate::chrome::command_available(id, web)); + rows.retain(|(id, _, _)| crate::chrome::command_available(id, web) && !crate::extensionsui::hidden(app, id)); let mut seen = std::collections::HashSet::new(); rows.retain(|(command, params, _)| seen.insert((command.clone(), params.to_string()))); rows.sort_by_cached_key(|a| a.2.to_lowercase()); @@ -118,6 +118,7 @@ fn rows(app: &RustGisApp, web: bool) -> Vec<(String, Value, String)> { /// Whether Command Search can open a matching row in the editor. pub fn can_customize(app: &RustGisApp, id: &str) -> bool { if !crate::chrome::command_available(id, cfg!(target_arch = "wasm32")) + || crate::extensionsui::hidden(app, id) || matches!(id, "edit.copy" | "edit.cut" | "edit.paste") || NEEDS_DIALOG.contains(&id) { diff --git a/crates/ui-egui/tests/smoke.rs b/crates/ui-egui/tests/smoke.rs index 03e99d6b9c..87ab13192f 100644 --- a/crates/ui-egui/tests/smoke.rs +++ b/crates/ui-egui/tests/smoke.rs @@ -714,6 +714,34 @@ fn process_is_on_the_analyze_tab_with_imagery_off_and_on() { } } +/// The AI Assistant extension's buttons and Command Search rows are there only while it is on +/// (#1752), and turning it off closes its pane. +#[test] +fn the_assistant_leaves_the_ribbon_and_command_search_while_its_extension_is_off() { + let mut h = harness(); + h.set_size(egui::vec2(2400.0, 860.0)); + for (on, command) in [(true, "extension.enable"), (false, "extension.disable"), (true, "extension.enable")] { + h.state_mut().run(command, json!({"id": "assistant"})).unwrap(); + for tab in ["Analyze", "View"] { + h.state_mut().run("ui.tab", json!({"tab": tab})).unwrap(); + h.run_steps(4); + assert_eq!(h.query_all_by_label("AI Assistant").count(), usize::from(on), "{tab}, on: {on}"); + } + // On the Home tab, only Command Search could name it. + h.state_mut().run("ui.tab", json!({"tab": "Home"})).unwrap(); + h.state_mut().ui.command_search = Some("ui.pane.assistant".into()); + h.run_steps(4); + assert_eq!(h.query_all_by_label_contains("AI Assistant").count() > 0, on, "Command Search, on: {on}"); + h.state_mut().ui.command_search = None; + h.run_steps(2); + } + h.state_mut().run("ui.pane.assistant", json!(null)).unwrap(); + h.run_steps(3); + h.state_mut().run("extension.disable", json!({"id": "assistant"})).unwrap(); + h.run_steps(3); + assert_eq!(h.state().ui.right, None); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn mcp_relay_early_start_wakes_queued_request_and_updates_ui() { diff --git a/docs/mcp.md b/docs/mcp.md index 3e8f867766..aeceae4893 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -77,7 +77,9 @@ Then ask, for example: 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. Ticking it +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 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 write files and use the network, without `--yes`. RustGIS remembers the choice and starts the diff --git a/docs/user-guide/assistant.md b/docs/user-guide/assistant.md index d3b6162ecc..74d29d884a 100644 --- a/docs/user-guide/assistant.md +++ b/docs/user-guide/assistant.md @@ -46,6 +46,24 @@ controls. From the command line, `rustgis-cli ask` sends one request (see [Command Line](../cli.md#asking-the-ai-assistant)). +## Turning the assistant off + +The AI Assistant is an [extension](index.md#extensions), on until you turn it off in +**Plugins › Extensions** (on a phone, in the desktop interface). While it is off, its pane, its +buttons and its entries in Command Search, the Keyboard Shortcuts editor, the Quick Access +Toolbar and the macOS menu bar are gone, and `ui.pane.assistant` is refused, from a shortcut you +gave it too. Turning it off stops a request that is running (what it had already done stays, with +Undo as usual; a request already under way may still finish at the provider, a ChatGPT one after +renewing its sign-in, and its reply is dropped), the agent threads it started and a ChatGPT +sign-in under way, and says so in a notice. The +conversation is kept until RustGIS closes and is there when you turn the extension on again. Its +settings, saved keys and sign-in are kept too. The desktop and web apps remember the choice. + +It doesn't cover agents and requests of your own: `rustgis-cli ask`, the +[MCP server](../mcp.md) (`rustgis-cli mcp`) and the desktop app's **MCP Relay** command run +either way. If agents were allowed to control RustGIS they still can, as the status bar shows; +click it there to stop them. + ## Attaching pictures A picture can go with a message: a map whose style you want, a screenshot of something that diff --git a/docs/user-guide/index.md b/docs/user-guide/index.md index 3208c9759a..c673b4afa0 100644 --- a/docs/user-guide/index.md +++ b/docs/user-guide/index.md @@ -178,17 +178,21 @@ Extensions are optional parts of RustGIS that you turn on or off. Unlike a [plugin](../plugins.md), an extension ships with RustGIS: there is nothing to download or install. **Plugins › Extensions** opens the Extensions window, which lists each extension with a switch, what it adds and where it shows. An extension with a tab of its own adds that tab after Help -(before plugins' own tabs) while it is on; one without a tab adds a group to the Plugins tab. +(before plugins' own tabs) while it is on; one without a tab adds its buttons to RustGIS's own +tabs, or a group to the Plugins tab. | Extension | Default | Adds | | --- | --- | --- | | **Imagery** (`imagery`) | Off | The Imagery tab: Ortho Mapping, Reality Mapping, Alignment (Georeference), Image Analysis, Image Classification (with Deep Learning Tools), Imagery Sharing, Mensuration and Imagery Tools (Indices, Pixel Editor), and their commands (`imagery.*`, `dl.*`, and the `raster.*` commands those groups run). Process (clip and resample a raster), Mosaic Rasters, Project Raster and Polygons to Raster aren't part of it and always run | - -While an extension is off, its tab, its buttons, its Workflows pane sections and its commands in -Command Search and the AI Assistant's command search are hidden. Its commands are refused with a -message naming the extension, whoever runs them: a script, a model, the command line, Python or -the assistant. Hiding the extension's tab in Settings › Customize › Ribbon only hides the tab; the -commands still run. +| **AI Assistant** (`assistant`) | On | The [AI Assistant](assistant.md) pane, with its buttons in Analyze › AI and View › Windows (`ui.pane.assistant`). The [MCP server](../mcp.md) (`rustgis-cli mcp`, and the desktop app's MCP Relay) and `rustgis-cli ask` aren't part of it and run either way | + +While an extension is off, its tab, its pane, its buttons, its Workflows pane sections and its +commands in Command Search, the Keyboard Shortcuts editor, the Quick Access Toolbar and the AI +Assistant's command search are hidden. Its commands are refused with a message naming the +extension, whoever runs them: a shortcut, a script, a model, the command line, Python or the +assistant. Shortcuts and Quick Access buttons you gave them are kept and come back with it. +Hiding the extension's tab in Settings › Customize › Ribbon only hides the tab; the commands still +run. The desktop and web apps start each extension at its default and remember your choices (the `extensions` setting). A setting saved by a newer RustGIS that names extensions this version