diff --git a/crates/assistant/src/tests.rs b/crates/assistant/src/tests.rs index cdc7803ba7..78ffecbea4 100644 --- a/crates/assistant/src/tests.rs +++ b/crates/assistant/src/tests.rs @@ -993,6 +993,23 @@ fn steps_are_bounded_and_stop_works() { assert!(!a.transcript.iter().any(|e| matches!(e, Entry::Assistant(t) if t == "late"))); } +/// An approval says when the SQL it shows has secrets taken out, which a marker in the text +/// doesn't always show (a secret setting is emptied to ''), and doesn't when it hasn't. +#[test] +fn an_sql_approval_says_when_its_text_has_secrets_taken_out() { + let mut s = sample(); + let mut hidden = |sql: &str| { + let mut a = Agent::new(cfg("openai"), &s); + a.ask("query", &s); + let query = call("q", "run_command", json!({"command": "sql.query", "params": {"sql": sql}})); + assert_eq!(a.receive(a.generation(), ok(query), &mut s), Step::Confirm, "{sql}"); + a.pending_review().map(|r| r.sql_hidden) + }; + assert_eq!(hidden("SET s3_secret_access_key = 'hunter2-secret'"), Some(true)); + assert_eq!(hidden("CREATE SECRET s (TYPE s3, KEY_ID 'a', SECRET 'b')"), Some(true)); + assert_eq!(hidden("SELECT name FROM 'cities.parquet' WHERE name = ''"), Some(false)); +} + #[test] fn missing_settings_are_reported() { let s = sample(); diff --git a/crates/engine/src/policy/plan.rs b/crates/engine/src/policy/plan.rs index b8eddfa503..d1619f9d3e 100644 --- a/crates/engine/src/policy/plan.rs +++ b/crates/engine/src/policy/plan.rs @@ -77,6 +77,9 @@ pub struct Review { pub explanation: (&'static str, Vec<(&'static str, String)>), /// Script line numbers and command ids needing review, for translated reason prefixes. pub lines: Vec<(usize, String)>, + /// The SQL shown has secrets taken out (a key, a `CREATE SECRET`'s options), which the query + /// still runs with: a card shows it, so the text isn't taken for all of it. + pub sql_hidden: bool, } pub(super) const MAX_NODES: usize = 1_000; const MAX_DEPTH: usize = 4; @@ -1338,12 +1341,20 @@ impl Plan { return Err("too long to show in full; run it yourself or ask for a smaller request".into()); } /// Lists every asking node and counts project-only edits without exposing private bindings. - fn shown(n: &Node, steps: &mut Vec, edits: &mut usize, details: &mut Vec) -> Result<(), String> { + fn shown( + n: &Node, + steps: &mut Vec, + edits: &mut usize, + details: &mut Vec, + sql_hidden: &mut bool, + ) -> Result<(), String> { if !n.display.targets.is_empty() || !n.display.places.is_empty() { details.push(n.display.clone()); } if n.effects.iter().any(|e| !matches!(e, Effect::Edits | Effect::History)) { - let mut line = format!("{} {}", n.id(), crate::project_log::review_params(&n.params)?); + let reviewed = crate::project_log::review_params(&n.params)?; + *sql_hidden |= ["sql", "query"].iter().any(|k| n.params.get(k).is_some_and(|raw| reviewed.get(k) != Some(raw))); + let mut line = format!("{} {}", n.id(), reviewed); if let Op::Plugin(_, p) = &n.op { line.push_str(&format!( " — {} {:?}, SHA-256 {}, permissions {:?}", @@ -1369,14 +1380,15 @@ impl Plan { *edits += 1; } for c in &n.children { - shown(c, steps, edits, details)?; + shown(c, steps, edits, details, sql_hidden)?; } Ok(()) } let mut steps = Vec::new(); let mut edits = 0; let mut details = Vec::new(); - shown(&self.root, &mut steps, &mut edits, &mut details)?; + let mut sql_hidden = false; + shown(&self.root, &mut steps, &mut edits, &mut details, &mut sql_hidden)?; let defaults = self.picked.as_ref().map(|(active, selection)| { let name = |id: &u32| { rustgis_data::diagnostics::Redacted::new( @@ -1414,7 +1426,7 @@ impl Plan { if bounded_size(&(&what, &why, &steps, &details, &defaults, &explanation, &lines), MAX_REVIEW).is_err() { return Err("too long to show in full; run it yourself or ask for a smaller request".into()); } - Ok(Review { what, why, steps, remember, edits, defaults, explanation, details, lines }) + Ok(Review { what, why, steps, remember, edits, defaults, explanation, details, lines, sql_hidden }) } } diff --git a/crates/ui-egui/src/approvalcard.rs b/crates/ui-egui/src/approvalcard.rs index 25c01254fb..7daf891373 100644 --- a/crates/ui-egui/src/approvalcard.rs +++ b/crates/ui-egui/src/approvalcard.rs @@ -3,6 +3,16 @@ use egui::{RichText, Ui}; use rustgis_engine::{Registry, policy::Review}; +/// The SQL a request runs, with the command that runs it, from the sanitized steps it asks about. +fn sql(review: &Review) -> Vec<(String, String)> { + let query = |step: &String| { + let (id, params) = step.split_once(' ').filter(|(id, _)| matches!(*id, "sql.query" | "layer.addSql"))?; + let params: serde_json::Value = serde_json::from_str(params).ok()?; + Some((id.to_string(), params.get("sql")?.as_str()?.to_string())) + }; + review.steps.iter().filter_map(query).collect() +} + /// Registry labels name operations without interpreting the request's script or parameters. fn operation(registry: &Registry, id: &str) -> String { registry.get(id).map_or_else(|| id.to_string(), |spec| tl_raw!(spec.label).to_string()) @@ -12,10 +22,12 @@ fn operation(registry: &Registry, id: &str) -> String { /// Callers bound the scroll area and keep their existing approval controls outside it. pub(crate) fn show(ui: &mut Ui, registry: &Registry, review: &Review) { ui.push_id((&review.what, &review.steps, &review.defaults, &review.lines), |ui| { + let queries = sql(review); let mut operations = Vec::new(); - for id in review.details.iter().map(|d| &d.operation).chain(review.lines.iter().map(|(_, id)| id)) { - if !id.is_empty() && !operations.contains(id) { - operations.push(id.clone()); + let asked = review.details.iter().map(|d| &d.operation).chain(review.lines.iter().map(|(_, id)| id)).cloned(); + for id in asked.chain(queries.iter().map(|(id, _)| id.clone())) { + if !id.is_empty() && !operations.contains(&id) { + operations.push(id); } } let actions = if operations.is_empty() { @@ -40,6 +52,15 @@ 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 !queries.is_empty() && review.sql_hidden { + ui.label(RichText::new(tl!("Secret values in this query are hidden here, but the query 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/assistant.rs b/crates/ui-egui/src/assistant.rs index 026a51b973..e5ee220a33 100644 --- a/crates/ui-egui/src/assistant.rs +++ b/crates/ui-egui/src/assistant.rs @@ -83,6 +83,8 @@ pub struct AssistantState { pub(crate) history_pos: Option, /// "Allow for this conversation" in the approval card. pub(crate) always: bool, + /// The approval [`Self::always`] was ticked for. + pub(crate) always_for: Option, pub(crate) loaded: bool, /// Settings changed and not yet saved: they are saved once no settings field is being typed in. pub(crate) unsaved: bool, @@ -1076,6 +1078,78 @@ fn send_from(app: &mut RustGisApp, text: String, from_box: bool, ctx: &egui::Con follow(app, step, ctx); } +/// A tool call in plain words: the command's name and the layer it is given, or what the tool does. +/// In logical order: the caller puts the line it goes into in display form once. +pub fn plain_call(app: &RustGisApp, name: &str, summary: &str) -> String { + use crate::i18n::fmt_raw; + use serde_json::Value; + const LONGEST: usize = 60; + // A subagent's calls are marked as its. + let (mark, summary) = match summary.strip_prefix("↳ ") { + Some(rest) => ("↳ ", rest), + None => ("", summary), + }; + let first = summary.split_whitespace().next().unwrap_or_default(); + // The summary's parameters, unless they were too long for it. + let args: Value = summary.split_once(' ').and_then(|(_, json)| serde_json::from_str(json).ok()).unwrap_or_default(); + let arg = |path: &str| { + let text = args.pointer(path).and_then(Value::as_str).map(str::trim).filter(|t| !t.is_empty()); + text.map(|t| rustgis_assistant::tools::clip(t, LONGEST)) + }; + let words = match name { + "run_command" => { + let label = match app.session.registry.get(first) { + // Without the dots of a label that opens a dialog: here it ran. + Some(spec) => tl_raw!(spec.label).trim_end_matches('…').to_string(), + None => first.to_string(), + }; + match arg("/layer") { + Some(layer) => format!("{label} · {layer}"), + None => label, + } + } + "run_tool" => match arg("/tool") { + Some(tool) => fmt_raw("Ran the tool {tool}", &[("tool", &tool)]), + None => tl_raw!("Ran a tool").to_string(), + }, + "run" => { + // The commands of each line, by name, as far as the summary goes. + let script = arg("/script").unwrap_or_default(); + let named: Vec = script + .lines() + .filter_map(|l| l.split_whitespace().next().filter(|w| !w.starts_with('#'))) + .map(|id| app.session.registry.get(id).map_or(id.to_string(), |s| tl_raw!(s.label).trim_end_matches('…').to_string())) + .collect(); + match named.as_slice() { + [] => tl_raw!("Ran several commands").to_string(), + names => fmt_raw("Ran {commands}", &[("commands", &rustgis_assistant::tools::clip(&names.join(", "), LONGEST))]), + } + } + "list_layers" => tl_raw!("Looked at the layers").to_string(), + "view_map" => tl_raw!("Looked at the map").to_string(), + "search_commands" => tl_raw!("Looked for a command").to_string(), + "search_tools" => tl_raw!("Looked for a tool").to_string(), + "describe_tool" => tl_raw!("Read about a tool").to_string(), + "read_features" => match arg("/layer").or_else(|| arg("/table")) { + Some(layer) => fmt_raw("Read features of {layer}", &[("layer", &layer)]), + None => tl_raw!("Read features").to_string(), + }, + "search_docs" | "read_doc" => tl_raw!("Read the user guide").to_string(), + "load_skill" => tl_raw!("Loaded a skill").to_string(), + "delegate" => tl_raw!("Handed a task to a subagent").to_string(), + _ => rustgis_assistant::tools::clip(summary, LONGEST), + }; + let query = if matches!(name, "search_commands" | "search_tools" | "search_docs") { + arg("/query") + } else { + arg("/tool").filter(|_| name == "describe_tool") + }; + match query { + Some(query) => format!("{mark}{words}: {query}"), + None => format!("{mark}{words}"), + } +} + /// An action waiting for the user's approval. #[derive(Clone)] pub struct Approval { @@ -1117,6 +1191,7 @@ pub fn stop(app: &mut RustGisApp) { if let Some(a) = app.assistant.agent.as_mut() { a.stop(); } + app.assistant.always = false; drop_request(&mut app.assistant); app.assistant.hold(); } diff --git a/crates/ui-egui/src/assistantpane.rs b/crates/ui-egui/src/assistantpane.rs index 2c13221779..f9586b6d57 100644 --- a/crates/ui-egui/src/assistantpane.rs +++ b/crates/ui-egui/src/assistantpane.rs @@ -35,26 +35,13 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { .unwrap_or_default(); let (r, _) = ui.allocate_exact_size(vec2(16.0, 16.0), egui::Sense::hover()); icons::paint(ui.painter(), r, "assistant", t.text_dim, t.accent); - let model_label = egui::Label::new(RichText::new(format!("{} · {}", tl!(label), model)).small().color(t.text_dim)) - .truncate() - .sense(egui::Sense::click()); - // Room for the two buttons; a long model name is cut short. - let w = (ui.available_width() - 2.0 * (26.0 + ui.spacing().item_spacing.x)).max(0.0); - if ui - .allocate_ui(vec2(w, 16.0), |ui| ui.add(model_label)) - .inner - .on_hover_text(tl!("The model answering; click to change it")) - .on_hover_cursor(egui::CursorIcon::PointingHand) - .clicked() - { - assistant::toggle_settings(app); - } + // The buttons first: the model's name is cut to the room they leave. ui.with_layout(Layout::right_to_left(Align::Center), |ui| { if crate::widgets::icon_button(ui, "settings", tl!("Assistant settings")).clicked() { assistant::toggle_settings(app); } let has_chat = !app.assistant.messages().is_empty(); - if has_chat && crate::widgets::icon_button(ui, "delete", tl!("New conversation")).clicked() { + if has_chat && crate::widgets::icon_button(ui, "new", tl!("New conversation")).clicked() { assistant::new_conversation(app); } if has_chat @@ -66,6 +53,17 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { { assistant::compact(app, &ctx); } + ui.with_layout(Layout::left_to_right(Align::Center), |ui| { + let label = RichText::new(format!("{} · {}", tl!(label), model)).small().color(t.text_dim); + if ui + .add(egui::Label::new(label).truncate().sense(egui::Sense::click())) + .on_hover_text(tl!("The model answering; click to change it")) + .on_hover_cursor(egui::CursorIcon::PointingHand) + .clicked() + { + assistant::toggle_settings(app); + } + }); }); }); }); @@ -141,15 +139,27 @@ fn provider_settings(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, cfg: &mut Co egui::ComboBox::from_id_salt("assistant_provider") .selected_text(tl!(current)) .width(180.0) + // Room for every provider and the headings over them. + .height(420.0) .show_ui(ui, |ui| { - for p in PRESETS { + // Grouped by who is paid: a plan, the provider for each request, or nobody (a server + // of the user's own, though one elsewhere may bill too). + let kinds: [(&str, fn(&provider::Preset) -> bool); 3] = [ + (tl!("With a plan you have"), |p| p.login), + (tl!("With an API key, billed by use"), |p| !p.login && !p.keyless), + (tl!("Your own server, or another address"), |p| !p.login && p.keyless), + ]; + for (kind, of) in kinds { // Signing in needs the browser and a server on this computer, and ollama.com // refuses web pages: the desktop app. - if !provider::usable_choice(p.id, cfg!(target_arch = "wasm32")) { - continue; - } - if ui.selectable_label(cfg.provider == p.id, tl!(p.label)).clicked() && cfg.provider != p.id { - assistant::choose_provider(app, cfg, p.id, ui.ctx()); + let usable = |p: &&provider::Preset| of(p) && provider::usable_choice(p.id, cfg!(target_arch = "wasm32")); + for (i, p) in PRESETS.iter().filter(usable).enumerate() { + if i == 0 { + ui.label(RichText::new(kind).small().color(t.text_dim)); + } + if ui.selectable_label(cfg.provider == p.id, tl!(p.label)).clicked() && cfg.provider != p.id { + assistant::choose_provider(app, cfg, p.id, ui.ctx()); + } } } }) @@ -444,10 +454,20 @@ fn local_agents_setting(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { tl!("No agents that speak ACP (Claude Code, Codex, Gemini CLI, GitHub Copilot CLI, Cursor, OpenCode, goose) were found on this computer.").to_string() } else { let names: Vec<&str> = found.iter().map(|(spec, _)| spec.label).collect(); - crate::i18n::fmt( - "Found: {names}. An agent works on this map through RustGIS's tools and with its own (web, scripts, files) in a folder of its own, kept in Documents › RustGIS › Agent work. It asks you before each action.", - &[("names", &names.join(", "))], - ) + let names = names.join(", "); + let names = [("names", names.as_str())]; + // "It asks you" isn't said beside the switch that turns asking off, when that is on. + if app.assistant.agents_auto { + crate::i18n::fmt( + "Found: {names}. An agent works on this map through RustGIS's tools and with its own (web, scripts, files) in a folder of its own, kept in Documents › RustGIS › Agent work.", + &names, + ) + } else { + crate::i18n::fmt( + "Found: {names}. An agent works on this map through RustGIS's tools and with its own (web, scripts, files) in a folder of its own, kept in Documents › RustGIS › Agent work. It asks you before each action.", + &names, + ) + } }; ui.label(RichText::new(note).small().color(t.text_dim)); if found.iter().any(|(spec, command)| { @@ -637,6 +657,11 @@ fn composer(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, busy: bool, ctx: &egu // An action waiting for approval comes first. if let Some(approval) = assistant::pending(app) { 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()); + } 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| { @@ -646,7 +671,7 @@ fn composer(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, busy: bool, ctx: &egu }); // Plugin commands, scripts and replacing the project are asked about every time. if *can_always { - ui.checkbox(&mut app.assistant.always, tl!("Allow such actions for this conversation")); + ui.checkbox(&mut app.assistant.always, tl!("Don't ask again for exactly this action")); } else { app.assistant.always = false; } @@ -773,7 +798,7 @@ fn transcript(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, ctx: &egui::Context return; } if app.assistant.messages().is_empty() { - 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; every change can be undone.")).color(t.text_dim)); + 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; for s in SUGGESTIONS { @@ -807,10 +832,10 @@ fn transcript(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, ctx: &egui::Context } Entry::Tool { name, summary, result, error } => { let (mark, col) = if *error { ("✗", t.red) } else { ("✓", t.green) }; - let head = format!("{mark} {}", summary.chars().take(90).collect::()); + let head = format!("{mark} {}", assistant::plain_call(app, name, summary)); // A header never wraps: it is cut to the room there is. Opened, it shows the whole call. let room = (ui.available_width() - ui.spacing().indent - ui.spacing().button_padding.x).max(0.0); - let head = egui::WidgetText::from(RichText::new(head).monospace().small().color(col)).into_galley( + let head = egui::WidgetText::from(RichText::new(crate::i18n::display(&head)).small().color(col)).into_galley( ui, Some(egui::TextWrapMode::Truncate), room, @@ -1321,6 +1346,75 @@ pub(crate) mod tests { ) } + /// Steps in words: the command's name and its layer, what a search was for, a subagent's + /// mark, and the call itself where its parameters were cut. + #[test] + fn steps_are_said_in_words() { + let app = RustGisApp::with_sample(); + let said = |name: &str, summary: &str| assistant::plain_call(&app, name, summary); + assert_eq!(said("run_command", r#"layer.visibility {"layer":"Rivers","visible":false}"#), "Visibility · Rivers"); + assert_eq!(said("run_command", "map.zoomIn {}"), "Fixed Zoom In"); + assert_eq!(said("run_command", "no.such {}"), "no.such"); + assert_eq!(said("read_features", r#"read_features {"layer":"Countries","limit":5}"#), "Read features of Countries"); + assert_eq!(said("read_features", r#"read_features {"table":"Stats"}"#), "Read features of Stats"); + assert_eq!(said("search_tools", r#"search_tools {"query":"buffer"}"#), "Looked for a tool: buffer"); + assert_eq!(said("describe_tool", r#"describe_tool {"tool":"clip"}"#), "Read about a tool: clip"); + assert_eq!(said("run_tool", r#"gp.run {"params":{},"tool":"buffer"}"#), "Ran the tool buffer"); + assert_eq!(said("list_layers", "↳ list_layers {}"), "↳ Looked at the layers"); + let script = serde_json::json!({"script": "# two\nmap.zoomIn {}\nlayer.visibility {\"layer\": \"Rivers\"}"}); + assert_eq!(said("run", &format!("run {script}")), "Ran Fixed Zoom In, Visibility"); + // Parameters cut short by the summary leave the name alone. + assert_eq!(said("read_features", r#"read_features {"layer":"Count…"#), "Read features"); + } + + /// An approval to remember is one action's: the box starts unticked for the next one. A query's + /// card shows its text without opening Details. + #[test] + fn the_next_approval_starts_unticked_and_a_query_shows_its_text() { + use egui_kittest::kittest::Queryable; + use serde_json::json; + let mut app = RustGisApp::with_sample(); + let config = + Config { provider: "custom".into(), base_url: "http://localhost:1/v1".into(), model: "m".into(), ..Config::from_env("custom") }; + let mut agent = Agent::new(config, &app.session); + agent.ask("ask", &app.session); + let query = |id: &str, sql: &str| { + json!({"id": id, "type": "function", "function": {"name": "run_command", + "arguments": json!({"command": "sql.query", "params": {"sql": sql}}).to_string()}}) + }; + let calls = [query("1", "SELECT 1 AS first"), query("2", "SELECT 2 AS second")]; + let body = + json!({"choices": [{"message": {"role": "assistant", "content": null, "tool_calls": calls}, "finish_reason": "tool_calls"}]}); + let body = body.to_string().into_bytes(); + agent.receive(agent.generation(), Ok(HttpResponse { status: 200, body, headers: vec![] }), &mut app.session); + app.assistant.agent = Some(agent); + app.assistant.loaded = true; + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(vec2(680.0, 600.0)).build_ui_state( + move |ui, app: &mut RustGisApp| { + if !fonts { + crate::theme::install_fonts(ui.ctx(), &[], None); + fonts = true; + ui.ctx().request_repaint(); + return; + } + let ctx = ui.ctx().clone(); + composer(app, ui, &Tokens::light(), true, &ctx); + }, + app, + ); + h.run_steps(3); + h.get_by_label("SELECT 1 AS first"); + assert!(h.query_by_label_contains("are hidden here").is_none(), "a query without secrets says nothing"); + h.get_by_label("Don't ask again for exactly this action").click(); + h.run_steps(3); + assert!(h.state().assistant.always); + h.get_by_label("Decline").click(); + h.run_steps(3); + h.get_by_label("SELECT 2 AS second"); + assert!(!h.state().assistant.always); + } + /// The actual Remember checkbox goes through the deferred save path and deletes the stored key. #[cfg(not(target_arch = "wasm32"))] #[test] @@ -1807,7 +1901,7 @@ pub(crate) mod tests { assert!(h.query_by_label_contains(text).is_some(), "missing overview context: {text}"); } assert!(h.query_by_label_contains("Starting active layer: Cities; selected layers: [Cities]").is_some()); - assert_eq!(h.query_by_label("Allow such actions for this conversation").is_some(), can_always); + assert_eq!(h.query_by_label("Don't ask again for exactly this action").is_some(), can_always); h.get_by_label("Details").click(); h.run(); h.get_by_label(&exact); diff --git a/crates/ui-egui/src/connectui.rs b/crates/ui-egui/src/connectui.rs index 0de308ebf8..7c0fadc723 100644 --- a/crates/ui-egui/src/connectui.rs +++ b/crates/ui-egui/src/connectui.rs @@ -264,6 +264,14 @@ fn details(app: &mut RustGisApp, ui: &mut egui::Ui) { bridge.set_full_access(full); } } + if full { + 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), + ); + } + 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()); diff --git a/crates/ui-touch/src/assistant.rs b/crates/ui-touch/src/assistant.rs index e3fbf1d6a7..77efd13bb0 100644 --- a/crates/ui-touch/src/assistant.rs +++ b/crates/ui-touch/src/assistant.rs @@ -64,7 +64,7 @@ pub(crate) struct Chat { /// The system's text field that was open as the extension was turned off: what it still sends /// is not taken, and said once. retired: Option, - /// The approval "Allow such actions for this conversation" is ticked for. + /// The approval "Don't ask again for exactly this action" is ticked for. always: Option, /// The approval card in sight, and when it came: its buttons take taps only after /// [`SETTLE`], so a tap meant for what was there before lands on nothing. @@ -264,7 +264,7 @@ fn doing(app: &RustGisApp) -> String { let last = messages.iter().rev().take_while(|e| !matches!(e, Entry::User(_))).find(|e| matches!(e, Entry::Tool { .. })); match last { Some(Entry::Tool { name, summary, error, .. }) if app.assistant.waiting() => { - let step = format!("{} {}", if *error { "✗" } else { "✓" }, plain(app, name, summary)); + let step = format!("{} {}", if *error { "✗" } else { "✓" }, assistant::plain_call(app, name, summary)); i18n::fmt("{step} · thinking…", &[("step", &step)]) } _ if app.assistant.waiting() => tl!("Thinking…").to_string(), @@ -276,42 +276,6 @@ fn doing(app: &RustGisApp) -> String { } } -/// A tool call in plain words: the command's name, or what the tool does. In logical order: the -/// caller puts the line it goes into in display form once. -fn plain(app: &RustGisApp, name: &str, summary: &str) -> String { - // A subagent's calls are marked as its. - let (mark, summary) = match summary.strip_prefix("↳ ") { - Some(rest) => ("↳ ", rest), - None => ("", summary), - }; - let first = summary.split_whitespace().next().unwrap_or_default(); - let words = match name { - "run_command" => match app.session.registry.get(first) { - // Without the dots of a label that opens a dialog: here it ran. - Some(spec) => tl_raw!(spec.label).trim_end_matches('…').to_string(), - None => first.to_string(), - }, - "run_tool" => { - let args: serde_json::Value = summary.split_once(' ').and_then(|(_, json)| serde_json::from_str(json).ok()).unwrap_or_default(); - match args.get("tool").and_then(serde_json::Value::as_str) { - Some(tool) => i18n::fmt_raw("Ran the tool {tool}", &[("tool", tool)]), - None => tl_raw!("Ran a tool").to_string(), - } - } - "list_layers" => tl_raw!("Looked at the layers").to_string(), - "view_map" => tl_raw!("Looked at the map").to_string(), - "search_commands" => tl_raw!("Looked for a command").to_string(), - "search_tools" => tl_raw!("Looked for a tool").to_string(), - "describe_tool" => tl_raw!("Read about a tool").to_string(), - "read_features" => tl_raw!("Read features").to_string(), - "search_docs" | "read_doc" => tl_raw!("Read the user guide").to_string(), - "load_skill" => tl_raw!("Loaded a skill").to_string(), - "delegate" => tl_raw!("Handed a task to a subagent").to_string(), - _ => summary.chars().take(60).collect(), - }; - format!("{mark}{words}") -} - /// The sheet: its heading, then the provider's settings until one is set up (or while they are /// asked for), else the conversation with its typing bar. pub(crate) fn show(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { @@ -359,7 +323,7 @@ fn heading(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, state: &mut Chat, set_ state.settings = !settings; } } - if has_chat && !settings && icon_button(ui, t, "delete", tl!("New conversation")) { + if has_chat && !settings && icon_button(ui, t, "new", tl!("New conversation")) { assistant::new_conversation(app); } }); @@ -403,7 +367,7 @@ fn conversation(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, state: &mut Chat) fn messages(app: &RustGisApp, ui: &mut Ui, t: &Tokens) { if app.assistant.messages().is_empty() && !app.assistant.waiting() { let hint = tl!( - "Ask about the map, or tell the Assistant what to do with it. It runs RustGIS's commands for you; every change it makes can be undone." + "Ask about the map, or tell the Assistant what to do with it. It runs RustGIS's commands for you. Changes to the project can be undone; files it writes can't." ); ui.label(RichText::new(hint).size(15.0).color(t.text_dim)); return; @@ -428,7 +392,8 @@ fn messages(app: &RustGisApp, ui: &mut Ui, t: &Tokens) { } Entry::Tool { name, summary, result, error } => { let (mark, ink) = if *error { ("✗", t.red) } else { ("✓", t.green) }; - let head = RichText::new(i18n::display(&format!("{mark} {}", plain(app, name, summary)))).size(14.0).color(ink); + let head = + RichText::new(i18n::display(&format!("{mark} {}", assistant::plain_call(app, name, summary)))).size(14.0).color(ink); egui::CollapsingHeader::new(head).id_salt(("touch_assistant_tool", i)).show(ui, |ui| { ui.label(RichText::new(summary).monospace().small()); let shown: String = result.chars().take(2000).collect(); @@ -463,7 +428,7 @@ fn messages(app: &RustGisApp, ui: &mut Ui, t: &Tokens) { } /// The approval waiting, as a card: what would run, Stop, Decline and Allow a finger's height, -/// and "Allow such actions for this conversation" where the action may be. `room` is the sheet's +/// and "Don't ask again for exactly this action" where the action may be. `room` is the sheet's /// body: the details scroll in what the card's other rows leave of it. /// /// Its widgets are its approval's own, and take taps only once it has been in sight a moment: a @@ -495,7 +460,7 @@ fn card(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, state: &mut Chat, approva } let width = ui.available_width(); let mut always = approval.can_always && state.always.as_ref() == Some(&approval.asked); - if approval.can_always && toggle_chip(ui, t, tl!("Allow such actions for this conversation"), width, always) && settled { + if approval.can_always && toggle_chip(ui, t, tl!("Don't ask again for exactly this action"), width, always) && settled { always = !always; state.always = always.then(|| approval.asked.clone()); } @@ -1041,7 +1006,7 @@ mod tests { let before = i18n::current(); i18n::set_current(i18n::Lang::from_code("fa").unwrap()); let logical = tl_raw!("Add PostGIS Layer").to_string(); - let words = plain(&held.app, "run_command", "pg.addLayer {}"); + let words = assistant::plain_call(&held.app, "run_command", "pg.addLayer {}"); let line = |step: &str| i18n::fmt("{step} · thinking…", &[("step", step)]); let (once, twice) = (line(&format!("✓ {words}")), line(&format!("✓ {}", i18n::display(&words)))); i18n::set_current(before); diff --git a/docs/user-guide/assistant.md b/docs/user-guide/assistant.md index d9f0166b7b..faf01bd2cf 100644 --- a/docs/user-guide/assistant.md +++ b/docs/user-guide/assistant.md @@ -21,7 +21,7 @@ actions outside the project. Check the tool results and map rather than relying model's reply. Commands that would read or write files, connect to an address on the internet, run a plugin, script, task or model, or replace the project wait for you: **Allow** or **Decline**. SQL queries also ask, because SQL can access files and the -network. **Allow such actions for this conversation** remembers the exact command and all +network. **Don't ask again for exactly this action** remembers the exact command and all its parameters, not general access to a file or server. Plugin commands and tools, user automation and project replacement ask every time.