From def6141322de566e1d7314f7dd3ab858a6472512 Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 26 Nov 2026 20:06:23 -0600 Subject: [PATCH 01/15] feat(mobile): the AI Assistant in a sheet of the touch interface, with a place on the bar The touch interface gets an Assistant sheet driven by the assistant module: the conversation drawn by RustGIS with tool calls in plain words, a typing bar that opens Android's own text field (a drawn box where there is none), Send and Stop, full and half heights, a strip with Stop while it works with the sheet lowered, and approvals as finger-sized cards. Nothing of it shows until a provider is set up: a Set Up the Assistant row in More opens a small settings form in the sheet. Once set up the bar is Add Data, Capture, Assistant, More, and Layers is a button at the map's top-right corner (on the bar while ModelBuilder covers the map); with the extension off there is nothing. Two fixes carried from #2991's review: a message waiting for the key or a picture is now the message being written plus a send-when-ready flag (`queued` is gone; a command's message waits apart and goes by itself), and `assistant::decide` carries the identity of the approval shown, which `Agent::decide` refuses once it is no longer the one waiting. --- apps/rustgis-mobile/README.md | 9 +- crates/assistant/src/agent.rs | 59 +- crates/assistant/src/lib.rs | 2 +- crates/assistant/src/tests.rs | 102 ++- crates/ui-egui/src/assistant.rs | 182 ++-- crates/ui-egui/src/assistantpane.rs | 152 ++-- crates/ui-egui/src/assistantpictures.rs | 85 +- crates/ui-egui/src/extensionsui.rs | 2 +- crates/ui-egui/src/lib.rs | 11 +- crates/ui-touch/src/assistant.rs | 1114 +++++++++++++++++++++++ crates/ui-touch/src/lib.rs | 185 +++- docs/user-guide/assistant.md | 13 + docs/user-guide/field-work.md | 6 +- 13 files changed, 1707 insertions(+), 215 deletions(-) create mode 100644 crates/ui-touch/src/assistant.rs diff --git a/apps/rustgis-mobile/README.md b/apps/rustgis-mobile/README.md index d516c685ee..f6a25707cc 100644 --- a/apps/rustgis-mobile/README.md +++ b/apps/rustgis-mobile/README.md @@ -94,8 +94,13 @@ Rust calls Java and never the other way: each frame the app collects what happen ## The touch interface -A phone starts in the touch interface: the map, a bar of four large buttons under it (Layers, Add -Data, Capture, More) and sheets that rise over the map. The Layers sheet switches between the +A phone starts in the touch interface: the map, with a Layers button at its top-right corner, a bar +of large buttons under it (Add Data, Capture, the AI Assistant once a provider is set up, More) and +sheets that rise over the map. Until then, **Set Up the Assistant** in the More sheet is the only +trace of the Assistant, and with its extension off there is none; its sheet types into Android's +own text field and stands full or half up, with a strip and Stop while it works +([AI Assistant › On a phone](../../docs/user-guide/assistant.md#on-a-phone)). `LAYERS_ON_THE_MAP` +in `crates/ui-touch/src/lib.rs` puts Layers back on the bar (five buttons). The Layers sheet switches between the project's maps and layouts when it has more than one, shows and hides layers, zooms to one and makes one the active layer; the More sheet has Full Extent, undo and redo, the project, the position, and **Use the Desktop Interface**, which brings back the ribbon and panes; **Touch diff --git a/crates/assistant/src/agent.rs b/crates/assistant/src/agent.rs index 168bda2f9b..73910e4b13 100644 --- a/crates/assistant/src/agent.rs +++ b/crates/assistant/src/agent.rs @@ -93,6 +93,19 @@ pub const INTERNAL_ERROR: &str = "RustGIS ran into an internal error while handl const PICTURES_AS_NAMES: &str = "This model doesn't read images: the pictures go to it as their names only. Pick a model that reads images to show them."; +/// An approval as the user was shown it ([`Agent::asking`]): the conversation, the run, the reply and the call it +/// is about (its place in the reply as well as its id, which a reply may repeat), and the +/// subagent's own when the call waiting is a subagent's. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct Asking { + conversation: u64, + generation: u64, + reply: u64, + place: usize, + call: String, + child: Option>, +} + pub struct Agent { pub config: Config, turns: Vec, @@ -103,6 +116,9 @@ pub struct Agent { last_context: String, /// Goes up when a run is stopped or cleared: responses to older requests are dropped. generation: u64, + /// The replies whose calls were queued so far: with the generation, it names the reply a + /// call waiting for approval came in ([`Asking`]), as call ids repeat from reply to reply. + replies: u64, /// Exact operations approved for the rest of this conversation and project generation. always: Vec, pending_policy: Option, @@ -204,6 +220,7 @@ impl Agent { steps: 0, last_context: String::new(), generation: 0, + replies: 0, always: Vec::new(), pending_policy: None, conversation: CONVERSATIONS.fetch_add(1, Ordering::Relaxed), @@ -423,6 +440,27 @@ impl Agent { self.pending_policy.as_ref().map(|p| p.review()) } + /// Which call [`Agent::pending`] is about, for [`Agent::decide`] to answer that one only: an + /// answer given to an approval no longer waiting (a second tap, a card drawn frames before) + /// is refused. + pub fn asking(&self) -> Option { + let State::Calls(q, done) = &self.state else { return None }; + let call = q.front()?; + let child = match &self.child { + Some(child) => Some(Box::new(child.asking()?)), + None if self.local_delegation(call) || self.pending_policy.is_some() => None, + None => return None, + }; + Some(Asking { + conversation: self.conversation, + generation: self.generation, + reply: self.replies, + place: done.len(), + call: call.id.clone(), + child, + }) + } + fn scope(&self) -> Scope { Scope::assistant(self.conversation, self.live.clone()) } @@ -888,6 +926,7 @@ impl Agent { self.state = State::Idle; return Step::Done; } + self.replies = self.replies.wrapping_add(1); self.state = State::Calls(calls.into(), Vec::new()); self.drain(s) } @@ -1126,10 +1165,14 @@ impl Agent { } } - /// The user's answer about [`Agent::pending`]; `always` approves calls like it for the rest of - /// the conversation. - pub fn decide(&mut self, allow: bool, always: bool, s: &mut Session) -> Step { - self.guard(|a| a.decide_unguarded(allow, always, s)) + /// The user's answer about the approval they were shown, `asked` ([`Agent::asking`]); `always` + /// approves calls like it for the rest of the conversation. `None`, and nothing done, when + /// that approval is no longer the one waiting: answered already, stopped, or another call's. + pub fn decide(&mut self, asked: &Asking, allow: bool, always: bool, s: &mut Session) -> Option { + if self.asking().as_ref() != Some(asked) { + return None; + } + Some(self.guard(|a| a.decide_unguarded(allow, always, s))) } fn decide_unguarded(&mut self, allow: bool, always: bool, s: &mut Session) -> Step { @@ -1137,7 +1180,8 @@ impl Agent { return Step::Done; } if let Some(child) = self.child.as_mut() { - let step = child.decide(allow, always, s); + // The child's own approval was checked with this one's ([`Agent::asking`]). + let step = child.decide_unguarded(allow, always, s); return self.after_child(step, s); } if allow @@ -1411,7 +1455,10 @@ pub fn run_blocking_with>( } Step::Confirm => { let allow = agent.pending(s).is_some_and(|(what, why, access)| confirm(&what, &why, access)); - agent.decide(allow, false, s) + match agent.asking() { + Some(asked) => agent.decide(&asked, allow, false, s).unwrap_or(Step::Done), + None => Step::Done, + } } Step::Retry(after) => { std::thread::sleep(after); diff --git a/crates/assistant/src/lib.rs b/crates/assistant/src/lib.rs index e092a7c590..f4f530598b 100644 --- a/crates/assistant/src/lib.rs +++ b/crates/assistant/src/lib.rs @@ -37,5 +37,5 @@ pub mod skills; mod tests; pub mod tools; -pub use agent::{Agent, Entry, Step}; +pub use agent::{Agent, Asking, Entry, Step}; pub use provider::{Api, Config, HttpRequest, HttpResponse, Note, PRESETS, Preset}; diff --git a/crates/assistant/src/tests.rs b/crates/assistant/src/tests.rs index 0f6597ca87..d3d5a66335 100644 --- a/crates/assistant/src/tests.rs +++ b/crates/assistant/src/tests.rs @@ -36,6 +36,12 @@ fn sample() -> Session { s } +/// Answers the approval waiting, as the user was shown it ([`Agent::asking`]). +fn answer(a: &mut Agent, allow: bool, always: bool, s: &mut Session) -> Step { + let asked = a.asking().expect("an approval is waiting"); + a.decide(&asked, allow, always, s).expect("the approval shown is the one waiting") +} + /// Deterministic provider defaults with a synthetic key and private routing enabled. fn cfg(provider: &str) -> Config { let p = preset(provider).unwrap_or(&PRESETS[0]); @@ -235,7 +241,7 @@ fn file_access_needs_approval() { assert_eq!(step, Step::Confirm); let (what, why, _) = a.pending(&s).unwrap_or_default(); assert!(what.starts_with("share.exportMap") && why.contains("files"), "{what} / {why}"); - let Step::Send(req) = a.decide(false, false, &mut s) else { panic!("expected a request") }; + let Step::Send(req) = answer(&mut a, false, false, &mut s) else { panic!("expected a request") }; assert!(!path.exists()); let b = body(&req); let tool_msg = b["messages"].as_array().and_then(|m| m.iter().find(|m| m["role"] == "tool").cloned()).unwrap_or(Value::Null); @@ -251,10 +257,10 @@ fn connection_management_requires_fresh_approval_but_can_run_in_app() { assert_eq!(a.receive(a.generation(), ok(call("first", "run_command", args.clone())), &mut s), Step::Confirm); assert!(s.connections.find("Approved connection").is_none()); assert!(!a.pending(&s).unwrap().2, "reserved commands cannot be allowed for the whole conversation"); - assert!(matches!(a.decide(true, true, &mut s), Step::Send(_))); + assert!(matches!(answer(&mut a, true, true, &mut s), Step::Send(_))); assert_eq!(s.connections.find("Approved connection").unwrap().kind, "s3"); assert_eq!(a.receive(a.generation(), ok(call("again", "run_command", args)), &mut s), Step::Confirm); - assert!(matches!(a.decide(false, false, &mut s), Step::Send(_))); + assert!(matches!(answer(&mut a, false, false, &mut s), Step::Send(_))); assert_eq!(s.connections.connections.len(), 1, "declining a repeat must leave the approved connection unchanged"); } @@ -305,12 +311,12 @@ fn connection_commands_require_fresh_approval_before_login_or_scripts() { assert!(s3::connection(&name).is_none(), "a pending call must not log in"); assert_eq!(s.map().name, map_name, "a script's earlier lines must wait too"); assert!(!a.pending(&s).unwrap().2, "connection operations cannot be allowed for the whole conversation"); - assert!(matches!(a.decide(false, false, &mut s), Step::Send(_))); + assert!(matches!(answer(&mut a, false, false, &mut s), Step::Send(_))); assert!(s3::connection(&name).is_none(), "a declined call must not log in"); assert_eq!(s.map().name, map_name, "declining must leave every script line unexecuted"); assert_eq!(a.receive(a.generation(), ok(call("allowed", tool, args.clone())), &mut s), Step::Confirm); - assert!(matches!(a.decide(true, true, &mut s), Step::Send(_))); + assert!(matches!(answer(&mut a, true, true, &mut s), Step::Send(_))); assert!(s3::connection(&name).is_some(), "a once-approved call must execute"); if scripted { assert_eq!(s.map().name, "Approved map"); @@ -322,7 +328,7 @@ fn connection_commands_require_fresh_approval_before_login_or_scripts() { "asking to remember an approval must not bypass the next confirmation" ); assert!(s3::connection(&name).is_none()); - assert!(matches!(a.decide(false, false, &mut s), Step::Send(_))); + assert!(matches!(answer(&mut a, false, false, &mut s), Step::Send(_))); assert!(s3::connection(&name).is_none(), "declining a repeat must leave it disconnected"); } } @@ -355,10 +361,10 @@ fn remembered_database_forget_requires_fresh_direct_and_script_approval() { assert!(!a.pending(&s).unwrap().2); assert!(store.load("connection/c1").unwrap().is_some()); assert_eq!(s.map().name, name); - a.decide(false, false, &mut s); + answer(&mut a, false, false, &mut s); assert!(store.load("connection/c1").unwrap().is_some()); assert_eq!(a.receive(a.generation(), ok(call("allow", tool, args.clone())), &mut s), Step::Confirm); - let sent = a.decide(true, true, &mut s); + let sent = answer(&mut a, true, true, &mut s); assert!(matches!(sent, Step::Send(_))); assert!(!format!("{sent:?}").contains("forgotten-sentinel")); assert_eq!(store.load("connection/c1").unwrap(), None); @@ -1087,14 +1093,14 @@ fn always_allow_is_per_command_and_never_for_reserved_actions() { assert!(a.pending(&s).is_some_and(|p| p.2)); // Allowing the export for the conversation allows that file only: the next export (another // file) asks again, and so do the tiles. - assert_eq!(a.decide(true, true, &mut s), Step::Confirm); + assert_eq!(answer(&mut a, true, true, &mut s), Step::Confirm); assert!(a.pending(&s).is_some_and(|p| p.0.starts_with("share.exportLayer") && p.2)); - assert_eq!(a.decide(false, false, &mut s), Step::Confirm); + assert_eq!(answer(&mut a, false, false, &mut s), Step::Confirm); assert!(a.pending(&s).is_some_and(|p| p.0.starts_with("map.addTiles"))); - assert_eq!(a.decide(false, false, &mut s), Step::Confirm); + assert_eq!(answer(&mut a, false, false, &mut s), Step::Confirm); // Replacing the project is never allowed for good. assert!(a.pending(&s).is_some_and(|p| p.0.starts_with("project.new") && !p.2)); - let _ = a.decide(false, false, &mut s); + let _ = answer(&mut a, false, false, &mut s); for n in [1, 2] { let _ = std::fs::remove_file(dir.join(format!("rustgis-assistant-test-{n}.geojson"))); } @@ -1116,7 +1122,7 @@ fn calls_after_one_turning_the_assistant_off_are_not_run() { 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!(matches!(answer(&mut a, 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:?}"); @@ -3528,7 +3534,7 @@ fn a_subagents_approvals_and_stops_reach_the_user() { let (what, _, _) = a.pending(&s).expect("an approval"); assert!(what.starts_with("Subagent: share.exportMap"), "{what}"); // Declined: the subagent hears so and goes on. - assert!(matches!(a.decide(false, false, &mut s), Step::Send(_))); + assert!(matches!(answer(&mut a, false, false, &mut s), Step::Send(_))); assert!(a.transcript.iter().any(|e| matches!(e, Entry::Tool { result, .. } if result == "Declined"))); // Stopping stops both; the delegate call gets a result, so the next request is well formed. a.stop(); @@ -3538,6 +3544,58 @@ fn a_subagents_approvals_and_stops_reach_the_user() { assert!(messages.iter().any(|m| m["role"] == "tool" && m["tool_call_id"] == "id-delegate")); } +/// An answer to an approval that is no longer the one waiting (a second tap, a card drawn before +/// the run moved on) does nothing: not the next call of the same id in the next reply, not a +/// subagent's call after the one shown, nothing after a stop. +#[test] +fn an_answer_to_an_approval_no_longer_waiting_is_refused() { + let mut s = sample(); + let mut a = Agent::new(cfg("openai"), &s); + assert!(a.asking().is_none()); + assert!(matches!(a.ask("export twice", &s), Step::Send(_))); + let never = |n: u32| std::env::temp_dir().join(format!("rustgis-assistant-stale-{}-{n}.png", std::process::id())); + let export = |n: u32| call("c0", "run_command", json!({"command": "share.exportMap", "params": {"path": never(n)}})); + assert_eq!(a.receive(a.generation(), ok(export(1)), &mut s), Step::Confirm); + let first = a.asking().expect("an approval"); + assert!(matches!(a.decide(&first, false, false, &mut s), Some(Step::Send(_)))); + // The next reply's call has the same id: the first card's answer isn't its. + assert_eq!(a.receive(a.generation(), ok(export(2)), &mut s), Step::Confirm); + let entries = a.transcript.len(); + assert_eq!(a.decide(&first, true, true, &mut s), None); + assert_eq!(a.transcript.len(), entries); + assert!(a.pending(&s).is_some_and(|p| p.0.contains(&never(2).display().to_string()))); + let second = a.asking().expect("an approval"); + assert_ne!(second, first); + // Stopped, nothing waits: the card shown before the stop answers nothing. + a.stop(); + assert_eq!(a.decide(&second, true, false, &mut s), None); + // A subagent's: one of its calls answered, the card for it doesn't answer the next. + assert!(matches!(a.ask("delegate it", &s), Step::Send(_))); + assert!(matches!(a.receive(a.generation(), ok(calls("delegate", json!({"task": "Export twice"}))), &mut s), Step::Send(_))); + assert_eq!(a.receive(a.generation(), ok(export(3)), &mut s), Step::Confirm); + let child = a.asking().expect("the subagent's approval"); + assert!(matches!(a.decide(&child, false, false, &mut s), Some(Step::Send(_)))); + assert_eq!(a.receive(a.generation(), ok(export(4)), &mut s), Step::Confirm); + assert_eq!(a.decide(&child, true, false, &mut s), None); + assert!(a.pending(&s).is_some_and(|p| p.0.starts_with("Subagent: share.exportMap") && p.0.contains(&never(4).display().to_string()))); + assert!(matches!(answer(&mut a, false, false, &mut s), Step::Send(_))); + assert!((1..=4).all(|n| !never(n).exists()), "nothing was exported"); + // Two calls of one id in one reply: the card for the first doesn't answer the second. + a.stop(); + assert!(matches!(a.ask("export both", &s), Step::Send(_))); + let args = |n: u32| json!({"command": "share.exportMap", "params": {"path": never(n)}}).to_string(); + let twice = json!({"choices": [{"message": {"role": "assistant", "content": null, "tool_calls": [ + {"id": "same", "type": "function", "function": {"name": "run_command", "arguments": args(5)}}, + {"id": "same", "type": "function", "function": {"name": "run_command", "arguments": args(6)}} + ]}, "finish_reason": "tool_calls"}]}); + assert_eq!(a.receive(a.generation(), ok(twice), &mut s), Step::Confirm); + let first = a.asking().expect("an approval"); + assert_eq!(a.decide(&first, false, false, &mut s), Some(Step::Confirm)); + assert_eq!(a.decide(&first, true, false, &mut s), None); + assert!(a.pending(&s).is_some_and(|p| p.0.contains(&never(6).display().to_string()))); + assert!(matches!(answer(&mut a, false, false, &mut s), Step::Send(_))); +} + #[test] fn a_subagent_uses_only_its_tools() { let mut s = sample(); @@ -3962,7 +4020,7 @@ fn a_subagents_declined_approval_returns_to_the_main_assistant() { )); let export = calls("run_command", json!({"command": "share.exportMap", "params": {"path": "map.png"}})); assert_eq!(a.receive(a.generation(), ok(export), &mut s), Step::Confirm); - assert!(matches!(a.decide(false, false, &mut s), Step::Send(_))); + assert!(matches!(answer(&mut a, false, false, &mut s), Step::Send(_))); assert!(matches!(a.receive(a.generation(), ok(say("Couldn't export.")), &mut s), Step::Send(_))); assert_eq!(a.receive(a.generation(), ok(say("Done.")), &mut s), Step::Done); assert!(!a.busy()); @@ -4289,12 +4347,12 @@ fn local_delegation_waits_for_rustgis_approval() { let (what, _, always) = a.pending(&s).unwrap(); assert!(!always); assert!(what.contains("npx -y @agentclientprotocol/claude-agent-acp@"), "the card names the package npx may run: {what}"); - assert!(matches!(a.decide(false, false, &mut s), Step::Send(_))); + assert!(matches!(answer(&mut a, false, false, &mut s), Step::Send(_))); assert!(a.take_delegations().is_empty()); let _ = a.receive(a.generation(), ok(say("declined")), &mut s); let _ = a.ask("try again", &s); assert_eq!(a.receive(a.generation(), ok(call()), &mut s), Step::Confirm); - assert!(matches!(a.decide(true, false, &mut s), Step::Send(_))); + assert!(matches!(answer(&mut a, true, false, &mut s), Step::Send(_))); assert_eq!(a.take_delegations().len(), 1); } @@ -4887,7 +4945,7 @@ fn permission_policy_real_plugin_approval_and_changed_first_card() { a.ask("select", &s); assert_eq!(a.receive(a.generation(), ok(call("real", name, args.clone())), &mut s), Step::Confirm); assert!(!a.pending(&s).unwrap().2, "every plugin run asks separately"); - a.decide(true, true, &mut s); + answer(&mut a, true, true, &mut s); assert_eq!(s.map().layer_by_name("Cities").unwrap().selection, [0, 2]); if !s.map().layer_by_name("Cities").unwrap().selection.is_empty() { s.run("select.clear", &json!({"layer":"Cities"})).unwrap(); @@ -4906,7 +4964,7 @@ fn permission_policy_real_plugin_approval_and_changed_first_card() { let first = a.pending(&s).unwrap(); assert!(first.0.contains("plugin:assistant-policy-real/f")); s.run("layer.select", &json!({"layer":"Countries"})).unwrap(); - a.decide(true, false, &mut s); + answer(&mut a, true, false, &mut s); assert!(s.map().layer_by_name("No stale rename").is_none()); assert!(a.transcript.iter().any(|e| matches!(e,Entry::Tool{error:true,result,..} if result.contains("changed")))); // The actual first shown item card also retains its original executable content. @@ -4921,7 +4979,7 @@ fn permission_policy_real_plugin_approval_and_changed_first_card() { assert!(a.pending(&s).unwrap().0.contains("Shown item")); let map = s.map().clone(); s.run("task.addStep", &json!({"task":"Shown item","title":"Changed content","command":"map.zoomIn","params":{}})).unwrap(); - a.decide(true, false, &mut s); + answer(&mut a, true, false, &mut s); assert_eq!(s.map().name, map.name); assert_eq!(s.map().camera, map.camera); assert_eq!(s.map().layer_by_name("Cities").unwrap().visible, map.layer_by_name("Cities").unwrap().visible); @@ -4971,7 +5029,7 @@ fn permission_policy_pending_effective_share_and_nested_sql() { let shown = a.pending(&s).unwrap().0; assert!(shown.contains("Cities") && shown.contains(&path.display().to_string()), "{shown}"); assert!(a.pending_review().unwrap().defaults.is_none()); - a.decide(false, false, &mut s); + answer(&mut a, false, false, &mut s); let params = json!({"sql":"FROM t","database":"/data/x.duckdb", "password":"RGSYNTH_direct_review_secret", "metadata":{"script":format!("layer.addUrl {}", json!({"url":"https://example.invalid/data?token=RGSYNTH_url_review_secret","token":"RGSYNTH_nested_review_secret"}))}}); let script = format!("layer.addSql {params}"); @@ -4995,7 +5053,7 @@ fn permission_policy_pending_effective_share_and_nested_sql() { assert!(!what.contains("RGSYNTH_"), "secrets cannot become consent display data"); assert!(!what.contains("structured content omitted"), "{what}"); } - a.decide(false, false, &mut s); + answer(&mut a, false, false, &mut s); } } diff --git a/crates/ui-egui/src/assistant.rs b/crates/ui-egui/src/assistant.rs index 4b003c8244..f153ba8de9 100644 --- a/crates/ui-egui/src/assistant.rs +++ b/crates/ui-egui/src/assistant.rs @@ -7,8 +7,11 @@ //! [`rustgis_assistant::Config::missing`] why it isn't set up; //! - [`AssistantState::messages`] and [`AssistantState::preview`] are what to draw, and //! [`AssistantState::busy`] and [`AssistantState::waiting`] what is going on; -//! - [`send`] a message, [`stop`] the run, start a [`new_conversation`] or [`compact`] it; -//! - [`pending`] is the action waiting for approval, which [`decide`] answers. +//! - [`AssistantState::input`] is the message being written, which [`send`] sends (or holds until +//! the key is read: [`AssistantState::sending_when_ready`]); [`stop`] the run, start a +//! [`new_conversation`] or [`compact`] it; +//! - [`pending`] is the action waiting for approval, which [`decide`] answers; +//! - [`choose_provider`] and [`apply_settings`] change the provider's settings. //! //! Requests go out off the frame: on a thread on the desktop, through `Services::http` (the //! browser's fetch) on the web. Their replies are taken in by [`RustGisApp::logic`] each frame. @@ -17,6 +20,9 @@ use rustgis_assistant::{Agent, Config, Entry, HttpRequest, HttpResponse, PRESETS use crate::{RustGisApp, Slot}; +/// The desktop pane's pieces another interface draws the conversation with. +pub use crate::assistantpane::{approval_details, error, reply}; + /// Where a response lands. pub(crate) type Reply = Slot>; /// A streamed reply's pieces, as they arrive. @@ -26,18 +32,21 @@ pub(crate) type Chunks = std::sync::Arc>>; #[derive(Default)] pub struct AssistantState { pub(crate) agent: Option, - /// The message being written. + /// The message being written. While it waits to be sent ([`AssistantState::sending_when_ready`]) + /// it is the message that goes, as it is when the key and its pictures are read. pub input: String, /// The pictures attached to the message being written. pub(crate) pictures: crate::assistantpictures::Pictures, /// The input box's height, set by dragging the grip above it (0 until dragged: two lines). pub(crate) input_height: f32, - /// A message to send on the next frame (`ui.pane.assistant {"ask": …}`), or once the key or a - /// picture it waits for is read. - pub queued: Option, - /// 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, + /// The message being written ([`AssistantState::input`]) is sent once the key and the pictures + /// it waits for are read: what the box shows while it waits is what goes, and what a send + /// clears. + pub(crate) send_when_ready: bool, + /// Messages a command asked to send (`ui.pane.assistant {"ask": …}`), oldest first: each is sent + /// by itself, as a suggestion would be, on the next frame once the key and pictures are read. + /// They never go into the message being written unless they can't be sent. + pub(crate) asked: Vec, /// 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. @@ -150,6 +159,42 @@ impl AssistantState { pub fn config(&self) -> Option<&Config> { self.agent.as_ref().map(|a| &a.config) } + + /// The message being written waits to be sent until the key or a picture is read. + pub fn sending_when_ready(&self) -> bool { + self.send_when_ready + } + + /// A message waits to be sent until the key or a picture is read: the one being written, or + /// one a command asked for. + pub fn waiting_to_send(&self) -> bool { + self.send_when_ready || !self.asked.is_empty() + } + + /// Whether API keys are remembered on this device ("Remember the key"), which + /// [`apply_settings`] compares with what the form started from. + pub fn remember_key(&self) -> bool { + self.remember_key + } + + /// Sets "Remember the key", for [`apply_settings`] to apply with the form's other changes. + pub fn set_remember_key(&mut self, on: bool) { + self.remember_key = on; + } + + /// The models the provider listed, once it has. + pub fn models(&self) -> &[String] { + &self.models + } + + /// Nothing waiting goes by itself any more: the message being written stays in the box, unsent, + /// and what a command asked to send goes into the box with it. + pub(crate) fn hold(&mut self) { + self.send_when_ready = false; + for text in std::mem::take(&mut self.asked) { + to_box(self, &text); + } + } } /// The ids of the settings fields typed into: changes are saved once none has focus. @@ -663,7 +708,7 @@ pub(crate) fn follow(app: &mut RustGisApp, step: Step, ctx: &egui::Context) { /// Runs `f` on the agent and the session; errors of the commands it ran show in the transcript, /// not as notices too. -fn with_agent(app: &mut RustGisApp, f: impl FnOnce(&mut Agent, &mut rustgis_engine::Session) -> Step) -> Option { +fn with_agent(app: &mut RustGisApp, f: impl FnOnce(&mut Agent, &mut rustgis_engine::Session) -> T) -> Option { let mut agent = app.assistant.agent.take()?; let before = app.session.notices.len(); let step = f(&mut agent, &mut app.session); @@ -692,8 +737,8 @@ pub(crate) fn turned_off(app: &mut RustGisApp) { 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); + // A message not sent yet stays in the message box. + app.assistant.hold(); if let Some(agent) = app.assistant.agent.as_mut() { agent.suspend(); } @@ -729,7 +774,8 @@ pub(crate) fn turned_off(app: &mut RustGisApp) { } } -/// Per-frame: responses that arrived, a message queued by a command, and settings to save. +/// Per-frame: responses that arrived, a message waiting or asked for 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. @@ -766,9 +812,21 @@ pub(crate) fn poll(app: &mut RustGisApp, ctx: &egui::Context) { if crate::assistantpictures::take_read(app) { ctx.request_repaint_after(web_time::Duration::from_millis(100)); } - let from_box = std::mem::take(&mut app.assistant.queued_from_box); - if let Some(text) = app.assistant.queued.take() { - send_from(app, text, from_box, ctx); + // A command's message is the first use of the Assistant, maybe: its provider is loaded (and + // its key read begun) before anything is judged ready. + if !app.assistant.asked.is_empty() { + ensure_loaded(app, ctx); + } + let ready = !key_loading(app) && !app.assistant.pictures.reading(); + if ready { + for text in std::mem::take(&mut app.assistant.asked) { + send_from(app, text, false, ctx); + } + } + if app.assistant.send_when_ready && ready { + app.assistant.send_when_ready = false; + let text = app.assistant.input.clone(); + send_from(app, text, true, ctx); } // The reply's text so far, as it streams in. if let Some((generation, chunks)) = &app.assistant.chunks { @@ -881,18 +939,20 @@ pub fn open(app: &mut RustGisApp, ctx: &egui::Context) { } /// Sends the user's message, with the pictures attached to it, to the selected provider (loading -/// it the first time), and clears the draft ([`AssistantState::input`]). While the key or a picture -/// is still being read, the message waits in [`AssistantState::queued`] and goes once it is; -/// another sent meanwhile takes its place, the one it replaces going back to the box, and the -/// draft is left as it is until then. Once sent, the draft is cleared only if it still holds that -/// message: text typed while it waited stays. While the assistant is busy it isn't sent: a notice -/// says so, and the message is in the box to send again. +/// it the first time). The message being written ([`AssistantState::input`]) is cleared when it is +/// the one sent; a message from elsewhere (a suggestion) leaves it as it is. +/// +/// While the key or a picture is still being read, the message waits as the message being written +/// ([`AssistantState::sending_when_ready`]) and goes, as the box then holds it, once they are. A +/// message from elsewhere becomes the message being written when there is none; when there is one, +/// it is put above it, and a notice says to send them from there. While the assistant is busy +/// nothing is sent: a notice says so, and the message is in the box to send again. pub fn send(app: &mut RustGisApp, text: String, ctx: &egui::Context) { let from_box = text.trim() == app.assistant.input.trim(); send_from(app, text, from_box, ctx); } -/// [`send`], told whether `text` is the input box's own draft (`from_box`), which the box keeps +/// [`send`], told whether `text` is the message being written (`from_box`), which the box keeps /// until it goes: a message from elsewhere (a suggestion, a command's) is put in the box when it /// isn't sent, the box's own is already there. fn send_from(app: &mut RustGisApp, text: String, from_box: bool, ctx: &egui::Context) { @@ -910,12 +970,22 @@ fn send_from(app: &mut RustGisApp, text: String, from_box: bool, ctx: &egui::Con app.session.notify(tl!("The assistant is busy; stop it or wait for it to finish."), true); return; } - // A message waits for the key, and for a picture still being read, which goes with it (a - // suggestion clicked meanwhile, say). + // A message waits for the key, and for a picture still being read, which goes with it, as the + // message being written: there is one place for it, which the box shows. if key_loading(app) || app.assistant.pictures.reading() { - unqueue(&mut app.assistant); - app.assistant.queued = Some(text); - app.assistant.queued_from_box = from_box; + let state = &mut app.assistant; + let draft = state.input.trim(); + if !from_box && !draft.is_empty() && draft != text.trim() { + // Not sent with what was being written, nor in its place: both stay to be sent. + to_box(state, &text); + state.send_when_ready = false; + app.session.notify(tl!("The message is in the message box, above what was being written: send it from there."), false); + return; + } + if !from_box && draft.is_empty() { + state.input = text.trim().to_string(); + } + state.send_when_ready = true; return; } let text = text.trim().to_string(); @@ -937,13 +1007,14 @@ fn send_from(app: &mut RustGisApp, text: String, from_box: bool, ctx: &egui::Con return; }; let step = agent.ask_with(&text, app.assistant.pictures.take(), session); - if app.assistant.input.trim() == text { + if from_box || app.assistant.input.trim() == text { app.assistant.input.clear(); } follow(app, step, ctx); } /// An action waiting for the user's approval. +#[derive(Clone)] pub struct Approval { /// What would run, in words. pub what: String, @@ -953,42 +1024,38 @@ pub struct Approval { pub can_always: bool, /// The engine's structured card of it, where there is one, taken before it was asked about. pub review: Option, + /// Which approval this is: [`decide`] answers it only while it is still the one waiting. + pub asked: rustgis_assistant::Asking, } /// The action waiting for approval, if one is. pub fn pending(app: &RustGisApp) -> Option { let agent = app.assistant.agent.as_ref()?; + let asked = agent.asking()?; let (what, why, can_always) = agent.pending(&app.session)?; - Some(Approval { what, why, can_always, review: agent.pending_review().cloned() }) + Some(Approval { what, why, can_always, review: agent.pending_review().cloned(), asked }) } -/// Answers the [`pending`] action: runs it, or declines it. With `always`, actions like it run -/// without asking for the rest of the conversation, where [`Approval::can_always`] says so. -pub fn decide(app: &mut RustGisApp, allow: bool, always: bool, ctx: &egui::Context) { - if let Some(step) = with_agent(app, |a, s| a.decide(allow, always, s)) { - follow(app, step, ctx); +/// Answers the approval `asked` ([`Approval::asked`]): runs its action, or declines it. With +/// `always`, actions like it run without asking for the rest of the conversation, where +/// [`Approval::can_always`] says so. An approval no longer waiting (answered already, stopped, or +/// followed by another) is answered by nothing, and a notice says so. +pub fn decide(app: &mut RustGisApp, asked: &rustgis_assistant::Asking, allow: bool, always: bool, ctx: &egui::Context) { + match with_agent(app, |a, s| a.decide(asked, allow, always, s)) { + Some(Some(step)) => follow(app, step, ctx), + Some(None) => app.session.notify(tl!("That approval was no longer waiting, so nothing was run or declined."), false), + None => {} } } -/// Stops the run: the request out is forgotten, and calls not yet run are skipped. +/// Stops the run: the request out is forgotten, calls not yet run are skipped, and a message +/// waiting for the key stays in the box unsent. pub fn stop(app: &mut RustGisApp) { if let Some(a) = app.assistant.agent.as_mut() { a.stop(); } drop_request(&mut app.assistant); -} - -/// Puts a message still waiting to be sent back into the input box, so it is never lost: as the -/// draft when the box is empty or already holds it, above newer typing otherwise. -pub(crate) fn unqueue(state: &mut AssistantState) { - let from_box = std::mem::take(&mut state.queued_from_box); - // The box's own draft is there still, or what the user typed over it; one they cleared - // comes back. - if let Some(text) = state.queued.take() - && (!from_box || state.input.trim().is_empty()) - { - to_box(state, &text); - } + app.assistant.hold(); } /// Puts a message that isn't being sent into the input box: as the draft when the box is empty @@ -1002,12 +1069,13 @@ fn to_box(state: &mut AssistantState, text: &str) { } /// Forgets the conversation, and ends the agent threads it started. A message still waiting to -/// be sent ([`AssistantState::queued`]) isn't sent into the new one: it goes back to the box. +/// 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) { if let Some(a) = app.assistant.agent.as_mut() { a.clear(); } - unqueue(&mut app.assistant); + app.assistant.hold(); drop_request(&mut app.assistant); end_threads(app); } @@ -1050,7 +1118,7 @@ pub(crate) fn fold_provider(app: &mut RustGisApp, closed: bool) { /// Puts another provider into the settings being edited (`cfg`, which [`apply_settings`] then /// takes), and drops what was read for the one before. -pub(crate) fn choose_provider(app: &mut RustGisApp, cfg: &mut Config, id: &str, ctx: &egui::Context) { +pub fn choose_provider(app: &mut RustGisApp, cfg: &mut Config, id: &str, ctx: &egui::Context) { #[cfg(not(target_arch = "wasm32"))] { app.assistant.login = None; @@ -1073,7 +1141,7 @@ pub(crate) fn choose_provider(app: &mut RustGisApp, cfg: &mut Config, id: &str, /// Applies what a settings form made of the provider's settings and of "Remember the key"; `before` /// is what the form started from. Nothing changes when they are the same. -pub(crate) fn apply_settings(app: &mut RustGisApp, mut cfg: Config, before: (Config, bool), ctx: &egui::Context) { +pub fn apply_settings(app: &mut RustGisApp, mut cfg: Config, before: (Config, bool), ctx: &egui::Context) { if cfg.login() { provider::use_catalog(&mut cfg, &app.assistant.catalog, true); } @@ -1193,13 +1261,13 @@ fn revoke_later(app: &mut RustGisApp, revocation: Option, c } /// After signing out or removing the account: no tokens, no catalog, and nothing waiting to be -/// sent with them (a queued message goes back to the input box, not to the provider). +/// sent with them (a message waiting stays in the input box, unsent). #[cfg(not(target_arch = "wasm32"))] pub(crate) fn forget_sign_in(app: &mut RustGisApp, cfg: &mut Config) { app.assistant.sign_in_read = None; app.assistant.models_slot = None; app.assistant.catalog_pending = false; - unqueue(&mut app.assistant); + app.assistant.hold(); cfg.key.clear(); app.assistant.account = None; app.assistant.models.clear(); @@ -1239,7 +1307,7 @@ pub(crate) fn peer_replaced(app: &mut RustGisApp) { } app.assistant.inflight = None; app.assistant.chunks = None; - // Not sent into the peer's project: back to the box. - unqueue(&mut app.assistant); + // Not sent into the peer's project: it stays in the box. + app.assistant.hold(); app.assistant.always = false; } diff --git a/crates/ui-egui/src/assistantpane.rs b/crates/ui-egui/src/assistantpane.rs index 042a0acdf1..e3e922e05d 100644 --- a/crates/ui-egui/src/assistantpane.rs +++ b/crates/ui-egui/src/assistantpane.rs @@ -634,36 +634,31 @@ fn composer(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, busy: bool, ctx: &egu #[cfg(not(target_arch = "wasm32"))] crate::agentthreads::list(app, ui, t); // An action waiting for approval comes first. - if let Some(Approval { what, why, can_always, review }) = assistant::pending(app) { + if let Some(approval) = assistant::pending(app) { + let Approval { what, why, can_always, asked, .. } = &approval; 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| { - if let Some(review) = &review { - crate::approvalcard::show(ui, &app.session.registry, review); - } else { - // Legacy requests have no structured review: keep all their context visible. - ui.label( - RichText::new(crate::i18n::fmt("The assistant wants to run this, and {why}:", &[("why", tl_raw!(&why))])) - .small(), - ); - ui.add(egui::Label::new(RichText::new(&what).monospace().small()).wrap()); - } + egui::ScrollArea::vertical().max_height(280.0).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 { + if *can_always { ui.checkbox(&mut app.assistant.always, tl!("Allow such actions for this conversation")); } else { app.assistant.always = false; } - ui.horizontal(|ui| { - let allow = crate::widgets::primary_button(ui, tl!("Allow"), true, vec2(70.0, 26.0)).clicked(); - let deny = ui.button(tl!("Decline")).clicked(); - if allow || deny { - let always = app.assistant.always; - assistant::decide(app, allow, always, ctx); - } + // 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| { + ui.horizontal(|ui| { + let allow = crate::widgets::primary_button(ui, tl!("Allow"), true, vec2(70.0, 26.0)).clicked(); + let deny = ui.button(tl!("Decline")).clicked(); + if allow || deny { + let always = app.assistant.always; + assistant::decide(app, asked, allow, always, ctx); + } + }); }); }, ); @@ -748,6 +743,30 @@ fn composer(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, busy: bool, ctx: &egu } } +/// What an approval is about, as the card asking for it shows it: the engine's structured card, +/// or the action in words with why it is asked about. +pub fn approval_details(ui: &mut Ui, app: &RustGisApp, approval: &Approval) { + if let Some(review) = &approval.review { + crate::approvalcard::show(ui, &app.session.registry, review); + } else { + // Legacy requests have no structured review: keep all their context visible. + ui.label( + RichText::new(crate::i18n::fmt("The assistant wants to run this, and {why}:", &[("why", tl_raw!(&approval.why))])).small(), + ); + ui.add(egui::Label::new(RichText::new(&approval.what).monospace().small()).wrap()); + } +} + +/// A reply of the assistant's, its Markdown laid out (headings, lists, quotes, code, tables as text). +pub fn reply(ui: &mut Ui, text: &str, t: &Tokens) { + markdown(ui, text, t); +} + +/// An error of the assistant's: what went wrong, a way out where there is one, and its diagnostics. +pub fn error(ui: &mut Ui, e: &rustgis_assistant::Error, t: &Tokens) { + show_error(ui, e, t); +} + fn transcript(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, ctx: &egui::Context) { if app.assistant.config().is_none() { return; @@ -1134,6 +1153,35 @@ pub(crate) mod tests { } } + /// A command's message that is the Assistant's first use waits for the saved key by itself: it + /// doesn't go into the message being written, and goes alone once the key is read. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_commands_first_message_waits_for_the_saved_key_apart() { + use rustgis_engine::data::secrets::{MemorySecrets, Secret, SecretStore}; + let store = std::sync::Arc::new(MemorySecrets::new()); + store.save("assistant/custom", &Secret::new("synthetic-stored")).unwrap(); + let (mut app, _) = keys_app(None, Some(store)); + // As at start-up: nothing loaded until the command asks. + app.assistant.agent = None; + app.assistant.loaded = false; + app.assistant.keys = Default::default(); + app.services.http = Some(Box::new(|_, _| {})); + app.assistant.input = "a draft".into(); + app.run("ui.pane.assistant", serde_json::json!({"ask": "Zoom to Tokyo"})).unwrap(); + let ctx = egui::Context::default(); + poll(&mut app, &ctx); + assert!(key_loading(&app), "the saved key is being read"); + assert!(app.assistant.waiting_to_send() && !app.assistant.sending_when_ready()); + assert_eq!(app.assistant.input, "a draft"); + settle_keys(&mut app); + poll(&mut app, &ctx); + assert!(!app.assistant.waiting_to_send()); + assert_eq!(app.assistant.input, "a draft"); + let agent = app.assistant.agent.as_ref().unwrap(); + assert!(matches!(agent.transcript.first(), Some(Entry::User(t)) if t == "Zoom to Tokyo"), "{:?}", agent.transcript); + } + /// Requests wait for the saved key instead of sending with a temporary empty/environment value. #[cfg(not(target_arch = "wasm32"))] #[test] @@ -1149,7 +1197,8 @@ pub(crate) mod tests { send(&mut app, "hello".into(), &ctx); assert!(app.assistant.catalog_pending && app.assistant.models_slot.is_none()); assert!(app.assistant.inflight.is_none()); - assert_eq!(app.assistant.queued.as_deref(), Some("hello")); + assert!(app.assistant.sending_when_ready()); + assert_eq!(app.assistant.input, "hello", "the box shows the message waiting"); settle_keys(&mut app); assert!(!key_loading(&app)); assert_eq!(app.assistant.agent.as_ref().unwrap().config.key, "synthetic-stored"); @@ -1457,7 +1506,7 @@ pub(crate) mod tests { assert!(!agent.busy()); let kept = agent.transcript.len(); assert!(kept > 0); - assert!(app.assistant.inflight.is_none() && app.assistant.queued.is_none()); + assert!(app.assistant.inflight.is_none() && app.assistant.asked.is_empty()); assert_eq!(app.assistant.input, "Label the cities"); assert!(app.ui.right_open.is_empty()); let notices = said(&app); @@ -1538,7 +1587,7 @@ pub(crate) mod tests { send(&mut app, "second thoughts".into(), &ctx); assert_eq!(app.session.notices.iter().filter(|n| n.text.contains(BUSY)).count(), 1); assert_eq!(app.assistant.input, "second thoughts"); - assert!(app.assistant.queued.is_none()); + assert!(!app.assistant.sending_when_ready()); let agent = app.assistant.agent.as_ref().unwrap(); assert_eq!(agent.transcript.len(), entries); assert!(app.assistant.history.iter().all(|h| h != "second thoughts")); @@ -1569,45 +1618,39 @@ pub(crate) mod tests { } } - /// Signing out puts a waiting message back into the box: as the draft, or above newer typing. + /// Signing out sends nothing still waiting: the message stays in the box, and one a command + /// asked for goes into it, above what was being written. #[cfg(not(target_arch = "wasm32"))] #[test] - fn signing_out_returns_a_waiting_message_to_the_box() { + fn signing_out_leaves_a_waiting_message_in_the_box() { let mut app = RustGisApp::with_sample(); let mut cfg = Config::from_env("custom"); - for (draft, kept) in [("typed since", "waited\ntyped since"), ("", "waited"), ("waited", "waited")] { - app.assistant.queued = Some("waited".into()); - app.assistant.input = draft.into(); - assistant::forget_sign_in(&mut app, &mut cfg); - assert!(app.assistant.queued.is_none()); - assert_eq!(app.assistant.input, kept); - } + app.assistant.input = "waited".into(); + app.assistant.send_when_ready = true; + app.assistant.asked.push("asked".into()); + assistant::forget_sign_in(&mut app, &mut cfg); + assert!(!app.assistant.sending_when_ready() && app.assistant.asked.is_empty()); + assert_eq!(app.assistant.input, "asked\nwaited"); } - /// A new conversation doesn't send a message still waiting into the next one: it goes back to - /// the box (a suggestion's too, which never was the draft). + /// A new conversation, or a peer's project replacing this one, sends nothing still waiting + /// into it: the message stays in the box. A command's message, asked for before, goes there too. #[test] - fn new_conversation_returns_a_waiting_message_to_the_box() { + fn a_message_waiting_is_kept_in_the_box_and_not_sent_into_what_follows() { let mut app = RustGisApp::with_sample(); app.assistant.agent = Some(Agent::new(Config::from_env("custom"), &app.session)); - for draft in ["from before", ""] { - app.assistant.queued = Some("from before".into()); - app.assistant.input = draft.into(); - assistant::new_conversation(&mut app); - assert!(app.assistant.queued.is_none()); + for replace in [assistant::new_conversation as fn(&mut RustGisApp), assistant::peer_replaced] { + app.assistant.input = "from before".into(); + app.assistant.send_when_ready = true; + replace(&mut app); + assert!(!app.assistant.sending_when_ready()); assert_eq!(app.assistant.input, "from before"); + app.assistant.input.clear(); + app.run("ui.pane.assistant", serde_json::json!({"ask": "from a command"})).unwrap(); + replace(&mut app); + assert!(app.assistant.asked.is_empty()); + assert_eq!(app.assistant.input, "from a command"); } - // A command's message doesn't push one still waiting out: that one goes to the box. - app.assistant.queued = Some("waiting".into()); - app.assistant.input.clear(); - app.run("ui.pane.assistant", serde_json::json!({"ask": "from a command"})).unwrap(); - assert_eq!((app.assistant.queued.as_deref(), app.assistant.input.as_str()), (Some("from a command"), "waiting")); - // Nor into a peer's project that replaces this one. - app.assistant.queued = Some("a suggestion".into()); - app.assistant.input.clear(); - assistant::peer_replaced(&mut app); - assert!(app.assistant.queued.is_none()); - assert_eq!(app.assistant.input, "a suggestion"); } /// Real pending reviews keep their reach visible while exact requests wait under Details. @@ -2005,7 +2048,8 @@ pub(crate) mod tests { app.assistant.models_slot = Some(late.clone()); app.assistant.models = vec!["first-model".into()]; // A message typed while the check was under way, and a catalog request it deferred. - app.assistant.queued = Some("synthetic question".into()); + app.assistant.input = "synthetic question".into(); + app.assistant.send_when_ready = true; app.assistant.catalog_pending = true; finish(&mut app, Some(first.binding()), None); assert!(app.assistant.agent.as_ref().unwrap().config.key.is_empty()); @@ -2018,8 +2062,8 @@ pub(crate) mod tests { })); poll(&mut app, &ctx); assert!(app.assistant.models.is_empty() && app.assistant.catalog.is_empty()); - // Neither goes out after the sign-out; the message is back in the input box. - assert!(app.assistant.queued.is_none() && !app.assistant.catalog_pending); + // Neither goes out after the sign-out; the message stays in the input box. + assert!(!app.assistant.sending_when_ready() && !app.assistant.catalog_pending); assert!(app.assistant.inflight.is_none() && app.assistant.models_slot.is_none()); assert_eq!(app.assistant.input, "synthetic question"); // Taking the selected account: another one stops work for the first and drops its catalog. diff --git a/crates/ui-egui/src/assistantpictures.rs b/crates/ui-egui/src/assistantpictures.rs index d87965ad5b..7bedb4f910 100644 --- a/crates/ui-egui/src/assistantpictures.rs +++ b/crates/ui-egui/src/assistantpictures.rs @@ -391,40 +391,83 @@ mod tests { spins += 1; std::thread::yield_now(); } - app.assistant.queued = Some("like this".into()); + app.assistant.input = "like this".into(); + app.assistant.send_when_ready = true; crate::assistant::poll(&mut app, &egui::Context::default()); - assert!(app.assistant.queued.is_none() && !app.assistant.pictures.reading()); + assert!(!app.assistant.sending_when_ready() && !app.assistant.pictures.reading()); + assert_eq!(app.assistant.input, "", "the message sent was the box's"); let Some(rustgis_assistant::provider::Turn::User(_, sent)) = app.assistant.agent.as_ref().unwrap().turns().last() else { panic!("sent") }; assert_eq!(sent.len(), 1); } - /// A second message sent while the first waits for a picture takes its place, and the first - /// goes back to the box rather than being lost. + /// While a picture is being read, the message waiting is the one in the box: a suggestion + /// clicked meanwhile becomes it, typing changes it, and once it goes it is sent once, as the + /// box held it, and the box is empty (#2991's review: a suggestion and then the box's own + /// message left the sent text in the box). A suggestion clicked while another message is + /// being written goes above it, unsent, and that is said. #[test] - fn a_message_replaced_while_waiting_goes_back_to_the_box() { + fn the_message_waiting_is_the_one_in_the_box() { let mut app = RustGisApp::with_sample(); - app.assistant.agent = Some(rustgis_assistant::Agent::new(rustgis_assistant::Config::from_env("custom"), &app.session)); + let mut cfg = rustgis_assistant::Config::from_env("custom"); + cfg.model = "test".into(); + app.assistant.agent = Some(rustgis_assistant::Agent::new(cfg.clone(), &app.session)); app.assistant.loaded = true; + // The request goes nowhere: the test is about what is sent and what the box keeps. + app.services.http = Some(Box::new(|_, _| {})); received(&mut app, "map.png", png()); - // Read in only by `take_read`, which nothing here calls: the messages keep waiting. assert!(app.assistant.pictures.reading()); let ctx = egui::Context::default(); - crate::assistant::send(&mut app, "first".into(), &ctx); - crate::assistant::send(&mut app, "second".into(), &ctx); - assert_eq!(app.assistant.queued.as_deref(), Some("second")); - assert_eq!(app.assistant.input, "first"); - // Typed on in the box and sent again: the box's own draft isn't put back a second time. - app.assistant.input = "A".into(); - crate::assistant::send(&mut app, "A".into(), &ctx); - app.assistant.input = "AB".into(); - crate::assistant::send(&mut app, "AB".into(), &ctx); - assert_eq!((app.assistant.queued.as_deref(), app.assistant.input.as_str()), (Some("AB"), "AB")); - // The box cleared meanwhile: a new conversation puts the waiting draft back. - app.assistant.input.clear(); - crate::assistant::new_conversation(&mut app); - assert_eq!((app.assistant.queued.as_deref(), app.assistant.input.as_str()), (None, "AB")); + crate::assistant::send(&mut app, "Zoom to Tokyo".into(), &ctx); + assert!(app.assistant.sending_when_ready()); + assert_eq!(app.assistant.input, "Zoom to Tokyo"); + // Typed on in the box, and sent from it. + app.assistant.input = "Zoom to Tokyo and label it".into(); + crate::assistant::send(&mut app, "Zoom to Tokyo and label it".into(), &ctx); + assert!(app.assistant.sending_when_ready()); + assert_eq!(app.assistant.input, "Zoom to Tokyo and label it"); + let read = |app: &RustGisApp| app.assistant.pictures.reading.iter().all(|(_, slot)| slot.lock().is_ok_and(|s| s.is_some())); + let mut spins = 0; + while !read(&app) { + assert!(spins < 10_000_000, "the picture was never read"); + spins += 1; + std::thread::yield_now(); + } + crate::assistant::poll(&mut app, &ctx); + assert!(!app.assistant.sending_when_ready()); + assert_eq!(app.assistant.input, ""); + let sent: Vec = app + .assistant + .agent + .as_ref() + .unwrap() + .turns() + .iter() + .filter_map(|t| match t { + rustgis_assistant::provider::Turn::User(text, _) => Some(text.clone()), + _ => None, + }) + .collect(); + assert_eq!(sent.len(), 1, "{sent:?}"); + assert!(sent[0].ends_with("Zoom to Tokyo and label it"), "{sent:?}"); + // Another message being written: a suggestion neither waits with it nor takes its place. + app.assistant.agent = Some(rustgis_assistant::Agent::new(cfg, &app.session)); + received(&mut app, "sketch.png", png()); + app.assistant.input = "a draft".into(); + let mark = app.session.notice_mark(); + crate::assistant::send(&mut app, "Zoom to Tokyo".into(), &ctx); + assert!(!app.assistant.sending_when_ready()); + assert_eq!(app.assistant.input, "Zoom to Tokyo\na draft"); + let said: Vec<&str> = app.session.notices_since(mark).iter().map(|n| n.text.as_str()).collect(); + assert_eq!(said.len(), 1, "{said:?}"); + assert!(said[0].contains("above what was being written"), "{said:?}"); + // Not without a reason: a message in the box alone waits and says nothing. + let mark = app.session.notice_mark(); + app.assistant.input = "a draft".into(); + crate::assistant::send(&mut app, "a draft".into(), &ctx); + assert!(app.assistant.sending_when_ready()); + assert!(app.session.notices_since(mark).is_empty()); } #[test] diff --git a/crates/ui-egui/src/extensionsui.rs b/crates/ui-egui/src/extensionsui.rs index 1eff5c528e..5dc2aeecc9 100644 --- a/crates/ui-egui/src/extensionsui.rs +++ b/crates/ui-egui/src/extensionsui.rs @@ -286,7 +286,7 @@ mod tests { 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); + assert!(app.assistant.asked.is_empty()); // A saved pane set doesn't bring the pane back. app.run("ui.paneSet", json!({"load": "with chat"})).unwrap(); close_panes(&mut app); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c795fb356f..6ca40154a4 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -5595,10 +5595,8 @@ impl RustGisApp { "ui.pane.assistant" => match p.get("ask").and_then(Value::as_str).map(str::trim).filter(|t| !t.is_empty()) { Some(text) => { self.ui.open_right(RightPane::Assistant); - // A message still waiting isn't lost to this one: it goes back to the box. - assistant::unqueue(&mut self.assistant); - self.assistant.queued = Some(text.to_string()); - self.assistant.queued_from_box = false; + // Sent on the next frame, as a suggestion is. + self.assistant.asked.push(text.to_string()); } None => toggle_right(&mut self.ui, RightPane::Assistant), }, @@ -10686,7 +10684,8 @@ mod peer_output_tests { app.session.project.maps[0].layers[0].dataset.source = Some("https://h.invalid/?token=RGSYNTH_4".into()); let (text, _) = app.session.project.saved_text(None).unwrap(); app.session.run("task.new", &json!({"name":"prior","steps":[]})).unwrap(); - app.assistant.queued = Some("old project action".into()); + app.assistant.input = "old project action".into(); + app.assistant.send_when_ready = true; app.ui.web_file = Some("prior.rgis".into()); let generation = app.session.opened; app.ui.cog_probes.push(( @@ -10715,7 +10714,7 @@ mod peer_output_tests { "a clean peer replacement does not replay a retired read" ); assert!(app.session.project.tasks.is_empty()); - assert!(app.ui.web_file.is_none() && app.assistant.queued.is_none()); + assert!(app.ui.web_file.is_none() && !app.assistant.sending_when_ready()); assert!(!serde_json::to_string(&app.session.project).unwrap().contains("RGSYNTH_4")); // Both replacement paths retire ready answers and reads still waiting for their document. diff --git a/crates/ui-touch/src/assistant.rs b/crates/ui-touch/src/assistant.rs new file mode 100644 index 0000000000..dbbcb5d8b8 --- /dev/null +++ b/crates/ui-touch/src/assistant.rs @@ -0,0 +1,1114 @@ +//! The AI Assistant's sheet: the conversation, drawn here, with a typing bar that opens the +//! system's text field where there is one (a phone's, with its paste, suggestions and dictation), +//! Send and Stop, approvals as finger-sized cards, and the provider's settings. It is driven by +//! [`rustgis_ui_egui::assistant`], as the desktop's pane is. +//! +//! It stands full (reading and typing) or half (the map and the conversation); lowered while the +//! Assistant works, a strip over the bar says what it is doing and has Stop. Nothing of it shows +//! until a provider is set up (a row in More sets one up), nor at all with the extension off. + +use egui::{Align, Layout, RichText, Sense, Stroke, Ui, Vec2}; +use rustgis_ui_egui::rustgis_assistant::{Asking, Entry, PRESETS, provider}; +use rustgis_ui_egui::rustgis_engine::platform::{TextEntry, TextKind, Typed}; +use rustgis_ui_egui::theme::Tokens; +use rustgis_ui_egui::{RustGisApp, assistant, i18n, tl}; + +use super::{Sheet, Swipe, TARGET, action, entry_box, heading_row, icon_button, set_sheet, sheet, toggle_chip}; + +/// How tall the sheet stands. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum Height { + /// Most of the window: for reading and typing. + Full, + /// About half: the map and the conversation together. + #[default] + Half, +} + +impl Height { + /// The share of the window the sheet takes. + pub(crate) fn share(self) -> f32 { + match self { + Height::Full => super::TYPING_SHARE, + Height::Half => super::SHEET_SHARE, + } + } +} + +/// A field of the sheet's that is typed into. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Field { + Message, + Model, + Address, + Key, +} + +/// What the sheet holds between frames, kept in egui's memory. +#[derive(Clone, Debug, Default)] +pub(crate) struct Chat { + pub(crate) height: Height, + /// The provider's settings are shown in place of the conversation. + settings: bool, + /// The system's text field open for one of the sheet's fields: its id, the field, and the + /// provider it was opened for (a provider's settings never take what was typed for another's). + entering: Option<(String, Field, String)>, + /// How many times the system's text field was opened: each opening's id is its own. + entries: u64, + /// 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. + 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. + card: Option<(Asking, f64)>, +} + +/// How long, in seconds, an approval card is in sight before its buttons take a tap. +const SETTLE: f64 = 0.3; +/// The approval card's rows besides its details: its title, the "for this conversation" chip and +/// its buttons, counted a finger tall each. +const CARD_ROWS: f32 = 3.0; + +fn chat(ctx: &egui::Context) -> Chat { + ctx.data(|d| d.get_temp(egui::Id::unique("touch_assistant"))).unwrap_or_default() +} + +fn set_chat(ctx: &egui::Context, chat: Chat) { + ctx.data_mut(|d| d.insert_temp(egui::Id::unique("touch_assistant"), chat)); +} + +/// Raises the sheet at `height`. +pub(crate) fn raise(ctx: &egui::Context, height: Height) { + let mut state = chat(ctx); + state.height = height; + set_chat(ctx, state); + set_sheet(ctx, Sheet::Assistant); +} + +/// The sheet's height while it is up. +pub(crate) fn height(ctx: &egui::Context) -> Height { + chat(ctx).height +} + +/// How far the Assistant is from being usable. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Setup { + /// Its extension is off: nothing of it shows. + Off, + /// Its provider or key is still being read. + Reading, + /// No provider is set up: More offers to set one up. + Missing, + /// Set up: the bar has its button. + Ready, +} + +/// Whether the AI Assistant's extension is on. +pub(crate) fn on(app: &RustGisApp) -> bool { + app.session.extensions().is_on(rustgis_ui_egui::rustgis_engine::extensions::ASSISTANT.id) +} + +/// How far the Assistant is from being usable. +pub(crate) fn setup(app: &RustGisApp) -> Setup { + if !on(app) { + return Setup::Off; + } + match app.assistant.config() { + None => Setup::Reading, + Some(_) if assistant::key_loading(app) => Setup::Reading, + Some(c) if c.missing().is_some() => Setup::Missing, + Some(_) => Setup::Ready, + } +} + +/// Each frame: with the extension on, the chosen provider is loaded the first time (its key +/// read off the frame), so the bar knows whether the Assistant is set up; with it off, its sheet +/// is lowered. +pub(crate) fn prepare(app: &mut RustGisApp, ctx: &egui::Context) { + if on(app) { + assistant::open(app, ctx); + return; + } + if sheet(ctx) == Sheet::Assistant { + set_sheet(ctx, Sheet::None); + } + let mut state = chat(ctx); + if let Some((id, ..)) = state.entering.take() { + state.retired = Some(id); + set_chat(ctx, state); + } +} + +/// Whether the strip shows: the Assistant works (or a message waits for its key) and its sheet +/// isn't up. +pub(crate) fn strip_shown(app: &RustGisApp, ctx: &egui::Context) -> bool { + on(app) && sheet(ctx) != Sheet::Assistant && (app.assistant.busy() || app.assistant.waiting_to_send()) +} + +/// Takes what the system's text field sent back for the sheet's fields, and gives back the rest. +pub(crate) fn take_typed(app: &mut RustGisApp, ctx: &egui::Context, typed: Vec) -> Vec { + let mut state = chat(ctx); + let mut rest = Vec::new(); + for typed in typed { + let id = match &typed { + Typed::Text { id, .. } | Typed::Closed { id, .. } => id, + }; + if !id.starts_with("assistant:") { + rest.push(typed); + continue; + } + // Open as the extension was turned off: nothing it sends is taken, which is said once, + // whether it comes while the extension is off or after it is on again. + if state.retired.as_deref() == Some(id.as_str()) { + if matches!(typed, Typed::Text { .. }) { + app.session.notify(tl!("What was typed wasn't kept: the AI Assistant was turned off while it was typed."), true); + } + state.retired = None; + continue; + } + let Some((open, field, provider)) = state.entering.clone() else { continue }; + match typed { + Typed::Text { id, text } if id == open => { + if field == Field::Message { + app.assistant.input = text; + continue; + } + let Some(mut cfg) = app.assistant.config().cloned().filter(|c| c.provider == provider) else { + state.entering = None; + app.session.notify(tl!("What was typed wasn't kept: the Assistant's provider changed while it was typed."), true); + continue; + }; + let before = (cfg.clone(), app.assistant.remember_key()); + match field { + Field::Model => cfg.model = text.trim().to_string(), + Field::Address => cfg.base_url = text.trim().to_string(), + Field::Key => cfg.key = text.trim().to_string(), + Field::Message => {} + } + assistant::apply_settings(app, cfg, before, ctx); + } + Typed::Closed { id, .. } if id == open => state.entering = None, + _ => {} + } + } + set_chat(ctx, state); + rest +} + +/// The strip over the bar while the Assistant works with its sheet lowered: what it is doing, +/// which raises the sheet when tapped, and Stop. +pub(crate) fn strip(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { + ui.horizontal_centered(|ui| { + ui.spinner(); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + if action(ui, t, tl!("Stop"), 88.0, false, true) { + assistant::stop(app); + } + let (rect, response) = ui.allocate_exact_size(Vec2::new(ui.available_width(), TARGET), Sense::click()); + let mut job = egui::text::LayoutJob::simple_singleline(doing(app), egui::FontId::proportional(14.0), t.text); + job.wrap = egui::text::TextWrapping::truncate_at_width(rect.width().max(0.0)); + let galley = ui.painter().layout_job(job); + ui.painter().galley(egui::pos2(rect.min.x, rect.center().y - galley.size().y / 2.0), galley, t.text); + if response.on_hover_text(tl!("Show the Assistant")).clicked() { + raise(ui.ctx(), Height::Half); + } + }); + }); +} + +/// What the Assistant is doing, in a few words. +fn doing(app: &RustGisApp) -> String { + if app.assistant.waiting_to_send() { + return tl!("Waiting to send: the key is still being read…").to_string(); + } + if assistant::pending(app).is_some() { + return tl!("Waiting for your approval: tap to see it.").to_string(); + } + if app.assistant.preview().is_some() { + return tl!("Writing its reply…").to_string(); + } + let messages = app.assistant.messages(); + 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)); + i18n::fmt("{step} · thinking…", &[("step", &step)]) + } + _ if app.assistant.waiting() => tl!("Thinking…").to_string(), + // Waiting to try again, say: the note says why and when. + _ => match messages.last() { + Some(Entry::Note(n)) => i18n::note(n), + _ => tl!("Working…").to_string(), + }, + } +} + +/// A tool call in plain words: the command's name, or what the tool does. +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!(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("Ran the tool {tool}", &[("tool", tool)]), + None => tl!("Ran a tool").to_string(), + } + } + "list_layers" => tl!("Looked at the layers").to_string(), + "view_map" => tl!("Looked at the map").to_string(), + "search_commands" => tl!("Looked for a command").to_string(), + "search_tools" => tl!("Looked for a tool").to_string(), + "describe_tool" => tl!("Read about a tool").to_string(), + "read_features" => tl!("Read features").to_string(), + "search_docs" | "read_doc" => tl!("Read the user guide").to_string(), + "load_skill" => tl!("Loaded a skill").to_string(), + "delegate" => tl!("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) { + let ctx = ui.ctx().clone(); + let mut state = chat(&ctx); + let set_up = setup(app); + // Shown to set the Assistant up, the settings stay until Start: a field filled in doesn't + // take them away while the rest is still typed. + if set_up == Setup::Missing { + state.settings = true; + } + let settings = state.settings; + heading(app, ui, t, &mut state, set_up, settings); + match set_up { + Setup::Off => {} + Setup::Reading => { + ui.horizontal(|ui| { + ui.set_min_height(TARGET); + ui.spinner(); + ui.label(RichText::new(tl!("Reading the Assistant's settings…")).size(15.0).color(t.text_dim)); + }); + } + _ if settings => settings_form(app, ui, t, &mut state), + _ => conversation(app, ui, t, &mut state), + } + set_chat(&ctx, state); +} + +/// The sheet's heading: the button that makes it taller or shorter, the settings, a new +/// conversation, and ×. A swipe down lowers it a step (full to half, half away), a swipe up +/// raises it. +fn heading(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, state: &mut Chat, set_up: Setup, settings: bool) { + let has_chat = !app.assistant.messages().is_empty(); + let swipe = heading_row(ui, t, tl!("Assistant"), |ui| { + let (icon, hint, to) = match state.height { + Height::Half => ("up", tl!("Make the sheet taller"), Height::Full), + Height::Full => ("down", tl!("Make the sheet shorter"), Height::Half), + }; + if icon_button(ui, t, icon, hint) { + state.height = to; + } + if set_up == Setup::Ready { + let hint = if settings { tl!("Back to the conversation") } else { tl!("Assistant settings") }; + if icon_button(ui, t, "settings", hint) { + state.settings = !settings; + } + } + if has_chat && !settings && icon_button(ui, t, "delete", tl!("New conversation")) { + assistant::new_conversation(app); + } + }); + match (swipe, state.height) { + (Some(Swipe::Down), Height::Full) => state.height = Height::Half, + (Some(Swipe::Down), Height::Half) => set_sheet(ui.ctx(), Sheet::None), + (Some(Swipe::Up), _) => state.height = Height::Full, + (None, _) => {} + } +} + +/// The conversation, with the approval waiting or the typing bar under it. +fn conversation(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, state: &mut Chat) { + let approval = assistant::pending(app); + let fresh = approval.as_ref().map(|a| &a.asked) != state.card.as_ref().map(|(asked, _)| asked); + if fresh { + state.card = approval.as_ref().map(|a| (a.asked.clone(), ui.input(|i| i.time))); + } + // What the sheet's body has: the card's details take what its heading and buttons leave. + let room = ui.available_height(); + // A card that doesn't fit half up (a phone held sideways) stands the sheet full as it comes; + // lowered again by hand, it stays lowered, and scrolls. + if fresh && approval.is_some() && state.height == Height::Half && room < CARD_ROWS * (TARGET + ui.spacing().item_spacing.y) + TARGET { + state.height = Height::Full; + ui.ctx().request_repaint(); + } + // The foot first, so the messages take what is left above it. + egui::Panel::bottom("touch_assistant_foot").frame(egui::Frame::NONE.inner_margin(egui::Margin::symmetric(0, 4))).show(ui, |ui| { + match &approval { + Some(approval) => card(app, ui, t, state, approval, room), + None => typing(app, ui, t, state), + } + }); + egui::ScrollArea::vertical().id_salt("touch_assistant_messages").auto_shrink([false, false]).stick_to_bottom(true).show(ui, |ui| { + ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Wrap); + messages(app, ui, t); + }); +} + +/// The conversation's messages, oldest first; the reply arriving, as it streams in. +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." + ); + ui.label(RichText::new(hint).size(15.0).color(t.text_dim)); + return; + } + for (i, e) in app.assistant.messages().iter().enumerate() { + match e { + // A message of pictures alone: its notes say them. + Entry::User(text) if text.is_empty() => {} + Entry::User(text) => { + ui.add_space(6.0); + ui.with_layout(Layout::right_to_left(Align::Min), |ui| { + egui::Frame::NONE.fill(t.selection).corner_radius(8).inner_margin(egui::Margin::symmetric(12, 8)).show(ui, |ui| { + ui.set_max_width(ui.available_width() * 0.85); + ui.add(egui::Label::new(RichText::new(text).size(15.0).color(t.text)).halign(Align::LEFT)); + }); + }); + ui.add_space(4.0); + } + Entry::Assistant(text) => { + assistant::reply(ui, text, t); + ui.add_space(4.0); + } + Entry::Tool { name, summary, result, error } => { + let (mark, ink) = if *error { ("✗", t.red) } else { ("✓", t.green) }; + let head = RichText::new(format!("{mark} {}", plain(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(); + ui.label(RichText::new(&shown).monospace().small().color(t.text_dim)); + let left = result.chars().count().saturating_sub(2000); + if left > 0 { + let more = i18n::fmt("… and {n} more characters.", &[("n", &left.to_string())]); + ui.label(RichText::new(more).small().italics().color(t.text_dim)); + } + }); + } + Entry::Error(e) => assistant::error(ui, e, t), + Entry::Note(n) => { + ui.label(RichText::new(i18n::note(n)).size(13.0).italics().color(t.text_dim)); + } + } + } + if app.assistant.waiting() { + match app.assistant.preview() { + Some(text) => { + assistant::reply(ui, text, t); + ui.spinner(); + } + None => { + ui.horizontal(|ui| { + ui.spinner(); + ui.label(RichText::new(tl!("Thinking…")).size(14.0).color(t.text_dim)); + }); + } + } + } +} + +/// 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 +/// 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 +/// tap begun on the card before, or meant for it, never answers this one. +fn card(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, state: &mut Chat, approval: &assistant::Approval, room: f32) { + let ctx = ui.ctx().clone(); + let now = ui.input(|i| i.time); + let since = state.card.as_ref().filter(|(asked, _)| *asked == approval.asked).map_or(now, |(_, at)| *at); + let settled = now - since >= SETTLE; + if !settled { + ctx.request_repaint_after(web_time::Duration::from_secs_f64(SETTLE)); + } + let frame = egui::Frame::NONE.fill(t.amber.gamma_multiply(0.15)).corner_radius(8).inner_margin(10).stroke(Stroke::new(1.0, t.amber)); + // The title, the "for this conversation" chip, the buttons and the card's margins. + let others = CARD_ROWS * (TARGET + ui.spacing().item_spacing.y) + 24.0; + // Too short for its details to have rows of their own beside the rest (a phone held + // sideways, with a track's strip): the whole card scrolls, its details before its buttons. + let cramped = room - others < 2.0 * TARGET; + ui.push_id(("touch_assistant_card", &approval.asked), |ui| { + let mut body = |ui: &mut Ui| { + frame.show(ui, |ui| { + ui.label(RichText::new(tl!("Allow this action?")).size(16.0).strong().color(t.text)); + if cramped { + assistant::approval_details(ui, app, approval); + } else { + egui::ScrollArea::vertical().id_salt("touch_assistant_approval").max_height(room - others).show(ui, |ui| { + assistant::approval_details(ui, app, approval); + }); + } + 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 { + always = !always; + state.always = always.then(|| approval.asked.clone()); + } + ui.horizontal(|ui| { + let third = (width - 2.0 * ui.spacing().item_spacing.x) / 3.0; + if action(ui, t, tl!("Stop"), third, false, settled) { + state.always = None; + assistant::stop(app); + return; + } + let decline = action(ui, t, tl!("Decline"), third, false, settled); + let allow = action(ui, t, tl!("Allow"), third, true, settled); + if allow || decline { + state.always = None; + assistant::decide(app, &approval.asked, allow, always, &ctx); + } + }); + }); + }; + if cramped { + egui::ScrollArea::vertical().id_salt("touch_assistant_card_scroll").max_height(room.max(TARGET)).show(ui, body); + } else { + body(ui); + } + }); +} + +/// The typing bar: the message being written, which opens the system's text field when tapped +/// (or is typed into here where there is none), and Send, or Stop while the Assistant works. +fn typing(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, state: &mut Chat) { + let ctx = ui.ctx().clone(); + let busy = app.assistant.busy(); + let waiting = app.assistant.waiting_to_send(); + if waiting { + ui.label(RichText::new(tl!("It is sent once the key is read.")).size(13.0).color(t.text_dim)); + } + let id = egui::Id::unique("touch_assistant_input"); + let mut send = false; + ui.horizontal(|ui| { + let gap = ui.spacing().item_spacing.x; + let button = 88.0; + let size = Vec2::new((ui.available_width() - button - gap).max(TARGET), TARGET); + let hint = tl!("Ask, or say what to do…"); + if let Some(enter) = &app.services.enter_text { + let open = state.entering.as_ref().is_some_and(|(_, f, _)| *f == Field::Message); + if entry_box(ui, t, size, &app.assistant.input, hint, open).clicked() { + let entry_id = format!("assistant:message:{}", state.entries); + state.entries += 1; + let entry = TextEntry { + id: entry_id.clone(), + value: app.assistant.input.clone(), + label: tl!("Message to the Assistant").to_string(), + kind: TextKind::Lines, + done: tl!("Done").to_string(), + }; + match enter(&entry) { + Ok(()) => { + state.entering = Some((entry_id, Field::Message, String::new())); + // Typing wants room: the conversation above, the keyboard below. + state.height = Height::Full; + } + Err(e) => app.session.notify(e, true), + } + } + } else { + // Enter sends; Shift+Enter starts a new line. Taken before the box sees it. + if !busy && ui.memory(|m| m.has_focus(id)) && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)) { + send = true; + } + let edit = egui::TextEdit::multiline(&mut app.assistant.input) + .id(id) + .desired_rows(1) + .hint_text(hint) + .font(egui::FontId::proportional(15.0)) + .margin(egui::Margin::symmetric(8, 10)); + let typed = ui.add_sized(size, edit); + if typed.gained_focus() { + state.height = Height::Full; + } + } + if busy || waiting { + if action(ui, t, tl!("Stop"), button, false, true) { + assistant::stop(app); + } + } else if action(ui, t, tl!("Send"), button, true, !app.assistant.input.trim().is_empty()) { + send = true; + } + }); + if send && !busy { + // What the system's field sends from now on is of the message sent, not of the next. + if state.entering.as_ref().is_some_and(|(_, f, _)| *f == Field::Message) { + state.entering = None; + } + let text = app.assistant.input.clone(); + assistant::send(app, text, &ctx); + } +} + +/// The provider's settings: the provider, its model, its address and its key, and whether the key +/// is remembered on this device. A ChatGPT sign-in is set up in the desktop interface. +fn settings_form(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, state: &mut Chat) { + let ctx = ui.ctx().clone(); + let Some(mut cfg) = app.assistant.config().cloned() else { return }; + let before = (cfg.clone(), app.assistant.remember_key()); + // Start the first time; Done once there is a conversation to go back to. + let started = !app.assistant.messages().is_empty(); + egui::ScrollArea::vertical().id_salt("touch_assistant_settings").auto_shrink([false, true]).show(ui, |ui| { + let intro = tl!("The Assistant sends your messages, and what it needs to know of the map, to the AI provider you choose."); + ui.label(RichText::new(intro).size(14.0).color(t.text_dim)); + label(ui, t, tl!("Provider")); + // Wrapped, so the provider chosen is in sight whichever it is. + ui.horizontal_wrapped(|ui| { + let chosen = cfg.provider.clone(); + for p in PRESETS.iter().filter(|p| !p.login || p.id == chosen) { + let on = p.id == chosen; + let text = RichText::new(tl!(p.label)).size(15.0).color(if on { t.accent_text } else { t.text }); + let chip = egui::Button::new(text).fill(if on { t.checked } else { t.input }).min_size(Vec2::new(TARGET, TARGET - 8.0)); + if ui.add(chip).clicked() && !on { + assistant::choose_provider(app, &mut cfg, p.id, &ctx); + } + } + }); + let preset = provider::preset(&cfg.provider); + if cfg.login() { + ui.label( + RichText::new(tl!("Signing in with ChatGPT is set up in the desktop interface: More › Use the Desktop Interface.")) + .size(14.0) + .color(t.text), + ); + } else { + label(ui, t, tl!("Model")); + field(app, ui, t, state, Field::Model, &mut cfg.model, tl!("the model's name")); + let models: Vec<(String, String)> = app.assistant.models().iter().map(|m| (m.clone(), m.clone())).collect(); + if !models.is_empty() { + super::chips(ui, t, "touch_assistant_models", &models, &mut cfg.model); + } + label(ui, t, tl!("Address")); + field(app, ui, t, state, Field::Address, &mut cfg.base_url, tl!("the provider's address")); + { + // A provider that works without a key may still take one (a server of the user's own). + label(ui, t, if preset.is_some_and(|p| p.keyless) { tl!("API key, if it needs one") } else { tl!("API key") }); + field(app, ui, t, state, Field::Key, &mut cfg.key, tl!("paste the provider's key here")); + if let Some(url) = preset.map(|p| p.key_url).filter(|u| !u.is_empty()) { + ui.label(RichText::new(i18n::fmt("A key comes from {url}", &[("url", url)])).size(13.0).color(t.text_dim)); + } + let mut remember = app.assistant.remember_key(); + if toggle_chip(ui, t, tl!("Remember the key on this device"), ui.available_width(), remember) { + remember = !remember; + app.assistant.set_remember_key(remember); + } + } + } + if let Some(why) = cfg.missing() { + ui.label(RichText::new(tl!(why)).size(14.0).color(t.amber)); + } else if action(ui, t, if started { tl!("Done") } else { tl!("Start") }, ui.available_width(), true, true) { + state.settings = false; + } + }); + assistant::apply_settings(app, cfg, before, &ctx); +} + +/// A label over a field of the settings. +fn label(ui: &mut Ui, t: &Tokens, text: &str) { + ui.add_space(4.0); + ui.label(RichText::new(text).size(13.0).color(t.text_dim)); +} + +/// A field of the settings: a box the system's text field opens on, where there is one, else +/// typed into here. The key shows as dots. +fn field(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, state: &mut Chat, field: Field, value: &mut String, hint: &str) { + let size = Vec2::new(ui.available_width(), TARGET - 6.0); + let secret = field == Field::Key; + let Some(enter) = &app.services.enter_text else { + // The desktop pane's ids: its settings are saved once none of them is typed in. + let id = match field { + Field::Model => "assistant_model", + Field::Address => "assistant_url", + _ => "assistant_key", + }; + let edit = egui::TextEdit::singleline(value) + .id(egui::Id::unique(id)) + .password(secret) + .hint_text(hint) + .font(egui::FontId::proportional(15.0)) + .margin(egui::Margin::symmetric(8, 10)); + ui.add_sized(size, edit); + return; + }; + let open = state.entering.as_ref().is_some_and(|(_, f, _)| *f == field); + let shown = if secret && !value.is_empty() { "•".repeat(12) } else { value.clone() }; + if entry_box(ui, t, size, &shown, hint, open).clicked() { + let id = format!("assistant:setting:{}", state.entries); + state.entries += 1; + let (label, kind) = match field { + Field::Model => (tl!("The model's name"), TextKind::Plain), + Field::Address => (tl!("The provider's address"), TextKind::Plain), + _ => (tl!("The provider's API key"), TextKind::Secret), + }; + let provider = app.assistant.config().map(|c| c.provider.clone()).unwrap_or_default(); + let entry = TextEntry { id: id.clone(), value: value.clone(), label: label.to_string(), kind, done: tl!("Done").to_string() }; + match enter(&entry) { + Ok(()) => state.entering = Some((id, field, provider)), + Err(e) => app.session.notify(e, true), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::tests::Held; + use egui::Rect; + use rustgis_ui_egui::rustgis_assistant::HttpResponse; + use serde_json::{Value, json}; + use std::cell::RefCell; + use std::collections::VecDeque; + use std::rc::Rc; + use std::sync::{Arc, Mutex}; + + /// The provider's requests answered in turn by `replies`, and once they are used up never + /// answered; gives how many were sent. + fn answering(held: &mut Held, replies: Vec) -> Arc> { + let sent = Arc::new(Mutex::new(0)); + let count = sent.clone(); + let replies = Mutex::new(VecDeque::from(replies)); + held.app.services.http = Some(Box::new(move |_, slot| { + *count.lock().unwrap() += 1; + if let Some(reply) = replies.lock().unwrap().pop_front() { + *slot.lock().unwrap() = Some(Ok(HttpResponse { status: 200, body: reply.to_string().into_bytes(), headers: vec![] })); + } + })); + sent + } + + fn say(text: &str) -> Value { + json!({"choices": [{"message": {"role": "assistant", "content": text}, "finish_reason": "stop"}]}) + } + + /// A reply calling one command. + fn command(id: &str, command: &str, params: Value) -> Value { + let args = json!({"command": command, "params": params}).to_string(); + json!({"choices": [{"message": {"role": "assistant", "content": null, + "tool_calls": [{"id": id, "type": "function", "function": {"name": "run_command", "arguments": args}}]}, + "finish_reason": "tool_calls"}]}) + } + + /// Chooses `provider` with `model` and no key: an OpenAI-compatible one needs none, so a model + /// sets it up and none leaves it not set up. + fn provider(held: &mut Held, provider: &str, model: &str) { + let ctx = held.ctx.clone(); + assistant::open(&mut held.app, &ctx); + let mut cfg = held.app.assistant.config().cloned().unwrap(); + let before = (cfg.clone(), held.app.assistant.remember_key()); + assistant::choose_provider(&mut held.app, &mut cfg, provider, &ctx); + cfg.model = model.into(); + cfg.key.clear(); + assistant::apply_settings(&mut held.app, cfg, before, &ctx); + held.frame(Vec::new()); + held.frame(Vec::new()); + } + + /// The bar's labels, left to right. + fn bar(held: &mut Held) -> Vec { + let foot = held.screen.y - crate::BAR; + let mut words: Vec<(String, Rect)> = held.frame(Vec::new()).into_iter().filter(|(_, at)| at.min.y >= foot).collect(); + words.sort_by(|a, b| a.1.min.x.total_cmp(&b.1.min.x)); + words.into_iter().map(|(word, _)| word).collect() + } + + /// Where `word` is on the bar. + fn on_bar(held: &mut Held, word: &str) -> egui::Pos2 { + let foot = held.screen.y - crate::BAR; + held.frame(Vec::new()).into_iter().find(|(w, at)| w == word && at.min.y >= foot).map(|(_, at)| at.center()).unwrap() + } + + /// The system's text field, as a phone's shell opens it: what was asked for is kept. + fn native(held: &mut Held) -> Rc>> { + let asked: Rc>> = Rc::default(); + let asking = asked.clone(); + held.app.services.enter_text = Some(Box::new(move |entry| { + asking.borrow_mut().push(entry.clone()); + Ok(()) + })); + asked + } + + fn said(held: &Held, mark: u64) -> Vec { + held.app.session.notices_since(mark).iter().map(|n| n.text.clone()).collect() + } + + #[test] + fn nothing_of_the_assistant_shows_until_it_is_set_up_nor_with_its_extension_off() { + let mut held = Held::new(); + // Tall enough for the whole of More. + held.screen = Vec2::new(411.0, 1600.0); + provider(&mut held, "custom", ""); + assert_eq!(setup(&held.app), Setup::Missing); + assert_eq!(bar(&mut held), ["Add Data", "Capture", "More"]); + assert!(!strip_shown(&held.app, &held.ctx)); + // The only trace: a row in More, which opens the settings. + held.raise(Sheet::More, "More"); + let row = held.find("Set Up the Assistant").expect("the row in More").center(); + held.touch(&[row]); + assert_eq!(sheet(&held.ctx), Sheet::Assistant); + assert!(held.find("Choose a model.").is_some(), "the settings say what is missing"); + // Set up: its button on the bar, and no row in More. + provider(&mut held, "custom", "test"); + assert_eq!(setup(&held.app), Setup::Ready); + assert_eq!(bar(&mut held), ["Add Data", "Capture", "Assistant", "More"]); + held.raise(Sheet::More, "More"); + assert!(held.find("Set Up the Assistant").is_none()); + // The extension off: none of it, and its sheet is lowered. + held.raise(Sheet::Assistant, "Assistant"); + crate::run(&mut held.app, "extension.disable", json!({"id": "assistant"})); + held.frame(Vec::new()); + assert_eq!(sheet(&held.ctx), Sheet::None); + assert_eq!(bar(&mut held), ["Add Data", "Capture", "More"]); + provider(&mut held, "custom", ""); + held.raise(Sheet::More, "More"); + assert!(held.find("Set Up the Assistant").is_none()); + } + + #[test] + fn layers_is_a_button_on_the_map_and_the_assistant_takes_its_place_on_the_bar() { + let mut held = Held::new(); + provider(&mut held, "custom", "test"); + // A finger's size at the map's top-right corner: it raises the Layers sheet and lowers it, + // and the map under it takes neither tap. + let map = held.app.map.view_rect.unwrap().0; + let corner = egui::pos2(map.max.x - 8.0 - TARGET / 2.0, map.min.y + 8.0 + TARGET / 2.0); + let camera = held.app.session.map().camera; + held.touch(&[corner + Vec2::new(TARGET / 2.0 - 4.0, TARGET / 2.0 - 4.0)]); + assert_eq!(sheet(&held.ctx), Sheet::Layers); + held.touch(&[corner]); + assert_eq!(sheet(&held.ctx), Sheet::None); + assert_eq!(held.app.session.map().camera, camera); + // ModelBuilder in the map's place has its own buttons there: Layers is on the bar then. + crate::run(&mut held.app, "ui.modelBuilder", json!({})); + assert_eq!(bar(&mut held), ["Layers", "Add Data", "Capture", "Assistant", "More"]); + let back = held.find("Back to the map").unwrap().center(); + held.touch(&[back]); + assert_eq!(bar(&mut held), ["Add Data", "Capture", "Assistant", "More"]); + // The bar's Assistant raises its sheet and lowers it. + let button = on_bar(&mut held, "Assistant"); + held.touch(&[button]); + assert_eq!(sheet(&held.ctx), Sheet::Assistant); + held.touch(&[button]); + assert_eq!(sheet(&held.ctx), Sheet::None); + } + + #[test] + fn a_message_typed_in_the_systems_text_field_is_sent_and_the_reply_drawn() { + let mut held = Held::new(); + provider(&mut held, "custom", "test"); + let sent = answering(&mut held, vec![say("Tokyo is in view.")]); + let asked = native(&mut held); + raise(&held.ctx, Height::Half); + held.frame(Vec::new()); + let bar = held.find("Ask, or say what to do…").unwrap().center(); + held.touch(&[bar]); + let entry = asked.borrow().last().cloned().expect("the system's text field"); + assert_eq!((entry.kind, entry.value.as_str()), (TextKind::Lines, "")); + assert_eq!(height(&held.ctx), Height::Full, "typing raises the sheet"); + held.app.typed.push(Typed::Text { id: entry.id.clone(), text: "Zoom to Tokyo".into() }); + held.frame(Vec::new()); + assert_eq!(held.app.assistant.input, "Zoom to Tokyo"); + let send = held.find("Send").unwrap().center(); + held.touch(&[send]); + assert_eq!(*sent.lock().unwrap(), 1); + assert!(held.app.assistant.messages().iter().any(|e| matches!(e, Entry::User(t) if t == "Zoom to Tokyo"))); + assert!(held.find("Tokyo is in view.").is_some(), "the reply is drawn"); + // What the field still sends after the message went is the message's, not the next one's. + held.app.typed.push(Typed::Text { id: entry.id.clone(), text: "Zoom to Tokyo".into() }); + held.app.typed.push(Typed::Closed { id: entry.id, failed: None }); + held.frame(Vec::new()); + assert_eq!(held.app.assistant.input, ""); + } + + #[test] + fn without_a_system_text_field_the_message_is_typed_here() { + let mut held = Held::new(); + provider(&mut held, "custom", "test"); + answering(&mut held, vec![say("Done.")]); + raise(&held.ctx, Height::Half); + held.frame(Vec::new()); + let bar = held.find("Ask, or say what to do…").unwrap().center(); + held.touch(&[bar]); + held.frame(vec![egui::Event::Text("Label the cities".into())]); + assert_eq!(held.app.assistant.input, "Label the cities"); + let enter = + egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + held.frame(vec![enter]); + held.frame(Vec::new()); + assert!(held.app.assistant.messages().iter().any(|e| matches!(e, Entry::User(t) if t == "Label the cities"))); + assert_eq!(held.app.assistant.input, "", "Enter sent it, adding no line"); + } + + #[test] + fn stop_ends_the_run_from_the_sheet_and_from_the_strip_left_while_it_works() { + let mut held = Held::new(); + provider(&mut held, "custom", "test"); + // Never answered: the Assistant works until it is stopped. + answering(&mut held, Vec::new()); + raise(&held.ctx, Height::Half); + held.app.assistant.input = "Buffer the cities".into(); + let send = held.find("Send").unwrap().center(); + held.touch(&[send]); + assert!(held.app.assistant.busy()); + let stop = held.find("Stop").unwrap().center(); + held.touch(&[stop]); + assert!(!held.app.assistant.busy()); + assert!(held.find("Stopped.").is_some()); + // Again, and the sheet lowered: the strip says what it is doing and has Stop. + held.app.assistant.input = "Buffer the cities again".into(); + let send = held.find("Send").unwrap().center(); + held.touch(&[send]); + set_sheet(&held.ctx, Sheet::None); + assert!(held.find("Thinking…").is_some(), "the strip"); + assert!(strip_shown(&held.app, &held.ctx)); + // Its words raise the sheet, half up. + let words = held.find("Thinking…").unwrap().center(); + held.touch(&[words]); + assert_eq!((sheet(&held.ctx), height(&held.ctx)), (Sheet::Assistant, Height::Half)); + set_sheet(&held.ctx, Sheet::None); + let stop = held.find("Stop").unwrap().center(); + held.touch(&[stop]); + assert!(!held.app.assistant.busy()); + assert!(!strip_shown(&held.app, &held.ctx)); + assert!(held.find("Thinking…").is_none()); + } + + #[test] + fn an_approval_is_a_card_and_one_no_longer_waiting_answers_nothing() { + let mut held = Held::new(); + provider(&mut held, "custom", "test"); + let path = std::env::temp_dir().join(format!("rustgis-touch-never-written-{}.png", std::process::id())); + let export = || command("c0", "share.exportMap", json!({"path": path})); + // The second reply calls the same id again, as some providers' replies do. + answering(&mut held, vec![export(), export(), say("Nothing exported.")]); + raise(&held.ctx, Height::Half); + held.app.assistant.input = "Export the map".into(); + let send = held.find("Send").unwrap().center(); + held.touch(&[send]); + held.frame(Vec::new()); + let shown = assistant::pending(&held.app).expect("an approval"); + assert!(held.find("Allow this action?").is_some()); + let decline = held.find("Decline").unwrap(); + let mark = held.app.session.notice_mark(); + held.touch(&[decline.center()]); + // Answered, and the next reply asks again. A second tap there as its card comes (a double + // tap meant for the first) answers nothing. + let next = assistant::pending(&held.app).expect("the next approval"); + assert!(next.asked != shown.asked); + held.touch(&[decline.center()]); + assert!(assistant::pending(&held.app).is_some_and(|p| p.asked == next.asked), "the second tap answered nothing"); + // Nor does the first card's answer, given late. + assert!(said(&held, mark).iter().all(|n| !n.contains("no longer waiting")), "{:?}", said(&held, mark)); + let entries = held.app.assistant.messages().len(); + let ctx = held.ctx.clone(); + assistant::decide(&mut held.app, &shown.asked, true, false, &ctx); + assert_eq!(held.app.assistant.messages().len(), entries); + assert!(assistant::pending(&held.app).is_some_and(|p| p.asked == next.asked)); + let notices = said(&held, mark); + assert_eq!(notices.iter().filter(|n| n.contains("no longer waiting")).count(), 1, "{notices:?}"); + // In sight a moment, its Decline answers it. + let decline = held.find("Decline").unwrap().center(); + held.touch(&[decline]); + held.frame(Vec::new()); + assert!(assistant::pending(&held.app).is_none()); + assert!(!path.exists()); + assert!(held.find("Nothing exported.").is_some()); + } + + #[test] + fn the_sheet_stands_full_or_half_by_its_button_or_a_swipe_and_a_swipe_lowers_it() { + let mut held = Held::new(); + provider(&mut held, "custom", "test"); + let title = |held: &mut Held| held.raise(Sheet::Assistant, "Assistant"); + raise(&held.ctx, Height::Half); + let half = title(&mut held); + // The button beside × makes it taller, and shorter again. + let spacing = held.ctx.global_style().spacing.item_spacing.x; + let button = egui::pos2(held.screen.x - 8.0 - TARGET - spacing - TARGET / 2.0, half.y); + held.touch(&[button]); + assert_eq!(height(&held.ctx), Height::Full); + let full = title(&mut held); + assert!(full.y < half.y - 100.0, "{full:?} over {half:?}"); + held.touch(&[egui::pos2(button.x, full.y)]); + assert_eq!(height(&held.ctx), Height::Half); + // Up a step by a swipe up; down a step by each swipe down, the last lowering it. + let swipe = + |held: &mut Held, from: egui::Pos2, dy: f32| held.touch(&[from, from + Vec2::new(0.0, dy / 2.0), from + Vec2::new(0.0, dy)]); + let from = egui::pos2(160.0, half.y); + swipe(&mut held, from, -120.0); + assert_eq!(height(&held.ctx), Height::Full); + let full = title(&mut held); + swipe(&mut held, egui::pos2(160.0, full.y), 120.0); + assert_eq!((sheet(&held.ctx), height(&held.ctx)), (Sheet::Assistant, Height::Half)); + let half = title(&mut held); + swipe(&mut held, egui::pos2(160.0, half.y), 120.0); + assert_eq!(sheet(&held.ctx), Sheet::None); + // Back lowers it as it does every sheet. + let back = egui::Event::Key { + key: egui::Key::BrowserBack, + physical_key: None, + pressed: true, + repeat: false, + modifiers: egui::Modifiers::NONE, + }; + title(&mut held); + held.frame(vec![back]); + assert_eq!(sheet(&held.ctx), Sheet::None); + } + + #[test] + fn the_settings_take_a_key_from_the_systems_text_field_for_its_provider_only() { + let mut held = Held::new(); + let asked = native(&mut held); + provider(&mut held, "openai", "gpt-test"); + assert_eq!(setup(&held.app), Setup::Missing); + raise(&held.ctx, Height::Full); + held.frame(Vec::new()); + assert!(held.find("Enter an API key.").is_some()); + let key = held.find("paste the provider's key here").unwrap().center(); + held.touch(&[key]); + let entry = asked.borrow().last().cloned().expect("the system's text field"); + assert_eq!(entry.kind, TextKind::Secret); + let mark = held.app.session.notice_mark(); + held.app.typed.push(Typed::Text { id: entry.id.clone(), text: " synthetic-key ".into() }); + held.frame(Vec::new()); + assert_eq!(held.app.assistant.config().map(|c| c.key.as_str()), Some("synthetic-key")); + assert_eq!(setup(&held.app), Setup::Ready); + assert!(said(&held, mark).is_empty()); + // Set up, the settings stay until Start, and the key shows as dots. + assert!(held.find("synthetic-key").is_none()); + let start = held.find("Start").expect("the settings stay up").center(); + held.touch(&[start]); + assert!(held.find("Ask, or say what to do…").is_some(), "the conversation"); + // Typed for one provider's key while another was chosen: not kept, and said once. + provider(&mut held, "openai", "gpt-test"); + raise(&held.ctx, Height::Full); + held.frame(Vec::new()); + let key = held.find("paste the provider's key here").unwrap().center(); + held.touch(&[key]); + let entry = asked.borrow().last().cloned().unwrap(); + provider(&mut held, "gemini", "gemini-test"); + held.app.typed.push(Typed::Text { id: entry.id.clone(), text: "for openai".into() }); + held.app.typed.push(Typed::Text { id: entry.id, text: "for openai, longer".into() }); + held.frame(Vec::new()); + assert_eq!(held.app.assistant.config().map(|c| c.key.as_str()), Some("")); + let notices = said(&held, mark); + assert_eq!(notices.iter().filter(|n| n.contains("wasn't kept")).count(), 1, "{notices:?}"); + } + + /// What the system's text field sends for the settings after the extension is turned off is + /// not taken, and that is said once; a provider that needs no key still offers its key field. + #[test] + fn typing_for_the_settings_after_the_assistant_is_turned_off_is_not_kept() { + let mut held = Held::new(); + let asked = native(&mut held); + provider(&mut held, "custom", ""); + raise(&held.ctx, Height::Full); + held.frame(Vec::new()); + assert!(held.find("API key, if it needs one").is_some()); + let model = held.find("the model's name").unwrap().center(); + held.touch(&[model]); + let entry = asked.borrow().last().cloned().expect("the system's text field"); + crate::run(&mut held.app, "extension.disable", json!({"id": "assistant"})); + let mark = held.app.session.notice_mark(); + held.app.typed.push(Typed::Text { id: entry.id.clone(), text: "test".into() }); + held.app.typed.push(Typed::Text { id: entry.id, text: "test model".into() }); + held.frame(Vec::new()); + assert_eq!(held.app.assistant.config().map(|c| c.model.as_str()), Some("")); + let notices = said(&held, mark); + assert_eq!(notices.iter().filter(|n| n.contains("turned off while it was typed")).count(), 1, "{notices:?}"); + // Nor what it sends only once the extension is on again. + crate::run(&mut held.app, "extension.enable", json!({"id": "assistant"})); + raise(&held.ctx, Height::Full); + held.frame(Vec::new()); + let model = held.find("the model's name").unwrap().center(); + held.touch(&[model]); + let entry = asked.borrow().last().cloned().expect("the system's text field"); + crate::run(&mut held.app, "extension.disable", json!({"id": "assistant"})); + held.frame(Vec::new()); + crate::run(&mut held.app, "extension.enable", json!({"id": "assistant"})); + let mark = held.app.session.notice_mark(); + held.app.typed.push(Typed::Text { id: entry.id.clone(), text: "late".into() }); + held.app.typed.push(Typed::Closed { id: entry.id, failed: None }); + held.frame(Vec::new()); + assert_eq!(held.app.assistant.config().map(|c| c.model.as_str()), Some("")); + let notices = said(&held, mark); + assert_eq!(notices.iter().filter(|n| n.contains("turned off while it was typed")).count(), 1, "{notices:?}"); + } + + /// In a short window (a phone held sideways) the approval card raises the sheet as it comes and + /// scrolls whole, what would run before its buttons; lowered by hand, the sheet stays lowered. + #[test] + fn an_approval_card_in_a_short_window_scrolls_whole_and_its_height_is_the_users() { + let mut held = Held::new(); + held.screen = Vec2::new(800.0, 360.0); + provider(&mut held, "custom", "test"); + let path = std::env::temp_dir().join(format!("rustgis-touch-short-never-written-{}.png", std::process::id())); + answering(&mut held, vec![command("c0", "share.exportMap", json!({"path": path})), say("Not exported.")]); + raise(&held.ctx, Height::Half); + held.app.assistant.input = "Export the map".into(); + let send = held.find("Send").unwrap().center(); + held.touch(&[send]); + held.frame(Vec::new()); + assert!(assistant::pending(&held.app).is_some()); + assert_eq!(height(&held.ctx), Height::Full, "raised as the card came"); + let words = held.frame(Vec::new()); + let title = words.iter().find(|(w, _)| w == "Allow this action?").map(|(_, at)| *at).expect("the card's title in sight"); + let what = words.iter().find(|(w, _)| w == "Export Map").map(|(_, at)| *at).expect("what would run, in sight"); + assert!(title.max.y <= what.min.y); + // Its buttons are reached by scrolling the card. + let over = egui::pos2(400.0, what.center().y); + let mut decline = None; + for _ in 0..20 { + let wheel = egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: Vec2::new(0.0, -60.0), + modifiers: egui::Modifiers::NONE, + phase: egui::TouchPhase::Move, + source: egui::MouseWheelSource::Wheel, + }; + let words = held.frame(vec![egui::Event::PointerMoved(over), wheel]); + decline = words.into_iter().find(|(w, at)| w == "Decline" && at.max.y <= held.screen.y - crate::BAR).map(|(_, at)| at.center()); + if decline.is_some() { + break; + } + } + held.touch(&[decline.expect("Decline scrolled into sight")]); + held.frame(Vec::new()); + assert!(assistant::pending(&held.app).is_none()); + assert!(!path.exists()); + // Lowered by hand while a card is up, it stays lowered. + held.app.assistant.input = "Export it again".into(); + answering(&mut held, vec![command("c0", "share.exportMap", json!({"path": path}))]); + let send = held.find("Send").unwrap().center(); + held.touch(&[send]); + held.frame(Vec::new()); + assert_eq!(height(&held.ctx), Height::Full); + let full = held.raise(Sheet::Assistant, "Assistant"); + held.touch(&[full, full + Vec2::new(0.0, 60.0), full + Vec2::new(0.0, 120.0)]); + held.frame(Vec::new()); + assert_eq!((sheet(&held.ctx), height(&held.ctx)), (Sheet::Assistant, Height::Half)); + } +} diff --git a/crates/ui-touch/src/lib.rs b/crates/ui-touch/src/lib.rs index 75ec4a16d8..fa826b8f4b 100644 --- a/crates/ui-touch/src/lib.rs +++ b/crates/ui-touch/src/lib.rs @@ -6,11 +6,13 @@ //! the desktop interface's View › Touch Interface can bring it back. Dialogs, notices and the //! Project page stay the front end's. //! -//! What is here: the map, the bar (Layers, Add Data, Capture, More), the Layers sheet (the +//! What is here: the map, with a Layers button at its top-right corner; the bar (Add Data, +//! Capture, the Assistant once it is set up, More); the Layers sheet (the //! project's maps and layouts; show, hide, zoom to, the active layer), the Capture sheet (a //! point, line or polygon placed by the cross on the map, with a form for its layer's attributes //! that follows the layer's data design: value lists, ranges and feature templates) and the More -//! sheet (full extent, undo, the project, the device's position, the desktop interface). A sheet +//! sheet (full extent, undo, the project, the device's position, the desktop interface) and the +//! Assistant's sheet (see [`assistant`]). A sheet //! is lowered by its ×, a swipe down on its heading, a tap on the map above it, or the system's //! Back. Where a shell reports the device's position (`RustGisApp::position`), it is drawn on the //! map and the capture cross can be put on it. @@ -27,6 +29,7 @@ use rustgis_ui_egui::theme::Tokens; use rustgis_ui_egui::{RustGisApp, i18n, icons, tl}; use serde_json::{Value, json}; +mod assistant; mod copies; mod edit; mod form; @@ -65,6 +68,8 @@ enum Sheet { /// Capturing a feature where the cross on the map is. Capture, More, + /// The AI Assistant's conversation, or its settings until it is set up. + Assistant, } /// The sheet shown, kept in egui's memory: the interface has no state of its own in the app. @@ -112,10 +117,14 @@ pub fn chrome(app: &mut RustGisApp, ui: &mut Ui) { track::take(app, &ctx); // What Remove Unused Copies found or removed, off the window's thread. copies::poll(app, &ctx); - // What the system's text field sent back goes in the Capture form's field it was opened for. + // The Assistant's provider, loaded the first time, says whether it is set up. + assistant::prepare(app, &ctx); + // What the system's text field sent back goes in the field it was opened for: the + // Assistant's, or the Capture form's. if !app.typed.is_empty() { - let mut state = form(&ctx); let typed = std::mem::take(&mut app.typed); + let typed = assistant::take_typed(app, &ctx, typed); + let mut state = form(&ctx); state.take_typed(app, typed); set_form(&ctx, state); } @@ -173,6 +182,16 @@ pub fn chrome(app: &mut RustGisApp, ui: &mut Ui) { egui::ScrollArea::horizontal().show(ui, |ui| ui.horizontal_centered(|ui| app.background_status(ui))); }); } + // The Assistant working with its sheet lowered: what it is doing, and Stop. + if assistant::strip_shown(app, &ctx) { + let margin = egui::Margin::symmetric(12, 0); + egui::Panel::bottom("touch_assistant_strip") + .exact_size(TARGET + 8.0) + .frame(frame.inner_margin(margin)) + .show(ui, |ui| assistant::strip(app, ui, &t)); + } + // Lowered by the strip's Stop or its Show: read again. + let shown = sheet(&ctx); if shown != Sheet::None { // As tall as its rows, up to its share of the window: a longer list scrolls. let rows = match shown { @@ -191,15 +210,20 @@ pub fn chrome(app: &mut RustGisApp, ui: &mut Ui) { } + usize::from(can_send_field_package(app)) + copies_rows(&ctx) + + usize::from(assistant::setup(app) == assistant::Setup::Missing) } Sheet::Capture => capture_rows(app, &ctx), - Sheet::None => 0, + // As tall as its height, not its rows: the conversation scrolls. + Sheet::Assistant | Sheet::None => 0, }; let spacing = ui.spacing().item_spacing.y; let groups = if shown == Sheet::More { MORE_GROUPS } else { 0 }; let wanted = (rows + 1) as f32 * (TARGET + spacing) + groups as f32 * (GROUP + spacing) + 2.0 * SHEET_MARGIN; let share = if ctx.egui_wants_keyboard_input() { TYPING_SHARE } else { SHEET_SHARE }; - let height = wanted.min(ui.available_height() * share); + let height = match shown { + Sheet::Assistant => ui.available_height() * assistant::height(&ctx).share().max(share), + _ => wanted.min(ui.available_height() * share), + }; let margin = egui::Margin::symmetric(8, SHEET_MARGIN as i8); egui::Panel::bottom("touch_sheet").resizable(false).exact_size(height).frame(frame.inner_margin(margin)).show( ui, @@ -207,6 +231,7 @@ pub fn chrome(app: &mut RustGisApp, ui: &mut Ui) { Sheet::Layers => layers(app, ui, &t), Sheet::More => more(app, ui, &t), Sheet::Capture => capture(app, ui, &t), + Sheet::Assistant => assistant::show(app, ui, &t), Sheet::None => {} }, ); @@ -224,6 +249,11 @@ pub fn chrome(app: &mut RustGisApp, ui: &mut Ui) { set_sheet(ui.ctx(), Sheet::None); } } + // Layers, at the map's top-right corner (where a desktop's zoom buttons are); on the bar + // while ModelBuilder, with its own buttons there, is in the map's place. + if LAYERS_ON_THE_MAP && map && layers_button(ui, &t, above, shown == Sheet::Layers) { + set_sheet(ui.ctx(), if shown == Sheet::Layers { Sheet::None } else { Sheet::Layers }); + } // While capturing, a cross marks the middle of the map: the point goes there, so the // map is moved under the cross, which a finger does more exactly than a tap. // Where the device is, while its position is shown. @@ -386,30 +416,76 @@ fn cross(painter: &egui::Painter, at: egui::Pos2, t: &Tokens) { } } +/// Whether Layers is a button at the map's top-right corner, leaving the bar's room to the +/// Assistant. `false` puts it back on the bar, first: five buttons with the Assistant. +const LAYERS_ON_THE_MAP: bool = true; + +/// The bar's buttons, in order: Add Data, Capture, the Assistant once it is set up, and More, +/// with Layers first when it isn't on the map ([`LAYERS_ON_THE_MAP`]) or ModelBuilder is in the +/// map's place. +fn bar_buttons(app: &RustGisApp) -> Vec { + let mut buttons = Vec::with_capacity(5); + if !LAYERS_ON_THE_MAP || app.mb.shown() { + buttons.push(Sheet::Layers); + } + // Add Data has no sheet of its own. + buttons.extend([Sheet::None, Sheet::Capture]); + if assistant::setup(app) == assistant::Setup::Ready { + buttons.push(Sheet::Assistant); + } + buttons.push(Sheet::More); + buttons +} + /// The bar: one large button for each thing done most, the sheet's own button marked while its /// sheet is up. fn bar(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, shown: Sheet) { let ctx = ui.ctx().clone(); - let toggle = |to: Sheet| set_sheet(&ctx, if shown == to { Sheet::None } else { to }); - ui.columns(4, |cols| { - if let [a, b, c, d] = cols { - if bar_button(a, t, "contents", tl!("Layers"), shown == Sheet::Layers) { - toggle(Sheet::Layers); - } - if bar_button(b, t, "add_data", tl!("Add Data"), false) { - set_sheet(&ctx, Sheet::None); - run(app, "ui.addData", Value::Null); - } - if bar_button(c, t, "vertices", tl!("Capture"), shown == Sheet::Capture) { - toggle(Sheet::Capture); + let buttons = bar_buttons(app); + ui.columns(buttons.len(), |cols| { + for (col, button) in cols.iter_mut().zip(buttons) { + let (icon, label) = match button { + Sheet::Layers => ("contents", tl!("Layers")), + Sheet::None => ("add_data", tl!("Add Data")), + Sheet::Capture => ("vertices", tl!("Capture")), + Sheet::Assistant => ("assistant", tl!("Assistant")), + Sheet::More => ("command", tl!("More")), + }; + let on = button != Sheet::None && shown == button; + if !bar_button(col, t, icon, label, on) { + continue; } - if bar_button(d, t, "command", tl!("More"), shown == Sheet::More) { - toggle(Sheet::More); + match button { + Sheet::None => { + set_sheet(&ctx, Sheet::None); + run(app, "ui.addData", Value::Null); + } + _ if on => set_sheet(&ctx, Sheet::None), + Sheet::Assistant => assistant::raise(&ctx, assistant::height(&ctx)), + _ => set_sheet(&ctx, button), } } }); } +/// The Layers button at the top-right corner of `map`, a finger's size, marked while its sheet is +/// up. Says whether it was tapped. +fn layers_button(ui: &mut Ui, t: &Tokens, map: Rect, on: bool) -> bool { + let rect = Rect::from_min_size(egui::pos2(map.max.x - TARGET - 8.0, map.min.y + 8.0), Vec2::splat(TARGET)); + let response = ui.interact(rect, egui::Id::unique("touch_layers_button"), Sense::click()).on_hover_text(tl!("Layers")); + let fill = if on { + t.checked + } else if response.is_pointer_button_down_on() { + t.pressed + } else { + t.pane + }; + ui.painter().rect(rect, CornerRadius::same(8), fill, Stroke::new(1.0, t.border), egui::StrokeKind::Inside); + let ink = if on { t.accent_text } else { t.icon }; + icons::paint(ui.painter(), Rect::from_center_size(rect.center(), Vec2::splat(24.0)), "contents", ink, t.accent); + response.clicked() +} + /// One of the bar's buttons, as wide as its column: the icon over the label. Says whether it /// was tapped. fn bar_button(ui: &mut Ui, t: &Tokens, icon: &str, label: &str, on: bool) -> bool { @@ -429,7 +505,22 @@ fn bar_button(ui: &mut Ui, t: &Tokens, icon: &str, label: &str, on: bool) -> boo /// A sheet's heading, with its drag handle and the button that lowers it. A swipe down on the /// heading lowers the sheet too. fn heading(ui: &mut Ui, t: &Tokens, title: &str) { - // The drag is sensed under the heading's widgets, so the button still takes its tap. + if heading_row(ui, t, title, |_| {}) == Some(Swipe::Down) { + set_sheet(ui.ctx(), Sheet::None); + } +} + +/// Which way a finger swiped. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Swipe { + Up, + Down, +} + +/// A sheet's heading: its title, its drag handle, the button that lowers the sheet, and before +/// that the sheet's own `buttons`, laid out right to left. Says which way a swipe on it went. +fn heading_row(ui: &mut Ui, t: &Tokens, title: &str, buttons: impl FnOnce(&mut Ui)) -> Option { + // The drag is sensed under the heading's widgets, so the buttons still take their taps. let row = ui .scope_builder(egui::UiBuilder::new().id_salt("touch_heading").sense(Sense::drag()), |ui| { ui.horizontal(|ui| { @@ -440,20 +531,19 @@ fn heading(ui: &mut Ui, t: &Tokens, title: &str) { if icon_button(ui, t, "close", tl!("Close")) { set_sheet(ui.ctx(), Sheet::None); } + buttons(ui); }); }); }) .response; let handle = Rect::from_center_size(egui::pos2(row.rect.center().x, row.rect.min.y + 4.0), Vec2::new(36.0, 4.0)); ui.painter().rect_filled(handle, CornerRadius::same(2), t.border_strong); - if swiped_down(ui, &row) { - set_sheet(ui.ctx(), Sheet::None); - } + swiped(ui, &row) } -/// Whether a drag on `row` ended this frame a finger's height or more below where it began, and -/// further down than sideways. -fn swiped_down(ui: &Ui, row: &egui::Response) -> bool { +/// Which way a drag on `row` that ended this frame went, when it went a finger's height or more +/// up or down, and further than sideways. +fn swiped(ui: &Ui, row: &egui::Response) -> Option { let id = egui::Id::unique("touch_swipe"); // Where the finger went down on the row, kept from the press: egui lets go of it as the // finger lifts. A drag the system takes away (a call, an edge gesture) ends only with the @@ -469,13 +559,15 @@ fn swiped_down(ui: &Ui, row: &egui::Response) -> bool { }); } if !row.drag_stopped() { - return false; + return None; } let from = ui.data_mut(|d| d.remove_temp::(id)); - from.zip(row.interact_pointer_pos()).is_some_and(|(from, to)| { - let moved = to - from; - moved.y >= TARGET && moved.y > moved.x.abs() - }) + let moved = from.zip(row.interact_pointer_pos()).map(|(from, to)| to - from)?; + match moved.y { + y if y >= TARGET && y > moved.x.abs() => Some(Swipe::Down), + y if -y >= TARGET && -y > moved.x.abs() => Some(Swipe::Up), + _ => None, + } } /// A square button of the smallest size a finger taps, showing an icon. Says whether it was @@ -1788,6 +1880,10 @@ fn more(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { } } group(ui, t, tl!("Tools")); + // The AI Assistant, until a provider is set up: then the bar has its button. + if assistant::setup(app) == assistant::Setup::Missing && row(ui, t, "assistant", tl!("Set Up the Assistant")) { + assistant::raise(&ctx, assistant::Height::Full); + } // The copies of picked files nothing in the project names, removed once agreed. if copies::folder().is_some_and(|f| f.is_dir()) { copies_row(app, ui, t, &ctx); @@ -2062,7 +2158,7 @@ mod tests { fn every_sheet_draws_for_the_sample_and_for_an_empty_map() { let ctx = egui::Context::default(); let mut app = RustGisApp::with_sample(); - for shown in [Sheet::None, Sheet::Layers, Sheet::Capture, Sheet::More] { + for shown in [Sheet::None, Sheet::Layers, Sheet::Capture, Sheet::More, Sheet::Assistant] { frame(&mut app, &ctx, shown); assert_eq!(sheet(&ctx), shown); } @@ -2108,15 +2204,18 @@ mod tests { } /// The whole app in the touch interface, in a phone's window, worked by one finger. - struct Held { - app: RustGisApp, - ctx: egui::Context, + pub(crate) struct Held { + pub(crate) app: RustGisApp, + pub(crate) ctx: egui::Context, time: f64, + /// The window's size. + pub(crate) screen: Vec2, } impl Held { - fn new() -> Held { - let mut held = Held { app: RustGisApp::with_sample(), ctx: egui::Context::default(), time: 0.0 }; + pub(crate) fn new() -> Held { + let mut held = + Held { app: RustGisApp::with_sample(), ctx: egui::Context::default(), time: 0.0, screen: Vec2::new(411.0, 800.0) }; held.app.chrome = Some(chrome); // The fonts and the panels take a few frames to settle. for _ in 0..5 { @@ -2126,9 +2225,9 @@ mod tests { } /// Runs a frame with `events`, returning the words painted in sight, each with its place. - fn frame(&mut self, events: Vec) -> Vec<(String, Rect)> { + pub(crate) fn frame(&mut self, events: Vec) -> Vec<(String, Rect)> { self.time += 0.1; - let screen_rect = Some(Rect::from_min_size(egui::Pos2::ZERO, Vec2::new(411.0, 800.0))); + let screen_rect = Some(Rect::from_min_size(egui::Pos2::ZERO, self.screen)); let input = egui::RawInput { screen_rect, time: Some(self.time), events, ..Default::default() }; let app = &mut self.app; let output = self.ctx.run_ui(input, |ui| { @@ -2152,7 +2251,7 @@ mod tests { /// A finger put down at the first of `path`, moved through the rest and lifted, a frame /// for each step. - fn touch(&mut self, path: &[egui::Pos2]) { + pub(crate) fn touch(&mut self, path: &[egui::Pos2]) { use egui::TouchPhase::{End, Move, Start}; let Some((&first, &last)) = path.first().zip(path.last()) else { return }; let touch = @@ -2236,12 +2335,12 @@ mod tests { } /// Where `word` is painted. - fn find(&mut self, word: &str) -> Option { + pub(crate) fn find(&mut self, word: &str) -> Option { self.frame(Vec::new()).into_iter().find(|(text, _)| text == word).map(|(_, at)| at) } /// Raises `to` and returns the middle of its heading's title. - fn raise(&mut self, to: Sheet, title: &str) -> egui::Pos2 { + pub(crate) fn raise(&mut self, to: Sheet, title: &str) -> egui::Pos2 { set_sheet(&self.ctx, to); // The bar has a button of the same word, below the heading: the heading comes first. self.frame(Vec::new()); diff --git a/docs/user-guide/assistant.md b/docs/user-guide/assistant.md index 1a3da1428e..0db61af743 100644 --- a/docs/user-guide/assistant.md +++ b/docs/user-guide/assistant.md @@ -46,6 +46,19 @@ controls. From the command line, `rustgis-cli ask` sends one request (see [Command Line](../cli.md#asking-the-ai-assistant)). +## On a phone + +In the [touch interface](field-work.md#the-touch-interface) nothing of the assistant shows until +a provider is set up: **Set Up the Assistant**, in the More sheet, chooses the provider, its model +and its key. Then the bar has an **Assistant** button, which opens the conversation in a sheet. +Tap the message box to type in Android's own text field (with its paste, suggestions and +dictation), then **Send**. The sheet stands half up, to see the map with the conversation, or full +for reading and typing: the arrow beside its **×** switches, and a swipe up or down on its heading +moves it a step. Lowered while the assistant works, a strip over the bar says what it is doing and +has **Stop**; tap its words to raise the sheet again. Approvals are a card with **Allow** and +**Decline**. The gear in the sheet's heading opens the settings again. Signing in with ChatGPT is +set up in the desktop interface. + ## Turning the assistant off The AI Assistant is an [extension](index.md#extensions), on until you turn it off in diff --git a/docs/user-guide/field-work.md b/docs/user-guide/field-work.md index 7093dfe448..f83351cc1c 100644 --- a/docs/user-guide/field-work.md +++ b/docs/user-guide/field-work.md @@ -14,13 +14,15 @@ brought back into the project it came from. ## The touch interface -A phone opens in the touch interface: the map, with a bar of four large buttons under it. +A phone opens in the touch interface: the map, with a **Layers** button at its top-right corner +and a bar of large buttons under it. | Button | What it does | | --- | --- | -| **Layers** | Shows and hides layers, zooms to one, makes one the active layer, and switches between the project's maps and layouts | +| **Layers** (on the map) | Shows and hides layers, zooms to one, makes one the active layer, and switches between the project's maps and layouts | | **Add Data** | Opens files with the system's picker (Android's Files, iOS's document picker) | | **Capture** | Adds and edits features at the cross in the middle of the map | +| **Assistant** | The [AI Assistant](assistant.md#on-a-phone), once it is set up | | **More** | Full Extent, Undo and Redo, the project, the position, tracks and the rest | Each button opens a sheet that rises over the map. To close it, tap its **×**, swipe down on its From f97ca33bb41a84fdbe4c72ed1fbd76b4f7669f6a Mon Sep 17 00:00:00 2001 From: mavrick Date: Thu, 26 Nov 2026 21:44:23 -0600 Subject: [PATCH 02/15] fix(ui): the scale bar leaves a map too short for it and the north arrow --- crates/ui-egui/src/mapview.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index dddaf738d0..b7b700f2a4 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -4129,6 +4129,11 @@ fn navigation(app: &mut RustGisApp, ui: &mut Ui, p: &egui::Painter, rect: Rect, } fn scale_bar(app: &RustGisApp, p: &egui::Painter, rect: Rect, t: &Tokens) { + // A map too short for both, such as the strip above a phone's full-height sheet, keeps the + // north arrow: the bar would sit on it. + if rect.height() < SCALE_BAR_MIN_HEIGHT { + return; + } let m_per_pt = app.session.map().ground_res(); let d = crate::measure_units::scale_distance(m_per_pt * 130.0, app.ui.measurement_imperial); if d <= 0.0 { @@ -4154,6 +4159,10 @@ fn scale_bar(app: &RustGisApp, p: &egui::Painter, rect: Rect, t: &Tokens) { ); } +/// The shortest map with room for the north arrow (top left, to 51 points down) and the scale +/// bar (its 42 points at the bottom left) apart. +const SCALE_BAR_MIN_HEIGHT: f32 = 100.0; + fn north_arrow_rect(rect: Rect) -> Rect { Rect::from_center_size(pos2(rect.min.x + 30.0, rect.min.y + 34.0), vec2(34.0, 34.0)) } From 1941917b674c86b5dec55aa991bc3eea1c6f3f5a Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 10:37:10 -0600 Subject: [PATCH 03/15] feat(mobile): the phone's Assistant settings describe the provider and offer OpenRouter's private routing --- crates/ui-touch/src/assistant.rs | 45 +++++++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/crates/ui-touch/src/assistant.rs b/crates/ui-touch/src/assistant.rs index dbbcb5d8b8..33f4be74eb 100644 --- a/crates/ui-touch/src/assistant.rs +++ b/crates/ui-touch/src/assistant.rs @@ -11,7 +11,7 @@ use egui::{Align, Layout, RichText, Sense, Stroke, Ui, Vec2}; use rustgis_ui_egui::rustgis_assistant::{Asking, Entry, PRESETS, provider}; use rustgis_ui_egui::rustgis_engine::platform::{TextEntry, TextKind, Typed}; use rustgis_ui_egui::theme::Tokens; -use rustgis_ui_egui::{RustGisApp, assistant, i18n, tl}; +use rustgis_ui_egui::{RustGisApp, assistant, i18n, tl, tl_raw}; use super::{Sheet, Swipe, TARGET, action, entry_box, heading_row, icon_button, set_sheet, sheet, toggle_chip}; @@ -587,6 +587,15 @@ fn settings_form(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, state: &mut Chat } }); let preset = provider::preset(&cfg.provider); + // What the provider does with what it is sent, as the desktop's settings say it. + if let Some(p) = preset { + let description = if p.login || matches!(p.id, "custom" | "ollama") { + tl!(p.description).to_owned() + } else { + i18n::fmt("At the default address: {description}", &[("description", tl_raw!(p.description))]) + }; + ui.label(RichText::new(description).size(13.0).color(t.text_dim)); + } if cfg.login() { ui.label( RichText::new(tl!("Signing in with ChatGPT is set up in the desktop interface: More › Use the Desktop Interface.")) @@ -615,6 +624,16 @@ fn settings_form(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, state: &mut Chat app.assistant.set_remember_key(remember); } } + if cfg.provider == "openrouter" { + ui.label( + RichText::new(tl!("Ask OpenRouter to exclude endpoints that collect request data. Turning this off permits more endpoints, subject to your OpenRouter account settings.")) + .size(13.0) + .color(t.text_dim), + ); + if toggle_chip(ui, t, tl!("Private routing"), ui.available_width(), cfg.openrouter_private) { + cfg.openrouter_private = !cfg.openrouter_private; + } + } } if let Some(why) = cfg.missing() { ui.label(RichText::new(tl!(why)).size(14.0).color(t.amber)); @@ -981,6 +1000,8 @@ mod tests { #[test] fn the_settings_take_a_key_from_the_systems_text_field_for_its_provider_only() { let mut held = Held::new(); + // Tall enough for the whole form, which scrolls on a phone. + held.screen = Vec2::new(411.0, 1600.0); let asked = native(&mut held); provider(&mut held, "openai", "gpt-test"); assert_eq!(setup(&held.app), Setup::Missing); @@ -1018,6 +1039,28 @@ mod tests { assert_eq!(notices.iter().filter(|n| n.contains("wasn't kept")).count(), 1, "{notices:?}"); } + /// The settings say what the provider does with what it is sent, and for OpenRouter offer + /// private routing, as the desktop's do; a tap turns it off. + #[test] + fn the_settings_describe_the_provider_and_offer_openrouters_private_routing() { + let mut held = Held::new(); + // Tall enough for the whole form, which scrolls on a phone. + held.screen = Vec2::new(411.0, 1600.0); + provider(&mut held, "openai", "gpt-test"); + raise(&held.ctx, Height::Full); + held.frame(Vec::new()); + assert!(held.find("Private routing").is_none(), "only for OpenRouter"); + provider(&mut held, "openrouter", "m"); + raise(&held.ctx, Height::Full); + held.frame(Vec::new()); + let description = provider::preset("openrouter").map(|p| p.description).unwrap(); + assert!(held.find(&format!("At the default address: {description}")).is_some()); + assert_eq!(held.app.assistant.config().map(|c| c.openrouter_private), Some(true)); + let chip = held.find("Private routing").expect("the choice").center(); + held.touch(&[chip]); + assert_eq!(held.app.assistant.config().map(|c| c.openrouter_private), Some(false)); + } + /// What the system's text field sends for the settings after the extension is turned off is /// not taken, and that is said once; a provider that needs no key still offers its key field. #[test] From 9af1a5182aef0945fd93408aeade5846dbd41252 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 11:50:12 -0600 Subject: [PATCH 04/15] fix(assistant): asks that can't go are kept in order and said once; a subagent's panic ends only it Of several messages a command asks for in one frame, those the assistant is too busy to send go into the box in the order asked, with one notice. A panic in a subagent's call run on an answer to its approval is caught by the subagent's own guard again. The phone's Layers button stays off a map strip too short for it, and the waiting wording says what it waits for. --- crates/assistant/src/agent.rs | 5 ++-- crates/assistant/src/tests.rs | 21 +++++++++++++++ crates/ui-egui/src/assistant.rs | 14 +++++++--- crates/ui-egui/src/assistantpane.rs | 4 ++- crates/ui-touch/src/assistant.rs | 40 ++++++++++++++++++++++++++--- crates/ui-touch/src/lib.rs | 4 ++- 6 files changed, 78 insertions(+), 10 deletions(-) diff --git a/crates/assistant/src/agent.rs b/crates/assistant/src/agent.rs index 73910e4b13..adedacaff6 100644 --- a/crates/assistant/src/agent.rs +++ b/crates/assistant/src/agent.rs @@ -1180,8 +1180,9 @@ impl Agent { return Step::Done; } if let Some(child) = self.child.as_mut() { - // The child's own approval was checked with this one's ([`Agent::asking`]). - let step = child.decide_unguarded(allow, always, s); + // The child's own approval was checked with this one's ([`Agent::asking`]); a panic + // in it ends the child, as its own guard says, not this run. + let step = child.guard(|c| c.decide_unguarded(allow, always, s)); return self.after_child(step, s); } if allow diff --git a/crates/assistant/src/tests.rs b/crates/assistant/src/tests.rs index d3d5a66335..79b7c5daca 100644 --- a/crates/assistant/src/tests.rs +++ b/crates/assistant/src/tests.rs @@ -3596,6 +3596,27 @@ fn an_answer_to_an_approval_no_longer_waiting_is_refused() { assert!(matches!(answer(&mut a, false, false, &mut s), Step::Send(_))); } +/// A panic in a subagent's call run on an answer to its approval ends the subagent, as its own +/// guard says, and the run that delegated to it goes on with its report. +#[test] +fn a_panic_in_a_subagent_after_its_approval_ends_the_subagent_not_the_run() { + let mut s = sample(); + let mut a = Agent::new(cfg("openai"), &s); + assert!(matches!(a.ask("delegate it", &s), Step::Send(_))); + assert!(matches!(a.receive(a.generation(), ok(calls("delegate", json!({"task": "Export, then fail"}))), &mut s), Step::Send(_))); + let never = std::env::temp_dir().join(format!("rustgis-assistant-child-panic-{}.png", std::process::id())); + let args = json!({"command": "share.exportMap", "params": {"path": never}}).to_string(); + let two = json!({"choices": [{"message": {"role": "assistant", "content": null, "tool_calls": [ + {"id": "c1", "type": "function", "function": {"name": "run_command", "arguments": args}}, + {"id": "c2", "type": "function", "function": {"name": "test_panic", "arguments": "{}"}} + ]}, "finish_reason": "tool_calls"}]}); + assert_eq!(a.receive(a.generation(), ok(two), &mut s), Step::Confirm); + // Declined, the subagent's next call panics: the subagent ends and the run asks its provider again. + assert!(matches!(answer(&mut a, false, false, &mut s), Step::Send(_))); + assert!(a.busy()); + assert!(!never.exists()); +} + #[test] fn a_subagent_uses_only_its_tools() { let mut s = sample(); diff --git a/crates/ui-egui/src/assistant.rs b/crates/ui-egui/src/assistant.rs index f153ba8de9..e9fe66a73e 100644 --- a/crates/ui-egui/src/assistant.rs +++ b/crates/ui-egui/src/assistant.rs @@ -45,7 +45,8 @@ pub struct AssistantState { pub(crate) send_when_ready: bool, /// Messages a command asked to send (`ui.pane.assistant {"ask": …}`), oldest first: each is sent /// by itself, as a suggestion would be, on the next frame once the key and pictures are read. - /// They never go into the message being written unless they can't be sent. + /// They never go into the message being written unless they can't be sent, as while the + /// assistant is busy with one before ([`AssistantState::hold`]). pub(crate) asked: Vec, /// Pictures that landed while the extension was off, to be said once. pub(crate) late_pictures: usize, @@ -191,7 +192,8 @@ impl AssistantState { /// and what a command asked to send goes into the box with it. pub(crate) fn hold(&mut self) { self.send_when_ready = false; - for text in std::mem::take(&mut self.asked) { + // Each goes above what the box holds, so the newest goes first and the oldest ends on top. + for text in std::mem::take(&mut self.asked).into_iter().rev() { to_box(self, &text); } } @@ -819,9 +821,15 @@ pub(crate) fn poll(app: &mut RustGisApp, ctx: &egui::Context) { } let ready = !key_loading(app) && !app.assistant.pictures.reading(); if ready { - for text in std::mem::take(&mut app.assistant.asked) { + while !app.assistant.busy() && !app.assistant.asked.is_empty() { + let text = app.assistant.asked.remove(0); send_from(app, text, false, ctx); } + // While it is busy the rest aren't sent, as no message is: they go into the box in order. + if !app.assistant.asked.is_empty() { + app.assistant.hold(); + app.session.notify(tl!("The assistant is busy; stop it or wait for it to finish."), true); + } } if app.assistant.send_when_ready && ready { app.assistant.send_when_ready = false; diff --git a/crates/ui-egui/src/assistantpane.rs b/crates/ui-egui/src/assistantpane.rs index e3e922e05d..32116b5593 100644 --- a/crates/ui-egui/src/assistantpane.rs +++ b/crates/ui-egui/src/assistantpane.rs @@ -1628,9 +1628,11 @@ pub(crate) mod tests { app.assistant.input = "waited".into(); app.assistant.send_when_ready = true; app.assistant.asked.push("asked".into()); + app.assistant.asked.push("asked next".into()); assistant::forget_sign_in(&mut app, &mut cfg); assert!(!app.assistant.sending_when_ready() && app.assistant.asked.is_empty()); - assert_eq!(app.assistant.input, "asked\nwaited"); + // In the order they were asked for, above what was being written. + assert_eq!(app.assistant.input, "asked\nasked next\nwaited"); } /// A new conversation, or a peer's project replacing this one, sends nothing still waiting diff --git a/crates/ui-touch/src/assistant.rs b/crates/ui-touch/src/assistant.rs index 33f4be74eb..46d252c97f 100644 --- a/crates/ui-touch/src/assistant.rs +++ b/crates/ui-touch/src/assistant.rs @@ -221,7 +221,7 @@ pub(crate) fn strip(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { /// What the Assistant is doing, in a few words. fn doing(app: &RustGisApp) -> String { if app.assistant.waiting_to_send() { - return tl!("Waiting to send: the key is still being read…").to_string(); + return tl!("Waiting to send: the key or a picture is still being read…").to_string(); } if assistant::pending(app).is_some() { return tl!("Waiting for your approval: tap to see it.").to_string(); @@ -497,8 +497,9 @@ fn typing(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, state: &mut Chat) { let ctx = ui.ctx().clone(); let busy = app.assistant.busy(); let waiting = app.assistant.waiting_to_send(); - if waiting { - ui.label(RichText::new(tl!("It is sent once the key is read.")).size(13.0).color(t.text_dim)); + // The box's own message: one a command asked for waits apart. + if app.assistant.sending_when_ready() { + ui.label(RichText::new(tl!("It is sent once the key and any picture are read.")).size(13.0).color(t.text_dim)); } let id = egui::Id::unique("touch_assistant_input"); let mut send = false; @@ -861,6 +862,39 @@ mod tests { assert_eq!(held.app.assistant.input, ""); } + /// Of several messages a command asks for in one frame, the first goes and, the Assistant busy + /// with it, the rest are put in the box in the order asked, said once, and aren't sent later. + #[test] + fn messages_a_command_asks_for_while_one_is_out_go_into_the_box_in_order() { + let mut held = Held::new(); + provider(&mut held, "custom", "test"); + // Requests whose replies are held back. + let out = Arc::new(Mutex::new(Vec::new())); + let asking = out.clone(); + held.app.services.http = Some(Box::new(move |_, slot| asking.lock().unwrap().push(slot))); + let mark = held.app.session.notice_mark(); + for ask in ["first", "second", "third"] { + crate::run(&mut held.app, "ui.pane.assistant", json!({"ask": ask})); + } + for _ in 0..3 { + held.frame(Vec::new()); + } + let asked = |held: &Held| -> Vec { + held.app.assistant.messages().iter().filter_map(|e| if let Entry::User(t) = e { Some(t.clone()) } else { None }).collect() + }; + assert_eq!(asked(&held), ["first"]); + assert_eq!(held.app.assistant.input, "second\nthird"); + assert_eq!(said(&held, mark).iter().filter(|n| n.contains("busy")).count(), 1, "{:?}", said(&held, mark)); + let slot = out.lock().unwrap().remove(0); + *slot.lock().unwrap() = Some(Ok(HttpResponse { status: 200, body: say("Done.").to_string().into_bytes(), headers: vec![] })); + for _ in 0..3 { + held.frame(Vec::new()); + } + assert!(out.lock().unwrap().is_empty(), "nothing more is sent by itself"); + assert_eq!(asked(&held), ["first"]); + assert_eq!(held.app.assistant.input, "second\nthird"); + } + #[test] fn without_a_system_text_field_the_message_is_typed_here() { let mut held = Held::new(); diff --git a/crates/ui-touch/src/lib.rs b/crates/ui-touch/src/lib.rs index fa826b8f4b..924a8af165 100644 --- a/crates/ui-touch/src/lib.rs +++ b/crates/ui-touch/src/lib.rs @@ -251,7 +251,9 @@ pub fn chrome(app: &mut RustGisApp, ui: &mut Ui) { } // Layers, at the map's top-right corner (where a desktop's zoom buttons are); on the bar // while ModelBuilder, with its own buttons there, is in the map's place. - if LAYERS_ON_THE_MAP && map && layers_button(ui, &t, above, shown == Sheet::Layers) { + // Not on a strip of map too short for it (a full sheet): it comes back as the sheet lowers. + let room = above.height() >= TARGET + 16.0; + if LAYERS_ON_THE_MAP && map && room && layers_button(ui, &t, above, shown == Sheet::Layers) { set_sheet(ui.ctx(), if shown == Sheet::Layers { Sheet::None } else { Sheet::Layers }); } // While capturing, a cross marks the middle of the map: the point goes there, so the From 8f178102792f334ba17c537a5b256fc9b2b57743 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 13:50:05 -0600 Subject: [PATCH 05/15] fix(mobile): a message put in the box while Android's text field is open on it is kept The field sends all it holds on each change, which replaced the whole message, and with it one put there meanwhile because the assistant was busy. --- crates/ui-touch/src/assistant.rs | 60 +++++++++++++++++++++++++++++++- 1 file changed, 59 insertions(+), 1 deletion(-) diff --git a/crates/ui-touch/src/assistant.rs b/crates/ui-touch/src/assistant.rs index 46d252c97f..d72210f5d6 100644 --- a/crates/ui-touch/src/assistant.rs +++ b/crates/ui-touch/src/assistant.rs @@ -53,6 +53,8 @@ pub(crate) struct Chat { /// The system's text field open for one of the sheet's fields: its id, the field, and the /// provider it was opened for (a provider's settings never take what was typed for another's). entering: Option<(String, Field, String)>, + /// What the system's text field open for the message last held. + entered: String, /// How many times the system's text field was opened: each opening's id is its own. entries: u64, /// The system's text field that was open as the extension was turned off: what it still sends @@ -147,6 +149,16 @@ pub(crate) fn strip_shown(app: &RustGisApp, ctx: &egui::Context) -> bool { on(app) && sheet(ctx) != Sheet::Assistant && (app.assistant.busy() || app.assistant.waiting_to_send()) } +/// The message `input` with the system's text field's part of it, `was`, now `text`. The field +/// sends all it holds and knows nothing of what was put in the box above it since (a message that +/// couldn't be sent), which is kept. +fn with_entered(input: &str, was: &str, text: &str) -> String { + // A draft of nothing but spaces is replaced by what is put in the box, not kept under it. + let above = input.strip_suffix(was).unwrap_or(if was.trim().is_empty() { input } else { "" }); + let line = if above.is_empty() || above.ends_with('\n') { "" } else { "\n" }; + format!("{above}{line}{text}") +} + /// Takes what the system's text field sent back for the sheet's fields, and gives back the rest. pub(crate) fn take_typed(app: &mut RustGisApp, ctx: &egui::Context, typed: Vec) -> Vec { let mut state = chat(ctx); @@ -172,7 +184,8 @@ pub(crate) fn take_typed(app: &mut RustGisApp, ctx: &egui::Context, typed: Vec { if field == Field::Message { - app.assistant.input = text; + app.assistant.input = with_entered(&app.assistant.input, &state.entered, &text); + state.entered = text; continue; } let Some(mut cfg) = app.assistant.config().cloned().filter(|c| c.provider == provider) else { @@ -523,6 +536,7 @@ fn typing(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, state: &mut Chat) { match enter(&entry) { Ok(()) => { state.entering = Some((entry_id, Field::Message, String::new())); + state.entered = app.assistant.input.clone(); // Typing wants room: the conversation above, the keyboard below. state.height = Height::Full; } @@ -895,6 +909,50 @@ mod tests { assert_eq!(held.app.assistant.input, "second\nthird"); } + /// A message put in the box while the system's text field is open on it stays, above what is + /// typed: the field sends all it holds and doesn't have it. + #[test] + fn a_message_put_in_the_box_while_the_systems_text_field_is_open_is_kept() { + for draft in ["", " ", "a draft"] { + let mut held = Held::new(); + provider(&mut held, "custom", "test"); + held.app.services.http = Some(Box::new(|_, _| {})); + let asked = native(&mut held); + raise(&held.ctx, Height::Half); + held.frame(Vec::new()); + let bar = held.find("Ask, or say what to do…").unwrap().center(); + held.touch(&[bar]); + let id = asked.borrow().last().cloned().expect("the system's text field").id; + held.app.typed.push(Typed::Text { id: id.clone(), text: draft.into() }); + held.frame(Vec::new()); + for ask in ["first", "second"] { + crate::run(&mut held.app, "ui.pane.assistant", json!({"ask": ask})); + } + held.frame(Vec::new()); + held.frame(Vec::new()); + for text in ["a draft, longer", "", "another"] { + held.app.typed.push(Typed::Text { id: id.clone(), text: text.into() }); + held.frame(Vec::new()); + assert_eq!(held.app.assistant.input, format!("second\n{text}"), "after the draft {draft:?}"); + } + } + } + + /// The Layers button isn't on a strip of map too short for it, and is back as the sheet lowers. + #[test] + fn layers_is_not_on_a_strip_of_map_too_short_for_it() { + let mut held = Held::new(); + held.screen = Vec2::new(800.0, 360.0); + provider(&mut held, "custom", "test"); + let layers = egui::pos2(800.0 - 8.0 - TARGET / 2.0, 16.0); + raise(&held.ctx, Height::Full); + held.frame(Vec::new()); + held.touch(&[layers]); + assert_eq!(sheet(&held.ctx), Sheet::None, "a tap on the map above the sheet lowers it"); + held.touch(&[layers]); + assert_eq!(sheet(&held.ctx), Sheet::Layers); + } + #[test] fn without_a_system_text_field_the_message_is_typed_here() { let mut held = Held::new(); From a4b03ffa52a976d2e2ee618f3e2b14330cc000fe Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 15:06:29 -0600 Subject: [PATCH 06/15] fix(mobile): a message sent while Android's text field is open on it doesn't come back The field's next text put a message already sent back in the box, or replaced one put there since, and what was typed after the sheet's Send was dropped without a word. Nothing more is taken from it, and a notice says so. --- crates/ui-touch/src/assistant.rs | 82 +++++++++++++++++++++++++++----- 1 file changed, 70 insertions(+), 12 deletions(-) diff --git a/crates/ui-touch/src/assistant.rs b/crates/ui-touch/src/assistant.rs index d72210f5d6..e69bde5d09 100644 --- a/crates/ui-touch/src/assistant.rs +++ b/crates/ui-touch/src/assistant.rs @@ -151,12 +151,16 @@ pub(crate) fn strip_shown(app: &RustGisApp, ctx: &egui::Context) -> bool { /// The message `input` with the system's text field's part of it, `was`, now `text`. The field /// sends all it holds and knows nothing of what was put in the box above it since (a message that -/// couldn't be sent), which is kept. -fn with_entered(input: &str, was: &str, text: &str) -> String { - // A draft of nothing but spaces is replaced by what is put in the box, not kept under it. - let above = input.strip_suffix(was).unwrap_or(if was.trim().is_empty() { input } else { "" }); +/// couldn't be sent), which is kept. `None` when its part is no longer there: the message was sent. +fn with_entered(input: &str, was: &str, text: &str) -> Option { + let above = if was.trim().is_empty() { + // A draft of nothing but spaces is replaced by what is put in the box, not kept under it. + input.strip_suffix(was).unwrap_or(input) + } else { + input.strip_suffix(was).filter(|above| above.is_empty() || above.ends_with('\n'))? + }; let line = if above.is_empty() || above.ends_with('\n') { "" } else { "\n" }; - format!("{above}{line}{text}") + Some(format!("{above}{line}{text}")) } /// Takes what the system's text field sent back for the sheet's fields, and gives back the rest. @@ -184,8 +188,18 @@ pub(crate) fn take_typed(app: &mut RustGisApp, ctx: &egui::Context, typed: Vec { if field == Field::Message { - app.assistant.input = with_entered(&app.assistant.input, &state.entered, &text); - state.entered = text; + match with_entered(&app.assistant.input, &state.entered, &text) { + Some(message) => { + app.assistant.input = message; + state.entered = text; + } + // What the field sends again as it was isn't new. + None if text == state.entered => {} + None => { + state.entering = None; + app.session.notify(tl!("What was typed wasn't kept: the message was sent while it was typed."), true); + } + } continue; } let Some(mut cfg) = app.assistant.config().cloned().filter(|c| c.provider == provider) else { @@ -568,10 +582,8 @@ fn typing(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, state: &mut Chat) { } }); if send && !busy { - // What the system's field sends from now on is of the message sent, not of the next. - if state.entering.as_ref().is_some_and(|(_, f, _)| *f == Field::Message) { - state.entering = None; - } + // What the system's field still sends is of the message sent, not of the next: `with_entered` + // finds it gone from the box. let text = app.assistant.input.clone(); assistant::send(app, text, &ctx); } @@ -869,8 +881,19 @@ mod tests { assert_eq!(*sent.lock().unwrap(), 1); assert!(held.app.assistant.messages().iter().any(|e| matches!(e, Entry::User(t) if t == "Zoom to Tokyo"))); assert!(held.find("Tokyo is in view.").is_some(), "the reply is drawn"); - // What the field still sends after the message went is the message's, not the next one's. + // What the field still sends after the message went is the message's, not the next one's: + // the same again is nothing new, and more typed is said, once, not to be kept. + let mark = held.app.session.notice_mark(); held.app.typed.push(Typed::Text { id: entry.id.clone(), text: "Zoom to Tokyo".into() }); + held.frame(Vec::new()); + assert!(said(&held, mark).is_empty(), "{:?}", said(&held, mark)); + for text in ["Zoom to Tokyo, then", "Zoom to Tokyo, then Osaka"] { + held.app.typed.push(Typed::Text { id: entry.id.clone(), text: text.into() }); + held.frame(Vec::new()); + assert_eq!(held.app.assistant.input, ""); + } + let notices = said(&held, mark); + assert_eq!(notices.iter().filter(|n| n.contains("wasn't kept")).count(), 1, "{notices:?}"); held.app.typed.push(Typed::Closed { id: entry.id, failed: None }); held.frame(Vec::new()); assert_eq!(held.app.assistant.input, ""); @@ -938,6 +961,41 @@ mod tests { } } + /// A message sent while the system's text field is open on it doesn't come back with what the + /// field sends next, which is said once and replaces nothing put in the box since. + #[test] + fn a_message_sent_while_the_systems_text_field_is_open_does_not_come_back() { + for later in ["", "show data", "keep Zoom in"] { + let mut held = Held::new(); + provider(&mut held, "custom", "test"); + held.app.services.http = Some(Box::new(|_, _| {})); + let asked = native(&mut held); + raise(&held.ctx, Height::Half); + held.frame(Vec::new()); + let bar = held.find("Ask, or say what to do…").unwrap().center(); + held.touch(&[bar]); + let id = asked.borrow().last().cloned().expect("the system's text field").id; + held.app.typed.push(Typed::Text { id: id.clone(), text: "Zoom in".into() }); + held.frame(Vec::new()); + // As a message waiting for the key goes once it is read, not by the sheet's Send. + let ctx = held.ctx.clone(); + assistant::send(&mut held.app, "Zoom in".into(), &ctx); + assert_eq!(held.app.assistant.input, ""); + if !later.is_empty() { + crate::run(&mut held.app, "ui.pane.assistant", json!({"ask": later})); + held.frame(Vec::new()); + } + let mark = held.app.session.notice_mark(); + for text in ["Zoom in", "Zoom in!", "Zoom in!!"] { + held.app.typed.push(Typed::Text { id: id.clone(), text: text.into() }); + held.frame(Vec::new()); + assert_eq!(held.app.assistant.input, later, "after {text:?}"); + } + let notices = said(&held, mark); + assert_eq!(notices.iter().filter(|n| n.contains("wasn't kept")).count(), 1, "{notices:?}"); + } + } + /// The Layers button isn't on a strip of map too short for it, and is back as the sheet lowers. #[test] fn layers_is_not_on_a_strip_of_map_too_short_for_it() { From 85092bae762e9e728a484245d5ce94ca7b43b1f7 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 16:11:03 -0600 Subject: [PATCH 07/15] fix(assistant): another message leaves the draft's pictures, and the phone's field tells what was sent A message a command asked for, or a suggestion sent while something else was written, took the pictures attached to the message being written. Android's field told from its text whether the message had gone, which another message of the same words misled; it now counts the messages sent. A message waiting for the key goes after the text the field had already sent is taken. --- crates/ui-egui/src/assistant.rs | 29 +++++++++-- crates/ui-egui/src/assistantpane.rs | 20 ++++++++ crates/ui-egui/src/assistantpictures.rs | 41 +++++++++++++++ crates/ui-touch/src/assistant.rs | 66 ++++++++++++++++--------- 4 files changed, 131 insertions(+), 25 deletions(-) diff --git a/crates/ui-egui/src/assistant.rs b/crates/ui-egui/src/assistant.rs index e9fe66a73e..7599ebbe93 100644 --- a/crates/ui-egui/src/assistant.rs +++ b/crates/ui-egui/src/assistant.rs @@ -43,6 +43,8 @@ pub struct AssistantState { /// it waits for are read: what the box shows while it waits is what goes, and what a send /// clears. pub(crate) send_when_ready: bool, + /// How many times the message being written has gone ([`AssistantState::sent`]). + sent: u64, /// Messages a command asked to send (`ui.pane.assistant {"ask": …}`), oldest first: each is sent /// by itself, as a suggestion would be, on the next frame once the key and pictures are read. /// They never go into the message being written unless they can't be sent, as while the @@ -166,6 +168,12 @@ impl AssistantState { self.send_when_ready } + /// How many times the message being written has gone: a front end typing it in a field of its + /// own tells by it that what the field holds was sent. + pub fn sent(&self) -> u64 { + self.sent + } + /// A message waits to be sent until the key or a picture is read: the one being written, or /// one a command asked for. pub fn waiting_to_send(&self) -> bool { @@ -819,11 +827,21 @@ pub(crate) fn poll(app: &mut RustGisApp, ctx: &egui::Context) { if !app.assistant.asked.is_empty() { ensure_loaded(app, ctx); } - let ready = !key_loading(app) && !app.assistant.pictures.reading(); + // Text a phone's own field sent, which its touch interface takes as it draws, goes first. In + // the backstage it isn't drawn, so nothing waits for it. + let typed = app.chrome.is_some() && !app.ui.backstage && !app.typed.is_empty(); + if typed && app.assistant.waiting_to_send() { + ctx.request_repaint(); + } + let ready = !key_loading(app) && !app.assistant.pictures.reading() && !typed; if ready { while !app.assistant.busy() && !app.assistant.asked.is_empty() { let text = app.assistant.asked.remove(0); + // The pictures are the message being written's, unless that is what was asked for. + let own = app.assistant.input.trim() == text.trim(); + let pictures = if own { Vec::new() } else { app.assistant.pictures.take() }; send_from(app, text, false, ctx); + app.assistant.pictures.put_back(pictures); } // While it is busy the rest aren't sent, as no message is: they go into the box in order. if !app.assistant.asked.is_empty() { @@ -1014,9 +1032,14 @@ fn send_from(app: &mut RustGisApp, text: String, from_box: bool, ctx: &egui::Con } return; }; - let step = agent.ask_with(&text, app.assistant.pictures.take(), session); - if from_box || app.assistant.input.trim() == text { + // Another message (a suggestion) goes without the pictures of the one being written. + let draft = app.assistant.input.trim(); + let own = from_box || draft == text; + let pictures = if own || draft.is_empty() { app.assistant.pictures.take() } else { Vec::new() }; + let step = agent.ask_with(&text, pictures, session); + if own { app.assistant.input.clear(); + app.assistant.sent = app.assistant.sent.wrapping_add(1); } follow(app, step, ctx); } diff --git a/crates/ui-egui/src/assistantpane.rs b/crates/ui-egui/src/assistantpane.rs index 32116b5593..d511ea4c05 100644 --- a/crates/ui-egui/src/assistantpane.rs +++ b/crates/ui-egui/src/assistantpane.rs @@ -1618,6 +1618,26 @@ pub(crate) mod tests { } } + /// A message waits for text a phone's own field sent until the touch interface takes it, and + /// only where that is drawn: not behind the backstage, nor in the desktop interface. + #[test] + fn a_message_waits_for_the_fields_text_only_where_it_is_taken() { + use rustgis_engine::platform::Typed; + for (touch, backstage, waits) in [(true, false, true), (true, true, false), (false, false, false)] { + let mut app = RustGisApp::with_sample(); + app.assistant.agent = Some(Agent::new(Config::from_env("custom"), &app.session)); + app.assistant.loaded = true; + app.services.http = Some(Box::new(|_, _| {})); + app.chrome = if touch { Some(|_, _| {}) } else { None }; + app.ui.backstage = backstage; + app.typed.push(Typed::Text { id: "assistant:message:0".into(), text: "more".into() }); + app.assistant.asked.push("Zoom to Tokyo".into()); + poll(&mut app, &egui::Context::default()); + assert_eq!(app.assistant.waiting_to_send(), waits, "touch {touch}, backstage {backstage}"); + assert_eq!(app.assistant.agent.as_ref().unwrap().busy(), !waits, "touch {touch}, backstage {backstage}"); + } + } + /// Signing out sends nothing still waiting: the message stays in the box, and one a command /// asked for goes into it, above what was being written. #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/assistantpictures.rs b/crates/ui-egui/src/assistantpictures.rs index 7bedb4f910..dc00a93bfa 100644 --- a/crates/ui-egui/src/assistantpictures.rs +++ b/crates/ui-egui/src/assistantpictures.rs @@ -47,6 +47,11 @@ impl Pictures { std::mem::take(&mut self.ready) } + /// Puts back pictures [`Pictures::take`] took, for the message they are of. + pub(crate) fn put_back(&mut self, pictures: Vec) { + self.ready.splice(0..0, pictures); + } + /// How many the message has or is reading. fn count(&self) -> usize { #[cfg(not(target_arch = "wasm32"))] @@ -402,6 +407,42 @@ mod tests { assert_eq!(sent.len(), 1); } + /// The pictures of the message being written stay with it when another message is sent: one a + /// command asked for, whatever the box holds, or a suggestion while something else is written. + #[test] + fn another_message_leaves_the_pictures_of_the_one_being_written() { + for (draft, command) in [("look at this", true), ("", true), ("look at this", false)] { + let mut app = RustGisApp::with_sample(); + let mut cfg = rustgis_assistant::Config::from_env("custom"); + cfg.model = "test".into(); + app.assistant.agent = Some(rustgis_assistant::Agent::new(cfg, &app.session)); + app.assistant.loaded = true; + app.services.http = Some(Box::new(|_, _| {})); + received(&mut app, "map.png", png()); + let mut spins = 0; + while !app.assistant.pictures.any() { + assert!(spins < 10_000_000, "the picture was never read"); + spins += 1; + take_read(&mut app); + std::thread::yield_now(); + } + app.assistant.input = draft.into(); + let ctx = egui::Context::default(); + if command { + app.run("ui.pane.assistant", serde_json::json!({"ask": "Zoom to Tokyo"})).unwrap(); + crate::assistant::poll(&mut app, &ctx); + } else { + crate::assistant::send(&mut app, "Zoom to Tokyo".into(), &ctx); + } + let Some(rustgis_assistant::provider::Turn::User(_, sent)) = app.assistant.agent.as_ref().unwrap().turns().last() else { + panic!("sent") + }; + assert!(sent.is_empty(), "draft {draft:?}, command {command}"); + assert!(app.assistant.pictures.any(), "draft {draft:?}, command {command}"); + assert_eq!(app.assistant.input, draft); + } + } + /// While a picture is being read, the message waiting is the one in the box: a suggestion /// clicked meanwhile becomes it, typing changes it, and once it goes it is sent once, as the /// box held it, and the box is empty (#2991's review: a suggestion and then the box's own diff --git a/crates/ui-touch/src/assistant.rs b/crates/ui-touch/src/assistant.rs index e69bde5d09..feebd83d0c 100644 --- a/crates/ui-touch/src/assistant.rs +++ b/crates/ui-touch/src/assistant.rs @@ -53,8 +53,10 @@ pub(crate) struct Chat { /// The system's text field open for one of the sheet's fields: its id, the field, and the /// provider it was opened for (a provider's settings never take what was typed for another's). entering: Option<(String, Field, String)>, - /// What the system's text field open for the message last held. + /// What the system's text field open for the message last held, and how many messages had gone + /// then ([`assistant::AssistantState::sent`]). entered: String, + entered_sent: u64, /// How many times the system's text field was opened: each opening's id is its own. entries: u64, /// The system's text field that was open as the extension was turned off: what it still sends @@ -151,16 +153,11 @@ pub(crate) fn strip_shown(app: &RustGisApp, ctx: &egui::Context) -> bool { /// The message `input` with the system's text field's part of it, `was`, now `text`. The field /// sends all it holds and knows nothing of what was put in the box above it since (a message that -/// couldn't be sent), which is kept. `None` when its part is no longer there: the message was sent. -fn with_entered(input: &str, was: &str, text: &str) -> Option { - let above = if was.trim().is_empty() { - // A draft of nothing but spaces is replaced by what is put in the box, not kept under it. - input.strip_suffix(was).unwrap_or(input) - } else { - input.strip_suffix(was).filter(|above| above.is_empty() || above.ends_with('\n'))? - }; +/// couldn't be sent), which is kept. +fn with_entered(input: &str, was: &str, text: &str) -> String { + let above = input.strip_suffix(was).filter(|above| above.is_empty() || above.ends_with('\n')).unwrap_or(input); let line = if above.is_empty() || above.ends_with('\n') { "" } else { "\n" }; - Some(format!("{above}{line}{text}")) + format!("{above}{line}{text}") } /// Takes what the system's text field sent back for the sheet's fields, and gives back the rest. @@ -188,18 +185,16 @@ pub(crate) fn take_typed(app: &mut RustGisApp, ctx: &egui::Context, typed: Vec { if field == Field::Message { - match with_entered(&app.assistant.input, &state.entered, &text) { - Some(message) => { - app.assistant.input = message; - state.entered = text; - } - // What the field sends again as it was isn't new. - None if text == state.entered => {} - None => { + // What it held was sent. The same again isn't new; a blank field held none of it. + if state.entered_sent != app.assistant.sent() && !state.entered.trim().is_empty() { + if text != state.entered { state.entering = None; app.session.notify(tl!("What was typed wasn't kept: the message was sent while it was typed."), true); } + continue; } + app.assistant.input = with_entered(&app.assistant.input, &state.entered, &text); + (state.entered, state.entered_sent) = (text, app.assistant.sent()); continue; } let Some(mut cfg) = app.assistant.config().cloned().filter(|c| c.provider == provider) else { @@ -550,7 +545,7 @@ fn typing(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, state: &mut Chat) { match enter(&entry) { Ok(()) => { state.entering = Some((entry_id, Field::Message, String::new())); - state.entered = app.assistant.input.clone(); + (state.entered, state.entered_sent) = (app.assistant.input.clone(), app.assistant.sent()); // Typing wants room: the conversation above, the keyboard below. state.height = Height::Full; } @@ -582,8 +577,8 @@ fn typing(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, state: &mut Chat) { } }); if send && !busy { - // What the system's field still sends is of the message sent, not of the next: `with_entered` - // finds it gone from the box. + // What the system's field still sends is of the message sent, not of the next: + // `take_typed` tells by how many have gone. let text = app.assistant.input.clone(); assistant::send(app, text, &ctx); } @@ -965,7 +960,7 @@ mod tests { /// field sends next, which is said once and replaces nothing put in the box since. #[test] fn a_message_sent_while_the_systems_text_field_is_open_does_not_come_back() { - for later in ["", "show data", "keep Zoom in"] { + for later in ["", "show data", "keep Zoom in", "notes\nZoom in", "Zoom in"] { let mut held = Held::new(); provider(&mut held, "custom", "test"); held.app.services.http = Some(Box::new(|_, _| {})); @@ -996,6 +991,33 @@ mod tests { } } + /// Text the system's field sent before the key was read goes with the message that waited for + /// it: the sheet takes it before the message is sent. + #[test] + fn a_message_waiting_goes_with_the_text_the_systems_field_had_sent() { + let mut held = Held::new(); + provider(&mut held, "custom", "test"); + held.app.chrome = Some(crate::chrome); + held.app.services.http = Some(Box::new(|_, _| {})); + let asked = native(&mut held); + raise(&held.ctx, Height::Half); + held.frame(Vec::new()); + let bar = held.find("Ask, or say what to do…").unwrap().center(); + held.touch(&[bar]); + let id = asked.borrow().last().cloned().expect("the system's text field").id; + held.app.typed.push(Typed::Text { id: id.clone(), text: "Zoom".into() }); + held.frame(Vec::new()); + let mark = held.app.session.notice_mark(); + // As one a command asks for, the same as is being written, is due once the key is read. + crate::run(&mut held.app, "ui.pane.assistant", json!({"ask": "Zoom"})); + held.app.typed.push(Typed::Text { id, text: "Zoom in".into() }); + held.frame(Vec::new()); + held.frame(Vec::new()); + assert_eq!(held.app.assistant.input, "Zoom in", "typed before the message went: kept"); + assert!(said(&held, mark).is_empty(), "{:?}", said(&held, mark)); + assert!(held.app.assistant.messages().iter().any(|e| matches!(e, Entry::User(t) if t == "Zoom"))); + } + /// The Layers button isn't on a strip of map too short for it, and is back as the sheet lowers. #[test] fn layers_is_not_on_a_strip_of_map_too_short_for_it() { From 089d5ea5642d4154fc8d58e53a0624fef115fe5f Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 16:19:01 -0600 Subject: [PATCH 08/15] refactor(mobile): drop the switch for Layers on the bar, now that the bar is settled --- apps/rustgis-mobile/README.md | 5 ++--- crates/ui-touch/src/lib.rs | 16 +++++----------- 2 files changed, 7 insertions(+), 14 deletions(-) diff --git a/apps/rustgis-mobile/README.md b/apps/rustgis-mobile/README.md index f6a25707cc..c2373c6511 100644 --- a/apps/rustgis-mobile/README.md +++ b/apps/rustgis-mobile/README.md @@ -99,9 +99,8 @@ of large buttons under it (Add Data, Capture, the AI Assistant once a provider i sheets that rise over the map. Until then, **Set Up the Assistant** in the More sheet is the only trace of the Assistant, and with its extension off there is none; its sheet types into Android's own text field and stands full or half up, with a strip and Stop while it works -([AI Assistant › On a phone](../../docs/user-guide/assistant.md#on-a-phone)). `LAYERS_ON_THE_MAP` -in `crates/ui-touch/src/lib.rs` puts Layers back on the bar (five buttons). The Layers sheet switches between the -project's maps and layouts when it has more than one, shows and hides layers, zooms to one and +([AI Assistant › On a phone](../../docs/user-guide/assistant.md#on-a-phone)). The Layers sheet +switches between the project's maps and layouts when it has more than one, shows and hides layers, zooms to one and makes one the active layer; the More sheet has Full Extent, undo and redo, the project, the position, and **Use the Desktop Interface**, which brings back the ribbon and panes; **Touch Interface**, on the View tab (or Use the Touch Interface in Command Search), returns to the phone's diff --git a/crates/ui-touch/src/lib.rs b/crates/ui-touch/src/lib.rs index 924a8af165..cf1756f9e0 100644 --- a/crates/ui-touch/src/lib.rs +++ b/crates/ui-touch/src/lib.rs @@ -12,9 +12,8 @@ //! point, line or polygon placed by the cross on the map, with a form for its layer's attributes //! that follows the layer's data design: value lists, ranges and feature templates) and the More //! sheet (full extent, undo, the project, the device's position, the desktop interface) and the -//! Assistant's sheet (see [`assistant`]). A sheet -//! is lowered by its ×, a swipe down on its heading, a tap on the map above it, or the system's -//! Back. Where a shell reports the device's position (`RustGisApp::position`), it is drawn on the +//! Assistant's sheet (see [`assistant`]). A sheet is lowered by its ×, a swipe down on its heading, +//! a tap on the map above it, or the system's Back. Where a shell reports the device's position (`RustGisApp::position`), it is drawn on the //! map and the capture cross can be put on it. //! The form marks the fields the layer's constraint rules require, narrows a field to the values //! its contingent value sets leave it, has a calendar for dates, and keeps the field being typed @@ -253,7 +252,7 @@ pub fn chrome(app: &mut RustGisApp, ui: &mut Ui) { // while ModelBuilder, with its own buttons there, is in the map's place. // Not on a strip of map too short for it (a full sheet): it comes back as the sheet lowers. let room = above.height() >= TARGET + 16.0; - if LAYERS_ON_THE_MAP && map && room && layers_button(ui, &t, above, shown == Sheet::Layers) { + if map && room && layers_button(ui, &t, above, shown == Sheet::Layers) { set_sheet(ui.ctx(), if shown == Sheet::Layers { Sheet::None } else { Sheet::Layers }); } // While capturing, a cross marks the middle of the map: the point goes there, so the @@ -418,16 +417,11 @@ fn cross(painter: &egui::Painter, at: egui::Pos2, t: &Tokens) { } } -/// Whether Layers is a button at the map's top-right corner, leaving the bar's room to the -/// Assistant. `false` puts it back on the bar, first: five buttons with the Assistant. -const LAYERS_ON_THE_MAP: bool = true; - /// The bar's buttons, in order: Add Data, Capture, the Assistant once it is set up, and More, -/// with Layers first when it isn't on the map ([`LAYERS_ON_THE_MAP`]) or ModelBuilder is in the -/// map's place. +/// with Layers first while ModelBuilder is in the place of the map, which has its button. fn bar_buttons(app: &RustGisApp) -> Vec { let mut buttons = Vec::with_capacity(5); - if !LAYERS_ON_THE_MAP || app.mb.shown() { + if app.mb.shown() { buttons.push(Sheet::Layers); } // Add Data has no sheet of its own. From 45d658ad1add8e33d327a2d41e0badc95e0db770 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 16:46:28 -0600 Subject: [PATCH 09/15] test(assistant): give the waiting-message test's provider a model, so a message can go --- crates/ui-egui/src/assistantpane.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/assistantpane.rs b/crates/ui-egui/src/assistantpane.rs index d511ea4c05..c7ad106304 100644 --- a/crates/ui-egui/src/assistantpane.rs +++ b/crates/ui-egui/src/assistantpane.rs @@ -1625,7 +1625,9 @@ pub(crate) mod tests { use rustgis_engine::platform::Typed; for (touch, backstage, waits) in [(true, false, true), (true, true, false), (false, false, false)] { let mut app = RustGisApp::with_sample(); - app.assistant.agent = Some(Agent::new(Config::from_env("custom"), &app.session)); + let mut cfg = Config::from_env("custom"); + cfg.model = "test".into(); + app.assistant.agent = Some(Agent::new(cfg, &app.session)); app.assistant.loaded = true; app.services.http = Some(Box::new(|_, _| {})); app.chrome = if touch { Some(|_, _| {}) } else { None }; From c0e9c0224dd10c52c09167edb60967a949327fbb Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 18:03:31 -0600 Subject: [PATCH 10/15] fix(assistant): say what a replaced text field sent isn't kept, and limit the messages waiting What Android's text field hadn't sent when another was opened in its place was dropped without a word. A command's messages piled up without a limit while the assistant couldn't send them; past 1 MiB waiting the command is refused. --- crates/ui-egui/src/assistant.rs | 18 +++++++++++++++ crates/ui-egui/src/assistantpane.rs | 16 +++++++++++++ crates/ui-egui/src/lib.rs | 4 ++-- crates/ui-touch/src/assistant.rs | 35 ++++++++++++++++++++++++++++- 4 files changed, 70 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/assistant.rs b/crates/ui-egui/src/assistant.rs index 7599ebbe93..369b791153 100644 --- a/crates/ui-egui/src/assistant.rs +++ b/crates/ui-egui/src/assistant.rs @@ -168,6 +168,20 @@ impl AssistantState { self.send_when_ready } + /// Takes a message a command asked to send, unless what waits, in the box and apart, would pass + /// [`MAX_WAITING`] with it. + pub(crate) fn ask(&mut self, text: &str) -> Result<(), String> { + let waiting = self.asked.iter().fold(self.input.len(), |n, t| n.saturating_add(t.len())); + if waiting.saturating_add(text.len()) > MAX_WAITING { + return Err(crate::i18n::fmt( + "The messages waiting for the assistant are at most {size} KiB together: this one isn't sent.", + &[("size", &(MAX_WAITING / 1024).to_string())], + )); + } + self.asked.push(text.to_string()); + Ok(()) + } + /// How many times the message being written has gone: a front end typing it in a field of its /// own tells by it that what the field holds was sent. pub fn sent(&self) -> u64 { @@ -207,6 +221,10 @@ impl AssistantState { } } +/// The most text that waits to be sent, in bytes: the message being written and those commands +/// asked for. +const MAX_WAITING: usize = 1 << 20; + /// The ids of the settings fields typed into: changes are saved once none has focus. pub(crate) const FIELDS: [&str; 3] = ["assistant_model", "assistant_url", "assistant_key"]; diff --git a/crates/ui-egui/src/assistantpane.rs b/crates/ui-egui/src/assistantpane.rs index c7ad106304..a22b0fe9bd 100644 --- a/crates/ui-egui/src/assistantpane.rs +++ b/crates/ui-egui/src/assistantpane.rs @@ -1618,6 +1618,22 @@ pub(crate) mod tests { } } + /// What commands ask to send is refused past a limit, whether one message or many, and counting + /// what the box holds; what was taken before is kept. + #[test] + fn messages_asked_for_are_refused_past_a_limit() { + let mut app = RustGisApp::with_sample(); + let ask = |app: &mut RustGisApp, n: usize| app.run("ui.pane.assistant", serde_json::json!({"ask": "a".repeat(n)})); + assert!(ask(&mut app, (1 << 20) + 1).is_err()); + assert!(app.assistant.asked.is_empty()); + assert!(ask(&mut app, 600 << 10).is_ok()); + assert!(ask(&mut app, 600 << 10).is_err_and(|e| e.contains("1024 KiB"))); + assert!(ask(&mut app, 10).is_ok()); + assert_eq!(app.assistant.asked.len(), 2); + app.assistant.input = "b".repeat(500 << 10); + assert!(ask(&mut app, 10).is_err()); + } + /// A message waits for text a phone's own field sent until the touch interface takes it, and /// only where that is drawn: not behind the backstage, nor in the desktop interface. #[test] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 6ca40154a4..2e6b86654c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -5594,9 +5594,9 @@ impl RustGisApp { // `{"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) => { - self.ui.open_right(RightPane::Assistant); // Sent on the next frame, as a suggestion is. - self.assistant.asked.push(text.to_string()); + self.assistant.ask(text)?; + self.ui.open_right(RightPane::Assistant); } None => toggle_right(&mut self.ui, RightPane::Assistant), }, diff --git a/crates/ui-touch/src/assistant.rs b/crates/ui-touch/src/assistant.rs index feebd83d0c..b8e49af259 100644 --- a/crates/ui-touch/src/assistant.rs +++ b/crates/ui-touch/src/assistant.rs @@ -211,8 +211,12 @@ pub(crate) fn take_typed(app: &mut RustGisApp, ctx: &egui::Context, typed: Vec { + app.session.notify(tl!("What was typed wasn't kept: another field was opened while it was typed."), true); + } Typed::Closed { id, .. } if id == open => state.entering = None, - _ => {} + Typed::Closed { .. } => {} } } set_chat(ctx, state); @@ -991,6 +995,35 @@ mod tests { } } + /// What a field sends once another was opened in its place is for neither, and is said. + #[test] + fn text_of_a_field_another_was_opened_in_place_of_is_said_not_to_be_kept() { + let mut held = Held::new(); + provider(&mut held, "custom", "test"); + let asked = native(&mut held); + raise(&held.ctx, Height::Full); + held.frame(Vec::new()); + for _ in 0..2 { + let bar = held.find("Ask, or say what to do…").unwrap().center(); + held.touch(&[bar]); + } + let ids: Vec = asked.borrow().iter().map(|e| e.id.clone()).collect(); + assert_eq!(ids.len(), 2); + let mark = held.app.session.notice_mark(); + held.app.typed.push(Typed::Text { id: ids[0].clone(), text: "late".into() }); + held.app.typed.push(Typed::Closed { id: ids[0].clone(), failed: None }); + held.frame(Vec::new()); + assert_eq!(held.app.assistant.input, ""); + let notices = said(&held, mark); + assert_eq!(notices.iter().filter(|n| n.contains("wasn't kept")).count(), 1, "{notices:?}"); + // The one open now still fills the box, and says nothing. + let mark = held.app.session.notice_mark(); + held.app.typed.push(Typed::Text { id: ids[1].clone(), text: "Zoom in".into() }); + held.frame(Vec::new()); + assert_eq!(held.app.assistant.input, "Zoom in"); + assert!(said(&held, mark).is_empty(), "{:?}", said(&held, mark)); + } + /// Text the system's field sent before the key was read goes with the message that waited for /// it: the sheet takes it before the message is sent. #[test] From 733495dc60d913783605aab339d958ce6e116a43 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 18:13:29 -0600 Subject: [PATCH 11/15] fix(assistant): a command's message leaves the draft and its pictures, the same text or not --- crates/ui-egui/src/assistant.rs | 12 +++++------ crates/ui-egui/src/assistantpane.rs | 16 +++++++++++---- crates/ui-egui/src/assistantpictures.rs | 2 +- crates/ui-touch/src/assistant.rs | 27 ------------------------- 4 files changed, 18 insertions(+), 39 deletions(-) diff --git a/crates/ui-egui/src/assistant.rs b/crates/ui-egui/src/assistant.rs index 369b791153..b2c9442fe9 100644 --- a/crates/ui-egui/src/assistant.rs +++ b/crates/ui-egui/src/assistant.rs @@ -855,9 +855,9 @@ pub(crate) fn poll(app: &mut RustGisApp, ctx: &egui::Context) { if ready { while !app.assistant.busy() && !app.assistant.asked.is_empty() { let text = app.assistant.asked.remove(0); - // The pictures are the message being written's, unless that is what was asked for. - let own = app.assistant.input.trim() == text.trim(); - let pictures = if own { Vec::new() } else { app.assistant.pictures.take() }; + // The pictures are the message being written's, even where that says the same: it is + // the user's to send. + let pictures = app.assistant.pictures.take(); send_from(app, text, false, ctx); app.assistant.pictures.put_back(pictures); } @@ -1051,11 +1051,9 @@ fn send_from(app: &mut RustGisApp, text: String, from_box: bool, ctx: &egui::Con return; }; // Another message (a suggestion) goes without the pictures of the one being written. - let draft = app.assistant.input.trim(); - let own = from_box || draft == text; - let pictures = if own || draft.is_empty() { app.assistant.pictures.take() } else { Vec::new() }; + let pictures = if from_box || app.assistant.input.trim().is_empty() { app.assistant.pictures.take() } else { Vec::new() }; let step = agent.ask_with(&text, pictures, session); - if own { + if from_box { app.assistant.input.clear(); app.assistant.sent = app.assistant.sent.wrapping_add(1); } diff --git a/crates/ui-egui/src/assistantpane.rs b/crates/ui-egui/src/assistantpane.rs index a22b0fe9bd..52ae9a242e 100644 --- a/crates/ui-egui/src/assistantpane.rs +++ b/crates/ui-egui/src/assistantpane.rs @@ -1639,7 +1639,9 @@ pub(crate) mod tests { #[test] fn a_message_waits_for_the_fields_text_only_where_it_is_taken() { use rustgis_engine::platform::Typed; - for (touch, backstage, waits) in [(true, false, true), (true, true, false), (false, false, false)] { + let places = [(true, false, true), (true, true, false), (false, false, false)]; + // The one being written, and one a command asked for. + for (command, (touch, backstage, waits)) in places.map(|p| (false, p)).into_iter().chain(places.map(|p| (true, p))) { let mut app = RustGisApp::with_sample(); let mut cfg = Config::from_env("custom"); cfg.model = "test".into(); @@ -1649,10 +1651,16 @@ pub(crate) mod tests { app.chrome = if touch { Some(|_, _| {}) } else { None }; app.ui.backstage = backstage; app.typed.push(Typed::Text { id: "assistant:message:0".into(), text: "more".into() }); - app.assistant.asked.push("Zoom to Tokyo".into()); + if command { + app.assistant.asked.push("Zoom to Tokyo".into()); + } else { + app.assistant.input = "Zoom to Tokyo".into(); + app.assistant.send_when_ready = true; + } poll(&mut app, &egui::Context::default()); - assert_eq!(app.assistant.waiting_to_send(), waits, "touch {touch}, backstage {backstage}"); - assert_eq!(app.assistant.agent.as_ref().unwrap().busy(), !waits, "touch {touch}, backstage {backstage}"); + let at = format!("command {command}, touch {touch}, backstage {backstage}"); + assert_eq!(app.assistant.waiting_to_send(), waits, "{at}"); + assert_eq!(app.assistant.agent.as_ref().unwrap().busy(), !waits, "{at}"); } } diff --git a/crates/ui-egui/src/assistantpictures.rs b/crates/ui-egui/src/assistantpictures.rs index dc00a93bfa..ad8f1387e9 100644 --- a/crates/ui-egui/src/assistantpictures.rs +++ b/crates/ui-egui/src/assistantpictures.rs @@ -411,7 +411,7 @@ mod tests { /// command asked for, whatever the box holds, or a suggestion while something else is written. #[test] fn another_message_leaves_the_pictures_of_the_one_being_written() { - for (draft, command) in [("look at this", true), ("", true), ("look at this", false)] { + for (draft, command) in [("look at this", true), ("", true), ("Zoom to Tokyo", true), ("look at this", false)] { let mut app = RustGisApp::with_sample(); let mut cfg = rustgis_assistant::Config::from_env("custom"); cfg.model = "test".into(); diff --git a/crates/ui-touch/src/assistant.rs b/crates/ui-touch/src/assistant.rs index b8e49af259..1b42022eae 100644 --- a/crates/ui-touch/src/assistant.rs +++ b/crates/ui-touch/src/assistant.rs @@ -1024,33 +1024,6 @@ mod tests { assert!(said(&held, mark).is_empty(), "{:?}", said(&held, mark)); } - /// Text the system's field sent before the key was read goes with the message that waited for - /// it: the sheet takes it before the message is sent. - #[test] - fn a_message_waiting_goes_with_the_text_the_systems_field_had_sent() { - let mut held = Held::new(); - provider(&mut held, "custom", "test"); - held.app.chrome = Some(crate::chrome); - held.app.services.http = Some(Box::new(|_, _| {})); - let asked = native(&mut held); - raise(&held.ctx, Height::Half); - held.frame(Vec::new()); - let bar = held.find("Ask, or say what to do…").unwrap().center(); - held.touch(&[bar]); - let id = asked.borrow().last().cloned().expect("the system's text field").id; - held.app.typed.push(Typed::Text { id: id.clone(), text: "Zoom".into() }); - held.frame(Vec::new()); - let mark = held.app.session.notice_mark(); - // As one a command asks for, the same as is being written, is due once the key is read. - crate::run(&mut held.app, "ui.pane.assistant", json!({"ask": "Zoom"})); - held.app.typed.push(Typed::Text { id, text: "Zoom in".into() }); - held.frame(Vec::new()); - held.frame(Vec::new()); - assert_eq!(held.app.assistant.input, "Zoom in", "typed before the message went: kept"); - assert!(said(&held, mark).is_empty(), "{:?}", said(&held, mark)); - assert!(held.app.assistant.messages().iter().any(|e| matches!(e, Entry::User(t) if t == "Zoom"))); - } - /// The Layers button isn't on a strip of map too short for it, and is back as the sheet lowers. #[test] fn layers_is_not_on_a_strip_of_map_too_short_for_it() { From 394b8dbbde138c7713a1379348e7862c8df04f3a Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 18:59:19 -0600 Subject: [PATCH 12/15] fix(mobile): the Assistant's words in display form once, and a replaced field said once In a right-to-left language the strip's line and a tool call's words were put in display form twice. Text of a replaced field is said once for each field, and at most 64 messages a command asked for wait. --- crates/ui-egui/src/assistant.rs | 9 ++++ crates/ui-egui/src/assistantpane.rs | 7 +++ crates/ui-egui/src/i18n/mod.rs | 2 +- crates/ui-touch/src/assistant.rs | 66 +++++++++++++++++++++-------- crates/ui-touch/src/lib.rs | 4 +- 5 files changed, 68 insertions(+), 20 deletions(-) diff --git a/crates/ui-egui/src/assistant.rs b/crates/ui-egui/src/assistant.rs index b2c9442fe9..ae09e8ca6e 100644 --- a/crates/ui-egui/src/assistant.rs +++ b/crates/ui-egui/src/assistant.rs @@ -171,6 +171,12 @@ impl AssistantState { /// Takes a message a command asked to send, unless what waits, in the box and apart, would pass /// [`MAX_WAITING`] with it. pub(crate) fn ask(&mut self, text: &str) -> Result<(), String> { + if self.asked.len() >= MAX_ASKED { + return Err(crate::i18n::fmt( + "At most {count} messages wait for the assistant: this one isn't sent.", + &[("count", &MAX_ASKED.to_string())], + )); + } let waiting = self.asked.iter().fold(self.input.len(), |n, t| n.saturating_add(t.len())); if waiting.saturating_add(text.len()) > MAX_WAITING { return Err(crate::i18n::fmt( @@ -225,6 +231,9 @@ impl AssistantState { /// asked for. const MAX_WAITING: usize = 1 << 20; +/// The most messages commands asked for that wait to be sent. +const MAX_ASKED: usize = 64; + /// The ids of the settings fields typed into: changes are saved once none has focus. pub(crate) const FIELDS: [&str; 3] = ["assistant_model", "assistant_url", "assistant_key"]; diff --git a/crates/ui-egui/src/assistantpane.rs b/crates/ui-egui/src/assistantpane.rs index 52ae9a242e..935df06d9e 100644 --- a/crates/ui-egui/src/assistantpane.rs +++ b/crates/ui-egui/src/assistantpane.rs @@ -1632,6 +1632,13 @@ pub(crate) mod tests { assert_eq!(app.assistant.asked.len(), 2); app.assistant.input = "b".repeat(500 << 10); assert!(ask(&mut app, 10).is_err()); + app.assistant.input.clear(); + app.assistant.asked.clear(); + for _ in 0..64 { + assert!(ask(&mut app, 1).is_ok()); + } + assert!(ask(&mut app, 1).is_err_and(|e| e.contains("64"))); + assert_eq!(app.assistant.asked.len(), 64); } /// A message waits for text a phone's own field sent until the touch interface takes it, and diff --git a/crates/ui-egui/src/i18n/mod.rs b/crates/ui-egui/src/i18n/mod.rs index 2372491ece..144bbf79fa 100644 --- a/crates/ui-egui/src/i18n/mod.rs +++ b/crates/ui-egui/src/i18n/mod.rs @@ -531,7 +531,7 @@ pub fn note_raw(n: &rustgis_assistant::provider::Note) -> String { /// `logical`, a message made in logical order (of parts from [`fmt_raw`] and [`t_raw`]), in /// display form, as [`fmt`] gives its message: for a message put together from parts, which /// is put in display form once, as a whole. -pub(crate) fn display(logical: &str) -> String { +pub fn display(logical: &str) -> String { rtl::visual(logical) } diff --git a/crates/ui-touch/src/assistant.rs b/crates/ui-touch/src/assistant.rs index 1b42022eae..e7dc48bc61 100644 --- a/crates/ui-touch/src/assistant.rs +++ b/crates/ui-touch/src/assistant.rs @@ -53,6 +53,8 @@ pub(crate) struct Chat { /// The system's text field open for one of the sheet's fields: its id, the field, and the /// provider it was opened for (a provider's settings never take what was typed for another's). entering: Option<(String, Field, String)>, + /// The replaced field whose late text was said not to be kept ([`take_typed`]): each is said once. + late_said: String, /// What the system's text field open for the message last held, and how many messages had gone /// then ([`assistant::AssistantState::sent`]). entered: String, @@ -212,8 +214,11 @@ pub(crate) fn take_typed(app: &mut RustGisApp, ctx: &egui::Context, typed: Vec { - app.session.notify(tl!("What was typed wasn't kept: another field was opened while it was typed."), true); + Typed::Text { id, .. } => { + if state.late_said != id { + app.session.notify(tl!("What was typed wasn't kept: another field was opened while it was typed."), true); + state.late_said = id; + } } Typed::Closed { id, .. } if id == open => state.entering = None, Typed::Closed { .. } => {} @@ -271,7 +276,8 @@ fn doing(app: &RustGisApp) -> String { } } -/// A tool call in plain words: the command's name, or what the tool does. +/// 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("↳ ") { @@ -282,25 +288,25 @@ fn plain(app: &RustGisApp, name: &str, summary: &str) -> String { 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!(spec.label).trim_end_matches('…').to_string(), + 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("Ran the tool {tool}", &[("tool", tool)]), - None => tl!("Ran a tool").to_string(), + Some(tool) => i18n::fmt_raw("Ran the tool {tool}", &[("tool", tool)]), + None => tl_raw!("Ran a tool").to_string(), } } - "list_layers" => tl!("Looked at the layers").to_string(), - "view_map" => tl!("Looked at the map").to_string(), - "search_commands" => tl!("Looked for a command").to_string(), - "search_tools" => tl!("Looked for a tool").to_string(), - "describe_tool" => tl!("Read about a tool").to_string(), - "read_features" => tl!("Read features").to_string(), - "search_docs" | "read_doc" => tl!("Read the user guide").to_string(), - "load_skill" => tl!("Loaded a skill").to_string(), - "delegate" => tl!("Handed a task to a subagent").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}") @@ -422,7 +428,7 @@ 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(format!("{mark} {}", plain(app, name, summary))).size(14.0).color(ink); + let head = RichText::new(i18n::display(&format!("{mark} {}", plain(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(); @@ -1010,7 +1016,9 @@ mod tests { let ids: Vec = asked.borrow().iter().map(|e| e.id.clone()).collect(); assert_eq!(ids.len(), 2); let mark = held.app.session.notice_mark(); - held.app.typed.push(Typed::Text { id: ids[0].clone(), text: "late".into() }); + for text in ["late", "later"] { + held.app.typed.push(Typed::Text { id: ids[0].clone(), text: text.into() }); + } held.app.typed.push(Typed::Closed { id: ids[0].clone(), failed: None }); held.frame(Vec::new()); assert_eq!(held.app.assistant.input, ""); @@ -1024,6 +1032,30 @@ mod tests { assert!(said(&held, mark).is_empty(), "{:?}", said(&held, mark)); } + /// In a right-to-left language the strip's words are put in display form once, not the part + /// of them a tool call fills in again. + #[test] + fn the_strips_words_are_put_in_display_form_once() { + let mut held = Held::new(); + provider(&mut held, "custom", "test"); + answering(&mut held, vec![command("c1", "map.goToXY", json!({"lon": 139.7, "lat": 35.7}))]); + let ctx = held.ctx.clone(); + assistant::send(&mut held.app, "Zoom to Tokyo".into(), &ctx); + held.frame(Vec::new()); + held.frame(Vec::new()); + let before = i18n::current(); + i18n::set_current(i18n::Lang::from_code("fa").unwrap()); + let label = tl_raw!(held.app.session.registry.get("map.goToXY").unwrap().label).trim_end_matches('…').to_string(); + let line = |step: &str| i18n::fmt("{step} · thinking…", &[("step", step)]); + let once = line(&format!("✓ {label}")); + let twice = line(&format!("✓ {}", i18n::display(&label))); + let said = doing(&held.app); + i18n::set_current(before); + assert!(!label.is_ascii(), "{label} has a translation"); + assert_ne!(once, twice, "the test can tell"); + assert_eq!(said, once); + } + /// The Layers button isn't on a strip of map too short for it, and is back as the sheet lowers. #[test] fn layers_is_not_on_a_strip_of_map_too_short_for_it() { diff --git a/crates/ui-touch/src/lib.rs b/crates/ui-touch/src/lib.rs index cf1756f9e0..46e4189d55 100644 --- a/crates/ui-touch/src/lib.rs +++ b/crates/ui-touch/src/lib.rs @@ -13,8 +13,8 @@ //! that follows the layer's data design: value lists, ranges and feature templates) and the More //! sheet (full extent, undo, the project, the device's position, the desktop interface) and the //! Assistant's sheet (see [`assistant`]). A sheet is lowered by its ×, a swipe down on its heading, -//! a tap on the map above it, or the system's Back. Where a shell reports the device's position (`RustGisApp::position`), it is drawn on the -//! map and the capture cross can be put on it. +//! a tap on the map above it, or the system's Back. Where a shell reports the device's position +//! (`RustGisApp::position`), it is drawn on the map and the capture cross can be put on it. //! The form marks the fields the layer's constraint rules require, narrows a field to the values //! its contingent value sets leave it, has a calendar for dates, and keeps the field being typed //! in above the soft keyboard (see [`form`]). From 4cd281ab75c02cb0756bced60b083546756b1dcf Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 19:04:21 -0600 Subject: [PATCH 13/15] test(mobile): a tool call's words in display form once, with Latin in them --- crates/ui-touch/src/assistant.rs | 22 ++++++++-------------- 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/crates/ui-touch/src/assistant.rs b/crates/ui-touch/src/assistant.rs index e7dc48bc61..a7638d9757 100644 --- a/crates/ui-touch/src/assistant.rs +++ b/crates/ui-touch/src/assistant.rs @@ -1032,28 +1032,22 @@ mod tests { assert!(said(&held, mark).is_empty(), "{:?}", said(&held, mark)); } - /// In a right-to-left language the strip's words are put in display form once, not the part - /// of them a tool call fills in again. + /// In a right-to-left language the words of a tool call are put in display form once, with the + /// line they go into: twice would turn the Latin in them back round. #[test] - fn the_strips_words_are_put_in_display_form_once() { + fn the_words_of_a_tool_call_are_put_in_display_form_once() { let mut held = Held::new(); provider(&mut held, "custom", "test"); - answering(&mut held, vec![command("c1", "map.goToXY", json!({"lon": 139.7, "lat": 35.7}))]); - let ctx = held.ctx.clone(); - assistant::send(&mut held.app, "Zoom to Tokyo".into(), &ctx); - held.frame(Vec::new()); - held.frame(Vec::new()); let before = i18n::current(); i18n::set_current(i18n::Lang::from_code("fa").unwrap()); - let label = tl_raw!(held.app.session.registry.get("map.goToXY").unwrap().label).trim_end_matches('…').to_string(); + let logical = tl_raw!("Add PostGIS Layer").to_string(); + let words = plain(&held.app, "run_command", "pg.addLayer {}"); let line = |step: &str| i18n::fmt("{step} · thinking…", &[("step", step)]); - let once = line(&format!("✓ {label}")); - let twice = line(&format!("✓ {}", i18n::display(&label))); - let said = doing(&held.app); + let (once, twice) = (line(&format!("✓ {words}")), line(&format!("✓ {}", i18n::display(&words)))); i18n::set_current(before); - assert!(!label.is_ascii(), "{label} has a translation"); + assert_eq!(words, logical); + assert!(!words.is_ascii() && words.contains("PostGIS"), "{words}"); assert_ne!(once, twice, "the test can tell"); - assert_eq!(said, once); } /// The Layers button isn't on a strip of map too short for it, and is back as the sheet lowers. From 5e536ef3393fa6491bf1a79d7092c2e667b424e1 Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 19:31:02 -0600 Subject: [PATCH 14/15] fix(assistant): a message the user sent goes before one a command asked for While it waited for the key or a picture, a command's message went first and the user's stayed in the box with a notice saying the assistant was busy. --- crates/ui-egui/src/assistant.rs | 11 ++++++----- crates/ui-egui/src/assistantpane.rs | 19 +++++++++++++++++++ 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/assistant.rs b/crates/ui-egui/src/assistant.rs index ae09e8ca6e..11cd38f9eb 100644 --- a/crates/ui-egui/src/assistant.rs +++ b/crates/ui-egui/src/assistant.rs @@ -861,6 +861,12 @@ pub(crate) fn poll(app: &mut RustGisApp, ctx: &egui::Context) { ctx.request_repaint(); } let ready = !key_loading(app) && !app.assistant.pictures.reading() && !typed; + // The user's own message goes before one a command asked for: it was sent before that was said. + if app.assistant.send_when_ready && ready { + app.assistant.send_when_ready = false; + let text = app.assistant.input.clone(); + send_from(app, text, true, ctx); + } if ready { while !app.assistant.busy() && !app.assistant.asked.is_empty() { let text = app.assistant.asked.remove(0); @@ -876,11 +882,6 @@ pub(crate) fn poll(app: &mut RustGisApp, ctx: &egui::Context) { app.session.notify(tl!("The assistant is busy; stop it or wait for it to finish."), true); } } - if app.assistant.send_when_ready && ready { - app.assistant.send_when_ready = false; - let text = app.assistant.input.clone(); - send_from(app, text, true, ctx); - } // The reply's text so far, as it streams in. if let Some((generation, chunks)) = &app.assistant.chunks { let generation = *generation; diff --git a/crates/ui-egui/src/assistantpane.rs b/crates/ui-egui/src/assistantpane.rs index 935df06d9e..8c00cc44ed 100644 --- a/crates/ui-egui/src/assistantpane.rs +++ b/crates/ui-egui/src/assistantpane.rs @@ -1618,6 +1618,25 @@ pub(crate) mod tests { } } + /// A message the user sent goes before one a command asked for meanwhile, which is then held + /// in the box with a notice, as any message while the assistant is busy. + #[test] + fn a_message_the_user_sent_goes_before_one_a_command_asked_for() { + let mut app = RustGisApp::with_sample(); + let mut cfg = Config::from_env("custom"); + cfg.model = "test".into(); + app.assistant.agent = Some(Agent::new(cfg, &app.session)); + app.assistant.loaded = true; + app.services.http = Some(Box::new(|_, _| {})); + app.assistant.input = "mine".into(); + app.assistant.send_when_ready = true; + app.assistant.asked.push("theirs".into()); + poll(&mut app, &egui::Context::default()); + let agent = app.assistant.agent.as_ref().unwrap(); + assert!(matches!(agent.transcript.first(), Some(Entry::User(t)) if t == "mine"), "{:?}", agent.transcript); + assert_eq!(app.assistant.input, "theirs"); + } + /// What commands ask to send is refused past a limit, whether one message or many, and counting /// what the box holds; what was taken before is kept. #[test] From 4712f2094be159e020d63db2d09637e84734babc Mon Sep 17 00:00:00 2001 From: mavrick Date: Sat, 28 Nov 2026 19:36:15 -0600 Subject: [PATCH 15/15] fix(assistant): a message a command asked for twice is kept twice when it can't be sent --- crates/ui-egui/src/assistant.rs | 10 +++++++--- crates/ui-egui/src/assistantpane.rs | 11 +++++++++-- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/assistant.rs b/crates/ui-egui/src/assistant.rs index 11cd38f9eb..b33d1defb6 100644 --- a/crates/ui-egui/src/assistant.rs +++ b/crates/ui-egui/src/assistant.rs @@ -220,9 +220,13 @@ impl AssistantState { /// and what a command asked to send goes into the box with it. pub(crate) fn hold(&mut self) { self.send_when_ready = false; - // Each goes above what the box holds, so the newest goes first and the oldest ends on top. - for text in std::mem::take(&mut self.asked).into_iter().rev() { - to_box(self, &text); + // Above what the box holds, oldest first. Each was asked for by itself, so one said twice + // stays twice. + let asked = std::mem::take(&mut self.asked); + if !asked.is_empty() { + let lines: Vec<&str> = + asked.iter().map(String::as_str).chain((!self.input.trim().is_empty()).then_some(self.input.as_str())).collect(); + self.input = lines.join("\n"); } } } diff --git a/crates/ui-egui/src/assistantpane.rs b/crates/ui-egui/src/assistantpane.rs index 8c00cc44ed..020f426f93 100644 --- a/crates/ui-egui/src/assistantpane.rs +++ b/crates/ui-egui/src/assistantpane.rs @@ -1701,10 +1701,17 @@ pub(crate) mod tests { app.assistant.send_when_ready = true; app.assistant.asked.push("asked".into()); app.assistant.asked.push("asked next".into()); + app.assistant.asked.push("asked next".into()); assistant::forget_sign_in(&mut app, &mut cfg); assert!(!app.assistant.sending_when_ready() && app.assistant.asked.is_empty()); - // In the order they were asked for, above what was being written. - assert_eq!(app.assistant.input, "asked\nasked next\nwaited"); + // In the order they were asked for, above what was being written, one asked for twice + // kept twice. + assert_eq!(app.assistant.input, "asked\nasked next\nasked next\nwaited"); + // The same with nothing being written. + app.assistant.input.clear(); + app.assistant.asked = vec!["again".into(), "again".into()]; + app.assistant.hold(); + assert_eq!(app.assistant.input, "again\nagain"); } /// A new conversation, or a peer's project replacing this one, sends nothing still waiting